diff --git a/src/AboutDialog.cpp b/src/AboutDialog.cpp index 29375c856..e4992dac8 100644 --- a/src/AboutDialog.cpp +++ b/src/AboutDialog.cpp @@ -20,15 +20,15 @@ #include "GcUpgrade.h" #include "GcCrashDialog.h" -AboutDialog::AboutDialog(MainWindow *mainWindow, QDir home) : mainWindow(mainWindow), home(home) +AboutDialog::AboutDialog(Context *context, QDir home) : context(context), home(home) { setWindowTitle(tr("About GoldenCheetah")); - aboutPage = new AboutPage(mainWindow, home); - versionPage = new VersionPage(mainWindow, home); - contributorsPage = new ContributorsPage(mainWindow, home); + aboutPage = new AboutPage(context, home); + versionPage = new VersionPage(context, home); + contributorsPage = new ContributorsPage(context, home); #ifndef GC_VERSION - configPage = new ConfigPage(mainWindow, home); + configPage = new ConfigPage(context, home); #endif tabWidget = new QTabWidget; @@ -53,7 +53,7 @@ AboutDialog::AboutDialog(MainWindow *mainWindow, QDir home) : mainWindow(mainWin // // About page // -AboutPage::AboutPage(MainWindow *main, QDir home) : main(main), home(home) +AboutPage::AboutPage(Context *context, QDir home) : context(context), home(home) { QLabel *text; text=new QLabel(this); @@ -94,7 +94,7 @@ AboutPage::AboutPage(MainWindow *main, QDir home) : main(main), home(home) // // Version page // -VersionPage::VersionPage(MainWindow *main, QDir home) : main(main), home(home) +VersionPage::VersionPage(Context *context, QDir home) : context(context), home(home) { QLabel *text; text=new QLabel(this); @@ -111,7 +111,7 @@ VersionPage::VersionPage(MainWindow *main, QDir home) : main(main), home(home) // // Contributors page // -ContributorsPage::ContributorsPage(MainWindow *main, QDir home) : main(main), home(home) +ContributorsPage::ContributorsPage(Context *context, QDir home) : context(context), home(home) { QStringList contributors; contributors.append("Alejandro Martinez"); @@ -186,7 +186,7 @@ ContributorsPage::ContributorsPage(MainWindow *main, QDir home) : main(main), ho setLayout(mainLayout); } -ConfigPage::ConfigPage(MainWindow *main, QDir home) : main(main), home(home) +ConfigPage::ConfigPage(Context *context, QDir home) : context(context), home(home) { QTextEdit *text = new QTextEdit(this); text->setAutoFillBackground(false); diff --git a/src/AboutDialog.h b/src/AboutDialog.h index d5a284e4c..b9cd6d334 100644 --- a/src/AboutDialog.h +++ b/src/AboutDialog.h @@ -5,7 +5,7 @@ #include "Pages.h" #include -class MainWindow; +class Context; class AboutPage; class VersionPage; class ConfigPage; @@ -17,10 +17,10 @@ class AboutDialog: public QDialog G_OBJECT public: - AboutDialog(MainWindow *mainWindow, QDir home); + AboutDialog(Context *context, QDir home); private: - MainWindow *mainWindow; + Context *context; QDir home; AboutPage *aboutPage; @@ -40,10 +40,10 @@ class AboutPage : public QWidget public: - AboutPage(MainWindow *main, QDir home); + AboutPage(Context *context, QDir home); private: - MainWindow *main; + Context *context; QDir home; }; @@ -54,10 +54,10 @@ class VersionPage : public QWidget public: - VersionPage(MainWindow *main, QDir home); + VersionPage(Context *context, QDir home); private: - MainWindow *main; + Context *context; QDir home; }; @@ -66,10 +66,10 @@ class ConfigPage : public QWidget Q_OBJECT public: - ConfigPage(MainWindow*main, QDir home); + ConfigPage(Context *context, QDir home); private: - MainWindow *main; + Context *context; QDir home; }; @@ -80,10 +80,10 @@ class ContributorsPage : public QWidget public: - ContributorsPage(MainWindow *main, QDir home); + ContributorsPage(Context *context, QDir home); private: - MainWindow *main; + Context *context; QDir home; }; diff --git a/src/AddDeviceWizard.cpp b/src/AddDeviceWizard.cpp index 0b4386017..919a4b036 100644 --- a/src/AddDeviceWizard.cpp +++ b/src/AddDeviceWizard.cpp @@ -17,6 +17,9 @@ */ #include "AddDeviceWizard.h" +#include "MainWindow.h" +#include "Athlete.h" +#include "Context.h" // WIZARD FLOW // @@ -29,7 +32,7 @@ // // Main wizard -AddDeviceWizard::AddDeviceWizard(MainWindow *main) : QWizard(main), main(main) +AddDeviceWizard::AddDeviceWizard(Context *context) : QWizard(context->mainWindow), context(context) { #ifdef Q_OS_MAC setWizardStyle(QWizard::ModernStyle); @@ -551,7 +554,7 @@ AddFirmware::validatePage() if (copy->isChecked()) { QString fileName = QFileInfo(filePath).fileName(); - QString targetFileName = QFileInfo(mainWindow->athlete->home.absolutePath() + "/../").absolutePath() + "/" + fileName; + QString targetFileName = QFileInfo(context->athlete->home.absolutePath() + "/../").absolutePath() + "/" + fileName; // check not the same thing! if(QFileInfo(fileName).absolutePath() != QFileInfo(targetFileName).absolutePath()) { @@ -1179,7 +1182,7 @@ AddFinal::validatePage() all.writeConfig(list); // tell everyone - wizard->main->context->notifyConfigChanged(); + wizard->context->notifyConfigChanged(); // shut down the controller, if it is there, since it will // still be connected to the device (in case we hit the back button) diff --git a/src/AddDeviceWizard.h b/src/AddDeviceWizard.h index 27ffbde85..2253d51df 100644 --- a/src/AddDeviceWizard.h +++ b/src/AddDeviceWizard.h @@ -20,7 +20,7 @@ #define _AddDeviceWizard_h #include "GoldenCheetah.h" -#include "MainWindow.h" +#include "Context.h" #include "DeviceTypes.h" #include "Serial.h" #include "RealtimeController.h" @@ -45,9 +45,9 @@ class AddDeviceWizard : public QWizard Q_OBJECT public: - AddDeviceWizard(MainWindow *main); + AddDeviceWizard(Context *context); - MainWindow *main; + Context *context; bool done; // have we finished? RealtimeController *controller; // for working with devices @@ -135,7 +135,7 @@ class AddFirmware : public QWizardPage QLabel *help; QLabel *file; QLineEdit *name; - MainWindow *mainWindow; + Context *context; AddDeviceWizard *wizard; }; diff --git a/src/AddIntervalDialog.cpp b/src/AddIntervalDialog.cpp index 6381ee501..aace4694b 100644 --- a/src/AddIntervalDialog.cpp +++ b/src/AddIntervalDialog.cpp @@ -18,14 +18,15 @@ #include "AddIntervalDialog.h" #include "MainWindow.h" +#include "Context.h" #include "IntervalItem.h" #include "RideFile.h" #include #include #include -AddIntervalDialog::AddIntervalDialog(MainWindow *mainWindow) : - mainWindow(mainWindow) +AddIntervalDialog::AddIntervalDialog(Context *context) : + context(context) { setAttribute(Qt::WA_DeleteOnClose); setWindowTitle(tr("Add Intervals")); @@ -303,7 +304,7 @@ struct CompareBests { void AddIntervalDialog::createClicked() { - const RideFile *ride = mainWindow->context->currentRide(); + const RideFile *ride = context->currentRide(); if (!ride) { QMessageBox::critical(this, tr("Select Ride"), tr("No ride selected!")); return; @@ -642,9 +643,9 @@ AddIntervalDialog::addClicked() double start = resultsTable->item(i,3)->text().toDouble(); double stop = resultsTable->item(i,4)->text().toDouble(); QString name = resultsTable->item(i,2)->text(); - const RideFile *ride = mainWindow->context->currentRide(); + const RideFile *ride = context->currentRide(); - QTreeWidgetItem *allIntervals = mainWindow->mutableIntervalItems(); + QTreeWidgetItem *allIntervals = context->mainWindow->mutableIntervalItems(); QTreeWidgetItem *last = new IntervalItem(ride, name, start, stop, ride->timeToDistance(start), @@ -655,5 +656,5 @@ AddIntervalDialog::addClicked() allIntervals->addChild(last); } } - mainWindow->updateRideFileIntervals(); + context->mainWindow->updateRideFileIntervals(); } diff --git a/src/AddIntervalDialog.h b/src/AddIntervalDialog.h index cadec9ad0..10eccd06b 100644 --- a/src/AddIntervalDialog.h +++ b/src/AddIntervalDialog.h @@ -22,7 +22,7 @@ #include -class MainWindow; +class Context; class RideFile; class AddIntervalDialog : public QDialog @@ -40,7 +40,7 @@ class AddIntervalDialog : public QDialog start(start), stop(stop), avg(avg) {} }; - AddIntervalDialog(MainWindow *mainWindow); + AddIntervalDialog(Context *context); static void findPeakPowerStandard(const RideFile *ride, QList &results); @@ -64,7 +64,7 @@ class AddIntervalDialog : public QDialog private: - MainWindow *mainWindow; + Context *context; QWidget *intervalMethodWidget, *intervalPeakPowerWidget, *intervalTypeWidget, *intervalTimeWidget, *intervalDistanceWidget, *intervalCountWidget; QHBoxLayout *intervalPeakPowerTypeLayout; diff --git a/src/AerobicDecoupling.cpp b/src/AerobicDecoupling.cpp index 5969e441a..f9f6107c0 100644 --- a/src/AerobicDecoupling.cpp +++ b/src/AerobicDecoupling.cpp @@ -58,7 +58,7 @@ class AerobicDecoupling : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { double firstHalfPower = 0.0, secondHalfPower = 0.0; double firstHalfHR = 0.0, secondHalfHR = 0.0; int halfway = ride->dataPoints().size() / 2; diff --git a/src/Aerolab.cpp b/src/Aerolab.cpp index 680b924cd..6d58f42e4 100644 --- a/src/Aerolab.cpp +++ b/src/Aerolab.cpp @@ -18,7 +18,8 @@ #include "Aerolab.h" #include "AerolabWindow.h" -#include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "IntervalItem.h" #include "RideFile.h" #include "RideItem.h" @@ -52,12 +53,12 @@ class IntervalAerolabData : public QwtSeriesData { public: Aerolab *aerolab; - MainWindow *mainWindow; + Context *context; IntervalAerolabData ( Aerolab *aerolab, - MainWindow *mainWindow - ) : aerolab( aerolab ), mainWindow( mainWindow ) { } + Context *context + ) : aerolab( aerolab ), context(context) { } double x( size_t ) const; double y( size_t ) const; @@ -90,7 +91,7 @@ IntervalItem *IntervalAerolabData::intervalNum ) const { int highlighted = 0; - const QTreeWidgetItem *allIntervals = mainWindow->allIntervalItems(); + const QTreeWidgetItem *allIntervals = context->mainWindow->allIntervalItems(); for ( int ii = 0; ii < allIntervals->childCount(); ii++) { @@ -120,9 +121,9 @@ int IntervalAerolabData::intervalCount() const { int highlighted = 0; - if ( mainWindow->allIntervalItems() != NULL ) + if ( context->mainWindow->allIntervalItems() != NULL ) { - const QTreeWidgetItem *allIntervals = mainWindow->allIntervalItems(); + const QTreeWidgetItem *allIntervals = context->mainWindow->allIntervalItems(); for ( int ii = 0; ii < allIntervals->childCount(); ii++) { IntervalItem *current = (IntervalItem *) allIntervals->child( ii ); @@ -144,7 +145,7 @@ int IntervalAerolabData::intervalCount() const * size returns the number of points */ // The interval curve data is derived from the intervals that have -// been selected in the MainWindow leftlayout for each selected +// been selected in the Context leftlayout for each selected // interval we return 4 data points; bottomleft, topleft, topright // and bottom right. // @@ -170,7 +171,7 @@ double IntervalAerolabData::x if ( current != NULL ) { - double multiplier = mainWindow->athlete->useMetricUnits ? 1 : MILES_PER_KM; + double multiplier = context->athlete->useMetricUnits ? 1 : MILES_PER_KM; // which point are we returning? //qDebug() << "number = " << number << endl; switch ( number % 4 ) @@ -229,10 +230,10 @@ QRectF IntervalAerolabData::boundingRect() const Aerolab::Aerolab( AerolabWindow *parent, - MainWindow *mainWindow + Context *context ): QwtPlot(parent), - mainWindow(mainWindow), + context(context), parent(parent), rideItem(NULL), smooth(1), bydist(true), autoEoffset(true) { @@ -264,7 +265,7 @@ Aerolab::Aerolab( intervalHighlighterCurve = new QwtPlotCurve(); intervalHighlighterCurve->setBaseline(-5000); intervalHighlighterCurve->setYAxis( yLeft ); - intervalHighlighterCurve->setData( new IntervalAerolabData( this, mainWindow ) ); + intervalHighlighterCurve->setData( new IntervalAerolabData( this, context ) ); intervalHighlighterCurve->attach( this ); this->legend()->remove( intervalHighlighterCurve ); // don't show in legend @@ -366,7 +367,7 @@ Aerolab::setData(RideItem *_rideItem, bool new_zoom) { timeArray[arrayLength] = p1->secs / 60.0; if ( have_recorded_alt_curve ) - altArray[arrayLength] = (mainWindow->athlete->useMetricUnits + altArray[arrayLength] = (context->athlete->useMetricUnits ? p1->alt : p1->alt * FEET_PER_METER); @@ -513,7 +514,7 @@ Aerolab::setYMax(bool new_zoom) if (veCurve->isVisible()) { - if ( mainWindow->athlete->useMetricUnits ) + if ( context->athlete->useMetricUnits ) { @@ -590,7 +591,7 @@ void Aerolab::setXTitle() { if (bydist) - setAxisTitle(xBottom, tr("Distance ")+QString(mainWindow->athlete->useMetricUnits?"(km)":"(miles)")); + setAxisTitle(xBottom, tr("Distance ")+QString(context->athlete->useMetricUnits?"(km)":"(miles)")); else setAxisTitle(xBottom, tr("Time (minutes)")); } @@ -760,7 +761,7 @@ void Aerolab::refreshIntervalMarkers() if (!bydist) mrk->setValue(interval.start / 60.0, 0.0); else - mrk->setValue((mainWindow->athlete->useMetricUnits ? 1 : MILES_PER_KM) * + mrk->setValue((context->athlete->useMetricUnits ? 1 : MILES_PER_KM) * rideItem->ride()->timeToDistance(interval.start), 0.0); mrk->setLabel(text); } diff --git a/src/Aerolab.h b/src/Aerolab.h index 253914eaf..21286d590 100644 --- a/src/Aerolab.h +++ b/src/Aerolab.h @@ -32,7 +32,7 @@ class QwtPlotCurve; class QwtPlotGrid; class QwtPlotMarker; class AerolabWindow; -class MainWindow; +class Context; class IntervalAerolabData; class LTMToolTip; class LTMCanvasPicker; @@ -45,7 +45,7 @@ class Aerolab : public QwtPlot { public: - Aerolab( AerolabWindow *, MainWindow * ); + Aerolab( AerolabWindow *, Context * ); bool byDistance() const { return bydist; } bool useMetricUnits; // whether metric units are used (or imperial) void setData(RideItem *_rideItem, bool new_zoom); @@ -54,7 +54,7 @@ class Aerolab : public QwtPlot { void refreshIntervalMarkers(); private: - MainWindow *mainWindow; + Context *context; AerolabWindow *parent; LTMToolTip *tooltip; diff --git a/src/AerolabWindow.cpp b/src/AerolabWindow.cpp index 7de6cc935..20e8eb46e 100644 --- a/src/AerolabWindow.cpp +++ b/src/AerolabWindow.cpp @@ -17,7 +17,8 @@ */ -#include "MainWindow.h" +#include "Context.h" +#include "Context.h" #include "AerolabWindow.h" #include "Aerolab.h" #include "IntervalItem.h" @@ -26,8 +27,8 @@ #include #include -AerolabWindow::AerolabWindow(MainWindow *mainWindow) : - GcWindow(mainWindow), mainWindow(mainWindow) { +AerolabWindow::AerolabWindow(Context *context) : + GcWindow(context), context(context) { setInstanceName("Aerolab Window"); setControls(NULL); @@ -36,7 +37,7 @@ AerolabWindow::AerolabWindow(MainWindow *mainWindow) : QHBoxLayout *cLayout = new QHBoxLayout; // Plot: - aerolab = new Aerolab(this, mainWindow); + aerolab = new Aerolab(this, context); // Left controls layout: QVBoxLayout *leftControls = new QVBoxLayout; @@ -241,10 +242,10 @@ AerolabWindow::AerolabWindow(MainWindow *mainWindow) : connect(eoffsetAuto, SIGNAL(stateChanged(int)), this, SLOT(setAutoEoffset(int))); connect(comboDistance, SIGNAL(currentIndexChanged(int)), this, SLOT(setByDistance(int))); connect(btnEstCdACrr, SIGNAL(clicked()), this, SLOT(doEstCdACrr())); - connect(mainWindow->context, SIGNAL(configChanged()), aerolab, SLOT(configChanged())); - connect(mainWindow->context, SIGNAL(configChanged()), this, SLOT(configChanged())); - connect(mainWindow, SIGNAL(intervalSelected() ), this, SLOT(intervalSelected())); - connect(mainWindow, SIGNAL(intervalZoom(IntervalItem*) ), this, SLOT(zoomInterval(IntervalItem*))); + connect(context, SIGNAL(configChanged()), aerolab, SLOT(configChanged())); + connect(context, SIGNAL(configChanged()), this, SLOT(configChanged())); + connect(context->mainWindow, SIGNAL(intervalSelected() ), this, SLOT(intervalSelected())); + connect(context->mainWindow, SIGNAL(intervalZoom(IntervalItem*) ), this, SLOT(zoomInterval(IntervalItem*))); connect(allZoomer, SIGNAL( zoomed(const QRectF) ), this, SLOT(zoomChanged())); @@ -317,7 +318,7 @@ AerolabWindow::setCrrFromText(const QString text) { aerolab->setIntCrr(value); //crrQLCDNumber->display(QString("%1").arg(aerolab->getCrr())); crrSlider->setValue(aerolab->intCrr()); - RideItem *ride = mainWindow->context->rideItem(); + RideItem *ride = context->rideItem(); aerolab->setData(ride, false); } } @@ -367,7 +368,7 @@ AerolabWindow::setTotalMassFromText(const QString text) { aerolab->setIntTotalMass(value); //mQLCDNumber->display(QString("%1").arg(aerolab->getTotalMass())); mSlider->setValue(aerolab->intTotalMass()); - RideItem *ride = mainWindow->context->rideItem(); + RideItem *ride = context->rideItem(); aerolab->setData(ride, false); } } @@ -474,7 +475,7 @@ AerolabWindow::setByDistance(int value) void AerolabWindow::doEstCdACrr() { - RideItem *ride = mainWindow->context->rideItem(); + RideItem *ride = context->rideItem(); /* Estimate Crr&Cda */ const QString errMsg = aerolab->estimateCdACrr(ride); if (errMsg.isEmpty()) { diff --git a/src/AerolabWindow.h b/src/AerolabWindow.h index f8b496021..12007f51c 100644 --- a/src/AerolabWindow.h +++ b/src/AerolabWindow.h @@ -23,7 +23,7 @@ #include class Aerolab; -class MainWindow; +class Context; class QCheckBox; class QwtPlotZoomer; class QwtPlotPicker; @@ -38,7 +38,7 @@ class AerolabWindow : public GcWindow { public: - AerolabWindow(MainWindow *mainWindow); + AerolabWindow(Context *context); void setData(RideItem *ride); double getCanvasTop() const; double getCanvasBottom() const; @@ -71,7 +71,7 @@ class AerolabWindow : public GcWindow { protected slots: protected: - MainWindow *mainWindow; + Context *context; Aerolab *aerolab; QwtPlotZoomer *allZoomer; diff --git a/src/AllPlot.cpp b/src/AllPlot.cpp index 0c01d7290..dfc5b2c8f 100644 --- a/src/AllPlot.cpp +++ b/src/AllPlot.cpp @@ -17,7 +17,8 @@ */ #include "AllPlot.h" -#include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "AllPlotWindow.h" #include "RideFile.h" #include "RideItem.h" @@ -44,8 +45,8 @@ class IntervalPlotData : public QwtSeriesData { public: - IntervalPlotData(AllPlot *allPlot, MainWindow *mainWindow) : - allPlot(allPlot), mainWindow(mainWindow) {} + IntervalPlotData(AllPlot *allPlot, Context *context) : + allPlot(allPlot), context(context) {} double x(size_t i) const ; double y(size_t i) const ; size_t size() const ; @@ -54,7 +55,7 @@ class IntervalPlotData : public QwtSeriesData IntervalItem *intervalNum(int n) const; int intervalCount() const; AllPlot *allPlot; - MainWindow *mainWindow; + Context *context; virtual QPointF sample(size_t i) const; virtual QRectF boundingRect() const; @@ -223,7 +224,7 @@ class TimeScaleDraw: public QwtScaleDraw static inline double max(double a, double b) { if (a > b) return a; else return b; } -AllPlot::AllPlot(AllPlotWindow *parent, MainWindow *mainWindow): +AllPlot::AllPlot(AllPlotWindow *parent, Context *context): QwtPlot(parent), rideItem(NULL), shade_zones(true), @@ -237,7 +238,7 @@ AllPlot::AllPlot(AllPlotWindow *parent, MainWindow *mainWindow): showTorque(true), showBalance(true), bydist(false), - mainWindow(mainWindow), + context(context), parent(parent) { setInstanceName("AllPlot"); @@ -276,7 +277,7 @@ AllPlot::AllPlot(AllPlotWindow *parent, MainWindow *mainWindow): altCurve->setYAxis(yRight2); tempCurve = new QwtPlotCurve(tr("Temperature")); - if (mainWindow->athlete->useMetricUnits) + if (context->athlete->useMetricUnits) tempCurve->setYAxis(yRight); // with speed else tempCurve->setYAxis(yLeft2); // with cadence @@ -295,7 +296,7 @@ AllPlot::AllPlot(AllPlotWindow *parent, MainWindow *mainWindow): intervalHighlighterCurve = new QwtPlotCurve(); intervalHighlighterCurve->setYAxis(yLeft); - intervalHighlighterCurve->setData(new IntervalPlotData(this, mainWindow)); + intervalHighlighterCurve->setData(new IntervalPlotData(this, context)); intervalHighlighterCurve->attach(this); //this->legend()->remove(intervalHighlighterCurve); // don't show in legend @@ -725,13 +726,13 @@ AllPlot::recalc() foreach (RideFilePoint *dp, rideItem->ride()->dataPoints()) { smoothWatts.append(dp->watts); smoothHr.append(dp->hr); - smoothSpeed.append(mainWindow->athlete->useMetricUnits ? dp->kph : dp->kph * MILES_PER_KM); + smoothSpeed.append(context->athlete->useMetricUnits ? dp->kph : dp->kph * MILES_PER_KM); smoothCad.append(dp->cad); smoothTime.append(dp->secs/60); - smoothDistance.append(mainWindow->athlete->useMetricUnits ? dp->km : dp->km * MILES_PER_KM); - smoothAltitude.append(mainWindow->athlete->useMetricUnits ? dp->alt : dp->alt * FEET_PER_METER); - smoothTemp.append(mainWindow->athlete->useMetricUnits ? dp->temp : dp->temp * FAHRENHEIT_PER_CENTIGRADE + FAHRENHEIT_ADD_CENTIGRADE); - smoothWind.append(mainWindow->athlete->useMetricUnits ? dp->headwind : dp->headwind * MILES_PER_KM); + smoothDistance.append(context->athlete->useMetricUnits ? dp->km : dp->km * MILES_PER_KM); + smoothAltitude.append(context->athlete->useMetricUnits ? dp->alt : dp->alt * FEET_PER_METER); + smoothTemp.append(context->athlete->useMetricUnits ? dp->temp : dp->temp * FAHRENHEIT_PER_CENTIGRADE + FAHRENHEIT_ADD_CENTIGRADE); + smoothWind.append(context->athlete->useMetricUnits ? dp->headwind : dp->headwind * MILES_PER_KM); smoothTorque.append(dp->nm); if (dp->lrbalance == 0) { @@ -747,8 +748,8 @@ AllPlot::recalc() smoothBalanceR.append(dp->lrbalance); } - double head = dp->headwind * (mainWindow->athlete->useMetricUnits ? 1.0f : MILES_PER_KM); - double speed = dp->kph * (mainWindow->athlete->useMetricUnits ? 1.0f : MILES_PER_KM); + double head = dp->headwind * (context->athlete->useMetricUnits ? 1.0f : MILES_PER_KM); + double speed = dp->kph * (context->athlete->useMetricUnits ? 1.0f : MILES_PER_KM); smoothRelSpeed.append(QwtIntervalSample( bydist ? smoothDistance.last() : smoothTime.last(), QwtInterval(qMin(head, speed) , qMax(head, speed) ) )); } @@ -781,7 +782,7 @@ AllPlot::recalc() } if (!tempArray.empty()) { tempCurve->setData(xaxis.data() + startingIndex, smoothTemp.data() + startingIndex, totalPoints); - if (mainWindow->athlete->useMetricUnits) + if (context->athlete->useMetricUnits) intervalHighlighterCurve->setYAxis(yRight); else intervalHighlighterCurve->setYAxis(yLeft2); @@ -835,7 +836,7 @@ AllPlot::refreshIntervalMarkers() if (!bydist) mrk->setValue(interval.start / 60.0, 0.0); else - mrk->setValue((mainWindow->athlete->useMetricUnits ? 1 : MILES_PER_KM) * + mrk->setValue((context->athlete->useMetricUnits ? 1 : MILES_PER_KM) * rideItem->ride()->timeToDistance(interval.start), 0.0); mrk->setLabel(text); } @@ -868,7 +869,7 @@ AllPlot::setYMax() setAxisLabelRotation(yLeft,270); setAxisLabelAlignment(yLeft,Qt::AlignVCenter); } - if (hrCurve->isVisible() || cadCurve->isVisible() || (!mainWindow->athlete->useMetricUnits && tempCurve->isVisible()) || balanceLCurve->isVisible()) { + if (hrCurve->isVisible() || cadCurve->isVisible() || (!context->athlete->useMetricUnits && tempCurve->isVisible()) || balanceLCurve->isVisible()) { double ymin = 0; double ymax = 0; @@ -887,7 +888,7 @@ AllPlot::setYMax() else ymax = qMax(ymax, referencePlot->cadCurve->maxYValue()); } - if (tempCurve->isVisible() && !mainWindow->athlete->useMetricUnits) { + if (tempCurve->isVisible() && !context->athlete->useMetricUnits) { labels << QString::fromUtf8("°F"); @@ -931,21 +932,21 @@ AllPlot::setYMax() setAxisLabelRotation(yLeft2,270); setAxisLabelAlignment(yLeft2,Qt::AlignVCenter); } - if (speedCurve->isVisible() || (mainWindow->athlete->useMetricUnits && tempCurve->isVisible()) || torqueCurve->isVisible()) { + if (speedCurve->isVisible() || (context->athlete->useMetricUnits && tempCurve->isVisible()) || torqueCurve->isVisible()) { double ymin = 0; double ymax = 0; QStringList labels; if (speedCurve->isVisible()) { - labels << (mainWindow->athlete->useMetricUnits ? tr("KPH") : tr("MPH")); + labels << (context->athlete->useMetricUnits ? tr("KPH") : tr("MPH")); if (referencePlot == NULL) ymax = speedCurve->maxYValue(); else ymax = referencePlot->speedCurve->maxYValue(); } - if (tempCurve->isVisible() && mainWindow->athlete->useMetricUnits) { + if (tempCurve->isVisible() && context->athlete->useMetricUnits) { labels << QString::fromUtf8("°C"); @@ -959,7 +960,7 @@ AllPlot::setYMax() } } if (torqueCurve->isVisible()) { - labels << (mainWindow->athlete->useMetricUnits ? tr("Nm") : tr("ftLb")); + labels << (context->athlete->useMetricUnits ? tr("Nm") : tr("ftLb")); if (referencePlot == NULL) ymax = qMax(ymax, torqueCurve->maxYValue()); @@ -972,7 +973,7 @@ AllPlot::setYMax() setAxisLabelAlignment(yRight,Qt::AlignVCenter); } if (altCurve->isVisible()) { - setAxisTitle(yRight2, mainWindow->athlete->useMetricUnits ? tr("Meters") : tr("Feet")); + setAxisTitle(yRight2, context->athlete->useMetricUnits ? tr("Meters") : tr("Feet")); double ymin,ymax; if (referencePlot == NULL) { @@ -1015,7 +1016,7 @@ void AllPlot::setXTitle() { if (bydist) - setAxisTitle(xBottom, tr("Distance ")+QString(mainWindow->athlete->useMetricUnits?"(km)":"(miles)")); + setAxisTitle(xBottom, tr("Distance ")+QString(context->athlete->useMetricUnits?"(km)":"(miles)")); else setAxisTitle(xBottom, tr("Time (Hours:Minutes)")); } @@ -1268,13 +1269,13 @@ AllPlot::setDataFromRide(RideItem *_rideItem) hrArray[arrayLength] = max(0, point->hr); if (!speedArray.empty()) speedArray[arrayLength] = max(0, - (mainWindow->athlete->useMetricUnits + (context->athlete->useMetricUnits ? point->kph : point->kph * MILES_PER_KM)); if (!cadArray.empty()) cadArray[arrayLength] = max(0, point->cad); if (!altArray.empty()) - altArray[arrayLength] = (mainWindow->athlete->useMetricUnits + altArray[arrayLength] = (context->athlete->useMetricUnits ? point->alt : point->alt * FEET_PER_METER); if (!tempArray.empty()) @@ -1282,7 +1283,7 @@ AllPlot::setDataFromRide(RideItem *_rideItem) if (!windArray.empty()) windArray[arrayLength] = max(0, - (mainWindow->athlete->useMetricUnits + (context->athlete->useMetricUnits ? point->headwind : point->headwind * MILES_PER_KM)); @@ -1290,13 +1291,13 @@ AllPlot::setDataFromRide(RideItem *_rideItem) balanceArray[arrayLength] = point->lrbalance; distanceArray[arrayLength] = max(0, - (mainWindow->athlete->useMetricUnits + (context->athlete->useMetricUnits ? point->km : point->km * MILES_PER_KM)); if (!torqueArray.empty()) torqueArray[arrayLength] = max(0, - (mainWindow->athlete->useMetricUnits + (context->athlete->useMetricUnits ? point->nm : point->nm * FEET_LB_PER_NM)); ++arrayLength; @@ -1530,7 +1531,7 @@ AllPlot::distanceIndex(double km) const IntervalItem *IntervalPlotData::intervalNum(int n) const { int highlighted=0; - const QTreeWidgetItem *allIntervals = mainWindow->allIntervalItems(); + const QTreeWidgetItem *allIntervals = context->mainWindow->allIntervalItems(); for (int i=0; ichildCount(); i++) { IntervalItem *current = (IntervalItem *)allIntervals->child(i); @@ -1549,9 +1550,9 @@ int IntervalPlotData::intervalCount() const { int highlighted; highlighted = 0; - if (mainWindow->allIntervalItems() == NULL) return 0; // not inited yet! + if (context->mainWindow->allIntervalItems() == NULL) return 0; // not inited yet! - const QTreeWidgetItem *allIntervals = mainWindow->allIntervalItems(); + const QTreeWidgetItem *allIntervals = context->mainWindow->allIntervalItems(); for (int i=0; ichildCount(); i++) { IntervalItem *current = (IntervalItem *)allIntervals->child(i); if (current != NULL) { @@ -1571,7 +1572,7 @@ int IntervalPlotData::intervalCount() const */ // The interval curve data is derived from the intervals that have -// been selected in the MainWindow leftlayout for each selected +// been selected in the Context leftlayout for each selected // interval we return 4 data points; bottomleft, topleft, topright // and bottom right. // @@ -1587,7 +1588,7 @@ double IntervalPlotData::x(size_t i) const int interval = i ? i/4 : 0; interval += 1; // interval numbers start at 1 not ZERO in the utility functions - double multiplier = mainWindow->athlete->useMetricUnits ? 1 : MILES_PER_KM; + double multiplier = context->mainWindow->athlete->useMetricUnits ? 1 : MILES_PER_KM; // get the interval IntervalItem *current = intervalNum(interval); diff --git a/src/AllPlot.h b/src/AllPlot.h index 39246efaa..8a4ef5fbf 100644 --- a/src/AllPlot.h +++ b/src/AllPlot.h @@ -35,7 +35,7 @@ class AllPlotWindow; class AllPlot; class IntervalItem; class IntervalPlotData; -class MainWindow; +class Context; class LTMToolTip; class LTMCanvasPicker; @@ -47,7 +47,7 @@ class AllPlot : public QwtPlot public: - AllPlot(AllPlotWindow *parent, MainWindow *mainWindow); + AllPlot(AllPlotWindow *parent, Context *context); // set the curve data e.g. when a ride is selected void setDataFromRide(RideItem *_rideItem); @@ -165,7 +165,7 @@ class AllPlot : public QwtPlot bool bydist; private: - MainWindow *mainWindow; + Context *context; AllPlot *referencePlot; AllPlotWindow *parent; diff --git a/src/AllPlotWindow.cpp b/src/AllPlotWindow.cpp index 065d59f22..9a49da102 100644 --- a/src/AllPlotWindow.cpp +++ b/src/AllPlotWindow.cpp @@ -17,10 +17,11 @@ */ -#include "MainWindow.h" +#include "Context.h" +#include "Context.h" +#include "Athlete.h" #include "AllPlotWindow.h" #include "AllPlot.h" -#include "MainWindow.h" #include "RideFile.h" #include "RideItem.h" #include "IntervalItem.h" @@ -48,8 +49,8 @@ // tooltip #include "LTMWindow.h" -AllPlotWindow::AllPlotWindow(MainWindow *mainWindow) : - GcChartWindow(mainWindow), current(NULL), mainWindow(mainWindow), active(false), stale(true), setupStack(false) +AllPlotWindow::AllPlotWindow(Context *context) : + GcChartWindow(context), current(NULL), context(context), active(false), stale(true), setupStack(false) { setInstanceName("Ride Plot Window"); @@ -205,7 +206,7 @@ AllPlotWindow::AllPlotWindow(MainWindow *mainWindow) : smoothLayout->addWidget(smoothSlider); cl3->addRow(smoothLabel, smoothLayout); - allPlot = new AllPlot(this, mainWindow); + allPlot = new AllPlot(this, context); allPlot->setInstanceName("allPlot"); allPlot->setContentsMargins(0,0,0,0); @@ -340,7 +341,7 @@ AllPlotWindow::AllPlotWindow(MainWindow *mainWindow) : scrollRight->setStyle(style); #endif - fullPlot = new AllPlot(this, mainWindow); + fullPlot = new AllPlot(this, context); fullPlot->setInstanceName("fullPlot"); fullPlot->grid->enableY(false); fullPlot->setFixedHeight(100); @@ -430,14 +431,14 @@ AllPlotWindow::AllPlotWindow(MainWindow *mainWindow) : // GC signals //connect(mainWindow, SIGNAL(rideSelected()), this, SLOT(rideSelected())); connect(this, SIGNAL(rideItemChanged(RideItem*)), this, SLOT(rideSelected())); - connect(mainWindow->context, SIGNAL(rideDirty(RideItem*)), this, SLOT(rideSelected())); - connect(mainWindow->context, SIGNAL(configChanged()), allPlot, SLOT(configChanged())); - connect(mainWindow->context, SIGNAL(configChanged()), this, SLOT(configChanged())); - connect(mainWindow->athlete, SIGNAL(zonesChanged()), this, SLOT(zonesChanged())); - connect(mainWindow, SIGNAL(intervalsChanged()), this, SLOT(intervalsChanged())); - connect(mainWindow, SIGNAL(intervalZoom(IntervalItem*)), this, SLOT(zoomInterval(IntervalItem*))); - connect(mainWindow, SIGNAL(intervalSelected()), this, SLOT(intervalSelected())); - connect(mainWindow, SIGNAL(rideDeleted(RideItem*)), this, SLOT(rideDeleted(RideItem*))); + connect(context, SIGNAL(rideDirty(RideItem*)), this, SLOT(rideSelected())); + connect(context, SIGNAL(configChanged()), allPlot, SLOT(configChanged())); + connect(context, SIGNAL(configChanged()), this, SLOT(configChanged())); + connect(context->athlete, SIGNAL(zonesChanged()), this, SLOT(zonesChanged())); + connect(context->mainWindow, SIGNAL(intervalsChanged()), this, SLOT(intervalsChanged())); + connect(context->mainWindow, SIGNAL(intervalZoom(IntervalItem*)), this, SLOT(zoomInterval(IntervalItem*))); + connect(context->mainWindow, SIGNAL(intervalSelected()), this, SLOT(intervalSelected())); + connect(context->mainWindow, SIGNAL(rideDeleted(RideItem*)), this, SLOT(rideDeleted(RideItem*))); // set initial colors configChanged(); @@ -515,8 +516,8 @@ AllPlotWindow::redrawFullPlot() if (fullPlot->bydist) fullPlot->setAxisScale(QwtPlot::xBottom, - ride->ride()->dataPoints().first()->km * (mainWindow->athlete->useMetricUnits ? 1 : MILES_PER_KM), - ride->ride()->dataPoints().last()->km * (mainWindow->athlete->useMetricUnits ? 1 : MILES_PER_KM)); + ride->ride()->dataPoints().first()->km * (context->athlete->useMetricUnits ? 1 : MILES_PER_KM), + ride->ride()->dataPoints().last()->km * (context->athlete->useMetricUnits ? 1 : MILES_PER_KM)); else fullPlot->setAxisScale(QwtPlot::xBottom, ride->ride()->dataPoints().first()->secs/60, ride->ride()->dataPoints().last()->secs/60); @@ -1056,7 +1057,7 @@ AllPlotWindow::setEndSelection(AllPlot* plot, double xValue, bool newInterval, Q // if we are in distance mode then x1 and x2 are distances // we need to make sure they are in KM for the rest of this // code. - if (plot->bydist && mainWindow->athlete->useMetricUnits == false) { + if (plot->bydist && context->athlete->useMetricUnits == false) { x1 *= KM_PER_MILE; x2 *= KM_PER_MILE; } @@ -1079,15 +1080,15 @@ AllPlotWindow::setEndSelection(AllPlot* plot, double xValue, bool newInterval, Q } } QString s("\n%1%2 %3 %4\n%5%6 %7%8 %9%10"); - s = s.arg(mainWindow->athlete->useMetricUnits ? distance2-distance1 : (distance2-distance1)*MILES_PER_KM, 0, 'f', 2); - s = s.arg((mainWindow->athlete->useMetricUnits? "km":"mi")); + s = s.arg(context->athlete->useMetricUnits ? distance2-distance1 : (distance2-distance1)*MILES_PER_KM, 0, 'f', 2); + s = s.arg((context->athlete->useMetricUnits? "km":"mi")); s = s.arg(time_to_string(duration2-duration1)); if (duration2-duration1-secsMoving>1) s = s.arg("("+time_to_string(secsMoving)+")"); else s = s.arg(""); - s = s.arg((mainWindow->athlete->useMetricUnits ? 1 : MILES_PER_KM) * (distance2-distance1)/secsMoving*3600, 0, 'f', 1); - s = s.arg((mainWindow->athlete->useMetricUnits? "km/h":"mph")); + s = s.arg((context->athlete->useMetricUnits ? 1 : MILES_PER_KM) * (distance2-distance1)/secsMoving*3600, 0, 'f', 1); + s = s.arg((context->athlete->useMetricUnits? "km/h":"mph")); if (wattsTotal>0) { s = s.arg(wattsTotal/arrayLength, 0, 'f', 1); s = s.arg("W"); @@ -1121,7 +1122,7 @@ AllPlotWindow::setEndSelection(AllPlot* plot, double xValue, bool newInterval, Q if (newInterval) { - QTreeWidgetItem *allIntervals = mainWindow->mutableIntervalItems(); + QTreeWidgetItem *allIntervals = context->mainWindow->mutableIntervalItems(); int count = allIntervals->childCount(); // are we adjusting an existing interval? - if so delete it and readd it @@ -1139,10 +1140,10 @@ AllPlotWindow::setEndSelection(AllPlot* plot, double xValue, bool newInterval, Q allIntervals->addChild(last); // select this new interval - mainWindow->intervalTreeWidget()->setItemSelected(last, true); + context->mainWindow->intervalTreeWidget()->setItemSelected(last, true); // now update the RideFileIntervals and all the plots etc - mainWindow->updateRideFileIntervals(); + context->mainWindow->updateRideFileIntervals(); } } active = false; @@ -1412,9 +1413,9 @@ AllPlotWindow::resetStackedDatas() int startIndex, stopIndex; if (plot->bydist) { startIndex = allPlot->rideItem->ride()->distanceIndex( - (mainWindow->athlete->useMetricUnits ? 1 : KM_PER_MILE) * _stackWidth*i); + (context->athlete->useMetricUnits ? 1 : KM_PER_MILE) * _stackWidth*i); stopIndex = allPlot->rideItem->ride()->distanceIndex( - (mainWindow->athlete->useMetricUnits ? 1 : KM_PER_MILE) * _stackWidth*(i+1)); + (context->athlete->useMetricUnits ? 1 : KM_PER_MILE) * _stackWidth*(i+1)); } else { startIndex = allPlot->rideItem->ride()->timeIndex(60*_stackWidth*i); stopIndex = allPlot->rideItem->ride()->timeIndex(60*_stackWidth*(i+1)); @@ -1552,7 +1553,7 @@ AllPlotWindow::setupStackPlots() if (!rideItem || !rideItem->ride() || rideItem->ride()->dataPoints().isEmpty()) return; double duration = rideItem->ride()->dataPoints().last()->secs; - double distance = (mainWindow->athlete->useMetricUnits ? 1 : MILES_PER_KM) * rideItem->ride()->dataPoints().last()->km; + double distance = (context->athlete->useMetricUnits ? 1 : MILES_PER_KM) * rideItem->ride()->dataPoints().last()->km; int nbplot; if (fullPlot->bydist) @@ -1568,9 +1569,9 @@ AllPlotWindow::setupStackPlots() // calculate the segment of ride this stack plot contains int startIndex, stopIndex; if (fullPlot->bydist) { - startIndex = fullPlot->rideItem->ride()->distanceIndex((mainWindow->athlete->useMetricUnits ? + startIndex = fullPlot->rideItem->ride()->distanceIndex((context->athlete->useMetricUnits ? 1 : KM_PER_MILE) * _stackWidth*i); - stopIndex = fullPlot->rideItem->ride()->distanceIndex((mainWindow->athlete->useMetricUnits ? + stopIndex = fullPlot->rideItem->ride()->distanceIndex((context->athlete->useMetricUnits ? 1 : KM_PER_MILE) * _stackWidth*(i+1)); } else { startIndex = fullPlot->rideItem->ride()->timeIndex(60*_stackWidth*i); @@ -1581,7 +1582,7 @@ AllPlotWindow::setupStackPlots() if (stopIndex - startIndex < 2) break; // create that plot - AllPlot *_allPlot = new AllPlot(this, mainWindow); + AllPlot *_allPlot = new AllPlot(this, context); _allPlot->setInstanceName("stackPlot"); _allPlot->setAutoFillBackground(false); _allPlot->setPalette(palette); diff --git a/src/AllPlotWindow.h b/src/AllPlotWindow.h index b5d6302c9..a923a3b02 100644 --- a/src/AllPlotWindow.h +++ b/src/AllPlotWindow.h @@ -24,7 +24,7 @@ #include // for Q_PROPERTY class AllPlot; -class MainWindow; +class Context; class QwtPlotPanner; class QwtPlotZoomer; class QwtPlotPicker; @@ -65,7 +65,7 @@ class AllPlotWindow : public GcChartWindow public: - AllPlotWindow(MainWindow *mainWindow); + AllPlotWindow(Context *context); void setData(RideItem *ride); bool hasReveal() { return true; } @@ -136,14 +136,14 @@ class AllPlotWindow : public GcChartWindow // whilst we refactor, lets make friend friend class IntervalPlotData; - friend class MainWindow; + friend class Context; void setAllPlotWidgets(RideItem *rideItem); // cached state RideItem *current; int selection; - MainWindow *mainWindow; + Context *context; // All the plot widgets QVBoxLayout *allPlotLayout; diff --git a/src/Athlete.h b/src/Athlete.h new file mode 100644 index 000000000..4cb775120 --- /dev/null +++ b/src/Athlete.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2013 Mark Liversedge (liversedge@gmail.com) + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef _GC_Athlete_h +#define _GC_Athlete_h 1 + +#include +#include +#include +#include + +class MetricAggregator; +class Zones; +class HrZones; +class RideFile; +class ErgFile; +class RideMetadata; +class WithingsDownload; +class ZeoDownload; +class CalendarDownload; +class ICalendar; +class CalDAV; +class Seasons; +class RideNavigator; +class Lucene; +class NamedSearches; +class RideFileCache; + +class Context; +class Context; + +class Athlete : public QObject +{ + Q_OBJECT + + public: + + // basic athlete info + QString cyclist; // the cyclist name + bool useMetricUnits; + QDir home; + const Zones *zones() const { return zones_; } + const HrZones *hrZones() const { return hrzones_; } + Zones *zones_; + HrZones *hrzones_; + void setCriticalPower(int cp); + QSqlDatabase db; + MetricAggregator *metricDB; + RideMetadata *_rideMetadata; + Seasons *seasons; + QList cpxCache; + + // athlete's calendar + CalendarDownload *calendarDownload; + WithingsDownload *withingsDownload; + ZeoDownload *zeoDownload; +#ifdef GC_HAVE_ICAL + ICalendar *rideCalendar; + CalDAV *davCalendar; +#endif + + // ride metadata definitions + RideMetadata *rideMetadata() { return _rideMetadata; } + + // indexes / filters +#ifdef GC_HAVE_LUCENE + Lucene *lucene; + NamedSearches *namedSearches; +#endif + Context *context; + + void notifyZonesChanged() { zonesChanged(); } + void notifySeasonsChanged() { seasonsChanged(); } + + signals: + void zonesChanged(); + void seasonsChanged(); + + public slots: + void configChanged(); + +}; +#endif diff --git a/src/BasicRideMetrics.cpp b/src/BasicRideMetrics.cpp index 55ebfd711..b000e66a3 100644 --- a/src/BasicRideMetrics.cpp +++ b/src/BasicRideMetrics.cpp @@ -17,6 +17,7 @@ */ #include "RideMetric.h" +#include "Context.h" #include "Settings.h" #include "LTMOutliers.h" #include "Units.h" @@ -43,7 +44,7 @@ class RideCount : public RideMetric { void compute(const RideFile *, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { setValue(1); } RideMetric *clone() const { return new RideCount(*this); } @@ -73,7 +74,7 @@ class WorkoutTime : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { if (!ride->dataPoints().isEmpty()) { seconds = ride->dataPoints().back()->secs - ride->dataPoints().front()->secs + ride->recIntSecs(); @@ -110,7 +111,7 @@ class TimeRiding : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { secsMovingOrPedaling = 0; if (ride->areDataPresent()->kph) { @@ -155,7 +156,7 @@ class TotalDistance : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { // Note: The 'km' in each sample is the distance travelled by the // *end* of the sampling period. The last term in this equation @@ -206,10 +207,10 @@ class ElevationGain : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *main) { + const Context *context) { // hysteresis can be configured, we default to 3.0 - double hysteresis = appsettings->value((QObject*)main, GC_ELEVATION_HYSTERESIS).toDouble(); + double hysteresis = appsettings->value((QObject*)context->mainWindow, GC_ELEVATION_HYSTERESIS).toDouble(); if (hysteresis <= 0.1) hysteresis = 3.00; bool first = true; @@ -255,7 +256,7 @@ class TotalWork : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { foreach (const RideFilePoint *point, ride->dataPoints()) { if (point->watts >= 0.0) joules += point->watts * ride->recIntSecs(); @@ -294,7 +295,7 @@ class AvgSpeed : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &deps, - const MainWindow *) { + const Context *) { assert(deps.contains("total_distance")); km = deps.value("total_distance")->value(true); @@ -351,7 +352,7 @@ class Pace : public RideMetric { void compute(const RideFile *, const Zones *, int, const HrZones *, int, const QHash &deps, - const MainWindow *) { + const Context *) { AvgSpeed *as = dynamic_cast(deps.value("average_speed")); @@ -397,7 +398,7 @@ struct AvgPower : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { total = count = 0; foreach (const RideFilePoint *point, ride->dataPoints()) { if (point->watts >= 0.0) { @@ -437,7 +438,7 @@ struct NonZeroPower : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { total = count = 0; foreach (const RideFilePoint *point, ride->dataPoints()) { if (point->watts > 0.0) { @@ -477,7 +478,7 @@ struct AvgHeartRate : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { total = count = 0; foreach (const RideFilePoint *point, ride->dataPoints()) { if (point->hr > 0) { @@ -517,7 +518,7 @@ struct AvgCadence : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { total = count = 0; foreach (const RideFilePoint *point, ride->dataPoints()) { if (point->cad > 0) { @@ -560,7 +561,7 @@ struct AvgTemp : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { if (ride->areDataPresent()->temp) { total = count = 0; @@ -603,7 +604,7 @@ class MaxPower : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { foreach (const RideFilePoint *point, ride->dataPoints()) { if (point->watts >= max) max = point->watts; @@ -636,7 +637,7 @@ class MaxHr : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { foreach (const RideFilePoint *point, ride->dataPoints()) { if (point->hr >= max) max = point->hr; @@ -672,7 +673,7 @@ class MaxSpeed : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { double max = 0.0; if (ride->areDataPresent()->kph) { @@ -716,7 +717,7 @@ class MaxCadence : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { double max = 0.0; foreach (const RideFilePoint *point, ride->dataPoints()) if (point->cad > max) max = point->cad; @@ -760,7 +761,7 @@ class MaxTemp : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { if (ride->areDataPresent()->temp) { double max = 0.0; @@ -805,7 +806,7 @@ class NinetyFivePercentHeartRate : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { QVector hrs; foreach (const RideFilePoint *point, ride->dataPoints()) { if (point->hr >= 0.0) @@ -843,7 +844,7 @@ class VAM : public RideMetric { void compute(const RideFile *, const Zones *, int, const HrZones *, int, const QHash &deps, - const MainWindow *) { + const Context *) { ElevationGain *el = dynamic_cast(deps.value("elevation_gain")); WorkoutTime *wt = dynamic_cast(deps.value("workout_time")); @@ -884,7 +885,7 @@ class Gradient : public RideMetric { void compute(const RideFile *, const Zones *, int, const HrZones *, int, const QHash &deps, - const MainWindow *) { + const Context *) { ElevationGain *el = dynamic_cast(deps.value("elevation_gain")); TotalDistance *td = dynamic_cast(deps.value("total_distance")); @@ -930,7 +931,7 @@ class MeanPowerVariance : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { // Less than 30s don't bother if (ride->dataPoints().count() < 30) { @@ -982,7 +983,7 @@ class MaxPowerVariance : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &deps, - const MainWindow *) { + const Context *) { MeanPowerVariance *mean = dynamic_cast(deps.value("meanpowervariance")); if (ride->dataPoints().count() < 30) diff --git a/src/BatchExportDialog.cpp b/src/BatchExportDialog.cpp index 24ab27644..f4d514df1 100644 --- a/src/BatchExportDialog.cpp +++ b/src/BatchExportDialog.cpp @@ -18,8 +18,11 @@ */ #include "BatchExportDialog.h" +#include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" -BatchExportDialog::BatchExportDialog(MainWindow *main) : QDialog(main), main(main) +BatchExportDialog::BatchExportDialog(Context *context) : QDialog(context->mainWindow), context(context) { setAttribute(Qt::WA_DeleteOnClose); //setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint); // must stop using this flag! @@ -50,7 +53,7 @@ BatchExportDialog::BatchExportDialog(MainWindow *main) : QDialog(main), main(mai files->setIndentation(0); // populate with each ride in the ridelist - const QTreeWidgetItem *allRides = main->allRideItems(); + const QTreeWidgetItem *allRides = context->mainWindow->allRideItems(); for (int i=0; ichildCount(); i++) { @@ -221,8 +224,8 @@ BatchExportDialog::exportFiles() // open it.. QStringList errors; QList rides; - QFile thisfile(QString(main->athlete->home.absolutePath()+"/"+current->text(1))); - RideFile *ride = RideFileFactory::instance().openRideFile(main, thisfile, errors, &rides); + QFile thisfile(QString(context->athlete->home.absolutePath()+"/"+current->text(1))); + RideFile *ride = RideFileFactory::instance().openRideFile(context, thisfile, errors, &rides); // open success? if (ride) { @@ -230,7 +233,7 @@ BatchExportDialog::exportFiles() current->setText(4, tr("Writing...")); QApplication::processEvents(); QFile out(filename); - bool success = RideFileFactory::instance().writeRideFile(main, ride, out, type); + bool success = RideFileFactory::instance().writeRideFile(context, ride, out, type); if (success) { exports++; diff --git a/src/BatchExportDialog.h b/src/BatchExportDialog.h index c3c958988..68a697ef9 100644 --- a/src/BatchExportDialog.h +++ b/src/BatchExportDialog.h @@ -20,7 +20,7 @@ #ifndef _BatchExportDialog_h #define _BatchExportDialog_h #include "GoldenCheetah.h" -#include "MainWindow.h" +#include "Context.h" #include "Settings.h" #include "Units.h" @@ -45,7 +45,7 @@ class BatchExportDialog : public QDialog public: - BatchExportDialog(MainWindow *main); + BatchExportDialog(Context *context); QTreeWidget *files; // choose files to export @@ -59,7 +59,7 @@ private slots: void allClicked(); private: - MainWindow *main; + Context *context; bool aborted; QCheckBox *all; diff --git a/src/BestIntervalDialog.cpp b/src/BestIntervalDialog.cpp index aa637b3a7..362bf280e 100644 --- a/src/BestIntervalDialog.cpp +++ b/src/BestIntervalDialog.cpp @@ -18,14 +18,15 @@ #include "BestIntervalDialog.h" #include "MainWindow.h" +#include "Context.h" #include "IntervalItem.h" #include "RideFile.h" #include #include #include -BestIntervalDialog::BestIntervalDialog(MainWindow *mainWindow) : - mainWindow(mainWindow) +BestIntervalDialog::BestIntervalDialog(Context *context) : + context(context) { setAttribute(Qt::WA_DeleteOnClose); setWindowTitle("Find Best Intervals"); @@ -144,7 +145,7 @@ struct CompareBests { void BestIntervalDialog::findClicked() { - const RideFile *ride = mainWindow->context->currentRide(); + const RideFile *ride = context->currentRide(); if (!ride) { QMessageBox::critical(this, tr("Select Ride"), tr("No ride selected!")); return; @@ -319,9 +320,9 @@ BestIntervalDialog::addClicked() double start = resultsTable->item(i,3)->text().toDouble(); double stop = resultsTable->item(i,4)->text().toDouble(); QString name = resultsTable->item(i,2)->text(); - const RideFile *ride = mainWindow->context->currentRide(); + const RideFile *ride = context->currentRide(); - QTreeWidgetItem *allIntervals = mainWindow->mutableIntervalItems(); + QTreeWidgetItem *allIntervals = context->mainWindow->mutableIntervalItems(); QTreeWidgetItem *last = new IntervalItem(ride, name, start, stop, ride->timeToDistance(start), @@ -332,5 +333,5 @@ BestIntervalDialog::addClicked() allIntervals->addChild(last); } } - mainWindow->updateRideFileIntervals(); + context->mainWindow->updateRideFileIntervals(); } diff --git a/src/BestIntervalDialog.h b/src/BestIntervalDialog.h index df45509ba..30eb4c66c 100644 --- a/src/BestIntervalDialog.h +++ b/src/BestIntervalDialog.h @@ -22,7 +22,7 @@ #include -class MainWindow; +class Context; class RideFile; class BestIntervalDialog : public QDialog @@ -39,7 +39,7 @@ class BestIntervalDialog : public QDialog start(start), stop(stop), avg(avg) {} }; - BestIntervalDialog(MainWindow *mainWindow); + BestIntervalDialog(Context *context); static void findBests(const RideFile *ride, double windowSizeSecs, int maxIntervals, QList &results); @@ -51,7 +51,7 @@ class BestIntervalDialog : public QDialog private: - MainWindow *mainWindow; + Context *context; QPushButton *findButton, *doneButton, *addButton; QDoubleSpinBox *hrsSpinBox, *minsSpinBox, *secsSpinBox, *countSpinBox; QTableWidget *resultsTable; diff --git a/src/BikeScore.cpp b/src/BikeScore.cpp index 3ba6803c5..850d68ac3 100644 --- a/src/BikeScore.cpp +++ b/src/BikeScore.cpp @@ -54,7 +54,7 @@ class XPower : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { static const double EPSILON = 0.1; static const double NEGLIGIBLE = 0.1; @@ -116,7 +116,7 @@ class VariabilityIndex : public RideMetric { void compute(const RideFile *, const Zones *, int, const HrZones *, int, const QHash &deps, - const MainWindow *) { + const Context *) { assert(deps.contains("skiba_xpower")); assert(deps.contains("average_power")); XPower *xp = dynamic_cast(deps.value("skiba_xpower")); @@ -153,7 +153,7 @@ class RelativeIntensity : public RideMetric { void compute(const RideFile *r, const Zones *zones, int zoneRange, const HrZones *, int, const QHash &deps, - const MainWindow *) { + const Context *) { if (zones && zoneRange >= 0) { assert(deps.contains("skiba_xpower")); XPower *xp = dynamic_cast(deps.value("skiba_xpower")); @@ -201,7 +201,7 @@ class BikeScore : public RideMetric { void compute(const RideFile *r, const Zones *zones, int zoneRange, const HrZones *, int, const QHash &deps, - const MainWindow *) { + const Context *) { if (!zones || zoneRange < 0) return; @@ -244,7 +244,7 @@ class ResponseIndex : public RideMetric { void compute(const RideFile *, const Zones *, int, const HrZones *, int, const QHash &deps, - const MainWindow *) { + const Context *) { assert(deps.contains("skiba_xpower")); assert(deps.contains("average_hr")); XPower *xp = dynamic_cast(deps.value("skiba_xpower")); diff --git a/src/BingMap.cpp b/src/BingMap.cpp index 677e8a877..50699d0a3 100644 --- a/src/BingMap.cpp +++ b/src/BingMap.cpp @@ -21,7 +21,8 @@ #include "RideItem.h" #include "RideFile.h" #include "IntervalItem.h" -#include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "Zones.h" #include "Settings.h" #include "Colors.h" @@ -30,7 +31,7 @@ #include -BingMap::BingMap(MainWindow *mw) : GcWindow(mw), main(mw), range(-1), current(NULL) +BingMap::BingMap(Context *context) : GcWindow(context), context(context), range(-1), current(NULL) { setInstanceName("Google Map"); setControls(NULL); @@ -40,7 +41,7 @@ BingMap::BingMap(MainWindow *mw) : GcWindow(mw), main(mw), range(-1), current(NU layout->setContentsMargins(2,0,2,2); setLayout(layout); - parent = mw; + //XXX ???? parent = context->mainWindow; view = new QWebView(); view->setContentsMargins(0,0,0,0); view->page()->view()->setContentsMargins(0,0,0,0); @@ -48,13 +49,13 @@ BingMap::BingMap(MainWindow *mw) : GcWindow(mw), main(mw), range(-1), current(NU view->setAcceptDrops(false); layout->addWidget(view); - webBridge = new BWebBridge(mw, this); + webBridge = new BWebBridge(context, this); connect(this, SIGNAL(rideItemChanged(RideItem*)), this, SLOT(rideSelected())); connect(view->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(updateFrame())); - connect(mw, SIGNAL(intervalsChanged()), webBridge, SLOT(intervalsChanged())); - connect(mw, SIGNAL(intervalSelected()), webBridge, SLOT(intervalsChanged())); - connect(mw, SIGNAL(intervalZoom(IntervalItem*)), this, SLOT(zoomInterval(IntervalItem*))); + connect(context->mainWindow, SIGNAL(intervalsChanged()), webBridge, SLOT(intervalsChanged())); + connect(context->mainWindow, SIGNAL(intervalSelected()), webBridge, SLOT(intervalsChanged())); + connect(context->mainWindow, SIGNAL(intervalZoom(IntervalItem*)), this, SLOT(zoomInterval(IntervalItem*))); first = true; } @@ -255,7 +256,7 @@ void BingMap::createHtml() QColor BingMap::GetColor(int watts) { if (range < 0) return Qt::red; - else return zoneColor(main->athlete->zones()->whichZone(range, watts), 7); + else return zoneColor(context->athlete->zones()->whichZone(range, watts), 7); } // create the ride line @@ -429,7 +430,7 @@ BingMap::createMarkers() // // INTERVAL MARKERS // - if (main->allIntervalItems() == NULL) return; // none to do, we are all done then + if (context->mainWindow->allIntervalItems() == NULL) return; // none to do, we are all done then int interval=0; foreach (const RideFileInterval x, myRideItem->ride()->intervals()) { @@ -508,11 +509,11 @@ BWebBridge::intervalCount() highlighted = 0; RideItem *rideItem = gm->property("ride").value(); - if (mainWindow->allIntervalItems() == NULL || + if (context->mainWindow->allIntervalItems() == NULL || rideItem == NULL || rideItem->ride() == NULL) return 0; // not inited yet! - for (int i=0; iallIntervalItems()->childCount(); i++) { - IntervalItem *current = dynamic_cast(mainWindow->allIntervalItems()->child(i)); + for (int i=0; imainWindow->allIntervalItems()->childCount(); i++) { + IntervalItem *current = dynamic_cast(context->mainWindow->allIntervalItems()->child(i)); if (current != NULL) { if (current->isSelected() == true) { ++highlighted; @@ -530,14 +531,14 @@ BWebBridge::getLatLons(int i) int highlighted=0; RideItem *rideItem = gm->property("ride").value(); - if (mainWindow->allIntervalItems() == NULL || + if (context->mainWindow->allIntervalItems() == NULL || rideItem ==NULL || rideItem->ride() == NULL) return latlons; // not inited yet! if (i) { // get for specific interval - for (int j=0; jallIntervalItems()->childCount(); j++) { - IntervalItem *current = dynamic_cast(mainWindow->allIntervalItems()->child(j)); + for (int j=0; jmainWindow->allIntervalItems()->childCount(); j++) { + IntervalItem *current = dynamic_cast(context->mainWindow->allIntervalItems()->child(j)); if (current != NULL) { if (current->isSelected() == true) { ++highlighted; @@ -590,6 +591,6 @@ BWebBridge::drawOverlays() void BWebBridge::toggleInterval(int x) { - IntervalItem *current = dynamic_cast(mainWindow->allIntervalItems()->child(x)); + IntervalItem *current = dynamic_cast(context->mainWindow->allIntervalItems()->child(x)); if (current) current->setSelected(!current->isSelected()); } diff --git a/src/BingMap.h b/src/BingMap.h index 8f635efb8..292e20733 100644 --- a/src/BingMap.h +++ b/src/BingMap.h @@ -28,10 +28,11 @@ #include #include "RideFile.h" #include "MainWindow.h" +#include "Context.h" class QMouseEvent; class RideItem; -class MainWindow; +class Context; class QColor; class QVBoxLayout; class QTabWidget; @@ -42,11 +43,11 @@ class BWebBridge : public QObject Q_OBJECT; private: - MainWindow *mainWindow; + Context *context; BingMap *gm; public: - BWebBridge(MainWindow *mainWindow, BingMap *gm) : mainWindow(mainWindow), gm(gm) {} + BWebBridge(Context *context, BingMap *gm) : context(context), gm(gm) {} public slots: Q_INVOKABLE void call(int count); @@ -74,7 +75,7 @@ class BingMap : public GcWindow G_OBJECT public: - BingMap(MainWindow *); + BingMap(Context *); virtual ~BingMap() {} bool first; @@ -85,10 +86,9 @@ class BingMap : public GcWindow void zoomInterval(IntervalItem*); private: - MainWindow *main; + Context *context; QVBoxLayout *layout; QWebView *view; - MainWindow *parent; BWebBridge *webBridge; BingMap(); // default ctor int range; diff --git a/src/BlankState.cpp b/src/BlankState.cpp index 559ce4bd5..72123150c 100644 --- a/src/BlankState.cpp +++ b/src/BlankState.cpp @@ -18,11 +18,13 @@ #include "BlankState.h" #include #include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" // // Replace home window when no ride // -BlankStatePage::BlankStatePage(MainWindow *main) : main(main) +BlankStatePage::BlankStatePage(Context *context) : context(context) { QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->addStretch(); @@ -125,9 +127,9 @@ BlankStatePage::addToShortCuts(ShortCut shortCut) // // Replace analysis window when no ride // -BlankStateAnalysisPage::BlankStateAnalysisPage(MainWindow *main) : BlankStatePage(main) +BlankStateAnalysisPage::BlankStateAnalysisPage(Context *context) : BlankStatePage(context) { - dontShow->setChecked(appsettings->cvalue(main->athlete->cyclist, GC_BLANK_ANALYSIS, false).toBool()); + dontShow->setChecked(appsettings->cvalue(context->athlete->cyclist, GC_BLANK_ANALYSIS, false).toBool()); welcomeTitle->setText(tr("Analysis")); welcomeText->setText(tr("No ride ?\nLet's start with some data.")); @@ -139,23 +141,23 @@ BlankStateAnalysisPage::BlankStateAnalysisPage(MainWindow *main) : BlankStatePag scImport.buttonLabel = tr("Import data"); scImport.buttonIconPath = ":images/mac/download.png"; QPushButton *importButton = addToShortCuts(scImport); - connect(importButton, SIGNAL(clicked()), main, SLOT(importFile())); + connect(importButton, SIGNAL(clicked()), context->mainWindow, SLOT(importFile())); ShortCut scDownload; scDownload.label = tr("Download from serial device."); scDownload.buttonLabel = tr("Download from device"); scDownload.buttonIconPath = ":images/mac/download.png"; QPushButton *downloadButton = addToShortCuts(scDownload); - connect(downloadButton, SIGNAL(clicked()), main, SLOT(downloadRide())); + connect(downloadButton, SIGNAL(clicked()), context->mainWindow, SLOT(downloadRide())); } // // Replace home window when no ride // -BlankStateHomePage::BlankStateHomePage(MainWindow *main) : BlankStatePage(main) +BlankStateHomePage::BlankStateHomePage(Context *context) : BlankStatePage(context) { - dontShow->setChecked(appsettings->cvalue(main->athlete->cyclist, GC_BLANK_HOME, false).toBool()); + dontShow->setChecked(appsettings->cvalue(context->athlete->cyclist, GC_BLANK_HOME, false).toBool()); welcomeTitle->setText(tr("Home")); welcomeText->setText(tr("No ride ?\nLet's start with some data.")); @@ -167,22 +169,22 @@ BlankStateHomePage::BlankStateHomePage(MainWindow *main) : BlankStatePage(main) scImport.buttonLabel = tr("Import data"); scImport.buttonIconPath = ":images/mac/download.png"; QPushButton *importButton = addToShortCuts(scImport); - connect(importButton, SIGNAL(clicked()), main, SLOT(importFile())); + connect(importButton, SIGNAL(clicked()), context->mainWindow, SLOT(importFile())); ShortCut scDownload; scDownload.label = tr("Download from serial device."); scDownload.buttonLabel = tr("Download from device"); scDownload.buttonIconPath = ":images/mac/download.png"; QPushButton *downloadButton = addToShortCuts(scDownload); - connect(downloadButton, SIGNAL(clicked()), main, SLOT(downloadRide())); + connect(downloadButton, SIGNAL(clicked()), context->mainWindow, SLOT(downloadRide())); } // // Replace diary window when no ride // -BlankStateDiaryPage::BlankStateDiaryPage(MainWindow *main) : BlankStatePage(main) +BlankStateDiaryPage::BlankStateDiaryPage(Context *context) : BlankStatePage(context) { - dontShow->setChecked(appsettings->cvalue(main->athlete->cyclist, GC_BLANK_DIARY, false).toBool()); + dontShow->setChecked(appsettings->cvalue(context->athlete->cyclist, GC_BLANK_DIARY, false).toBool()); welcomeTitle->setText(tr("Diary")); welcomeText->setText(tr("No ride ?\nLet's start with some data.")); @@ -194,22 +196,22 @@ BlankStateDiaryPage::BlankStateDiaryPage(MainWindow *main) : BlankStatePage(main scImport.buttonLabel = tr("Import data"); scImport.buttonIconPath = ":images/mac/download.png"; QPushButton *importButton = addToShortCuts(scImport); - connect(importButton, SIGNAL(clicked()), main, SLOT(importFile())); + connect(importButton, SIGNAL(clicked()), context->mainWindow, SLOT(importFile())); ShortCut scDownload; scDownload.label = tr("Download from serial device."); scDownload.buttonLabel = tr("Download from device"); scDownload.buttonIconPath = ":images/mac/download.png"; QPushButton *downloadButton = addToShortCuts(scDownload); - connect(downloadButton, SIGNAL(clicked()), main, SLOT(downloadRide())); + connect(downloadButton, SIGNAL(clicked()), context->mainWindow, SLOT(downloadRide())); } // // Replace train window when no ride // -BlankStateTrainPage::BlankStateTrainPage(MainWindow *main) : BlankStatePage(main) +BlankStateTrainPage::BlankStateTrainPage(Context *context) : BlankStatePage(context) { - dontShow->setChecked(appsettings->cvalue(main->athlete->cyclist, GC_BLANK_TRAIN, false).toBool()); + dontShow->setChecked(appsettings->cvalue(context->athlete->cyclist, GC_BLANK_TRAIN, false).toBool()); welcomeTitle->setText(tr("Train")); welcomeText->setText(tr("No devices or workouts ?\nLet's get you setup.")); @@ -223,7 +225,7 @@ BlankStateTrainPage::BlankStateTrainPage(MainWindow *main) : BlankStatePage(main scAddDevice.buttonLabel = tr("Add device"); scAddDevice.buttonIconPath = ":images/devices/kickr.png"; QPushButton *addDeviceButton = addToShortCuts(scAddDevice); - connect(addDeviceButton, SIGNAL(clicked()), main, SLOT(addDevice())); + connect(addDeviceButton, SIGNAL(clicked()), context->mainWindow, SLOT(addDevice())); ShortCut scImportWorkout; @@ -231,12 +233,12 @@ BlankStateTrainPage::BlankStateTrainPage(MainWindow *main) : BlankStatePage(main scImportWorkout.buttonLabel = tr("Scan hard drives"); scImportWorkout.buttonIconPath = ":images/toolbar/Disk.png"; QPushButton *importWorkoutButton = addToShortCuts(scImportWorkout); - connect(importWorkoutButton, SIGNAL(clicked()), main, SLOT(manageLibrary())); + connect(importWorkoutButton, SIGNAL(clicked()), context->mainWindow, SLOT(manageLibrary())); ShortCut scDownloadWorkout; scDownloadWorkout.label = tr("Download workout files from the Erg DB."); scDownloadWorkout.buttonLabel = tr("Download workouts"); scDownloadWorkout.buttonIconPath = ":images/mac/download.png"; QPushButton *downloadWorkoutButton = addToShortCuts(scDownloadWorkout); - connect(downloadWorkoutButton, SIGNAL(clicked()), main, SLOT(downloadErgDB())); + connect(downloadWorkoutButton, SIGNAL(clicked()), context->mainWindow, SLOT(downloadErgDB())); } diff --git a/src/BlankState.h b/src/BlankState.h index 5bcebe2e8..cf3013f97 100644 --- a/src/BlankState.h +++ b/src/BlankState.h @@ -38,7 +38,7 @@ class BlankStatePage : public GcWindow G_OBJECT public: - BlankStatePage(MainWindow *main); + BlankStatePage(Context *context); QPushButton *addToShortCuts(ShortCut shortCut); QCheckBox *dontShow; @@ -47,7 +47,7 @@ class BlankStatePage : public GcWindow void closeClicked(); protected: - MainWindow *main; + Context *context; QVBoxLayout *leftLayout; QLabel *welcomeTitle; @@ -68,7 +68,7 @@ class BlankStateAnalysisPage : public BlankStatePage G_OBJECT public: - BlankStateAnalysisPage(MainWindow *main); + BlankStateAnalysisPage(Context *context); }; @@ -78,7 +78,7 @@ class BlankStateHomePage : public BlankStatePage G_OBJECT public: - BlankStateHomePage(MainWindow *main); + BlankStateHomePage(Context *context); }; @@ -88,7 +88,7 @@ class BlankStateDiaryPage : public BlankStatePage G_OBJECT public: - BlankStateDiaryPage(MainWindow *main); + BlankStateDiaryPage(Context *context); }; @@ -98,7 +98,7 @@ class BlankStateTrainPage : public BlankStatePage G_OBJECT public: - BlankStateTrainPage(MainWindow *main); + BlankStateTrainPage(Context *context); }; diff --git a/src/CalDAV.cpp b/src/CalDAV.cpp index 482d7adef..7409672b2 100644 --- a/src/CalDAV.cpp +++ b/src/CalDAV.cpp @@ -17,8 +17,10 @@ */ #include "CalDAV.h" +#include "MainWindow.h" +#include "Athlete.h" -CalDAV::CalDAV(MainWindow *main) : main(main), mode(None) +CalDAV::CalDAV(Context *context) : context(context), mode(None) { nam = new QNetworkAccessManager(this); connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestReply(QNetworkReply*))); @@ -35,7 +37,7 @@ CalDAV::CalDAV(MainWindow *main) : main(main), mode(None) bool CalDAV::download() { - QString url = appsettings->cvalue(main->athlete->cyclist, GC_DVURL, "").toString(); + QString url = appsettings->cvalue(context->athlete->cyclist, GC_DVURL, "").toString(); if (url == "") return false; // not configured QNetworkRequest request = QNetworkRequest(QUrl(url)); @@ -65,7 +67,7 @@ CalDAV::download() mode = Events; QNetworkReply *reply = nam->sendCustomRequest(request, "REPORT", query); if (reply->error() != QNetworkReply::NoError) { - QMessageBox::warning(main, tr("CalDAV REPORT url error"), reply->errorString()); + QMessageBox::warning(context->mainWindow, tr("CalDAV REPORT url error"), reply->errorString()); mode = None; return false; } @@ -78,7 +80,7 @@ CalDAV::download() bool CalDAV::options() { - QString url = appsettings->cvalue(main->athlete->cyclist, GC_DVURL, "").toString(); + QString url = appsettings->cvalue(context->athlete->cyclist, GC_DVURL, "").toString(); if (url == "") return false; // not configured QNetworkRequest request = QNetworkRequest(QUrl(url)); @@ -98,7 +100,7 @@ CalDAV::options() mode = Options; QNetworkReply *reply = nam->sendCustomRequest(request, "OPTIONS", query); if (reply->error() != QNetworkReply::NoError) { - QMessageBox::warning(main, tr("CalDAV OPTIONS url error"), reply->errorString()); + QMessageBox::warning(context->mainWindow, tr("CalDAV OPTIONS url error"), reply->errorString()); mode = None; return false; } @@ -111,7 +113,7 @@ CalDAV::options() bool CalDAV::propfind() { - QString url = appsettings->cvalue(main->athlete->cyclist, GC_DVURL, "").toString(); + QString url = appsettings->cvalue(context->athlete->cyclist, GC_DVURL, "").toString(); if (url == "") return false; // not configured QNetworkRequest request = QNetworkRequest(QUrl(url)); @@ -136,7 +138,7 @@ CalDAV::propfind() mode = PropFind; QNetworkReply *reply = nam->sendCustomRequest(request, "PROPFIND" , query); if (reply->error() != QNetworkReply::NoError) { - QMessageBox::warning(main, tr("CalDAV OPTIONS url error"), reply->errorString()); + QMessageBox::warning(context->mainWindow, tr("CalDAV OPTIONS url error"), reply->errorString()); mode = None; return false; } @@ -150,7 +152,7 @@ CalDAV::propfind() bool CalDAV::report() { - QString url = appsettings->cvalue(main->athlete->cyclist, GC_DVURL, "").toString(); + QString url = appsettings->cvalue(context->athlete->cyclist, GC_DVURL, "").toString(); if (url == "") return false; // not configured QNetworkRequest request = QNetworkRequest(QUrl(url)); @@ -173,7 +175,7 @@ CalDAV::report() mode = Report; QNetworkReply *reply = nam->sendCustomRequest(request, "REPORT", query); if (reply->error() != QNetworkReply::NoError) { - QMessageBox::warning(main, tr("CalDAV REPORT url error"), reply->errorString()); + QMessageBox::warning(context->mainWindow, tr("CalDAV REPORT url error"), reply->errorString()); mode = None; return false; } @@ -318,7 +320,7 @@ CalDAV::upload(RideItem *rideItem) // is this a valid ride? if (!rideItem || !rideItem->ride()) return false; - QString url = appsettings->cvalue(main->athlete->cyclist, GC_DVURL, "").toString(); + QString url = appsettings->cvalue(context->athlete->cyclist, GC_DVURL, "").toString(); if (url == "") return false; // not configured // lets upload to calendar @@ -339,7 +341,7 @@ CalDAV::upload(RideItem *rideItem) QNetworkReply *reply = nam->put(request, vcardtext); if (reply->error() != QNetworkReply::NoError) { mode = None; - QMessageBox::warning(main, tr("CalDAV Calendar url error"), reply->errorString()); + QMessageBox::warning(context->mainWindow, tr("CalDAV Calendar url error"), reply->errorString()); return false; } return true; @@ -356,7 +358,7 @@ CalDAV::requestReply(QNetworkReply *reply) switch (mode) { case Report: case Events: - main->athlete->rideCalendar->refreshRemote(extractComponents(response)); + context->athlete->rideCalendar->refreshRemote(extractComponents(response)); break; default: case Options: @@ -374,8 +376,8 @@ CalDAV::requestReply(QNetworkReply *reply) void CalDAV::userpass(QNetworkReply*,QAuthenticator*a) { - QString user = appsettings->cvalue(main->athlete->cyclist, GC_DVUSER, "").toString(); - QString pass = appsettings->cvalue(main->athlete->cyclist, GC_DVPASS, "").toString(); + QString user = appsettings->cvalue(context->athlete->cyclist, GC_DVUSER, "").toString(); + QString pass = appsettings->cvalue(context->athlete->cyclist, GC_DVPASS, "").toString(); a->setUser(user); a->setPassword(pass); } diff --git a/src/CalDAV.h b/src/CalDAV.h index 8520520de..44bcadd50 100644 --- a/src/CalDAV.h +++ b/src/CalDAV.h @@ -29,7 +29,8 @@ // set user and password #include -#include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" // work with calDAV protocol // ... @@ -58,7 +59,7 @@ class CalDAV : public QObject typedef enum action ActionType; public: - CalDAV(MainWindow *main); + CalDAV(Context *context); public slots: @@ -84,7 +85,7 @@ public slots: void sslErrors(QNetworkReply*,QList&); private: - MainWindow *main; + Context *context; QNetworkAccessManager *nam; ActionType mode; }; diff --git a/src/CalendarDownload.cpp b/src/CalendarDownload.cpp index 029fdcf19..1f0cd98ca 100644 --- a/src/CalendarDownload.cpp +++ b/src/CalendarDownload.cpp @@ -17,12 +17,14 @@ */ #include "CalendarDownload.h" +#include "MainWindow.h" +#include "Athlete.h" #ifdef GC_HAVE_ICAL #include "ICalendar.h" #include #endif -CalendarDownload::CalendarDownload(MainWindow *main) : main(main) +CalendarDownload::CalendarDownload(Context *context) : context(context) { nam = new QNetworkAccessManager(this); connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(downloadFinished(QNetworkReply*))); @@ -31,7 +33,7 @@ CalendarDownload::CalendarDownload(MainWindow *main) : main(main) bool CalendarDownload::download() { - QString request = appsettings->cvalue(main->athlete->cyclist, GC_WEBCAL_URL, "").toString(); + QString request = appsettings->cvalue(context->athlete->cyclist, GC_WEBCAL_URL, "").toString(); if (request == "") return false; else { // change webcal to http, since it is basically the same port @@ -42,7 +44,7 @@ CalendarDownload::download() QNetworkReply *reply = nam->get(QNetworkRequest(QUrl(request))); if (reply->error() != QNetworkReply::NoError) { - QMessageBox::warning(main, tr("Calendar Data Download"), reply->errorString()); + QMessageBox::warning(context->mainWindow, tr("Calendar Data Download"), reply->errorString()); return false; } return true; @@ -55,7 +57,7 @@ CalendarDownload::downloadFinished(QNetworkReply *reply) QStringList errors; #ifdef GC_HAVE_ICAL - QString remoteCache = main->athlete->home.absolutePath()+"/remote.ics"; + QString remoteCache = context->athlete->home.absolutePath()+"/remote.ics"; QFile remoteCacheFile(remoteCache); if (fulltext != "") { @@ -83,6 +85,6 @@ CalendarDownload::downloadFinished(QNetworkReply *reply) } } - if (fulltext != "") main->athlete->rideCalendar->refreshRemote(fulltext); + if (fulltext != "") context->athlete->rideCalendar->refreshRemote(fulltext); #endif } diff --git a/src/CalendarDownload.h b/src/CalendarDownload.h index 65555b867..9725fd5fd 100644 --- a/src/CalendarDownload.h +++ b/src/CalendarDownload.h @@ -23,7 +23,7 @@ #include #include #include -#include "MainWindow.h" +#include "Context.h" #include "Settings.h" /* #include "CalendarParser.h" */ #include "MetricAggregator.h" @@ -35,14 +35,14 @@ class CalendarDownload : public QObject public: - CalendarDownload(MainWindow *main); + CalendarDownload(Context *context); bool download(); public slots: void downloadFinished(QNetworkReply *reply); private: - MainWindow *main; + Context *context; QNetworkAccessManager *nam; /* CalendarParser *parser; */ }; diff --git a/src/ChooseCyclistDialog.cpp b/src/ChooseCyclistDialog.cpp index 08110b472..40d73554e 100644 --- a/src/ChooseCyclistDialog.cpp +++ b/src/ChooseCyclistDialog.cpp @@ -18,7 +18,9 @@ #include "ChooseCyclistDialog.h" #include "NewCyclistDialog.h" -#include "MainWindow.h" +#include "Mainwindow.h" +#include "Context.h" +#include "Athlete.h" #include ChooseCyclistDialog::ChooseCyclistDialog(const QDir &home, bool allowNew) : diff --git a/src/Coggan.cpp b/src/Coggan.cpp index 648ba0931..278e87390 100644 --- a/src/Coggan.cpp +++ b/src/Coggan.cpp @@ -43,7 +43,7 @@ class NP : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { if(ride->recIntSecs() == 0) return; @@ -110,7 +110,7 @@ class VI : public RideMetric { void compute(const RideFile *, const Zones *, int, const HrZones *, int, const QHash &deps, - const MainWindow *) { + const Context *) { assert(deps.contains("coggan_np")); assert(deps.contains("average_power")); NP *np = dynamic_cast(deps.value("coggan_np")); @@ -147,7 +147,7 @@ class IntensityFactor : public RideMetric { void compute(const RideFile *r, const Zones *zones, int zoneRange, const HrZones *, int, const QHash &deps, - const MainWindow *) { + const Context *) { if (zones && zoneRange >= 0) { assert(deps.contains("coggan_np")); NP *np = dynamic_cast(deps.value("coggan_np")); @@ -182,7 +182,7 @@ class TSS : public RideMetric { void compute(const RideFile *r, const Zones *zones, int zoneRange, const HrZones *, int, const QHash &deps, - const MainWindow *) { + const Context *) { if (!zones || zoneRange < 0) return; assert(deps.contains("coggan_np")); @@ -224,7 +224,7 @@ class EfficiencyFactor : public RideMetric { void compute(const RideFile *, const Zones *, int, const HrZones *, int, const QHash &deps, - const MainWindow *) { + const Context *) { assert(deps.contains("coggan_np")); assert(deps.contains("average_hr")); NP *np = dynamic_cast(deps.value("coggan_np")); diff --git a/src/Colors.cpp b/src/Colors.cpp index 55b418cba..697079502 100644 --- a/src/Colors.cpp +++ b/src/Colors.cpp @@ -17,7 +17,9 @@ */ #include "Colors.h" -#include "MainWindow.h" +#include "Context.h" +#include "Context.h" +#include "Athlete.h" #include "RideMetadata.h" #include #include @@ -152,11 +154,11 @@ GCColor::defaultSizes(int width, int height) return defaultAppearance[0]; // shouldn't get here } -GCColor::GCColor(MainWindow *main) : QObject(main) +GCColor::GCColor(Context *context) : QObject(context) { setupColors(); readConfig(); - connect(main->context, SIGNAL(configChanged()), this, SLOT(readConfig())); + connect(context, SIGNAL(configChanged()), this, SLOT(readConfig())); } const Colors * GCColor::colorSet() @@ -213,10 +215,10 @@ GCColor::getColor(int colornum) return ColorList[colornum].color; } -ColorEngine::ColorEngine(MainWindow* main) : QObject(main), defaultColor(QColor(Qt::white)), mainWindow(main) +ColorEngine::ColorEngine(Context* context) : QObject(context), defaultColor(QColor(Qt::white)), context(context) { configUpdate(); - connect(mainWindow->context, SIGNAL(configChanged()), this, SLOT(configUpdate())); + connect(context, SIGNAL(configChanged()), this, SLOT(configUpdate())); } void ColorEngine::configUpdate() @@ -225,7 +227,7 @@ void ColorEngine::configUpdate() workoutCodes.clear(); // setup the keyword/color combinations from config settings - foreach (KeywordDefinition keyword, mainWindow->athlete->rideMetadata()->getKeywords()) { + foreach (KeywordDefinition keyword, context->athlete->rideMetadata()->getKeywords()) { if (keyword.name == "Default") defaultColor = keyword.color; else { diff --git a/src/Colors.h b/src/Colors.h index 74b74ea18..4e85b0ceb 100644 --- a/src/Colors.h +++ b/src/Colors.h @@ -24,7 +24,7 @@ #include #include -class MainWindow; +class Context; // set appearace defaults based upon screen size struct SizeSettings { @@ -62,7 +62,7 @@ class GCColor : public QObject void setupColors(); public: - GCColor(MainWindow*); + GCColor(Context *); static QColor getColor(int); static const Colors *colorSet(); static const Colors *defaultColorSet(); @@ -81,7 +81,7 @@ class ColorEngine : public QObject G_OBJECT public: - ColorEngine(MainWindow*); + ColorEngine(Context *); QColor colorFor(QString); @@ -91,7 +91,7 @@ class ColorEngine : public QObject private: QMap workoutCodes; QColor defaultColor; - MainWindow *mainWindow; + Context *context; }; diff --git a/src/ConfigDialog.cpp b/src/ConfigDialog.cpp index 46a185a33..f0a490236 100644 --- a/src/ConfigDialog.cpp +++ b/src/ConfigDialog.cpp @@ -20,7 +20,9 @@ #include #include -#include "MainWindow.h" +#include "Context.h" +#include "Context.h" +#include "Athlete.h" #include "ConfigDialog.h" #include "Pages.h" #include "Settings.h" @@ -29,8 +31,8 @@ #include "AddDeviceWizard.h" -ConfigDialog::ConfigDialog(QDir _home, Zones *_zones, MainWindow *mainWindow) : - home(_home), zones(_zones), mainWindow(mainWindow) +ConfigDialog::ConfigDialog(QDir _home, Zones *_zones, Context *context) : + home(_home), zones(_zones), context(context) { setAttribute(Qt::WA_DeleteOnClose); @@ -93,25 +95,25 @@ ConfigDialog::ConfigDialog(QDir _home, Zones *_zones, MainWindow *mainWindow) : pagesWidget = new QStackedWidget(this); // create those config pages - general = new GeneralConfig(_home, _zones, mainWindow); + general = new GeneralConfig(_home, _zones, context); pagesWidget->addWidget(general); - athlete = new AthleteConfig(_home, _zones, mainWindow); + athlete = new AthleteConfig(_home, _zones, context); pagesWidget->addWidget(athlete); - password = new PasswordConfig(_home, _zones, mainWindow); + password = new PasswordConfig(_home, _zones, context); pagesWidget->addWidget(password); - appearance = new AppearanceConfig(_home, _zones, mainWindow); + appearance = new AppearanceConfig(_home, _zones, context); pagesWidget->addWidget(appearance); - data = new DataConfig(_home, _zones, mainWindow); + data = new DataConfig(_home, _zones, context); pagesWidget->addWidget(data); - metric = new MetricConfig(_home, _zones, mainWindow); + metric = new MetricConfig(_home, _zones, context); pagesWidget->addWidget(metric); - device = new DeviceConfig(_home, _zones, mainWindow); + device = new DeviceConfig(_home, _zones, context); pagesWidget->addWidget(device); @@ -171,15 +173,15 @@ void ConfigDialog::saveClicked() hide(); // do the zones first.. - mainWindow->context->notifyConfigChanged(); + context->notifyConfigChanged(); close(); } // GENERAL CONFIG -GeneralConfig::GeneralConfig(QDir home, Zones *zones, MainWindow *mainWindow) : - home(home), zones(zones), mainWindow(mainWindow) +GeneralConfig::GeneralConfig(QDir home, Zones *zones, Context *context) : + home(home), zones(zones), context(context) { - generalPage = new GeneralPage(mainWindow); + generalPage = new GeneralPage(context); QVBoxLayout *layout = new QVBoxLayout(this); layout->addWidget(generalPage); @@ -193,13 +195,13 @@ void GeneralConfig::saveClicked() } // ATHLETE CONFIG -AthleteConfig::AthleteConfig(QDir home, Zones *zones, MainWindow *mainWindow) : - home(home), zones(zones), mainWindow(mainWindow) +AthleteConfig::AthleteConfig(QDir home, Zones *zones, Context *context) : + home(home), zones(zones), context(context) { // the widgets - athletePage = new RiderPage(this, mainWindow); - zonePage = new ZonePage(mainWindow); - hrZonePage = new HrZonePage(mainWindow); + athletePage = new RiderPage(this, context); + zonePage = new ZonePage(context); + hrZonePage = new HrZonePage(context); setContentsMargins(0,0,0,0); QHBoxLayout *mainLayout = new QHBoxLayout(this); @@ -222,8 +224,8 @@ void AthleteConfig::saveClicked() } // APPEARANCE CONFIG -AppearanceConfig::AppearanceConfig(QDir home, Zones *zones, MainWindow *mainWindow) : - home(home), zones(zones), mainWindow(mainWindow) +AppearanceConfig::AppearanceConfig(QDir home, Zones *zones, Context *context) : + home(home), zones(zones), context(context) { appearancePage = new ColorsPage(this); QVBoxLayout *layout = new QVBoxLayout(this); @@ -239,10 +241,10 @@ void AppearanceConfig::saveClicked() } // PASSWORD CONFIG -PasswordConfig::PasswordConfig(QDir home, Zones *zones, MainWindow *mainWindow) : - home(home), zones(zones), mainWindow(mainWindow) +PasswordConfig::PasswordConfig(QDir home, Zones *zones, Context *context) : + home(home), zones(zones), context(context) { - passwordPage = new CredentialsPage(this, mainWindow); + passwordPage = new CredentialsPage(this, context); QVBoxLayout *layout = new QVBoxLayout(this); layout->addWidget(passwordPage); @@ -256,10 +258,10 @@ void PasswordConfig::saveClicked() } // METADATA CONFIG -DataConfig::DataConfig(QDir home, Zones *zones, MainWindow *mainWindow) : - home(home), zones(zones), mainWindow(mainWindow) +DataConfig::DataConfig(QDir home, Zones *zones, Context *context) : + home(home), zones(zones), context(context) { - dataPage = new MetadataPage(mainWindow); + dataPage = new MetadataPage(context); QVBoxLayout *layout = new QVBoxLayout(this); layout->addWidget(dataPage); @@ -273,8 +275,8 @@ void DataConfig::saveClicked() } // GENERAL CONFIG -MetricConfig::MetricConfig(QDir home, Zones *zones, MainWindow *mainWindow) : - home(home), zones(zones), mainWindow(mainWindow) +MetricConfig::MetricConfig(QDir home, Zones *zones, Context *context) : + home(home), zones(zones), context(context) { // the widgets intervalsPage = new IntervalMetricsPage(this); @@ -299,10 +301,10 @@ void MetricConfig::saveClicked() } // GENERAL CONFIG -DeviceConfig::DeviceConfig(QDir home, Zones *zones, MainWindow *mainWindow) : - home(home), zones(zones), mainWindow(mainWindow) +DeviceConfig::DeviceConfig(QDir home, Zones *zones, Context *context) : + home(home), zones(zones), context(context) { - devicePage = new DevicePage(this, mainWindow); + devicePage = new DevicePage(this, context); QVBoxLayout *layout = new QVBoxLayout(this); layout->addWidget(devicePage); diff --git a/src/ConfigDialog.h b/src/ConfigDialog.h index ba6d17cf6..5bc3dfb17 100644 --- a/src/ConfigDialog.h +++ b/src/ConfigDialog.h @@ -23,12 +23,12 @@ #include #include #include "Pages.h" -#include "MainWindow.h" +#include "Context.h" class QListWidget; class QListWidgetItem; class QStackedWidget; -class MainWindow; +class Context; class Zones; // GENERAL PAGE @@ -37,7 +37,7 @@ class GeneralConfig : public QWidget Q_OBJECT public: - GeneralConfig(QDir home, Zones *zones, MainWindow *mainWindow); + GeneralConfig(QDir home, Zones *zones, Context *context); public slots: void saveClicked(); @@ -45,7 +45,7 @@ class GeneralConfig : public QWidget private: QDir home; Zones *zones; - MainWindow *mainWindow; + Context *context; GeneralPage *generalPage; }; @@ -56,7 +56,7 @@ class AthleteConfig : public QWidget Q_OBJECT public: - AthleteConfig(QDir home, Zones *zones, MainWindow *mainWindow); + AthleteConfig(QDir home, Zones *zones, Context *context); public slots: void saveClicked(); @@ -64,7 +64,7 @@ class AthleteConfig : public QWidget private: QDir home; Zones *zones; - MainWindow *mainWindow; + Context *context; // about me, power ones and hr zones RiderPage *athletePage; @@ -78,7 +78,7 @@ class AppearanceConfig : public QWidget Q_OBJECT public: - AppearanceConfig(QDir home, Zones *zones, MainWindow *mainWindow); + AppearanceConfig(QDir home, Zones *zones, Context *context); public slots: void saveClicked(); @@ -86,7 +86,7 @@ class AppearanceConfig : public QWidget private: QDir home; Zones *zones; - MainWindow *mainWindow; + Context *context; ColorsPage *appearancePage; }; @@ -97,7 +97,7 @@ class PasswordConfig : public QWidget Q_OBJECT public: - PasswordConfig(QDir home, Zones *zones, MainWindow *mainWindow); + PasswordConfig(QDir home, Zones *zones, Context *context); public slots: void saveClicked(); @@ -105,7 +105,7 @@ class PasswordConfig : public QWidget private: QDir home; Zones *zones; - MainWindow *mainWindow; + Context *context; CredentialsPage *passwordPage; }; @@ -116,7 +116,7 @@ class DataConfig : public QWidget Q_OBJECT public: - DataConfig(QDir home, Zones *zones, MainWindow *mainWindow); + DataConfig(QDir home, Zones *zones, Context *context); public slots: void saveClicked(); @@ -124,7 +124,7 @@ class DataConfig : public QWidget private: QDir home; Zones *zones; - MainWindow *mainWindow; + Context *context; MetadataPage *dataPage; }; @@ -135,7 +135,7 @@ class MetricConfig : public QWidget Q_OBJECT public: - MetricConfig(QDir home, Zones *zones, MainWindow *mainWindow); + MetricConfig(QDir home, Zones *zones, Context *context); public slots: void saveClicked(); @@ -143,7 +143,7 @@ class MetricConfig : public QWidget private: QDir home; Zones *zones; - MainWindow *mainWindow; + Context *context; IntervalMetricsPage *intervalsPage; SummaryMetricsPage *summaryPage; @@ -155,7 +155,7 @@ class DeviceConfig : public QWidget Q_OBJECT public: - DeviceConfig(QDir home, Zones *zones, MainWindow *mainWindow); + DeviceConfig(QDir home, Zones *zones, Context *context); public slots: void saveClicked(); @@ -163,7 +163,7 @@ class DeviceConfig : public QWidget private: QDir home; Zones *zones; - MainWindow *mainWindow; + Context *context; DevicePage *devicePage; }; @@ -174,7 +174,7 @@ class ConfigDialog : public QMainWindow G_OBJECT public: - ConfigDialog(QDir home, Zones *zones, MainWindow *mainWindow); + ConfigDialog(QDir home, Zones *zones, Context *context); public slots: void changePage(int); @@ -184,7 +184,7 @@ class ConfigDialog : public QMainWindow QSettings *settings; QDir home; Zones *zones; - MainWindow *mainWindow; + Context *context; QStackedWidget *pagesWidget; QPushButton *saveButton; diff --git a/src/Context.h b/src/Context.h new file mode 100644 index 000000000..ace5c1e3c --- /dev/null +++ b/src/Context.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2013 Mark Liversedge (liversedge@gmail.com) + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef _GC_Context_h +#define _GC_Context_h 1 + +#include "TimeUtils.h" // for class DateRange +#include "RealtimeData.h" // for class RealtimeData + +class RideFile; +class RideItem; +class ErgFile; + +class Context; +class Athlete; +class MainWindow; + +class Context : public QObject +{ + Q_OBJECT; + + public: + + // ride item + RideItem *rideItem() const { return ride; } + const RideFile *currentRide(); + const RideItem *currentRideItem() { return ride; } + + // last date range selected in diary/home view + DateRange currentDateRange() { return _dr; } + + + // current selections + MainWindow *mainWindow; + Athlete *athlete; + RideItem *ride; // the currently selected ride + DateRange _dr; // the currently selected date range + ErgFile *workout; // the currently selected workout file + long now; // point in time during train session + + // ********************************************* + // APPLICATION EVENTS + // ********************************************* + void notifyConfigChanged(); // used by ConfigDialog to notify Context * + // when config has changed - and to get a + // signal emitted to notify its children + + // realtime signals + void notifyTelemetryUpdate(const RealtimeData &rtData) { telemetryUpdate(rtData); } + void notifyErgFileSelected(ErgFile *x) { workout=x; ergFileSelected(x); } + ErgFile *currentErgFile() { return workout; } + void notifyMediaSelected( QString x) { mediaSelected(x); } + void notifySelectVideo(QString x) { selectMedia(x); } + void notifySelectWorkout(QString x) { selectWorkout(x); } + void notifySetNow(long x) { now = x; setNow(x); } + long getNow() { return now; } + void notifyNewLap() { emit newLap(); } + void notifyStart() { emit start(); } + void notifyUnPause() { emit unpause(); } + void notifyPause() { emit pause(); } + void notifyStop() { emit stop(); } + void notifySeek(long x) { emit seek(x); } + + void notifyRideClean() { rideClean(ride); } + void notifyRideDirty() { rideDirty(ride); } + + signals: + + void configChanged(); + + void rideDirty(RideItem*); + void rideClean(RideItem*); + + // realtime + void telemetryUpdate(RealtimeData rtData); + void ergFileSelected(ErgFile *); + void mediaSelected(QString); + void selectWorkout(QString); // ask traintool to select this + void selectMedia(QString); // ask traintool to select this + void setNow(long); + void seek(long); + void newLap(); + void start(); + void unpause(); + void pause(); + void stop(); + +}; +#endif // _GC_Context_h diff --git a/src/CpintPlot.cpp b/src/CpintPlot.cpp index dde891578..8ad47dc62 100644 --- a/src/CpintPlot.cpp +++ b/src/CpintPlot.cpp @@ -16,6 +16,7 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ +#include "Athlete.h" #include "Zones.h" #include "Colors.h" #include "CpintPlot.h" @@ -42,14 +43,14 @@ #define USE_T0_IN_CP_MODEL 0 // added djconnel 08Apr2009: allow 3-parameter CP model -CpintPlot::CpintPlot(MainWindow *main, QString p, const Zones *zones) : +CpintPlot::CpintPlot(Context *context, QString p, const Zones *zones) : path(p), thisCurve(NULL), CPCurve(NULL), allCurve(NULL), zones(zones), series(RideFile::watts), - mainWindow(main), + context(context), current(NULL), bests(NULL), isFiltered(false), @@ -177,7 +178,7 @@ CpintPlot::setSeries(RideFile::SeriesType x) break; case RideFile::wattsKg: - if (mainWindow->athlete->useMetricUnits) + if (context->athlete->useMetricUnits) setAxisTitle(yLeft, tr("Watts per kilo (watts/kg)")); else setAxisTitle(yLeft, tr("Watts per lb (watts/lb)")); @@ -549,10 +550,10 @@ CpintPlot::calculate(RideItem *rideItem) // zap any existing ridefilecache then get new one if (current) delete current; - current = new RideFileCache(mainWindow, mainWindow->athlete->home.absolutePath() + "/" + fileName); + current = new RideFileCache(context, context->athlete->home.absolutePath() + "/" + fileName); // get aggregates - incase not initialised from date change - if (bests == NULL) bests = new RideFileCache(mainWindow, startDate, endDate, isFiltered, files); + if (bests == NULL) bests = new RideFileCache(context, startDate, endDate, isFiltered, files); // // PLOT MODEL CURVE (DERIVED) @@ -782,7 +783,7 @@ CpintPlot::pointHover(QwtPlotCurve *curve, int index) text = QString("%1\n%3 %4%5") .arg(interval_to_str(60.0*xvalue)) .arg(yvalue, 0, 'f', RideFile::decimalsFor(series)) - .arg(RideFile::unitName(series, mainWindow)) + .arg(RideFile::unitName(series, context)) .arg(dateStr); // set that text up diff --git a/src/CpintPlot.h b/src/CpintPlot.h index fd516c1b6..ccd304b05 100644 --- a/src/CpintPlot.h +++ b/src/CpintPlot.h @@ -34,7 +34,7 @@ class QwtPlotGrid; class QwtPlotMarker; class RideItem; class Zones; -class MainWindow; +class Context; class LTMCanvasPicker; class penTooltip: public QwtPlotZoomer @@ -81,7 +81,7 @@ class CpintPlot : public QwtPlot public: - CpintPlot(MainWindow *, QString path, const Zones *zones); + CpintPlot(Context *, QString path, const Zones *zones); const QwtPlotCurve *getThisCurve() const { return thisCurve; } const QwtPlotCurve *getCPCurve() const { return CPCurve; } @@ -127,7 +127,7 @@ class CpintPlot : public QwtPlot const Zones *zones; int dateCP; RideFile::SeriesType series; - MainWindow *mainWindow; + Context *context; RideFileCache *current, *bests; LTMCanvasPicker *canvasPicker; diff --git a/src/CriticalPowerWindow.cpp b/src/CriticalPowerWindow.cpp index 71564b835..d75903626 100644 --- a/src/CriticalPowerWindow.cpp +++ b/src/CriticalPowerWindow.cpp @@ -20,7 +20,9 @@ #include "SearchFilterBox.h" #include "MetricAggregator.h" #include "CpintPlot.h" -#include "MainWindow.h" +#include "Context.h" +#include "Context.h" +#include "Athlete.h" #include "RideItem.h" #include "TimeUtils.h" #include @@ -35,8 +37,8 @@ #include #include -CriticalPowerWindow::CriticalPowerWindow(const QDir &home, MainWindow *parent, bool rangemode) : - GcChartWindow(parent), _dateRange("{00000000-0000-0000-0000-000000000001}"), home(home), mainWindow(parent), currentRide(NULL), rangemode(rangemode), isfiltered(false), stale(true), useCustom(false), useToToday(false) +CriticalPowerWindow::CriticalPowerWindow(const QDir &home, Context *context, bool rangemode) : + GcChartWindow(context), _dateRange("{00000000-0000-0000-0000-000000000001}"), home(home), context(context), currentRide(NULL), rangemode(rangemode), isfiltered(false), stale(true), useCustom(false), useToToday(false) { setInstanceName("Critical Power Window"); @@ -55,7 +57,7 @@ CriticalPowerWindow::CriticalPowerWindow(const QDir &home, MainWindow *parent, b // main plot area // QVBoxLayout *vlayout = new QVBoxLayout; - cpintPlot = new CpintPlot(mainWindow, home.path(), mainWindow->athlete->zones()); + cpintPlot = new CpintPlot(context, home.path(), context->athlete->zones()); vlayout->addWidget(cpintPlot); QGridLayout *mainLayout = new QGridLayout(); @@ -122,7 +124,7 @@ CriticalPowerWindow::CriticalPowerWindow(const QDir &home, MainWindow *parent, b #ifdef GC_HAVE_LUCENE // filter / searchbox - searchBox = new SearchFilterBox(this, parent); + searchBox = new SearchFilterBox(this, context); connect(searchBox, SIGNAL(searchClear()), cpintPlot, SLOT(clearFilter())); connect(searchBox, SIGNAL(searchResults(QStringList)), cpintPlot, SLOT(setFilter(QStringList))); connect(searchBox, SIGNAL(searchClear()), this, SLOT(filterChanged())); @@ -137,7 +139,7 @@ CriticalPowerWindow::CriticalPowerWindow(const QDir &home, MainWindow *parent, b // data -- season / daterange edit cComboSeason = new QComboBox(this); - seasons = parent->athlete->seasons; + seasons = context->athlete->seasons; resetSeasons(); QLabel *label = new QLabel(tr("Date range")); QLabel *label2 = new QLabel(tr("Date range")); @@ -181,14 +183,14 @@ CriticalPowerWindow::CriticalPowerWindow(const QDir &home, MainWindow *parent, b connect(seriesCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(setSeries(int))); connect(this, SIGNAL(rideItemChanged(RideItem*)), this, SLOT(rideSelected())); - connect(mainWindow->context, SIGNAL(configChanged()), cpintPlot, SLOT(configChanged())); + connect(context, SIGNAL(configChanged()), cpintPlot, SLOT(configChanged())); // redraw on config change -- this seems the simplest approach - connect(mainWindow, SIGNAL(filterChanged(QStringList&)), this, SLOT(forceReplot())); - connect(mainWindow->context, SIGNAL(configChanged()), this, SLOT(rideSelected())); - connect(mainWindow->athlete->metricDB, SIGNAL(dataChanged()), this, SLOT(refreshRideSaved())); - connect(mainWindow, SIGNAL(rideAdded(RideItem*)), this, SLOT(newRideAdded(RideItem*))); - connect(mainWindow, SIGNAL(rideDeleted(RideItem*)), this, SLOT(newRideAdded(RideItem*))); + connect(context->mainWindow, SIGNAL(filterChanged(QStringList&)), this, SLOT(forceReplot())); + connect(context, SIGNAL(configChanged()), this, SLOT(rideSelected())); + connect(context->athlete->metricDB, SIGNAL(dataChanged()), this, SLOT(refreshRideSaved())); + connect(context->mainWindow, SIGNAL(rideAdded(RideItem*)), this, SLOT(newRideAdded(RideItem*))); + connect(context->mainWindow, SIGNAL(rideDeleted(RideItem*)), this, SLOT(newRideAdded(RideItem*))); connect(seasons, SIGNAL(seasonsChanged()), this, SLOT(resetSeasons())); connect(shadeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(shadingSelected(int))); connect(dateSetting, SIGNAL(useCustomRange(DateRange)), this, SLOT(useCustomRange(DateRange))); @@ -199,7 +201,7 @@ CriticalPowerWindow::CriticalPowerWindow(const QDir &home, MainWindow *parent, b void CriticalPowerWindow::refreshRideSaved() { - const RideItem *current = mainWindow->context->rideItem(); + const RideItem *current = context->rideItem(); if (!current) return; // if the saved ride is in the aggregated time period @@ -266,9 +268,9 @@ CriticalPowerWindow::rideSelected() currentRide = myRideItem; if (currentRide) { - if (mainWindow->athlete->zones()) { - int zoneRange = mainWindow->athlete->zones()->whichRange(currentRide->dateTime.date()); - int CP = zoneRange >= 0 ? mainWindow->athlete->zones()->getCP(zoneRange) : 0; + if (context->athlete->zones()) { + int zoneRange = context->athlete->zones()->whichRange(currentRide->dateTime.date()); + int CP = zoneRange >= 0 ? context->athlete->zones()->getCP(zoneRange) : 0; cpintPlot->setDateCP(CP); } else { cpintPlot->setDateCP(0); @@ -522,12 +524,12 @@ CriticalPowerWindow::dateRangeChanged(DateRange dateRange) cto = dateRange.to; // lets work out the average CP configure value - if (mainWindow->athlete->zones()) { - int fromZoneRange = mainWindow->athlete->zones()->whichRange(cfrom); - int toZoneRange = mainWindow->athlete->zones()->whichRange(cto); + if (context->athlete->zones()) { + int fromZoneRange = context->athlete->zones()->whichRange(cfrom); + int toZoneRange = context->athlete->zones()->whichRange(cto); - int CPfrom = fromZoneRange >= 0 ? mainWindow->athlete->zones()->getCP(fromZoneRange) : 0; - int CPto = toZoneRange >= 0 ? mainWindow->athlete->zones()->getCP(toZoneRange) : CPfrom; + int CPfrom = fromZoneRange >= 0 ? context->athlete->zones()->getCP(fromZoneRange) : 0; + int CPto = toZoneRange >= 0 ? context->athlete->zones()->getCP(toZoneRange) : CPfrom; if (CPfrom == 0) CPfrom = CPto; int dateCP = (CPfrom + CPto) / 2; diff --git a/src/CriticalPowerWindow.h b/src/CriticalPowerWindow.h index ad61d7b3c..1fac3ddea 100644 --- a/src/CriticalPowerWindow.h +++ b/src/CriticalPowerWindow.h @@ -21,13 +21,14 @@ #include "GoldenCheetah.h" #include +#include "MainWindow.h" #include "Season.h" #ifdef GC_HAVE_LUCENE #include "SearchFilterBox.h" #endif class CpintPlot; -class MainWindow; +class Context; class RideItem; class QwtPlotPicker; @@ -57,7 +58,7 @@ class CriticalPowerWindow : public GcChartWindow public: - CriticalPowerWindow(const QDir &home, MainWindow *parent, bool range = false); + CriticalPowerWindow(const QDir &home, Context *context, bool range = false); // reveal bool hasReveal() { return false; } @@ -71,7 +72,7 @@ class CriticalPowerWindow : public GcChartWindow #ifdef GC_HAVE_LUCENE // filter - bool isFiltered() const { return (searchBox->isFiltered() || mainWindow->isfiltered); } + bool isFiltered() const { return (searchBox->isFiltered() || context->mainWindow->isfiltered); } QString filter() const { return searchBox->filter(); } void setFilter(QString x) { searchBox->setFilter(x); } #endif @@ -140,7 +141,7 @@ class CriticalPowerWindow : public GcChartWindow QDir home; CpintPlot *cpintPlot; - MainWindow *mainWindow; + Context *context; QLabel *cpintTimeValue; QLabel *cpintTodayValue; QLabel *cpintAllValue; diff --git a/src/CsvRideFile.cpp b/src/CsvRideFile.cpp index ec5dfaf43..31e3f6b77 100644 --- a/src/CsvRideFile.cpp +++ b/src/CsvRideFile.cpp @@ -476,7 +476,7 @@ RideFile *CsvFileReader::openRideFile(QFile &file, QStringList &errors, QList* = 0) const; - bool writeRideFile(MainWindow *main, const RideFile *ride, QFile &file) const; + bool writeRideFile(Context *context, const RideFile *ride, QFile &file) const; bool hasWrite() const { return true; } }; diff --git a/src/DBAccess.cpp b/src/DBAccess.cpp index 363982533..c47234417 100644 --- a/src/DBAccess.cpp +++ b/src/DBAccess.cpp @@ -16,6 +16,8 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ +#include "MainWindow.h" +#include "Athlete.h" #include "DBAccess.h" #include #include @@ -68,11 +70,11 @@ int DBSchemaVersion = 48; -DBAccess::DBAccess(MainWindow* main) : main(main) +DBAccess::DBAccess(Context* context) : context(context) { // check we have one and use built in if not there RideMetadata::readXML(":/xml/measures.xml", mkeywordDefinitions, mfieldDefinitions, mcolorfield); - initDatabase(main->athlete->home); + initDatabase(context->athlete->home); } void DBAccess::closeConnection() @@ -93,18 +95,18 @@ DBAccess::initDatabase(QDir home) if(dbconn.isOpen()) return; QString cyclist = QFileInfo(home.path()).baseName(); - sessionid = QString("%1%2").arg(cyclist).arg(main->session++); + sessionid = QString("%1%2").arg(cyclist).arg(context->mainWindow->session++); - if (main->session == 1) { + if (context->mainWindow->session == 1) { // use different name for v3 metricDB to avoid constant rebuilding // when switching between v2 stable and v3 development builds - main->athlete->db = QSqlDatabase::addDatabase("QSQLITE", sessionid); - main->athlete->db.setDatabaseName(home.absolutePath() + "/metricDBv3"); + context->athlete->db = QSqlDatabase::addDatabase("QSQLITE", sessionid); + context->athlete->db.setDatabaseName(home.absolutePath() + "/metricDBv3"); //dbconn = db.database(QString("GC")); - dbconn = main->athlete->db.database(sessionid); + dbconn = context->athlete->db.database(sessionid); } else { // clone the first one! - dbconn = QSqlDatabase::cloneDatabase(main->athlete->db, sessionid); + dbconn = QSqlDatabase::cloneDatabase(context->athlete->db, sessionid); dbconn.open(); } @@ -175,16 +177,16 @@ bool DBAccess::createMetricsTable() createMetricTable += QString(", X%1 double").arg(factory.metricName(i)); // And all the metadata texts - foreach(FieldDefinition field, main->athlete->rideMetadata()->getFields()) { - if (!main->specialFields.isMetric(field.name) && (field.type < 3 || field.type == 7)) { - createMetricTable += QString(", Z%1 varchar").arg(main->specialFields.makeTechName(field.name)); + foreach(FieldDefinition field, context->athlete->rideMetadata()->getFields()) { + if (!context->mainWindow->specialFields.isMetric(field.name) && (field.type < 3 || field.type == 7)) { + createMetricTable += QString(", Z%1 varchar").arg(context->mainWindow->specialFields.makeTechName(field.name)); } } // And all the metadata metrics - foreach(FieldDefinition field, main->athlete->rideMetadata()->getFields()) { - if (!main->specialFields.isMetric(field.name) && (field.type == 3 || field.type == 4)) { - createMetricTable += QString(", Z%1 double").arg(main->specialFields.makeTechName(field.name)); + foreach(FieldDefinition field, context->athlete->rideMetadata()->getFields()) { + if (!context->mainWindow->specialFields.isMetric(field.name) && (field.type == 3 || field.type == 4)) { + createMetricTable += QString(", Z%1 double").arg(context->mainWindow->specialFields.makeTechName(field.name)); } } createMetricTable += " )"; @@ -193,7 +195,7 @@ bool DBAccess::createMetricsTable() //if (!rc) qDebug()<<"create table failed!" << query.lastError(); // add row to version database - QString metadataXML = QString(main->athlete->home.absolutePath()) + "/metadata.xml"; + QString metadataXML = QString(context->athlete->home.absolutePath()) + "/metadata.xml"; int metadatacrcnow = computeFileCRC(metadataXML); QDateTime timestamp = QDateTime::currentDateTime(); @@ -243,12 +245,12 @@ bool DBAccess::createMeasuresTable() // And all the metadata texts foreach(FieldDefinition field, mfieldDefinitions) - if (field.type < 3 || field.type == 7) createMeasuresTable += QString(", Z%1 varchar").arg(main->specialFields.makeTechName(field.name)); + if (field.type < 3 || field.type == 7) createMeasuresTable += QString(", Z%1 varchar").arg(context->mainWindow->specialFields.makeTechName(field.name)); // And all the metadata measures foreach(FieldDefinition field, mfieldDefinitions) if (field.type == 3 || field.type == 4) - createMeasuresTable += QString(", Z%1 double").arg(main->specialFields.makeTechName(field.name)); + createMeasuresTable += QString(", Z%1 double").arg(context->mainWindow->specialFields.makeTechName(field.name)); createMeasuresTable += " )"; @@ -298,7 +300,7 @@ bool DBAccess::createDatabase() void DBAccess::checkDBVersion() { // get a CRC for metadata.xml - QString metadataXML = QString(main->athlete->home.absolutePath()) + "/metadata.xml"; + QString metadataXML = QString(context->athlete->home.absolutePath()) + "/metadata.xml"; int metadatacrcnow = computeFileCRC(metadataXML); // get a CRC for measures.xml @@ -407,23 +409,23 @@ bool DBAccess::importRide(SummaryMetrics *summaryMetrics, RideFile *ride, QColor insertStatement += QString(", X%1 ").arg(factory.metricName(i)); // And all the metadata texts - foreach(FieldDefinition field, main->athlete->rideMetadata()->getFields()) { - if (!main->specialFields.isMetric(field.name) && (field.type < 3 || field.type == 7)) { - insertStatement += QString(", Z%1 ").arg(main->specialFields.makeTechName(field.name)); + foreach(FieldDefinition field, context->athlete->rideMetadata()->getFields()) { + if (!context->mainWindow->specialFields.isMetric(field.name) && (field.type < 3 || field.type == 7)) { + insertStatement += QString(", Z%1 ").arg(context->mainWindow->specialFields.makeTechName(field.name)); } } // And all the metadata metrics - foreach(FieldDefinition field, main->athlete->rideMetadata()->getFields()) { - if (!main->specialFields.isMetric(field.name) && (field.type == 3 || field.type == 4)) { - insertStatement += QString(", Z%1 ").arg(main->specialFields.makeTechName(field.name)); + foreach(FieldDefinition field, context->athlete->rideMetadata()->getFields()) { + if (!context->mainWindow->specialFields.isMetric(field.name) && (field.type == 3 || field.type == 4)) { + insertStatement += QString(", Z%1 ").arg(context->mainWindow->specialFields.makeTechName(field.name)); } } insertStatement += " ) values (?,?,?,?,?,?"; // filename, identifier, timestamp, ride_date, color, fingerprint for (int i=0; iathlete->rideMetadata()->getFields()) { - if (!main->specialFields.isMetric(field.name) && (field.type < 5 || field.type == 7)) { + foreach(FieldDefinition field, context->athlete->rideMetadata()->getFields()) { + if (!context->mainWindow->specialFields.isMetric(field.name) && (field.type < 5 || field.type == 7)) { insertStatement += ",?"; } } @@ -445,18 +447,18 @@ bool DBAccess::importRide(SummaryMetrics *summaryMetrics, RideFile *ride, QColor } // And all the metadata texts - foreach(FieldDefinition field, main->athlete->rideMetadata()->getFields()) { + foreach(FieldDefinition field, context->athlete->rideMetadata()->getFields()) { - if (!main->specialFields.isMetric(field.name) && (field.type < 3 || field.type ==7)) { + if (!context->mainWindow->specialFields.isMetric(field.name) && (field.type < 3 || field.type ==7)) { query.addBindValue(ride->getTag(field.name, "")); } } // And all the metadata metrics - foreach(FieldDefinition field, main->athlete->rideMetadata()->getFields()) { + foreach(FieldDefinition field, context->athlete->rideMetadata()->getFields()) { - if (!main->specialFields.isMetric(field.name) && (field.type == 3 || field.type == 4)) { + if (!context->mainWindow->specialFields.isMetric(field.name) && (field.type == 3 || field.type == 4)) { query.addBindValue(ride->getTag(field.name, "0.0").toDouble()); - } else if (!main->specialFields.isMetric(field.name)) { + } else if (!context->mainWindow->specialFields.isMetric(field.name)) { if (field.name == "Recording Interval") query.addBindValue(ride->recIntSecs()); } @@ -505,9 +507,9 @@ DBAccess::getRide(QString filename, SummaryMetrics &summaryMetrics, QColor&color const RideMetricFactory &factory = RideMetricFactory::instance(); for (int i=0; iathlete->rideMetadata()->getFields()) { - if (!main->specialFields.isMetric(field.name) && (field.type < 5 || field.type == 7)) { - selectStatement += QString(", Z%1 ").arg(main->specialFields.makeTechName(field.name)); + foreach(FieldDefinition field, context->athlete->rideMetadata()->getFields()) { + if (!context->mainWindow->specialFields.isMetric(field.name) && (field.type < 5 || field.type == 7)) { + selectStatement += QString(", Z%1 ").arg(context->mainWindow->specialFields.makeTechName(field.name)); } } selectStatement += " FROM metrics where filename = :name;"; @@ -532,12 +534,12 @@ DBAccess::getRide(QString filename, SummaryMetrics &summaryMetrics, QColor&color for (; iathlete->rideMetadata()->getFields()) { - if (!main->specialFields.isMetric(field.name) && (field.type == 3 || field.type == 4)) { + foreach(FieldDefinition field, context->athlete->rideMetadata()->getFields()) { + if (!context->mainWindow->specialFields.isMetric(field.name) && (field.type == 3 || field.type == 4)) { QString underscored = field.name; summaryMetrics.setForSymbol(underscored.replace("_"," "), query.value(i+4).toDouble()); i++; - } else if (!main->specialFields.isMetric(field.name) && field.type < 3) { + } else if (!context->mainWindow->specialFields.isMetric(field.name) && field.type < 3) { QString underscored = field.name; summaryMetrics.setText(underscored.replace("_"," "), query.value(i+4).toString()); i++; @@ -561,9 +563,9 @@ QList DBAccess::getAllMetricsFor(QDateTime start, QDateTime end) const RideMetricFactory &factory = RideMetricFactory::instance(); for (int i=0; iathlete->rideMetadata()->getFields()) { - if (!main->specialFields.isMetric(field.name) && (field.type < 5 || field.type == 7)) { - selectStatement += QString(", Z%1 ").arg(main->specialFields.makeTechName(field.name)); + foreach(FieldDefinition field, context->athlete->rideMetadata()->getFields()) { + if (!context->mainWindow->specialFields.isMetric(field.name) && (field.type < 5 || field.type == 7)) { + selectStatement += QString(", Z%1 ").arg(context->mainWindow->specialFields.makeTechName(field.name)); } } selectStatement += " FROM metrics where DATE(ride_date) >=DATE(:start) AND DATE(ride_date) <=DATE(:end) " @@ -586,12 +588,12 @@ QList DBAccess::getAllMetricsFor(QDateTime start, QDateTime end) int i=0; for (; iathlete->rideMetadata()->getFields()) { - if (!main->specialFields.isMetric(field.name) && (field.type == 3 || field.type == 4)) { + foreach(FieldDefinition field, context->athlete->rideMetadata()->getFields()) { + if (!context->mainWindow->specialFields.isMetric(field.name) && (field.type == 3 || field.type == 4)) { QString underscored = field.name; summaryMetrics.setForSymbol(underscored.replace("_"," "), query.value(i+3).toDouble()); i++; - } else if (!main->specialFields.isMetric(field.name) && (field.type < 3 || field.type == 7)) { + } else if (!context->mainWindow->specialFields.isMetric(field.name) && (field.type < 3 || field.type == 7)) { QString underscored = field.name; summaryMetrics.setText(underscored.replace("_"," "), query.value(i+3).toString()); i++; @@ -611,9 +613,9 @@ SummaryMetrics DBAccess::getRideMetrics(QString filename) const RideMetricFactory &factory = RideMetricFactory::instance(); for (int i=0; iathlete->rideMetadata()->getFields()) { - if (!main->specialFields.isMetric(field.name) && (field.type < 5 || field.type == 7)) { - selectStatement += QString(", Z%1 ").arg(main->specialFields.makeTechName(field.name)); + foreach(FieldDefinition field, context->athlete->rideMetadata()->getFields()) { + if (!context->mainWindow->specialFields.isMetric(field.name) && (field.type < 5 || field.type == 7)) { + selectStatement += QString(", Z%1 ").arg(context->mainWindow->specialFields.makeTechName(field.name)); } } selectStatement += " FROM metrics where filename == :filename ;"; @@ -631,12 +633,12 @@ SummaryMetrics DBAccess::getRideMetrics(QString filename) int i=0; for (; iathlete->rideMetadata()->getFields()) { - if (!main->specialFields.isMetric(field.name) && (field.type == 3 || field.type == 4)) { + foreach(FieldDefinition field, context->athlete->rideMetadata()->getFields()) { + if (!context->mainWindow->specialFields.isMetric(field.name) && (field.type == 3 || field.type == 4)) { QString underscored = field.name; summaryMetrics.setForSymbol(underscored.replace(" ","_"), query.value(i+2).toDouble()); i++; - } else if (!main->specialFields.isMetric(field.name) && (field.type < 3 || field.type == 7)) { + } else if (!context->mainWindow->specialFields.isMetric(field.name) && (field.type < 3 || field.type == 7)) { QString underscored = field.name; summaryMetrics.setText(underscored.replace("_"," "), query.value(i+2).toString()); i++; @@ -716,8 +718,8 @@ QList DBAccess::getAllMeasuresFor(QDateTime start, QDateTime end // construct the select statement QString selectStatement = "SELECT timestamp, measure_date"; foreach(FieldDefinition field, mfieldDefinitions) { - if (!main->specialFields.isMetric(field.name) && (field.type < 5 || field.type == 7)) { - selectStatement += QString(", Z%1 ").arg(main->specialFields.makeTechName(field.name)); + if (!context->mainWindow->specialFields.isMetric(field.name) && (field.type < 5 || field.type == 7)) { + selectStatement += QString(", Z%1 ").arg(context->mainWindow->specialFields.makeTechName(field.name)); } } selectStatement += " FROM measures where DATE(measure_date) >=DATE(:start) AND DATE(measure_date) <=DATE(:end) " diff --git a/src/DBAccess.h b/src/DBAccess.h index 57517b968..0885a6e8d 100644 --- a/src/DBAccess.h +++ b/src/DBAccess.h @@ -26,7 +26,7 @@ #include #include #include "SummaryMetrics.h" -#include "MainWindow.h" +#include "Context.h" #include "Season.h" #include "RideFile.h" #include "SpecialFields.h" @@ -52,7 +52,7 @@ class DBAccess int getDBVersion(); // create and drop connections - DBAccess(MainWindow *main); + DBAccess(Context *context); ~DBAccess(); // Create/Delete Metrics @@ -80,7 +80,7 @@ class DBAccess QList getAllSeasons(); private: - MainWindow *main; + Context *context; QSqlDatabase dbconn; QString sessionid; diff --git a/src/DanielsPoints.cpp b/src/DanielsPoints.cpp index a708c86a0..aa308f4ec 100644 --- a/src/DanielsPoints.cpp +++ b/src/DanielsPoints.cpp @@ -56,7 +56,7 @@ class DanielsPoints : public RideMetric { void compute(const RideFile *ride, const Zones *zones, int zoneRange, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { if (!zones || zoneRange < 0) { setValue(0); return; @@ -122,7 +122,7 @@ class DanielsEquivalentPower : public RideMetric { void compute(const RideFile *, const Zones *zones, int zoneRange, const HrZones *, int, const QHash &deps, - const MainWindow *) + const Context *) { if (!zones || zoneRange < 0) { setValue(0); diff --git a/src/DataFilter.cpp b/src/DataFilter.cpp index 6dad8a5d5..59ba0ef1e 100644 --- a/src/DataFilter.cpp +++ b/src/DataFilter.cpp @@ -17,7 +17,9 @@ */ #include "DataFilter.h" -#include "MainWindow.h" +#include "Context.h" +#include "Context.h" +#include "Athlete.h" #include "RideNavigator.h" #include @@ -134,10 +136,10 @@ void Leaf::validateFilter(DataFilter *df, Leaf *leaf) } } -DataFilter::DataFilter(QObject *parent, MainWindow *mainWindow) : QObject(parent), mainWindow(mainWindow), treeRoot(NULL) +DataFilter::DataFilter(QObject *parent, Context *context) : QObject(parent), context(context), treeRoot(NULL) { configUpdate(); - connect(mainWindow->context, SIGNAL(configChanged()), this, SLOT(configUpdate())); + connect(context, SIGNAL(configChanged()), this, SLOT(configUpdate())); } QStringList DataFilter::parseFilter(QString query) @@ -174,7 +176,7 @@ QStringList DataFilter::parseFilter(QString query) emit parseGood(); // get all fields... - QList allRides = mainWindow->athlete->metricDB->getAllMetricsFor(QDateTime(), QDateTime()); + QList allRides = context->athlete->metricDB->getAllMetricsFor(QDateTime(), QDateTime()); filenames.clear(); @@ -217,9 +219,9 @@ void DataFilter::configUpdate() } // now add the ride metadata fields -- should be the same generally - foreach(FieldDefinition field, mainWindow->athlete->rideMetadata()->getFields()) { + foreach(FieldDefinition field, context->athlete->rideMetadata()->getFields()) { QString underscored = field.name; - if (!mainWindow->specialFields.isMetric(underscored)) { + if (!context->mainWindow->specialFields.isMetric(underscored)) { lookupMap.insert(underscored.replace(" ","_"), field.name); lookupType.insert(underscored.replace(" ","_"), (field.type > 2)); // true if is number } diff --git a/src/DataFilter.h b/src/DataFilter.h index 1fce45cc9..95322e635 100644 --- a/src/DataFilter.h +++ b/src/DataFilter.h @@ -22,7 +22,7 @@ #include #include -class MainWindow; +class Context; class RideMetric; class FieldDefinition; class SummaryMetrics; @@ -59,7 +59,7 @@ class DataFilter : public QObject Q_OBJECT public: - DataFilter(QObject *parent, MainWindow *mainWindow); + DataFilter(QObject *parent, Context *context); QStringList &files() { return filenames; } // used by Leaf @@ -80,7 +80,7 @@ class DataFilter : public QObject void results(QStringList); private: - MainWindow *mainWindow; + Context *context; Leaf *treeRoot; QStringList errors; diff --git a/src/DataProcessor.cpp b/src/DataProcessor.cpp index ffbb3c27a..a45026776 100644 --- a/src/DataProcessor.cpp +++ b/src/DataProcessor.cpp @@ -17,7 +17,7 @@ */ #include "DataProcessor.h" -#include "MainWindow.h" +#include "Context.h" #include "AllPlot.h" #include "Settings.h" #include "Units.h" @@ -56,7 +56,7 @@ DataProcessorFactory::autoProcess(RideFile *ride) return changed; } -ManualDataProcessorDialog::ManualDataProcessorDialog(MainWindow *main, QString name, RideItem *ride) : main(main), ride(ride) +ManualDataProcessorDialog::ManualDataProcessorDialog(Context *context, QString name, RideItem *ride) : context(context), ride(ride) { setAttribute(Qt::WA_DeleteOnClose); setWindowTitle(name); diff --git a/src/DataProcessor.h b/src/DataProcessor.h index 544b4020c..9d16cd9b1 100644 --- a/src/DataProcessor.h +++ b/src/DataProcessor.h @@ -93,7 +93,7 @@ class DataProcessorFactory { bool autoProcess(RideFile *); // run auto processes (after open rideFile) }; -class MainWindow; +class Context; class ManualDataProcessorDialog : public QDialog { Q_OBJECT @@ -101,7 +101,7 @@ class ManualDataProcessorDialog : public QDialog public: - ManualDataProcessorDialog(MainWindow *, QString, RideItem *); + ManualDataProcessorDialog(Context *, QString, RideItem *); private slots: void cancelClicked(); @@ -109,7 +109,7 @@ class ManualDataProcessorDialog : public QDialog private: - MainWindow *main; + Context *context; RideItem *ride; DataProcessor *processor; DataProcessorConfig *config; diff --git a/src/DialWindow.cpp b/src/DialWindow.cpp index 069cf716b..5a13ca0b0 100644 --- a/src/DialWindow.cpp +++ b/src/DialWindow.cpp @@ -18,9 +18,11 @@ #include "DialWindow.h" +#include "Athlete.h" +#include "Context.h" -DialWindow::DialWindow(MainWindow *mainWindow) : - GcWindow(mainWindow), mainWindow(mainWindow), average(1), isNewLap(false) +DialWindow::DialWindow(Context *context) : + GcWindow(context), context(context), average(1), isNewLap(false) { rolling.resize(150); // enough for 30 seconds at 5hz @@ -77,11 +79,11 @@ DialWindow::DialWindow(MainWindow *mainWindow) : layout->addWidget(valueLabel); // get updates.. - connect(mainWindow->context, SIGNAL(telemetryUpdate(RealtimeData)), this, SLOT(telemetryUpdate(RealtimeData))); - connect(mainWindow->context, SIGNAL(configChanged()), this, SLOT(seriesChanged())); - connect(mainWindow->context, SIGNAL(stop()), this, SLOT(stop())); - connect(mainWindow->context, SIGNAL(start()), this, SLOT(start())); - connect(mainWindow->context, SIGNAL(newLap()), this, SLOT(onNewLap())); + connect(context, SIGNAL(telemetryUpdate(RealtimeData)), this, SLOT(telemetryUpdate(RealtimeData))); + connect(context, SIGNAL(configChanged()), this, SLOT(seriesChanged())); + connect(context, SIGNAL(stop()), this, SLOT(stop())); + connect(context, SIGNAL(start()), this, SLOT(start())); + connect(context, SIGNAL(newLap()), this, SLOT(onNewLap())); connect(seriesSelector, SIGNAL(currentIndexChanged(int)), this, SLOT(seriesChanged())); connect(averageSlider, SIGNAL(valueChanged(int)),this, SLOT(setAverageFromSlider())); @@ -204,12 +206,12 @@ DialWindow::telemetryUpdate(const RealtimeData &rtData) case RealtimeData::Speed: case RealtimeData::VirtualSpeed: - if (!mainWindow->athlete->useMetricUnits) value *= MILES_PER_KM; + if (!context->athlete->useMetricUnits) value *= MILES_PER_KM; valueLabel->setText(QString("%1").arg(value, 0, 'f', 1)); break; case RealtimeData::Distance: - if (!mainWindow->athlete->useMetricUnits) value *= MILES_PER_KM; + if (!context->athlete->useMetricUnits) value *= MILES_PER_KM; valueLabel->setText(QString("%1").arg(value, 0, 'f', 3)); break; @@ -226,7 +228,7 @@ DialWindow::telemetryUpdate(const RealtimeData &rtData) sum += rtData.value(RealtimeData::Speed); count++; value = sum / count; - if (!mainWindow->athlete->useMetricUnits) value *= MILES_PER_KM; + if (!context->athlete->useMetricUnits) value *= MILES_PER_KM; valueLabel->setText(QString("%1").arg(value, 0, 'f', 1)); break; @@ -282,11 +284,11 @@ DialWindow::telemetryUpdate(const RealtimeData &rtData) double rif, cp; // carry on and calculate IF - if (mainWindow->athlete->zones()) { + if (context->athlete->zones()) { // get cp for today - int zonerange = mainWindow->athlete->zones()->whichRange(QDateTime::currentDateTime().date()); - if (zonerange >= 0) cp = mainWindow->athlete->zones()->getCP(zonerange); + int zonerange = context->athlete->zones()->whichRange(QDateTime::currentDateTime().date()); + if (zonerange >= 0) cp = context->athlete->zones()->getCP(zonerange); else cp = 0; } else { @@ -368,11 +370,11 @@ DialWindow::telemetryUpdate(const RealtimeData &rtData) double rif, cp; // carry on and calculate IF - if (mainWindow->athlete->zones()) { + if (context->athlete->zones()) { // get cp for today - int zonerange = mainWindow->athlete->zones()->whichRange(QDateTime::currentDateTime().date()); - if (zonerange >= 0) cp = mainWindow->athlete->zones()->getCP(zonerange); + int zonerange = context->athlete->zones()->whichRange(QDateTime::currentDateTime().date()); + if (zonerange >= 0) cp = context->athlete->zones()->getCP(zonerange); else cp = 0; } else { diff --git a/src/DialWindow.h b/src/DialWindow.h index 4e0029fae..faa27ce38 100644 --- a/src/DialWindow.h +++ b/src/DialWindow.h @@ -24,7 +24,7 @@ #include // for Q_PROPERTY -#include "MainWindow.h" +#include "Context.h" #include "Zones.h" // for data series types #include "RideFile.h" // for data series types #include "ErgFile.h" // for workout modes @@ -60,7 +60,7 @@ class DialWindow : public GcWindow public: - DialWindow(MainWindow *mainWindow); + DialWindow(Context *context); // get properties - the setters are below bool isInstant() const { return _instant; } @@ -91,7 +91,7 @@ class DialWindow : public GcWindow private: - MainWindow *mainWindow; + Context *context; // properties bool _instant; diff --git a/src/DiaryWindow.cpp b/src/DiaryWindow.cpp index 511aa3990..c83de502c 100644 --- a/src/DiaryWindow.cpp +++ b/src/DiaryWindow.cpp @@ -18,15 +18,18 @@ #include "DiaryWindow.h" +#include "RideMetadata.h" +#include "Athlete.h" +#include "Context.h" -DiaryWindow::DiaryWindow(MainWindow *mainWindow) : - GcWindow(mainWindow), mainWindow(mainWindow), active(false) +DiaryWindow::DiaryWindow(Context *context) : + GcWindow(context), context(context), active(false) { setInstanceName("Diary Window"); setControls(NULL); // get config - fieldDefinitions = mainWindow->athlete->rideMetadata()->getFields(); + fieldDefinitions = context->athlete->rideMetadata()->getFields(); QVBoxLayout *vlayout = new QVBoxLayout(this); @@ -57,8 +60,8 @@ DiaryWindow::DiaryWindow(MainWindow *mainWindow) : vlayout->addLayout(controls); // monthly view via QCalendarWidget - calendarModel = new GcCalendarModel(this, &fieldDefinitions, mainWindow); - calendarModel->setSourceModel(mainWindow->listView->sqlModel); + calendarModel = new GcCalendarModel(this, &fieldDefinitions, context); + calendarModel->setSourceModel(context->mainWindow->listView->sqlModel); monthlyView = new QTableView(this); monthlyView->setItemDelegate(new GcCalendarDelegate); @@ -81,9 +84,9 @@ DiaryWindow::DiaryWindow(MainWindow *mainWindow) : //connect(viewMode, SIGNAL(currentIndexChanged(int)), this, SLOT(setDefaultView(int))); //connect(viewMode, SIGNAL(currentIndexChanged(int)), this, SLOT(rideSelected())); connect(this, SIGNAL(rideItemChanged(RideItem*)), this, SLOT(rideSelected())); - connect(mainWindow, SIGNAL(filterChanged(QStringList&)), this, SLOT(rideSelected())); + connect(context->mainWindow, SIGNAL(filterChanged(QStringList&)), this, SLOT(rideSelected())); //connect(mainWindow, SIGNAL(rideSelected()), this, SLOT(rideSelected())); - connect(mainWindow->context, SIGNAL(configChanged()), this, SLOT(configChanged())); + connect(context, SIGNAL(configChanged()), this, SLOT(configChanged())); connect(next, SIGNAL(clicked()), this, SLOT(nextClicked())); connect(prev, SIGNAL(clicked()), this, SLOT(prevClicked())); } @@ -92,13 +95,13 @@ void DiaryWindow::configChanged() { // get config - fieldDefinitions = mainWindow->athlete->rideMetadata()->getFields(); + fieldDefinitions = context->athlete->rideMetadata()->getFields(); } void DiaryWindow::setDefaultView(int view) { - appsettings->setCValue(mainWindow->athlete->cyclist, GC_DIARY_VIEW, view); + appsettings->setCValue(context->athlete->cyclist, GC_DIARY_VIEW, view); } void DiaryWindow::rideSelected() @@ -156,7 +159,7 @@ DiaryWindow::eventFilter(QObject *object, QEvent *e) { if (e->type() != QEvent::ToolTip && e->type() != QEvent::Paint && e->type() != QEvent::Destroy) - mainWindow->setBubble(""); + context->mainWindow->setBubble(""); switch (e->type()) { case QEvent::MouseButtonPress: @@ -175,7 +178,7 @@ DiaryWindow::eventFilter(QObject *object, QEvent *e) // clicked on cell contents if (files.count() == 1) { if (files[0] == "calendar") ; // handle planned rides - else mainWindow->selectRideFile(QFileInfo(files[0]).fileName()); + else context->mainWindow->selectRideFile(QFileInfo(files[0]).fileName()); } else if (files.count()) { @@ -185,7 +188,7 @@ DiaryWindow::eventFilter(QObject *object, QEvent *e) for(i=files.count()-1; i>=0; i--) if (y > (c.y()+15+(h*i))) break; if (files[i] == "calendar") ; // handle planned rides - else mainWindow->selectRideFile(QFileInfo(files[i]).fileName()); + else context->mainWindow->selectRideFile(QFileInfo(files[i]).fileName()); } // force a repaint @@ -212,7 +215,7 @@ DiaryWindow::eventFilter(QObject *object, QEvent *e) // Popup bubble for ride if (files.count() == 1) { if (files[0] == "calendar") ; // handle planned rides - else mainWindow->setBubble(files.at(0), monthlyView->viewport()->mapToGlobal(pos)); + else context->mainWindow->setBubble(files.at(0), monthlyView->viewport()->mapToGlobal(pos)); } else if (files.count()) { @@ -224,14 +227,14 @@ DiaryWindow::eventFilter(QObject *object, QEvent *e) for(i=files.count()-1; i>=0; i--) if (pos.y() > (c.y()+15+(h*i))) break; if (i<0) { - mainWindow->setBubble(""); + context->mainWindow->setBubble(""); return true; } if (files.at(i) == "calendar") ; // handle planned rides - else mainWindow->setBubble(files.at(i), monthlyView->viewport()->mapToGlobal(pos)); + else context->mainWindow->setBubble(files.at(i), monthlyView->viewport()->mapToGlobal(pos)); } else { - mainWindow->setBubble(""); + context->mainWindow->setBubble(""); } } } diff --git a/src/DiaryWindow.h b/src/DiaryWindow.h index be58aac45..1f5214150 100644 --- a/src/DiaryWindow.h +++ b/src/DiaryWindow.h @@ -25,7 +25,7 @@ #include #include -#include "MainWindow.h" +#include "Context.h" #include "RideMetadata.h" // list view @@ -48,13 +48,13 @@ class DiaryWindow : public GcWindow public: - DiaryWindow(MainWindow *); + DiaryWindow(Context *); int view() const { return 0; /* viewMode->currentIndex(); */ } void setView(int /* x */ ) { /* viewMode->setCurrentIndex(x); */ } #ifdef GC_HAVE_LUCENE - bool isFiltered() const { return mainWindow->isfiltered; } + bool isFiltered() const { return context->mainWindow->isfiltered; } #endif public slots: @@ -66,7 +66,7 @@ class DiaryWindow : public GcWindow bool eventFilter(QObject *object, QEvent *e); // traps monthly view protected: - MainWindow *mainWindow; + Context *context; QLabel *title; QPushButton *prev, *next; diff --git a/src/DownloadRideDialog.cpp b/src/DownloadRideDialog.cpp index 58e43b9ca..d2dc7232b 100644 --- a/src/DownloadRideDialog.cpp +++ b/src/DownloadRideDialog.cpp @@ -21,14 +21,15 @@ #include "DownloadRideDialog.h" #include "Device.h" #include "MainWindow.h" +#include "Context.h" #include "Settings.h" #include #include #include -DownloadRideDialog::DownloadRideDialog(MainWindow *mainWindow, +DownloadRideDialog::DownloadRideDialog(Context *context, const QDir &home) : - mainWindow(mainWindow), home(home), cancelled(false), + context(context), home(home), cancelled(false), action(actionIdle) { setAttribute(Qt::WA_DeleteOnClose); @@ -389,7 +390,7 @@ DownloadRideDialog::downloadClicked() } QFile::remove(files.at(i).name); - mainWindow->addRide(filename); + context->mainWindow->addRide(filename); } if( ! failures ) diff --git a/src/DownloadRideDialog.h b/src/DownloadRideDialog.h index 645b43b99..ce76fad0b 100644 --- a/src/DownloadRideDialog.h +++ b/src/DownloadRideDialog.h @@ -23,7 +23,7 @@ #include "CommPort.h" #include -class MainWindow; +class Context; class DownloadRideDialog : public QDialog { @@ -32,7 +32,7 @@ class DownloadRideDialog : public QDialog public: - DownloadRideDialog(MainWindow *mainWindow, const QDir &home); + DownloadRideDialog(Context *context, const QDir &home); bool isCancelled(); @@ -52,7 +52,7 @@ class DownloadRideDialog : public QDialog private: - MainWindow *mainWindow; + Context *context; QDir home; QPushButton *downloadButton, *eraseRideButton, *rescanButton, *cancelButton, *closeButton; diff --git a/src/ErgDB.h b/src/ErgDB.h index 40d7966d4..c4c167366 100644 --- a/src/ErgDB.h +++ b/src/ErgDB.h @@ -21,6 +21,7 @@ #include "GoldenCheetah.h" #include "ErgFile.h" #include +#include #include #include #include diff --git a/src/ErgDBDownloadDialog.cpp b/src/ErgDBDownloadDialog.cpp index 31cc08f99..44c51133b 100644 --- a/src/ErgDBDownloadDialog.cpp +++ b/src/ErgDBDownloadDialog.cpp @@ -17,9 +17,10 @@ */ #include "ErgDBDownloadDialog.h" +#include "MainWindow.h" #include "TrainDB.h" -ErgDBDownloadDialog::ErgDBDownloadDialog(MainWindow *main) : QDialog(main), main(main) +ErgDBDownloadDialog::ErgDBDownloadDialog(Context *context) : QDialog(context->mainWindow), context(context) { setAttribute(Qt::WA_DeleteOnClose); setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint); @@ -131,7 +132,7 @@ ErgDBDownloadDialog::okClicked() status->setText(QString("%1 workouts downloaded, %2 failed or skipped.").arg(downloads).arg(fails)); ok->setText("Finish"); - main->trainTool->configChanged(); + context->mainWindow->trainTool->configChanged(); } else if (ok->text() == "Abort") { aborted = true; @@ -185,7 +186,7 @@ ErgDBDownloadDialog::downloadFiles() QString content = ergdb.getFile(id, 300); QString filename = workoutDir + "/" + current->text(1) + ".erg"; - ErgFile *p = ErgFile::fromContent(content, main); + ErgFile *p = ErgFile::fromContent(content, context); // open success? if (p->isValid()) { diff --git a/src/ErgDBDownloadDialog.h b/src/ErgDBDownloadDialog.h index ca63ed8cb..e5e0cb52b 100644 --- a/src/ErgDBDownloadDialog.h +++ b/src/ErgDBDownloadDialog.h @@ -20,7 +20,7 @@ #ifndef _ErgDBDownloadDialog_h #define _ErgDBDownloadDialog_h #include "GoldenCheetah.h" -#include "MainWindow.h" +#include "Context.h" #include "Settings.h" #include "Units.h" @@ -47,7 +47,7 @@ class ErgDBDownloadDialog : public QDialog public: - ErgDBDownloadDialog(MainWindow *main); + ErgDBDownloadDialog(Context *context); QTreeWidget *files; // choose files to export @@ -60,7 +60,7 @@ private slots: void allClicked(); private: - MainWindow *main; + Context *context; bool aborted; QCheckBox *all; diff --git a/src/ErgFile.cpp b/src/ErgFile.cpp index 2f8a3cfe4..be7ae5028 100644 --- a/src/ErgFile.cpp +++ b/src/ErgFile.cpp @@ -17,6 +17,7 @@ */ #include "ErgFile.h" +#include "Athlete.h" #include #include "Units.h" @@ -40,21 +41,21 @@ bool ErgFile::isWorkout(QString name) } return false; } -ErgFile::ErgFile(QString filename, int &mode, MainWindow *main) : - filename(filename), main(main), mode(mode) +ErgFile::ErgFile(QString filename, int &mode, Context *context) : + filename(filename), context(context), mode(mode) { - if (main->athlete->zones()) { - int zonerange = main->athlete->zones()->whichRange(QDateTime::currentDateTime().date()); - if (zonerange >= 0) CP = main->athlete->zones()->getCP(zonerange); + if (context->athlete->zones()) { + int zonerange = context->athlete->zones()->whichRange(QDateTime::currentDateTime().date()); + if (zonerange >= 0) CP = context->athlete->zones()->getCP(zonerange); } reload(); } -ErgFile::ErgFile(MainWindow *main) : main(main), mode(nomode) +ErgFile::ErgFile(Context *context) : context(context), mode(nomode) { - if (main->athlete->zones()) { - int zonerange = main->athlete->zones()->whichRange(QDateTime::currentDateTime().date()); - if (zonerange >= 0) CP = main->athlete->zones()->getCP(zonerange); + if (context->athlete->zones()) { + int zonerange = context->athlete->zones()->whichRange(QDateTime::currentDateTime().date()); + if (zonerange >= 0) CP = context->athlete->zones()->getCP(zonerange); } else { CP = 300; } @@ -62,9 +63,9 @@ ErgFile::ErgFile(MainWindow *main) : main(main), mode(nomode) } ErgFile * -ErgFile::fromContent(QString contents, MainWindow *main) +ErgFile::fromContent(QString contents, Context *context) { - ErgFile *p = new ErgFile(main); + ErgFile *p = new ErgFile(context); p->parseComputrainer(contents); return p; } @@ -719,9 +720,9 @@ ErgFile::calculateMetrics() AP = apsum / count; // CP - if (main->athlete->zones()) { - int zonerange = main->athlete->zones()->whichRange(QDateTime::currentDateTime().date()); - if (zonerange >= 0) CP = main->athlete->zones()->getCP(zonerange); + if (context->athlete->zones()) { + int zonerange = context->athlete->zones()->whichRange(QDateTime::currentDateTime().date()); + if (zonerange >= 0) CP = context->athlete->zones()->getCP(zonerange); } // IF diff --git a/src/ErgFile.h b/src/ErgFile.h index 40f00d998..9a39dfa6c 100644 --- a/src/ErgFile.h +++ b/src/ErgFile.h @@ -19,7 +19,7 @@ #ifndef _ErgFile_h #define _ErgFile_h #include "GoldenCheetah.h" -#include "MainWindow.h" +#include "Context.h" #include #include @@ -66,12 +66,12 @@ class ErgFileLap class ErgFile { public: - ErgFile(QString, int&, MainWindow *main); // constructor uses filename - ErgFile(MainWindow *main); // no filename, going to use a string + ErgFile(QString, int&, Context *context); // constructor uses filename + ErgFile(Context *context); // no filename, going to use a string ~ErgFile(); // delete the contents - static ErgFile *fromContent(QString, MainWindow *); // read from memory + static ErgFile *fromContent(QString, Context *); // read from memory static bool isWorkout(QString); // is this a supported workout? void reload(); // reload after messed about @@ -112,7 +112,7 @@ class ErgFile double ELE, ELEDIST, GRADE; // crs private: - MainWindow *main; + Context *context; int &mode; int nomode; }; diff --git a/src/ErgFilePlot.cpp b/src/ErgFilePlot.cpp index 82138a102..4c992c887 100644 --- a/src/ErgFilePlot.cpp +++ b/src/ErgFilePlot.cpp @@ -18,22 +18,24 @@ #include "ErgFilePlot.h" +#include "MainWindow.h" +#include "Context.h" // Bridge between QwtPlot and ErgFile to avoid having to // create a separate array for the ergfile data, we plot // directly from the ErgFile points array double ErgFileData::x(size_t i) const { - if (main->context->currentErgFile()) return main->context->currentErgFile()->Points.at(i).x; + if (context->currentErgFile()) return context->currentErgFile()->Points.at(i).x; else return 0; } double ErgFileData::y(size_t i) const { - if (main->context->currentErgFile()) return main->context->currentErgFile()->Points.at(i).y; + if (context->currentErgFile()) return context->currentErgFile()->Points.at(i).y; else return 0; } size_t ErgFileData::size() const { - if (main->context->currentErgFile()) return main->context->currentErgFile()->Points.count(); + if (context->currentErgFile()) return context->currentErgFile()->Points.count(); else return 0; } @@ -44,10 +46,10 @@ QPointF ErgFileData::sample(size_t i) const QRectF ErgFileData::boundingRect() const { - if (main->context->currentErgFile()) { + if (context->currentErgFile()) { double minX, minY, maxX, maxY; minX=minY=maxX=maxY=0.0f; - foreach(ErgFilePoint x, main->context->currentErgFile()->Points) { + foreach(ErgFilePoint x, context->currentErgFile()->Points) { if (x.y > maxY) maxY = x.y; if (x.x > maxX) maxX = x.x; if (x.y < minY) minY = x.y; @@ -61,10 +63,10 @@ QRectF ErgFileData::boundingRect() const // Now bar -double NowData::x(size_t) const { return main->context->getNow(); } +double NowData::x(size_t) const { return context->getNow(); } double NowData::y(size_t i) const { if (i) { - if (main->context->currentErgFile()) return main->context->currentErgFile()->maxY; + if (context->currentErgFile()) return context->currentErgFile()->maxY; else return 0; } else return 0; } @@ -82,7 +84,7 @@ QPointF NowData::sample(size_t i) const return QRectF(0, 0, 0, 0); }*/ -ErgFilePlot::ErgFilePlot(MainWindow *main) : main(main) +ErgFilePlot::ErgFilePlot(Context *context) : context(context) { setInstanceName("ErgFile Plot"); @@ -144,7 +146,7 @@ ErgFilePlot::ErgFilePlot(MainWindow *main) : main(main) enableAxis(yRight2, false); // data bridge to ergfile - lodData = new ErgFileData(main); + lodData = new ErgFileData(context); // Load Curve LodCurve = new QwtPlotCurve("Course Load"); LodCurve->setData(lodData); @@ -197,7 +199,7 @@ ErgFilePlot::ErgFilePlot(MainWindow *main) : main(main) speedCurve->setData(speedData->x(), speedData->y(), speedData->count()); // Now data bridge - nowData = new NowData(main); + nowData = new NowData(context); // Now pointer NowCurve = new QwtPlotCurve("Now"); @@ -292,8 +294,8 @@ ErgFilePlot::setData(ErgFile *ergfile) } // set the axis so we use all the screen estate - if (main->context->currentErgFile() && main->context->currentErgFile()->Points.count()) { - double maxX = (double)main->context->currentErgFile()->Points.last().x; + if (context->currentErgFile() && context->currentErgFile()->Points.count()) { + double maxX = (double)context->currentErgFile()->Points.last().x; if (bydist) { diff --git a/src/ErgFilePlot.h b/src/ErgFilePlot.h index 16c96aa68..1b805beca 100644 --- a/src/ErgFilePlot.h +++ b/src/ErgFilePlot.h @@ -19,7 +19,7 @@ #ifndef _GC_ErgFilePlot_h #define _GC_ErgFilePlot_h 1 #include "GoldenCheetah.h" -#include "MainWindow.h" +#include "Context.h" #include #include @@ -47,13 +47,13 @@ class ErgFileData : public QwtPointArrayData { public: - ErgFileData (MainWindow *main) : QwtPointArrayData(QVector(), QVector()), main(main) {} + ErgFileData (Context *context) : QwtPointArrayData(QVector(), QVector()), context(context) {} double x(size_t i) const ; double y(size_t i) const ; size_t size() const ; private: - MainWindow *main; + Context *context; virtual QPointF sample(size_t i) const; virtual QRectF boundingRect() const; @@ -62,14 +62,14 @@ class ErgFileData : public QwtPointArrayData class NowData : public QwtPointArrayData { public: - NowData (MainWindow *main) : QwtPointArrayData(QVector(), QVector()), main(main) {} + NowData (Context *context) : QwtPointArrayData(QVector(), QVector()), context(context) {} double x(size_t i) const ; double y(size_t i) const ; size_t size() const ; void init() ; private: - MainWindow *main; + Context *context; virtual QPointF sample(size_t i) const; //virtual QRectF boundingRect() const; @@ -128,7 +128,7 @@ class ErgFilePlot : public QwtPlot public: - ErgFilePlot(MainWindow *main); + ErgFilePlot(Context *context); QList Marks; void setData(ErgFile *); // set the course @@ -142,7 +142,7 @@ class ErgFilePlot : public QwtPlot private: - MainWindow *main; + Context *context; bool bydist; ErgFile *ergFile; diff --git a/src/FitlogRideFile.cpp b/src/FitlogRideFile.cpp index 8e33df846..c3d347506 100644 --- a/src/FitlogRideFile.cpp +++ b/src/FitlogRideFile.cpp @@ -20,7 +20,8 @@ #include "FitlogParser.h" #include -#include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "RideMetric.h" #ifndef GC_VERSION @@ -50,7 +51,7 @@ RideFile *FitlogFileReader::openRideFile(QFile &file, QStringList &errors, QList } bool -FitlogFileReader::writeRideFile(MainWindow *mainWindow, const RideFile *ride, QFile &file) const +FitlogFileReader::writeRideFile(Context *context, const RideFile *ride, QFile &file) const { QDomText text; QDomDocument doc; @@ -69,7 +70,7 @@ FitlogFileReader::writeRideFile(MainWindow *mainWindow, const RideFile *ride, QF fitnessWorkbook.appendChild(athleteLog); QDomElement athlete = doc.createElement("Athlete"); - athlete.setAttribute("athlete",mainWindow->athlete->cyclist); + athlete.setAttribute("athlete",context->athlete->cyclist); athleteLog.appendChild(athlete); QDomElement activity = doc.createElement("Activity"); @@ -100,7 +101,7 @@ FitlogFileReader::writeRideFile(MainWindow *mainWindow, const RideFile *ride, QF QStringList worklist = QStringList(); for (int i=0; metrics[i];i++) worklist << metrics[i]; - QHash computed = RideMetric::computeMetrics(mainWindow, ride, mainWindow->athlete->zones(), mainWindow->athlete->hrZones(), worklist); + QHash computed = RideMetric::computeMetrics(context, ride, context->athlete->zones(), context->athlete->hrZones(), worklist); QDomElement duration = doc.createElement("Duration"); duration.setAttribute("TotalSeconds", QString("%1").arg(computed.value("workout_time")->value(true))); @@ -157,7 +158,7 @@ FitlogFileReader::writeRideFile(MainWindow *mainWindow, const RideFile *ride, QF } computed = - RideMetric::computeMetrics(mainWindow, &f, mainWindow->athlete->zones(), mainWindow->athlete->hrZones(), worklist); + RideMetric::computeMetrics(context, &f, context->athlete->zones(), context->athlete->hrZones(), worklist); QDomElement lap = doc.createElement("Lap"); lap.setAttribute("StartTime", ride->startTime().addSecs(interval.start).toString(Qt::ISODate)+"Z"); diff --git a/src/FitlogRideFile.h b/src/FitlogRideFile.h index 016a09ad5..4e78b5f98 100644 --- a/src/FitlogRideFile.h +++ b/src/FitlogRideFile.h @@ -24,7 +24,7 @@ struct FitlogFileReader : public RideFileReader { virtual RideFile *openRideFile(QFile &file, QStringList &errors, QList* = 0) const; - bool writeRideFile(MainWindow *mainWindow, const RideFile *ride, QFile &file) const; + bool writeRideFile(Context *context, const RideFile *ride, QFile &file) const; bool hasWrite() const { return true; } }; diff --git a/src/GcBubble.cpp b/src/GcBubble.cpp index 908e5123b..a4549ebad 100644 --- a/src/GcBubble.cpp +++ b/src/GcBubble.cpp @@ -26,13 +26,17 @@ static const int spikeMargin = 40; #include "GcBubble.h" +#include "Athlete.h" +#include "MainWindow.h" #include "MetricAggregator.h" #include "SummaryMetrics.h" #include "DBAccess.h" #include "Settings.h" #include "Units.h" -GcBubble::GcBubble(MainWindow *parent) : QWidget(parent, Qt::FramelessWindowHint), mainWindow(parent), borderWidth(3), parent(parent), orientation(Qt::Horizontal) +GcBubble::GcBubble(Context *context) : + QWidget(context->mainWindow, Qt::FramelessWindowHint), + context(context), borderWidth(3), orientation(Qt::Horizontal) { setAttribute(Qt::WA_DeleteOnClose); setAttribute(Qt::WA_TranslucentBackground); @@ -211,7 +215,7 @@ GcBubble::paintEvent(QPaintEvent *) void GcBubble::setPos(int x, int y, Qt::Orientation orientation) // always uses global co-ords { - QPoint here = parent->mapFromGlobal(QPoint(x,y)); + QPoint here = context->mainWindow->mapFromGlobal(QPoint(x,y)); this->orientation = orientation; // set to as big as possible @@ -222,7 +226,7 @@ GcBubble::setPos(int x, int y, Qt::Orientation orientation) // always uses globa if (orientation == Qt::Horizontal) { // would the window be off mainwindow? - if ((x+width()) > parent->geometry().x()+parent->geometry().width()) { + if ((x+width()) > context->mainWindow->geometry().x()+context->mainWindow->geometry().width()) { spikePosition = right; } else { spikePosition = left; @@ -232,7 +236,7 @@ GcBubble::setPos(int x, int y, Qt::Orientation orientation) // always uses globa } else { // would the window be off mainwindow? - if ((y-height()) < (parent->geometry().y()+40)) { // +40 for menu and title bar + if ((y-height()) < (context->mainWindow->geometry().y()+40)) { // +40 for menu and title bar spikePosition = top; } else { spikePosition = bottom; @@ -246,12 +250,12 @@ GcBubble::setPos(int x, int y, Qt::Orientation orientation) // always uses globa // stay visible in mainwindow if (orientation == Qt::Horizontal) { - if (y-(height()/2) < (parent->geometry().y()+40)) { // +40 for menu and title bar of mainwindow + if (y-(height()/2) < (context->mainWindow->geometry().y()+40)) { // +40 for menu and title bar of mainwindow // put it at the top if (spikePosition == left) start = QPoint(lineWidth, 40); else start = QPoint(width()-lineWidth, 40); - } else if (y+(height()/2) > (parent->geometry().y()+parent->geometry().height())) { + } else if (y+(height()/2) > (context->mainWindow->geometry().y()+context->mainWindow->geometry().height())) { // put it at the bottom if (spikePosition == left) start = QPoint(lineWidth, height()-40); else start = QPoint(width()-lineWidth, height()-40); @@ -265,12 +269,12 @@ GcBubble::setPos(int x, int y, Qt::Orientation orientation) // always uses globa } else { // Qt::Vertical - if (x-(width()/2) < parent->geometry().x()) { + if (x-(width()/2) < context->mainWindow->geometry().x()) { // put it at the left if (spikePosition == top) start = QPoint(40, lineWidth); else start = QPoint(40, height()-lineWidth); - } else if (x+(width()/2) > (parent->geometry().x()+parent->geometry().width())) { + } else if (x+(width()/2) > (context->mainWindow->geometry().x()+context->mainWindow->geometry().width())) { // put it at the right if (spikePosition == top) start = QPoint(width()-40, lineWidth); else start = QPoint(width()-40, height()-lineWidth); @@ -411,8 +415,8 @@ GcBubble::setPos(int x, int y, Qt::Orientation orientation) // always uses globa void GcBubble::setText(QString filename) { - SummaryMetrics metrics = parent->athlete->metricDB->getAllMetricsFor(filename); - useMetricUnits = mainWindow->athlete->useMetricUnits; + SummaryMetrics metrics = context->athlete->metricDB->getAllMetricsFor(filename); + useMetricUnits = context->athlete->useMetricUnits; // diff --git a/src/GcBubble.h b/src/GcBubble.h index 06703cd75..e65c802ec 100644 --- a/src/GcBubble.h +++ b/src/GcBubble.h @@ -19,7 +19,7 @@ #ifndef _GC_GcBubble_h #define _GC_GcBubble_h 1 #include "GoldenCheetah.h" -#include "MainWindow.h" +#include "Context.h" #include #include "Colors.h" @@ -30,7 +30,7 @@ class GcBubble : public QWidget G_OBJECT public: - GcBubble(MainWindow *parent = NULL); + GcBubble(Context *context = NULL); void setText(QString); // set the text displayed according to filename protected: @@ -47,10 +47,9 @@ class GcBubble : public QWidget virtual void paintEvent(QPaintEvent *); private: - MainWindow *mainWindow; + Context *context; int borderWidth; - MainWindow *parent; QPoint start; // where the bubble spike is QPoint coords; // where on the screen (global) the bubble should be placed diff --git a/src/GcCalendar.cpp b/src/GcCalendar.cpp index 24bd9c2bb..95bf41ed8 100644 --- a/src/GcCalendar.cpp +++ b/src/GcCalendar.cpp @@ -17,6 +17,8 @@ */ #include "GcCalendar.h" +#include "Athlete.h" +#include "Context.h" #include "GcWindowLayout.h" #include "Settings.h" #include @@ -26,7 +28,7 @@ //******************************************************************************** // CALENDAR SIDEBAR (GcCalendar) //******************************************************************************** -GcCalendar::GcCalendar(MainWindow *main) : main(main) +GcCalendar::GcCalendar(Context *context) : context(context) { setContentsMargins(0,0,0,0); setAutoFillBackground(true); @@ -70,13 +72,13 @@ GcCalendar::GcCalendar(MainWindow *main) : main(main) splitter->addWidget(calendarItem); splitter->addWidget(summaryItem); - splitter->prepare(main->athlete->cyclist, "diary"); + splitter->prepare(context->athlete->cyclist, "diary"); black.setColor(QPalette::WindowText, Qt::gray); white.setColor(QPalette::WindowText, Qt::white); grey.setColor(QPalette::WindowText, Qt::gray); - multiCalendar = new GcMultiCalendar(main); + multiCalendar = new GcMultiCalendar(context); layout->addWidget(multiCalendar); // Summary level selector @@ -110,9 +112,9 @@ GcCalendar::GcCalendar(MainWindow *main) : main(main) connect(summarySelect, SIGNAL(currentIndexChanged(int)), this, SLOT(refresh())); // refresh on these events... - connect(main, SIGNAL(rideAdded(RideItem*)), this, SLOT(refresh())); - connect(main, SIGNAL(rideDeleted(RideItem*)), this, SLOT(refresh())); - connect(main->context, SIGNAL(configChanged()), this, SLOT(refresh())); + connect(context->mainWindow, SIGNAL(rideAdded(RideItem*)), this, SLOT(refresh())); + connect(context->mainWindow, SIGNAL(rideDeleted(RideItem*)), this, SLOT(refresh())); + connect(context, SIGNAL(configChanged()), this, SLOT(refresh())); // set up for current selections refresh(); @@ -222,7 +224,7 @@ void GcCalendar::setSummary() { // are we metric? - bool useMetricUnits = main->athlete->useMetricUnits; + bool useMetricUnits = context->athlete->useMetricUnits; // where we construct the text QString summaryText(""); @@ -288,7 +290,7 @@ GcCalendar::setSummary() to = newTo; // lets get the metrics - QListresults = main->athlete->metricDB->getAllMetricsFor(QDateTime(from,QTime(0,0,0)), QDateTime(to, QTime(24,59,59))); + QListresults = context->athlete->metricDB->getAllMetricsFor(QDateTime(from,QTime(0,0,0)), QDateTime(to, QTime(24,59,59))); // foreach of the metrics get an aggregated value // header of summary @@ -340,7 +342,7 @@ GcCalendar::setSummary() const RideMetric *metric = RideMetricFactory::instance().rideMetric(metricname); QStringList empty; // usually for filters, but we don't do that - QString value = SummaryMetrics::getAggregated(main, metricname, results, empty, false, useMetricUnits); + QString value = SummaryMetrics::getAggregated(context, metricname, results, empty, false, useMetricUnits); // Maximum Max and Average Average looks nasty, remove from name for display @@ -392,7 +394,7 @@ GcCalendar::setSummary() //******************************************************************************** // MINI CALENDAR (GcMiniCalendar) //******************************************************************************** -GcMiniCalendar::GcMiniCalendar(MainWindow *main, bool master) : main(main), master(master) +GcMiniCalendar::GcMiniCalendar(Context *context, bool master) : context(context), master(master) { setContentsMargins(0,0,0,0); setAutoFillBackground(true); @@ -410,9 +412,9 @@ GcMiniCalendar::GcMiniCalendar(MainWindow *main, bool master) : main(main), mast grey.setColor(QPalette::WindowText, Qt::gray); // get the model - fieldDefinitions = main->athlete->rideMetadata()->getFields(); - calendarModel = new GcCalendarModel(this, &fieldDefinitions, main); - calendarModel->setSourceModel(main->listView->sqlModel); + fieldDefinitions = context->athlete->rideMetadata()->getFields(); + calendarModel = new GcCalendarModel(this, &fieldDefinitions, context); + calendarModel->setSourceModel(context->mainWindow->listView->sqlModel); QHBoxLayout *line = new QHBoxLayout; line->setSpacing(0); @@ -584,7 +586,7 @@ GcMiniCalendar::event(QEvent *e) { if (e->type() != QEvent::ToolTip && e->type() != QEvent::Paint && e->type() != QEvent::Destroy && e->type() != QEvent::LayoutRequest) { - main->setBubble(""); + context->mainWindow->setBubble(""); } if (e->type() == QEvent::Paint) { @@ -615,7 +617,7 @@ GcMiniCalendar::event(QEvent *e) // Popup bubble for ride if (files.count()) { if (files[0] == "calendar") ; // handle planned rides - else main->setBubble(files.at(0), mapToGlobal(pos+QPoint(+2,+2))); + else context->mainWindow->setBubble(files.at(0), mapToGlobal(pos+QPoint(+2,+2))); } } n++; @@ -638,14 +640,14 @@ GcMiniCalendar::dayClicked(int i) QStringList files = calendarModel->data(p, GcCalendarModel::FilenamesRole).toStringList(); if (files.count()) // if more than one file cycle through them? - main->selectRideFile(QFileInfo(files[0]).fileName()); + context->mainWindow->selectRideFile(QFileInfo(files[0]).fileName()); } void GcMiniCalendar::previous() { - QList allDates = main->athlete->metricDB->db()->getAllDates(); + QList allDates = context->athlete->metricDB->db()->getAllDates(); qSort(allDates); // begin of month @@ -667,7 +669,7 @@ GcMiniCalendar::previous() if (date == heredate) { // select this ride... QStringList files = calendarModel->data(p, GcCalendarModel::FilenamesRole).toStringList(); - if (files.count()) main->selectRideFile(QFileInfo(files[0]).fileName()); + if (files.count()) context->mainWindow->selectRideFile(QFileInfo(files[0]).fileName()); } } emit dateChanged(month,year); @@ -679,7 +681,7 @@ GcMiniCalendar::previous() void GcMiniCalendar::next() { - QList allDates = main->athlete->metricDB->db()->getAllDates(); + QList allDates = context->athlete->metricDB->db()->getAllDates(); qSort(allDates); // end of month @@ -700,7 +702,7 @@ GcMiniCalendar::next() if (date == heredate) { // select this ride... QStringList files = calendarModel->data(p, GcCalendarModel::FilenamesRole).toStringList(); - if (files.count()) main->selectRideFile(QFileInfo(files[0]).fileName()); + if (files.count()) context->mainWindow->selectRideFile(QFileInfo(files[0]).fileName()); } } emit dateChanged(month,year); @@ -811,7 +813,7 @@ GcMiniCalendar::setDate(int _month, int _year) //******************************************************************************** // MULTI CALENDAR (GcMultiCalendar) //******************************************************************************** -GcMultiCalendar::GcMultiCalendar(MainWindow *main) : QScrollArea(main), main(main), active(false) +GcMultiCalendar::GcMultiCalendar(Context *context) : QScrollArea(context->mainWindow), context(context), active(false) { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setContentsMargins(0,0,0,0); @@ -826,7 +828,7 @@ GcMultiCalendar::GcMultiCalendar(MainWindow *main) : QScrollArea(main), main(mai pal.setColor(QPalette::Window, Qt::white); setPalette(pal); - GcMiniCalendar *mini = new GcMiniCalendar(main, true); + GcMiniCalendar *mini = new GcMiniCalendar(context, true); calendars.append(mini); mini->setDate(QDate::currentDate().month(), QDate::currentDate().year()); // default to this month layout->addWidget(mini); @@ -919,7 +921,7 @@ GcMultiCalendar::resizeEvent(QResizeEvent*) if (showing > calendars.count()) { for (int i=have; isetFilter(this->filters); calendars.append(mini); layout->insert(i, mini); diff --git a/src/GcCalendar.h b/src/GcCalendar.h index 0e02883bc..6e3824bbf 100644 --- a/src/GcCalendar.h +++ b/src/GcCalendar.h @@ -24,7 +24,8 @@ #include #include -#include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "TimeUtils.h" #include "GcCalendarModel.h" #include "RideItem.h" @@ -75,7 +76,7 @@ class GcMiniCalendar : public QWidget public: - GcMiniCalendar(MainWindow *, bool master); + GcMiniCalendar(Context *, bool master); void setDate(int month, int year); void getDate(int &_month, int &_year) { _month = month; _year = year; } @@ -99,7 +100,7 @@ class GcMiniCalendar : public QWidget void dateChanged(int month, int year); protected: - MainWindow *main; + Context *context; RideItem *_ride; int month, year; @@ -127,7 +128,7 @@ class GcMultiCalendar : public QScrollArea public: - GcMultiCalendar(MainWindow*); + GcMultiCalendar(Context *); void refresh(); public slots: @@ -142,7 +143,7 @@ class GcMultiCalendar : public QScrollArea private: GcWindowLayout *layout; QVector calendars; - MainWindow *main; + Context *context; int showing; QStringList filters; bool active; @@ -157,7 +158,7 @@ class GcCalendar : public QWidget // not a GcWindow - belongs on sidebar public: - GcCalendar(MainWindow *); + GcCalendar(Context *); public slots: @@ -172,7 +173,7 @@ class GcCalendar : public QWidget // not a GcWindow - belongs on sidebar void dateRangeChanged(DateRange); protected: - MainWindow *main; + Context *context; RideItem *_ride; int month, year; diff --git a/src/GcCalendarModel.h b/src/GcCalendarModel.h index b82b9a4a3..852a4dde8 100644 --- a/src/GcCalendarModel.h +++ b/src/GcCalendarModel.h @@ -40,6 +40,9 @@ #include #include "qxtscheduleview.h" #include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" +#include "RideItem.h" #include "RideMetadata.h" #ifdef GC_HAVE_ICAL #include "ICalendar.h" @@ -65,7 +68,7 @@ private: QMap * > dateToRows; // map a date to SQL rows QList columns; // what columns in the sql model - MainWindow *mainWindow; + Context *context; int filenameIndex, durationIndex, dateIndex, textIndex, colorIndex; public slots: @@ -135,7 +138,7 @@ public slots: public: - GcCalendarModel(QWidget *parent, QList *, MainWindow *main) : QAbstractProxyModel(parent), mainWindow(main) { + GcCalendarModel(QWidget *parent, QList *, Context *context) : QAbstractProxyModel(parent), context(context) { setParent(parent); stale = true; @@ -143,9 +146,9 @@ public: setMonth(today.month(), today.year()); // invalidate model if rides added or deleted or filter applier - connect(main, SIGNAL(rideAdded(RideItem*)), this, SLOT(rideChange(RideItem*))); - connect(main, SIGNAL(rideDeleted(RideItem*)), this, SLOT(rideChange(RideItem*))); - connect(main, SIGNAL(filterChanged(QStringList&)), this, SLOT(setStale())); + connect(context->mainWindow, SIGNAL(rideAdded(RideItem*)), this, SLOT(rideChange(RideItem*))); + connect(context->mainWindow, SIGNAL(rideDeleted(RideItem*)), this, SLOT(rideChange(RideItem*))); + connect(context->mainWindow, SIGNAL(filterChanged(QStringList&)), this, SLOT(setStale())); } ~GcCalendarModel() {} @@ -178,7 +181,7 @@ public: connect(model, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)), this, SLOT(refresh())); connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(refresh())); #ifdef GC_HAVE_ICAL - connect(mainWindow->athlete->rideCalendar, SIGNAL(dataChanged()), this, SLOT(refresh())); + connect(context->athlete->rideCalendar, SIGNAL(dataChanged()), this, SLOT(refresh())); #endif refresh(); } @@ -238,7 +241,7 @@ public: QVector *arr = dateToRows.value(date(proxyIndex), NULL); if (arr) { foreach (int i, *arr) { - if (mainWindow->context->rideItem() && sourceModel()->data(index(i, dateIndex, QModelIndex())).toDateTime() == mainWindow->context->rideItem()->dateTime) { + if (context->rideItem() && sourceModel()->data(index(i, dateIndex, QModelIndex())).toDateTime() == context->rideItem()->dateTime) { colors << GColor(CCALCURRENT); // its the current ride! } else { colors << QColor(sourceModel()->data(index(i, colorIndex, QModelIndex())).toString()); @@ -248,7 +251,7 @@ public: #ifdef GC_HAVE_ICAL // added planned workouts - for (int k= mainWindow->athlete->rideCalendar->data(date(proxyIndex), EventCountRole).toInt(); k>0; k--) + for (int k= context->athlete->rideCalendar->data(date(proxyIndex), EventCountRole).toInt(); k>0; k--) colors.append(GColor(CCALPLANNED)); #endif @@ -263,7 +266,7 @@ public: if (arr) { foreach (int i, *arr) { QString filename = sourceModel()->data(index(i, filenameIndex, QModelIndex())).toString(); - if (mainWindow->isfiltered && mainWindow->filters.contains(filename)) + if (context->mainWindow->isfiltered && context->mainWindow->filters.contains(filename)) colors << GColor(CCALCURRENT); else colors << QColor(Qt::black); @@ -272,7 +275,7 @@ public: #ifdef GC_HAVE_ICAL // added planned workouts - for (int k= mainWindow->athlete->rideCalendar->data(date(proxyIndex), EventCountRole).toInt(); k>0; k--) + for (int k= context->athlete->rideCalendar->data(date(proxyIndex), EventCountRole).toInt(); k>0; k--) colors.append(Qt::black); #endif @@ -319,8 +322,8 @@ public: #ifdef GC_HAVE_ICAL // fold in planned workouts - if (mainWindow->athlete->rideCalendar->data(date(proxyIndex), EventCountRole).toInt()) { - foreach(QString x, mainWindow->athlete->rideCalendar->data(date(proxyIndex), Qt::DisplayRole).toStringList()) + if (context->athlete->rideCalendar->data(date(proxyIndex), EventCountRole).toInt()) { + foreach(QString x, context->athlete->rideCalendar->data(date(proxyIndex), Qt::DisplayRole).toStringList()) filenames << "calendar"; } #endif @@ -341,9 +344,9 @@ public: #ifdef GC_HAVE_ICAL // fold in planned workouts - if (mainWindow->athlete->rideCalendar->data(date(proxyIndex), EventCountRole).toInt()) { + if (context->athlete->rideCalendar->data(date(proxyIndex), EventCountRole).toInt()) { QStringList planned; - planned = mainWindow->athlete->rideCalendar->data(date(proxyIndex), Qt::DisplayRole).toStringList(); + planned = context->athlete->rideCalendar->data(date(proxyIndex), Qt::DisplayRole).toStringList(); strings << planned; } #endif diff --git a/src/GcCrashDialog.cpp b/src/GcCrashDialog.cpp index de168f54f..b5ad2bce5 100644 --- a/src/GcCrashDialog.cpp +++ b/src/GcCrashDialog.cpp @@ -25,6 +25,7 @@ #include "DBAccess.h" #include "MetricAggregator.h" #include +#include #define GCC_VERSION QString("%1.%2.%3").arg(__GNUC__).arg(__GNUC_MINOR__).arg(__GNUC_PATCHLEVEL__) diff --git a/src/GcRideFile.cpp b/src/GcRideFile.cpp index c1aece2d7..498ec36d0 100644 --- a/src/GcRideFile.cpp +++ b/src/GcRideFile.cpp @@ -173,7 +173,7 @@ GcFileReader::openRideFile(QFile &file, QStringList &errors, QList*) if (present->name) \ sample.setAttribute(#name, QString("%1").arg(point->name, 0, 'g', 11)); bool -GcFileReader::writeRideFile(MainWindow *,const RideFile *ride, QFile &file) const +GcFileReader::writeRideFile(Context *,const RideFile *ride, QFile &file) const { QDomDocument doc("GoldenCheetah"); QDomElement root = doc.createElement("ride"); diff --git a/src/GcRideFile.h b/src/GcRideFile.h index de742d6ca..e3c86e411 100644 --- a/src/GcRideFile.h +++ b/src/GcRideFile.h @@ -24,7 +24,7 @@ struct GcFileReader : public RideFileReader { virtual RideFile *openRideFile(QFile &file, QStringList &errors, QList* = 0) const; - bool writeRideFile(MainWindow *, const RideFile *ride, QFile &file) const; + bool writeRideFile(Context *, const RideFile *ride, QFile &file) const; bool hasWrite() const { return true; } }; diff --git a/src/GcScopeBar.cpp b/src/GcScopeBar.cpp index 24fcdfc50..e3d27c904 100644 --- a/src/GcScopeBar.cpp +++ b/src/GcScopeBar.cpp @@ -18,10 +18,10 @@ #include "GcScopeBar.h" #include "GcCalendar.h" -#include "MainWindow.h" +#include "Context.h" #include "QtMacButton.h" -GcScopeBar::GcScopeBar(MainWindow *main, QWidget *traintool) : QWidget(main), mainWindow(main) +GcScopeBar::GcScopeBar(Context *context, QWidget *traintool) : QWidget(context->mainWindow), context(context) { setFixedHeight(23); @@ -51,7 +51,7 @@ GcScopeBar::GcScopeBar(MainWindow *main, QWidget *traintool) : QWidget(main), ma searchLabel->hide(); #ifdef GC_HAVE_LUCENE - connect(mainWindow, SIGNAL(filterChanged(QStringList&)), this, SLOT(setHighlighted())); + connect(context->mainWindow, SIGNAL(filterChanged(QStringList&)), this, SLOT(setHighlighted())); #endif // Mac uses QtMacButton - recessed etc @@ -120,7 +120,7 @@ void GcScopeBar::setHighlighted() { #ifdef GC_HAVE_LUCENE - if (mainWindow->isfiltered) { + if (context->mainWindow->isfiltered) { searchLabel->setHighlighted(true); searchLabel->show(); #ifndef Q_OS_MAC diff --git a/src/GcScopeBar.h b/src/GcScopeBar.h index 47d4f2701..339e4d808 100644 --- a/src/GcScopeBar.h +++ b/src/GcScopeBar.h @@ -23,7 +23,7 @@ #include #include -class MainWindow; +class Context; #ifdef Q_OS_MAC class QtMacButton; #else @@ -59,7 +59,7 @@ class GcScopeBar : public QWidget public: - GcScopeBar(MainWindow *parent, QWidget *traintool); + GcScopeBar(Context *context, QWidget *traintool); ~GcScopeBar(); public slots: @@ -87,7 +87,7 @@ signals: private: void paintBackground(QPaintEvent *); - MainWindow *mainWindow; + Context *context; QHBoxLayout *layout; GcLabel *searchLabel; #ifdef Q_OS_MAC diff --git a/src/GcWindowRegistry.cpp b/src/GcWindowRegistry.cpp index a48988e23..ddbc67293 100644 --- a/src/GcWindowRegistry.cpp +++ b/src/GcWindowRegistry.cpp @@ -18,6 +18,7 @@ #include "GoldenCheetah.h" #include "GcWindowRegistry.h" +#include "Athlete.h" // all the windows we have defined #include "AerolabWindow.h" @@ -48,6 +49,7 @@ #include "SummaryWindow.h" #include "MetadataWindow.h" #include "TreeMapWindow.h" +#include "RideWindow.h" #include "DialWindow.h" #include "RealtimePlotWindow.h" #include "SpinScanPlotWindow.h" @@ -104,54 +106,54 @@ GcWindowRegistry::initialize() // instantiate a new window GcWindow * -GcWindowRegistry::newGcWindow(GcWinID id, MainWindow *main) +GcWindowRegistry::newGcWindow(GcWinID id, Context *context) { GcWindow *returning = NULL; switch(id) { - case GcWindowTypes::Aerolab: returning = new AerolabWindow(main); break; - case GcWindowTypes::AllPlot: returning = new AllPlotWindow(main); break; - case GcWindowTypes::CriticalPower: returning = new CriticalPowerWindow(main->athlete->home, main); break; - case GcWindowTypes::CriticalPowerSummary: returning = new CriticalPowerWindow(main->athlete->home, main, true); break; + case GcWindowTypes::Aerolab: returning = new AerolabWindow(context); break; + case GcWindowTypes::AllPlot: returning = new AllPlotWindow(context); break; + case GcWindowTypes::CriticalPower: returning = new CriticalPowerWindow(context->athlete->home, context); break; + case GcWindowTypes::CriticalPowerSummary: returning = new CriticalPowerWindow(context->athlete->home, context, true); break; #ifdef GC_HAVE_ICAL - case GcWindowTypes::Diary: returning = new DiaryWindow(main); break; + case GcWindowTypes::Diary: returning = new DiaryWindow(context); break; #else case GcWindowTypes::Diary: returning = new GcWindow(); break; #endif - case GcWindowTypes::GoogleMap: returning = new GoogleMapControl(main); break; - case GcWindowTypes::Histogram: returning = new HistogramWindow(main); break; - case GcWindowTypes::Distribution: returning = new HistogramWindow(main, true); break; - case GcWindowTypes::LTM: returning = new LTMWindow(main); break; + case GcWindowTypes::GoogleMap: returning = new GoogleMapControl(context); break; + case GcWindowTypes::Histogram: returning = new HistogramWindow(context); break; + case GcWindowTypes::Distribution: returning = new HistogramWindow(context, true); break; + case GcWindowTypes::LTM: returning = new LTMWindow(context); break; #ifdef GC_HAVE_QWTPLOT3D - case GcWindowTypes::Model: returning = new ModelWindow(main, main->athlete->home); break; + case GcWindowTypes::Model: returning = new ModelWindow(context, context->athlete->home); break; #else case GcWindowTypes::Model: returning = new GcWindow(); break; #endif - case GcWindowTypes::PerformanceManager: returning = new PerformanceManagerWindow(main); break; - case GcWindowTypes::PfPv: returning = new PfPvWindow(main); break; - case GcWindowTypes::HrPw: returning = new HrPwWindow(main); break; - case GcWindowTypes::RideEditor: returning = new RideEditor(main); break; - case GcWindowTypes::RideSummary: returning = new RideSummaryWindow(main, true); break; - case GcWindowTypes::DateRangeSummary: returning = new RideSummaryWindow(main, false); break; - case GcWindowTypes::Scatter: returning = new ScatterWindow(main, main->athlete->home); break; - case GcWindowTypes::Summary: returning = new SummaryWindow(main); break; - case GcWindowTypes::TreeMap: returning = new TreeMapWindow(main); break; - case GcWindowTypes::WeeklySummary: returning = new SummaryWindow(main); break; // deprecated + case GcWindowTypes::PerformanceManager: returning = new PerformanceManagerWindow(context); break; + case GcWindowTypes::PfPv: returning = new PfPvWindow(context); break; + case GcWindowTypes::HrPw: returning = new HrPwWindow(context); break; + case GcWindowTypes::RideEditor: returning = new RideEditor(context); break; + case GcWindowTypes::RideSummary: returning = new RideSummaryWindow(context, true); break; + case GcWindowTypes::DateRangeSummary: returning = new RideSummaryWindow(context, false); break; + case GcWindowTypes::Scatter: returning = new ScatterWindow(context, context->athlete->home); break; + case GcWindowTypes::Summary: returning = new SummaryWindow(context); break; + case GcWindowTypes::TreeMap: returning = new TreeMapWindow(context); break; + case GcWindowTypes::WeeklySummary: returning = new SummaryWindow(context); break; // deprecated #if defined Q_OS_MAC || defined GC_HAVE_VLC // mac uses Quicktime / Win/Linux uses VLC - case GcWindowTypes::VideoPlayer: returning = new VideoWindow(main, main->athlete->home); break; + case GcWindowTypes::VideoPlayer: returning = new VideoWindow(context, context->athlete->home); break; #else case GcWindowTypes::VideoPlayer: returning = new GcWindow(); break; #endif - case GcWindowTypes::DialWindow: returning = new DialWindow(main); break; - case GcWindowTypes::MetadataWindow: returning = new MetadataWindow(main); break; + case GcWindowTypes::DialWindow: returning = new DialWindow(context); break; + case GcWindowTypes::MetadataWindow: returning = new MetadataWindow(context); break; case GcWindowTypes::RealtimeControls: returning = new GcWindow(); break; - case GcWindowTypes::RealtimePlot: returning = new RealtimePlotWindow(main); break; - case GcWindowTypes::SpinScanPlot: returning = new SpinScanPlotWindow(main); break; - case GcWindowTypes::WorkoutPlot: returning = new WorkoutPlotWindow(main); break; - case GcWindowTypes::BingMap: returning = new BingMap(main); break; - case GcWindowTypes::MapWindow: returning = new MapWindow(main); break; - case GcWindowTypes::StreetViewWindow: returning = new StreetViewWindow(main); break; - case GcWindowTypes::ActivityNavigator: returning = new RideNavigator(main); break; + case GcWindowTypes::RealtimePlot: returning = new RealtimePlotWindow(context); break; + case GcWindowTypes::SpinScanPlot: returning = new SpinScanPlotWindow(context); break; + case GcWindowTypes::WorkoutPlot: returning = new WorkoutPlotWindow(context); break; + case GcWindowTypes::BingMap: returning = new BingMap(context); break; + case GcWindowTypes::MapWindow: returning = new MapWindow(context); break; + case GcWindowTypes::StreetViewWindow: returning = new StreetViewWindow(context); break; + case GcWindowTypes::ActivityNavigator: returning = new RideNavigator(context); break; default: return NULL; break; } if (returning) returning->setProperty("type", QVariant::fromValue(id)); diff --git a/src/GcWindowRegistry.h b/src/GcWindowRegistry.h index b54cd7da1..235c8cb60 100644 --- a/src/GcWindowRegistry.h +++ b/src/GcWindowRegistry.h @@ -22,7 +22,7 @@ #include "GoldenCheetah.h" #include -class MainWindow; +class Context; // all the windows we have defined namespace GcWindowTypes { @@ -80,7 +80,7 @@ class GcWindowRegistry { GcWinID id; static void initialize(); // initialize global registry - static GcWindow *newGcWindow(GcWinID id, MainWindow *main); //XXX main is gonna go + static GcWindow *newGcWindow(GcWinID id, Context *context); //XXX main is gonna go }; extern GcWindowRegistry* GcWindows; diff --git a/src/GcWindowTool.h b/src/GcWindowTool.h index 2a80f5d6e..c11119630 100644 --- a/src/GcWindowTool.h +++ b/src/GcWindowTool.h @@ -20,7 +20,7 @@ #define _GC_GcWindowTool_h 1 #include "GoldenCheetah.h" -#include "MainWindow.h" +#include "Context.h" #include "Season.h" #include "RideMetric.h" #include "LTMSettings.h" diff --git a/src/GoldenCheetah.cpp b/src/GoldenCheetah.cpp index 4f1c58b87..e0f5fa027 100644 --- a/src/GoldenCheetah.cpp +++ b/src/GoldenCheetah.cpp @@ -17,6 +17,8 @@ */ #include "GoldenCheetah.h" +#include "MainWindow.h" +#include "Context.h" #include "Colors.h" #include "Settings.h" #include @@ -186,7 +188,7 @@ GcWindow::GcWindow() #endif } -GcWindow::GcWindow(QWidget *parent) : QFrame(parent), dragState(None) { +GcWindow::GcWindow(Context *context) : QFrame(context->mainWindow), dragState(None) { qRegisterMetaType("controls"); qRegisterMetaType("ride"); qRegisterMetaType("type"); @@ -194,7 +196,7 @@ GcWindow::GcWindow(QWidget *parent) : QFrame(parent), dragState(None) { qRegisterMetaType("dateRange"); qRegisterMetaType("nomenu"); revealed = false; - setParent(parent); + setParent(context->mainWindow); setControls(NULL); setRideItem(NULL); setTitle(""); @@ -651,7 +653,7 @@ GcWindow::_closeWindow() emit closeWindow(this); } -GcChartWindow::GcChartWindow(QWidget *parent) : GcWindow(parent) { +GcChartWindow::GcChartWindow(Context *context) : GcWindow(context) { // // Default layout // diff --git a/src/GoldenCheetah.h b/src/GoldenCheetah.h index d8031edbd..90bc72f6c 100644 --- a/src/GoldenCheetah.h +++ b/src/GoldenCheetah.h @@ -19,6 +19,8 @@ #ifndef _GC_GoldenCheetah_h #define _GC_GoldenCheetah_h #include "TimeUtils.h" +class RideItem; +class GcWindow; #define G_OBJECT Q_PROPERTY(QString instanceName READ instanceName WRITE setInstanceName) #define setInstanceName(x) setProperty("instanceName", x) @@ -37,11 +39,8 @@ #include #include -class RideItem; -class GcWindow; #include "GcWindowRegistry.h" - Q_DECLARE_METATYPE(QWidget*) Q_DECLARE_METATYPE(RideItem*) Q_DECLARE_METATYPE(GcWinID) @@ -126,7 +125,7 @@ public: GcWindow(); ~GcWindow(); - GcWindow(QWidget *p); + GcWindow(Context *context); void _setInstanceName(QString x); // GOBJECTS can set their instance name, but not be GcWindows QString instanceName() const; @@ -200,6 +199,7 @@ public: class GcChartWindow : public GcWindow { private: + Q_OBJECT QStackedLayout *_layout; @@ -219,6 +219,7 @@ private: QPropertyAnimation *_revealAnim, *_unrevealAnim; QTimer *_unrevealTimer; + Context *context; // reveal bool virtual hasReveal() { return false; } @@ -226,7 +227,7 @@ private: void unreveal(); public: - GcChartWindow(QWidget *p); + GcChartWindow(Context *context); QWidget *mainWidget() { return _mainWidget; } diff --git a/src/GoogleMapControl.cpp b/src/GoogleMapControl.cpp index 58e511578..677a0437b 100644 --- a/src/GoogleMapControl.cpp +++ b/src/GoogleMapControl.cpp @@ -19,10 +19,12 @@ #include "GoogleMapControl.h" +#include "MainWindow.h" #include "RideItem.h" #include "RideFile.h" #include "IntervalItem.h" -#include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "Zones.h" #include "Settings.h" #include "Colors.h" @@ -31,7 +33,7 @@ #include -GoogleMapControl::GoogleMapControl(MainWindow *mw) : GcChartWindow(mw), main(mw), range(-1), current(NULL) +GoogleMapControl::GoogleMapControl(Context *context) : GcChartWindow(context), context(context), range(-1), current(NULL) { setInstanceName("Google Map"); setControls(NULL); @@ -41,7 +43,7 @@ GoogleMapControl::GoogleMapControl(MainWindow *mw) : GcChartWindow(mw), main(mw) layout->setContentsMargins(2,0,2,2); setChartLayout(layout); - parent = mw; + //XXX ???? parent = context->mainWindow;; view = new QWebView(); view->setPage(new myWebPage()); view->setContentsMargins(0,0,0,0); @@ -50,16 +52,16 @@ GoogleMapControl::GoogleMapControl(MainWindow *mw) : GcChartWindow(mw), main(mw) view->setAcceptDrops(false); layout->addWidget(view); - webBridge = new WebBridge(mw, this); + webBridge = new WebBridge(context, this); // // connects // connect(this, SIGNAL(rideItemChanged(RideItem*)), this, SLOT(rideSelected())); connect(view->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(updateFrame())); - connect(mw, SIGNAL(intervalsChanged()), webBridge, SLOT(intervalsChanged())); - connect(mw, SIGNAL(intervalSelected()), webBridge, SLOT(intervalsChanged())); - connect(mw, SIGNAL(intervalZoom(IntervalItem*)), this, SLOT(zoomInterval(IntervalItem*))); + connect(context->mainWindow, SIGNAL(intervalsChanged()), webBridge, SLOT(intervalsChanged())); + connect(context->mainWindow, SIGNAL(intervalSelected()), webBridge, SLOT(intervalsChanged())); + connect(context->mainWindow, SIGNAL(intervalZoom(IntervalItem*)), this, SLOT(zoomInterval(IntervalItem*))); first = true; } @@ -276,7 +278,7 @@ void GoogleMapControl::createHtml() QColor GoogleMapControl::GetColor(int watts) { if (range < 0) return Qt::red; - else return zoneColor(main->athlete->zones()->whichZone(range, watts), 7); + else return zoneColor(context->athlete->zones()->whichZone(range, watts), 7); } // create the ride line @@ -446,7 +448,7 @@ GoogleMapControl::createMarkers() // // INTERVAL MARKERS // - if (main->allIntervalItems() == NULL) return; // none to do, we are all done then + if (context->mainWindow->allIntervalItems() == NULL) return; // none to do, we are all done then int interval=0; foreach (const RideFileInterval x, myRideItem->ride()->intervals()) { @@ -529,11 +531,11 @@ WebBridge::intervalCount() highlighted = 0; RideItem *rideItem = gm->property("ride").value(); - if (mainWindow->allIntervalItems() == NULL || + if (context->mainWindow->allIntervalItems() == NULL || rideItem == NULL || rideItem->ride() == NULL) return 0; // not inited yet! - for (int i=0; iallIntervalItems()->childCount(); i++) { - IntervalItem *current = dynamic_cast(mainWindow->allIntervalItems()->child(i)); + for (int i=0; imainWindow->allIntervalItems()->childCount(); i++) { + IntervalItem *current = dynamic_cast(context->mainWindow->allIntervalItems()->child(i)); if (current != NULL) { if (current->isSelected() == true) { ++highlighted; @@ -551,14 +553,14 @@ WebBridge::getLatLons(int i) int highlighted=0; RideItem *rideItem = gm->property("ride").value(); - if (mainWindow->allIntervalItems() == NULL || + if (context->mainWindow->allIntervalItems() == NULL || rideItem ==NULL || rideItem->ride() == NULL) return latlons; // not inited yet! if (i) { // get for specific interval - for (int j=0; jallIntervalItems()->childCount(); j++) { - IntervalItem *current = dynamic_cast(mainWindow->allIntervalItems()->child(j)); + for (int j=0; jmainWindow->allIntervalItems()->childCount(); j++) { + IntervalItem *current = dynamic_cast(context->mainWindow->allIntervalItems()->child(j)); if (current != NULL) { if (current->isSelected() == true) { ++highlighted; @@ -612,6 +614,6 @@ void WebBridge::toggleInterval(int x) { return; - IntervalItem *current = dynamic_cast(mainWindow->allIntervalItems()->child(x)); + IntervalItem *current = dynamic_cast(context->mainWindow->allIntervalItems()->child(x)); if (current) current->setSelected(!current->isSelected()); } diff --git a/src/GoogleMapControl.h b/src/GoogleMapControl.h index bd25055d8..6490c0fa8 100644 --- a/src/GoogleMapControl.h +++ b/src/GoogleMapControl.h @@ -27,11 +27,12 @@ #include #include #include "RideFile.h" -#include "MainWindow.h" +#include "IntervalItem.h" +#include "Context.h" class QMouseEvent; class RideItem; -class MainWindow; +class Context; class QColor; class QVBoxLayout; class QTabWidget; @@ -53,11 +54,11 @@ class WebBridge : public QObject Q_OBJECT; private: - MainWindow *mainWindow; + Context *context; GoogleMapControl *gm; public: - WebBridge(MainWindow *mainWindow, GoogleMapControl *gm) : mainWindow(mainWindow), gm(gm) {} + WebBridge(Context *context, GoogleMapControl *gm) : context(context), gm(gm) {} public slots: Q_INVOKABLE void call(int count); @@ -85,7 +86,7 @@ class GoogleMapControl : public GcChartWindow G_OBJECT public: - GoogleMapControl(MainWindow *); + GoogleMapControl(Context *); ~GoogleMapControl(); bool first; @@ -96,10 +97,9 @@ class GoogleMapControl : public GcChartWindow void zoomInterval(IntervalItem*); private: - MainWindow *main; + Context *context; QVBoxLayout *layout; QWebView *view; - MainWindow *parent; WebBridge *webBridge; GoogleMapControl(); // default ctor int range; diff --git a/src/HelpWindow.cpp b/src/HelpWindow.cpp index c533a0b2c..8802d0566 100644 --- a/src/HelpWindow.cpp +++ b/src/HelpWindow.cpp @@ -17,18 +17,16 @@ */ #include "HelpWindow.h" +#include "MainWindow.h" -#include - - -HelpWindow::HelpWindow(MainWindow *mw) : QDialog(mw) +HelpWindow::HelpWindow(Context *context) : QDialog(context->mainWindow) { setWindowTitle("Help"); setAttribute(Qt::WA_DeleteOnClose); setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint | Qt::Tool); setInstanceName("Help Window"); - parent = mw; + //XXX ???? parent = context->mainWindow; view = new QWebView(); layout = new QVBoxLayout(); layout->addWidget(view); diff --git a/src/HelpWindow.h b/src/HelpWindow.h index b349e6cfe..a0c7b4492 100644 --- a/src/HelpWindow.h +++ b/src/HelpWindow.h @@ -22,7 +22,7 @@ #include #include -#include "MainWindow.h" +#include "Context.h" class HelpWindow : public QDialog { @@ -31,16 +31,15 @@ G_OBJECT private: - MainWindow *main; + Context *context; QVBoxLayout *layout; QWebView *view; - MainWindow *parent; HelpWindow(); // default ctor protected: public: - HelpWindow(MainWindow *); + HelpWindow(Context *); }; #endif diff --git a/src/HistogramWindow.cpp b/src/HistogramWindow.cpp index ec8e9a277..7c8c152f5 100644 --- a/src/HistogramWindow.cpp +++ b/src/HistogramWindow.cpp @@ -18,21 +18,6 @@ */ #include "HistogramWindow.h" -#include "MainWindow.h" -#include "MetricAggregator.h" -#include "SummaryMetrics.h" -#include "ChartSettings.h" -#include "ColorButton.h" -#include "PowerHist.h" -#include "RideFile.h" -#include "RideFileCache.h" -#include "RideItem.h" -#include "Settings.h" -#include -#include - -#include "Zones.h" -#include "HrZones.h" // predefined deltas for each series static const double wattsDelta = 1.0; @@ -54,7 +39,7 @@ static const int cadDigits = 0; // // Constructor // -HistogramWindow::HistogramWindow(MainWindow *mainWindow, bool rangemode) : GcChartWindow(mainWindow), mainWindow(mainWindow), stale(true), source(NULL), active(false), bactive(false), rangemode(rangemode), useCustom(false), useToToday(false), precision(99) +HistogramWindow::HistogramWindow(Context *context, bool rangemode) : GcChartWindow(context), context(context), stale(true), source(NULL), active(false), bactive(false), rangemode(rangemode), useCustom(false), useToToday(false), precision(99) { setInstanceName("Histogram Window"); @@ -99,7 +84,7 @@ HistogramWindow::HistogramWindow(MainWindow *mainWindow, bool rangemode) : GcCha // plot QVBoxLayout *vlayout = new QVBoxLayout; vlayout->setSpacing(10); - powerHist = new PowerHist(mainWindow); + powerHist = new PowerHist(context); vlayout->addWidget(powerHist); setChartLayout(vlayout); @@ -107,7 +92,7 @@ HistogramWindow::HistogramWindow(MainWindow *mainWindow, bool rangemode) : GcCha #ifdef GC_HAVE_LUCENE // search filter box isfiltered = false; - searchBox = new SearchFilterBox(this, mainWindow); + searchBox = new SearchFilterBox(this, context); connect(searchBox, SIGNAL(searchClear()), this, SLOT(clearFilter())); connect(searchBox, SIGNAL(searchResults(QStringList)), this, SLOT(setFilter(QStringList))); if (!rangemode) searchBox->hide(); @@ -305,7 +290,7 @@ HistogramWindow::HistogramWindow(MainWindow *mainWindow, bool rangemode) : GcCha } else { dateSetting->hide(); connect(this, SIGNAL(rideItemChanged(RideItem*)), this, SLOT(rideSelected())); - connect(mainWindow, SIGNAL(intervalSelected()), this, SLOT(intervalSelected())); + connect(context->mainWindow, SIGNAL(intervalSelected()), this, SLOT(intervalSelected())); } // if any of the controls change we pass the chart everything @@ -318,12 +303,12 @@ HistogramWindow::HistogramWindow(MainWindow *mainWindow, bool rangemode) : GcCha connect(shadeZones, SIGNAL(stateChanged(int)), this, SLOT(updateChart())); connect(showSumY, SIGNAL(currentIndexChanged(int)), this, SLOT(updateChart())); - connect(mainWindow->athlete, SIGNAL(zonesChanged()), this, SLOT(zonesChanged())); - connect(mainWindow->context, SIGNAL(configChanged()), powerHist, SLOT(configChanged())); + connect(context->athlete, SIGNAL(zonesChanged()), this, SLOT(zonesChanged())); + connect(context, SIGNAL(configChanged()), powerHist, SLOT(configChanged())); - connect(mainWindow, SIGNAL(rideAdded(RideItem*)), this, SLOT(rideAddorRemove(RideItem*))); - connect(mainWindow, SIGNAL(rideDeleted(RideItem*)), this, SLOT(rideAddorRemove(RideItem*))); - connect(mainWindow, SIGNAL(filterChanged(QStringList&)), this, SLOT(forceReplot())); + connect(context->mainWindow, SIGNAL(rideAdded(RideItem*)), this, SLOT(rideAddorRemove(RideItem*))); + connect(context->mainWindow, SIGNAL(rideDeleted(RideItem*)), this, SLOT(rideAddorRemove(RideItem*))); + connect(context->mainWindow, SIGNAL(filterChanged(QStringList&)), this, SLOT(forceReplot())); } // @@ -543,7 +528,7 @@ HistogramWindow::switchMode() // select the series.. (but without the half second delay) treeSelectionTimeout(); } - mainWindow->chartSettings->adjustSize(); + context->mainWindow->chartSettings->adjustSize(); stale = true; updateChart(); // to whatever is currently selected. @@ -642,8 +627,8 @@ HistogramWindow::rideSelected() if (rangemode) { // get range that applies to this ride - powerRange = mainWindow->athlete->zones()->whichRange(ride->dateTime.date()); - hrRange = mainWindow->athlete->hrZones()->whichRange(ride->dateTime.date()); + powerRange = context->athlete->zones()->whichRange(ride->dateTime.date()); + hrRange = context->athlete->hrZones()->whichRange(ride->dateTime.date()); } // update @@ -840,9 +825,9 @@ HistogramWindow::updateChart() // plotting a data series, so refresh the ridefilecache #ifdef GC_HAVE_LUCENE - source = new RideFileCache(mainWindow, use.from, use.to, isfiltered, files); + source = new RideFileCache(context, use.from, use.to, isfiltered, files); #else - source = new RideFileCache(mainWindow, use.from, use.to); + source = new RideFileCache(context, use.from, use.to); #endif cfrom = use.from; cto = use.to; @@ -872,7 +857,7 @@ HistogramWindow::updateChart() last = use; // plotting a metric, reread the metrics for the selected date range - results = mainWindow->athlete->metricDB->getAllMetricsFor(use); + results = context->athlete->metricDB->getAllMetricsFor(use); } diff --git a/src/HistogramWindow.h b/src/HistogramWindow.h index f34b62a56..aa52b39e0 100644 --- a/src/HistogramWindow.h +++ b/src/HistogramWindow.h @@ -20,17 +20,35 @@ #ifndef _GC_HistogramWindow_h #define _GC_HistogramWindow_h 1 #include "GoldenCheetah.h" +#include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" +#include "MetricAggregator.h" +#include "SummaryMetrics.h" +#include "ChartSettings.h" +#include "ColorButton.h" +#include "PowerHist.h" +#include "RideFile.h" +#include "RideFileCache.h" +#include "RideItem.h" +#include "Settings.h" +#include +#include + +#include "Zones.h" +#include "HrZones.h" #include "SummaryMetrics.h" #include "Season.h" #include "SeasonParser.h" + #ifdef GC_HAVE_LUCENE #include "SearchFilterBox.h" #endif #include -class MainWindow; +class Context; class PowerHist; class RideItem; class RideFileCache; @@ -65,7 +83,7 @@ class HistogramWindow : public GcChartWindow public: - HistogramWindow(MainWindow *mainWindow, bool rangemode = false); + HistogramWindow(Context *context, bool rangemode = false); // reveal bool hasReveal() { return true; } @@ -86,7 +104,7 @@ class HistogramWindow : public GcChartWindow bool zoned() const { return showInZones->isChecked(); } void setZoned(bool x) { return showInZones->setChecked(x); } #ifdef GC_HAVE_LUCENE - bool isFiltered() const { if (rangemode) return (isfiltered || mainWindow->isfiltered); + bool isFiltered() const { if (rangemode) return (isfiltered || context->mainWindow->isfiltered); else return false; } QString filter() const { return searchBox->filter(); } void setFilter(QString x) { searchBox->setFilter(x); } @@ -163,7 +181,7 @@ class HistogramWindow : public GcChartWindow private: - MainWindow *mainWindow; + Context *context; PowerHist *powerHist; QSlider *binWidthSlider; // seet Bin Width from a slider diff --git a/src/HomeWindow.cpp b/src/HomeWindow.cpp index db277a4dc..58e556404 100644 --- a/src/HomeWindow.cpp +++ b/src/HomeWindow.cpp @@ -16,7 +16,9 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ - +#include "MainWindow.h" +#include "Athlete.h" +#include "Context.h" #include "HomeWindow.h" #include "LTMTool.h" #include "LTMSettings.h" @@ -27,8 +29,8 @@ static const int tileMargin = 20; static const int tileSpacing = 10; -HomeWindow::HomeWindow(MainWindow *mainWindow, QString name, QString /* windowtitle */) : - GcWindow(mainWindow), mainWindow(mainWindow), name(name), active(false), +HomeWindow::HomeWindow(Context *context, QString name, QString /* windowtitle */) : + GcWindow(context), context(context), name(name), active(false), clicked(NULL), dropPending(false), chartCursor(-2), loaded(false) { setInstanceName("Home Window"); @@ -157,7 +159,7 @@ HomeWindow::HomeWindow(MainWindow *mainWindow, QString name, QString /* windowti connect(this, SIGNAL(rideItemChanged(RideItem*)), this, SLOT(rideSelected())); connect(this, SIGNAL(dateRangeChanged(DateRange)), this, SLOT(dateRangeChanged(DateRange))); - connect(mainWindow->context, SIGNAL(configChanged()), this, SLOT(configChanged())); + connect(context, SIGNAL(configChanged()), this, SLOT(configChanged())); connect(tabbed, SIGNAL(currentChanged(int)), this, SLOT(tabSelected(int))); connect(tabbed, SIGNAL(tabCloseRequested(int)), this, SLOT(removeChart(int))); connect(tb, SIGNAL(tabMoved(int,int)), this, SLOT(tabMoved(int,int))); @@ -188,7 +190,7 @@ HomeWindow::addChartFromMenu(QAction*action) } } - if (id != GcWindowTypes::None) appendChart(id); // called from MainWindow to inset chart + if (id != GcWindowTypes::None) appendChart(id); // called from Context to inset chart } void @@ -425,7 +427,7 @@ void HomeWindow::appendChart(GcWinID id) { // GcWindowDialog is delete on close, so no need to delete - GcWindowDialog *f = new GcWindowDialog(id, mainWindow); + GcWindowDialog *f = new GcWindowDialog(id, context); GcWindow *newone = f->exec(); // returns null if cancelled or closed @@ -474,8 +476,8 @@ HomeWindow::dropEvent(QDropEvent *event) void HomeWindow::showControls() { - mainWindow->chartSettings->adjustSize(); - mainWindow->chartSettings->show(); + context->mainWindow->chartSettings->adjustSize(); + context->mainWindow->chartSettings->show(); } void @@ -503,7 +505,7 @@ HomeWindow::addChart(GcWindow* newone) // watch for enter events! newone->installEventFilter(this); - RideItem *notconst = (RideItem*)mainWindow->context->currentRideItem(); + RideItem *notconst = (RideItem*)context->currentRideItem(); newone->setProperty("ride", QVariant::fromValue(notconst)); newone->setProperty("dateRange", property("dateRange")); @@ -589,7 +591,7 @@ HomeWindow::removeChart(int num, bool confirm) // better let the user confirm since this // is undoable etc - code swiped from delete - // ride in MainWindow, seems to work ok ;) + // ride in Context, seems to work ok ;) if(confirm == true) { QMessageBox msgBox; @@ -648,9 +650,9 @@ HomeWindow::resetLayout() } restoreState(true); for(int i = 0; i < charts.count(); i++) { - RideItem *notconst = (RideItem*)mainWindow->context->currentRideItem(); + RideItem *notconst = (RideItem*)context->currentRideItem(); charts[i]->setProperty("ride", QVariant::fromValue(notconst)); - DateRange dr = mainWindow->context->currentDateRange(); + DateRange dr = context->currentDateRange(); charts[i]->setProperty("dateRange", QVariant::fromValue(dr)); if (currentStyle != 0) charts[i]->show(); @@ -1009,7 +1011,7 @@ HomeWindow::drawCursor() } } -GcWindowDialog::GcWindowDialog(GcWinID type, MainWindow *mainWindow) : mainWindow(mainWindow), type(type) +GcWindowDialog::GcWindowDialog(GcWinID type, Context *context) : context(context), type(type) { //setAttribute(Qt::WA_DeleteOnClose); setWindowFlags(windowFlags()); @@ -1027,7 +1029,7 @@ GcWindowDialog::GcWindowDialog(GcWinID type, MainWindow *mainWindow) : mainWindo title = new QLineEdit(this); chartLayout->addWidget(title); - win = GcWindowRegistry::newGcWindow(type, mainWindow); + win = GcWindowRegistry::newGcWindow(type, context); chartLayout->addWidget(win); //win->setFrameStyle(QFrame::Box); @@ -1040,9 +1042,9 @@ GcWindowDialog::GcWindowDialog(GcWinID type, MainWindow *mainWindow) : mainWindo layout->setStretch(1, 50); } - RideItem *notconst = (RideItem*)mainWindow->context->currentRideItem(); + RideItem *notconst = (RideItem*)context->currentRideItem(); win->setProperty("ride", QVariant::fromValue(notconst)); - DateRange dr = mainWindow->context->currentDateRange(); + DateRange dr = context->currentDateRange(); win->setProperty("dateRange", QVariant::fromValue(dr)); @@ -1135,7 +1137,7 @@ HomeWindow::saveState() // NOTE: currently we support QString, int, double and bool types - beware custom types!! if (charts.count() == 0) return; // don't save empty, use default instead - QString filename = mainWindow->athlete->home.absolutePath() + "/" + name + "-layout.xml"; + QString filename = context->athlete->home.absolutePath() + "/" + name + "-layout.xml"; QFile file(filename); file.open(QFile::WriteOnly); file.resize(0); @@ -1187,7 +1189,7 @@ void HomeWindow::restoreState(bool useDefault) { // restore window state - QString filename = mainWindow->athlete->home.absolutePath() + "/" + name + "-layout.xml"; + QString filename = context->athlete->home.absolutePath() + "/" + name + "-layout.xml"; QFileInfo finfo(filename); if (useDefault) QFile::remove(filename); @@ -1201,7 +1203,7 @@ HomeWindow::restoreState(bool useDefault) // setup the handler QXmlInputSource source(&file); QXmlSimpleReader xmlReader; - ViewParser handler(mainWindow); + ViewParser handler(context); xmlReader.setContentHandler(&handler); xmlReader.setErrorHandler(&handler); @@ -1254,7 +1256,7 @@ bool ViewParser::startElement( const QString&, const QString&, const QString &na // new chart type = static_cast(typeStr.toInt()); - chart = GcWindowRegistry::newGcWindow(type, mainWindow); + chart = GcWindowRegistry::newGcWindow(type, context); chart->hide(); chart->setProperty("title", QVariant(title)); chart->setProperty("instanceName", QVariant(name)); diff --git a/src/HomeWindow.h b/src/HomeWindow.h index 39d71c98a..621b271cc 100644 --- a/src/HomeWindow.h +++ b/src/HomeWindow.h @@ -25,7 +25,7 @@ #include #include -#include "MainWindow.h" +#include "Context.h" #ifdef Q_OS_MAC #include "QtMacSegmentedButton.h" @@ -40,7 +40,7 @@ class HomeWindow : public GcWindow public: - HomeWindow(MainWindow *, QString name, QString title); + HomeWindow(Context *, QString name, QString title); ~HomeWindow(); void resetLayout(); @@ -69,7 +69,7 @@ class HomeWindow : public GcWindow void styleChanged(int); void addChart(GcWindow* newone); void addChartFromMenu(QAction*action); // called with an action - void appendChart(GcWinID id); // called from MainWindow to inset chart + void appendChart(GcWinID id); // called from Context *to inset chart bool removeChart(int, bool confirm = true); void titleChanged(); @@ -96,7 +96,7 @@ class HomeWindow : public GcWindow void rightClick(const QPoint &pos); protected: - MainWindow *mainWindow; + Context *context; QString name; bool active; // ignore gui signals when changing views GcWindow *clicked; // keep track of selected charts @@ -136,7 +136,7 @@ class GcWindowDialog : public QDialog Q_OBJECT public: - GcWindowDialog(GcWinID, MainWindow*); + GcWindowDialog(GcWinID, Context *); GcWindow *exec(); // return pointer to window, or NULL if cancelled public slots: @@ -144,7 +144,7 @@ class GcWindowDialog : public QDialog void cancelClicked(); protected: - MainWindow *mainWindow; + Context *context; GcWinID type; // we remove from the layout at the end @@ -163,7 +163,7 @@ class ViewParser : public QXmlDefaultHandler { public: - ViewParser(MainWindow *mainWindow) : style(2), mainWindow(mainWindow) {} + ViewParser(Context *context) : style(2), context(context) {} // the results! QList charts; @@ -177,7 +177,7 @@ public: bool characters( const QString& str ); protected: - MainWindow *mainWindow; + Context *context; GcWindow *chart; }; diff --git a/src/HrPwPlot.cpp b/src/HrPwPlot.cpp index e758283f3..071799603 100644 --- a/src/HrPwPlot.cpp +++ b/src/HrPwPlot.cpp @@ -17,7 +17,7 @@ */ #include "HrPwPlot.h" -#include "MainWindow.h" +#include "Context.h" #include "HrPwWindow.h" #include "RideFile.h" #include "RideItem.h" @@ -39,10 +39,10 @@ static inline double max(double a, double b) { if (a > b) return a; else return b; } -HrPwPlot::HrPwPlot(MainWindow *mainWindow, HrPwWindow *hrPwWindow) : +HrPwPlot::HrPwPlot(Context *context, HrPwWindow *hrPwWindow) : QwtPlot(hrPwWindow), hrPwWindow(hrPwWindow), - mainWindow(mainWindow), + context(context), bg(NULL), delay(-1), minHr(50), minWatt(50), maxWatt(500) { diff --git a/src/HrPwPlot.h b/src/HrPwPlot.h index 2e024c593..c9a4dd51a 100644 --- a/src/HrPwPlot.h +++ b/src/HrPwPlot.h @@ -26,7 +26,7 @@ class QwtPlotCurve; class QwtPlotGrid; class QwtPlotMarker; -class MainWindow; +class Context; class HrPwWindow; class RideItem; class HrPwPlotBackground; @@ -42,7 +42,7 @@ class HrPwPlot : public QwtPlot public: - HrPwPlot(MainWindow *mainWindow, HrPwWindow *hrPwWindow); + HrPwPlot(Context *context, HrPwWindow *hrPwWindow); RideItem *rideItem; QwtPlotMarker *r_mrk1; @@ -67,7 +67,7 @@ class HrPwPlot : public QwtPlot friend class ::HrPwWindow; HrPwWindow *hrPwWindow; - MainWindow *mainWindow; + Context *context; HrPwPlotBackground *bg; diff --git a/src/HrPwWindow.cpp b/src/HrPwWindow.cpp index 118554b17..c8a90b63a 100644 --- a/src/HrPwWindow.cpp +++ b/src/HrPwWindow.cpp @@ -18,7 +18,7 @@ #include "GoldenCheetah.h" #include "HrPwWindow.h" -#include "MainWindow.h" +#include "Context.h" #include "LTMWindow.h" #include "HrPwPlot.h" #include "SmallPlot.h" @@ -30,8 +30,8 @@ // tooltip -HrPwWindow::HrPwWindow(MainWindow *mainWindow) : - GcChartWindow(mainWindow), mainWindow(mainWindow), current(NULL) +HrPwWindow::HrPwWindow(Context *context) : + GcChartWindow(context), context(context), current(NULL) { setControls(NULL); setInstanceName("HrPw"); @@ -85,7 +85,7 @@ HrPwWindow::HrPwWindow(MainWindow *mainWindow) : QVBoxLayout *vlayout = new QVBoxLayout; // main plot - hrPwPlot = new HrPwPlot(mainWindow, this); + hrPwPlot = new HrPwPlot(context, this); // tooltip on hover over point diff --git a/src/HrPwWindow.h b/src/HrPwWindow.h index edd71b9fc..048bec19d 100644 --- a/src/HrPwWindow.h +++ b/src/HrPwWindow.h @@ -27,7 +27,7 @@ class QCheckBox; class QLineEdit; class RideItem; class HrPwPlot; -class MainWindow; +class Context; class SmallPlot; class QSlider; @@ -52,7 +52,7 @@ class HrPwWindow : public GcChartWindow public: - HrPwWindow(MainWindow *mainWindow); + HrPwWindow(Context *context); void setData(RideItem *item); int findDelay(QVector &wattsArray, QVector &hrArray, int rideTimeSecs); @@ -86,7 +86,7 @@ class HrPwWindow : public GcChartWindow void setDelay(int); protected: - MainWindow *mainWindow; + Context *context; HrPwPlot *hrPwPlot; SmallPlot *smallPlot; diff --git a/src/HrTimeInZone.cpp b/src/HrTimeInZone.cpp index 27429caed..6f70d8c36 100644 --- a/src/HrTimeInZone.cpp +++ b/src/HrTimeInZone.cpp @@ -43,7 +43,7 @@ public: } void setLevel(int level) { this->level=level-1; } // zones start from zero not 1 void compute(const RideFile *ride, const Zones *, int, const HrZones *hrZone, int hrZoneRange, - const QHash &, const MainWindow *) + const QHash &, const Context *) { seconds = 0; // get zone ranges diff --git a/src/ICalendar.cpp b/src/ICalendar.cpp index a94202ffc..cddb7a2a5 100644 --- a/src/ICalendar.cpp +++ b/src/ICalendar.cpp @@ -16,6 +16,7 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ +#include "Athlete.h" #include "ICalendar.h" #include "GcCalendarModel.h" #include "CalendarDownload.h" @@ -163,12 +164,12 @@ static QDateTime propertyToDate(icalproperty *p) } } -ICalendar::ICalendar(MainWindow *parent) : QWidget(parent), main(parent) +ICalendar::ICalendar(Context *context) : QWidget(context->mainWindow), context(context) { // get from local and remote calendar // local file - QString localFilename = main->athlete->home.absolutePath()+"/calendar.ics"; + QString localFilename = context->athlete->home.absolutePath()+"/calendar.ics"; QFile localFile(localFilename); if (localFile.exists() && localFile.open(QFile::ReadOnly | QFile::Text)) { @@ -182,7 +183,7 @@ ICalendar::ICalendar(MainWindow *parent) : QWidget(parent), main(parent) } // remote file - main->athlete->calendarDownload->download(); + context->athlete->calendarDownload->download(); } void ICalendar::refreshRemote(QString fulltext) diff --git a/src/ICalendar.h b/src/ICalendar.h index f307222eb..f76fe4b3a 100644 --- a/src/ICalendar.h +++ b/src/ICalendar.h @@ -21,7 +21,7 @@ #include "GoldenCheetah.h" #include -#include "MainWindow.h" +#include "Context.h" #include "RideMetric.h" #include @@ -33,7 +33,7 @@ class ICalendar : public QWidget public: - ICalendar(MainWindow *parent); + ICalendar(Context *context); // to get access to from the Calendar QVariant data(QDate date, int role = Qt::DisplayRole); @@ -48,7 +48,7 @@ class ICalendar : public QWidget private: - MainWindow *main; + Context *context; // We store the calendar as an associative array // For each date we have a list of events that diff --git a/src/IntervalSummaryWindow.cpp b/src/IntervalSummaryWindow.cpp index a76b67b90..92ba9eaf1 100644 --- a/src/IntervalSummaryWindow.cpp +++ b/src/IntervalSummaryWindow.cpp @@ -17,12 +17,14 @@ */ #include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "IntervalItem.h" #include "IntervalSummaryWindow.h" #include "Settings.h" #include "TimeUtils.h" -IntervalSummaryWindow::IntervalSummaryWindow(MainWindow *mainWindow) : mainWindow(mainWindow) +IntervalSummaryWindow::IntervalSummaryWindow(Context *context) : context(context) { setWindowTitle(tr("Interval Summary")); setReadOnly(true); @@ -31,7 +33,7 @@ IntervalSummaryWindow::IntervalSummaryWindow(MainWindow *mainWindow) : mainWindo #ifdef Q_OS_MAC setAttribute(Qt::WA_MacShowFocusRect, 0); #endif - connect(mainWindow, SIGNAL(intervalSelected()), this, SLOT(intervalSelected())); + connect(context->mainWindow, SIGNAL(intervalSelected()), this, SLOT(intervalSelected())); } IntervalSummaryWindow::~IntervalSummaryWindow() { @@ -40,12 +42,12 @@ IntervalSummaryWindow::~IntervalSummaryWindow() { void IntervalSummaryWindow::intervalSelected() { // if no ride available don't bother - if (mainWindow->context->currentRideItem() == NULL || mainWindow->context->currentRide() == NULL) return; + if (context->currentRideItem() == NULL || context->currentRide() == NULL) return; QString html; - if (mainWindow->allIntervalItems() != NULL) { - for (int i=0; iallIntervalItems()->childCount(); i++) { - IntervalItem *current = dynamic_cast(mainWindow->allIntervalItems()->child(i)); + if (context->mainWindow->allIntervalItems() != NULL) { + for (int i=0; imainWindow->allIntervalItems()->childCount(); i++) { + IntervalItem *current = dynamic_cast(context->mainWindow->allIntervalItems()->child(i)); if (current != NULL) { if (current->isSelected()) { calcInterval(current, html); @@ -62,12 +64,12 @@ void IntervalSummaryWindow::intervalSelected() void IntervalSummaryWindow::calcInterval(IntervalItem* interval, QString& html) { - const RideFile* ride = mainWindow->context->currentRide(); + const RideFile* ride = context->currentRide(); - bool metricUnits = mainWindow->athlete->useMetricUnits; + bool metricUnits = context->athlete->useMetricUnits; RideFile f(ride->startTime(), ride->recIntSecs()); - f.mainwindow = mainWindow; + f.context = context; int start = ride->timeIndex(interval->start); int end = ride->timeIndex(interval->stop); for (int i = start; i < end; ++i) { @@ -88,7 +90,7 @@ void IntervalSummaryWindow::calcInterval(IntervalItem* interval, QString& html) QStringList intervalMetrics = s.split(","); QHash metrics = - RideMetric::computeMetrics(mainWindow, &f, mainWindow->athlete->zones(), mainWindow->athlete->hrZones(), intervalMetrics); + RideMetric::computeMetrics(context, &f, context->athlete->zones(), context->athlete->hrZones(), intervalMetrics); html += "" + interval->text(0) + ""; html += " -class MainWindow; +class Context; class IntervalItem; class IntervalSummaryWindow : public QTextEdit { Q_OBJECT; public: - IntervalSummaryWindow(MainWindow *mainWindow); + IntervalSummaryWindow(Context *context); virtual ~IntervalSummaryWindow(); public slots: @@ -38,7 +38,7 @@ public slots: protected: void calcInterval(IntervalItem* interval, QString& html); - MainWindow *mainWindow; + Context *context; }; #endif /* INTERVALSUMMARYWINDOW_H_ */ diff --git a/src/IntervalTreeView.cpp b/src/IntervalTreeView.cpp index c67b4eb04..0556061d0 100644 --- a/src/IntervalTreeView.cpp +++ b/src/IntervalTreeView.cpp @@ -18,10 +18,10 @@ #include "IntervalTreeView.h" #include "IntervalItem.h" -#include "MainWindow.h" +#include "Context.h" -IntervalTreeView::IntervalTreeView(MainWindow *mainWindow) : mainWindow(mainWindow) +IntervalTreeView::IntervalTreeView(Context *context) : context(context) { setDragDropMode(QAbstractItemView::InternalMove); setDragDropOverwriteMode(true); diff --git a/src/IntervalTreeView.h b/src/IntervalTreeView.h index 4a411374a..db511c2ed 100644 --- a/src/IntervalTreeView.h +++ b/src/IntervalTreeView.h @@ -22,17 +22,17 @@ #include -class MainWindow; +class Context; class IntervalTreeView : public QTreeWidget { Q_OBJECT; public: - IntervalTreeView(MainWindow *main); + IntervalTreeView(Context *context); protected: - MainWindow *mainWindow; + Context *context; void dropEvent(QDropEvent* event); diff --git a/src/JsonRideFile.h b/src/JsonRideFile.h index 2ed57d377..f219b7f1a 100644 --- a/src/JsonRideFile.h +++ b/src/JsonRideFile.h @@ -32,7 +32,7 @@ struct JsonFileReader : public RideFileReader { virtual RideFile *openRideFile(QFile &file, QStringList &errors, QList* = 0) const; - bool writeRideFile(MainWindow *, const RideFile *ride, QFile &file) const; + bool writeRideFile(Context *, const RideFile *ride, QFile &file) const; bool hasWrite() const { return true; } }; diff --git a/src/JsonRideFile.y b/src/JsonRideFile.y index e66e8d183..58c8b5dd9 100644 --- a/src/JsonRideFile.y +++ b/src/JsonRideFile.y @@ -302,7 +302,7 @@ JsonFileReader::openRideFile(QFile &file, QStringList &errors, QList* // Writes valid .json (validated at www.jsonlint.com) bool -JsonFileReader::writeRideFile(MainWindow *, const RideFile *ride, QFile &file) const +JsonFileReader::writeRideFile(Context *, const RideFile *ride, QFile &file) const { // can we open the file for writing? if (!file.open(QIODevice::WriteOnly)) return false; diff --git a/src/KmlRideFile.cpp b/src/KmlRideFile.cpp index ffc3df38a..a5d825318 100644 --- a/src/KmlRideFile.cpp +++ b/src/KmlRideFile.cpp @@ -176,7 +176,7 @@ static StyleMapPtr CreateStyleMap(const char* id) { // Serialise the ride // bool -KmlFileReader::writeRideFile(MainWindow *, const RideFile * ride, QFile &file) const +KmlFileReader::writeRideFile(Context *, const RideFile * ride, QFile &file) const { // Create a new DOM document and setup styles et al kmldom::KmlFactory* kml_factory = kmldom::KmlFactory::GetFactory(); diff --git a/src/KmlRideFile.h b/src/KmlRideFile.h index 711968bab..891cfca93 100644 --- a/src/KmlRideFile.h +++ b/src/KmlRideFile.h @@ -24,7 +24,7 @@ struct KmlFileReader : public RideFileReader { virtual RideFile *openRideFile(QFile &, QStringList &, QList* =0) const { return NULL; } // does not support reading - bool writeRideFile(MainWindow *, const RideFile *ride, QFile &file) const; + bool writeRideFile(Context *, const RideFile *ride, QFile &file) const; bool hasWrite() const { return true; } }; diff --git a/src/LTMPlot.cpp b/src/LTMPlot.cpp index d967a3e90..22b314f40 100644 --- a/src/LTMPlot.cpp +++ b/src/LTMPlot.cpp @@ -16,6 +16,8 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ +#include "Athlete.h" +#include "Context.h" #include "LTMPlot.h" #include "LTMTool.h" #include "LTMTrend.h" @@ -42,8 +44,8 @@ static int supported_axes[] = { QwtPlot::yLeft, QwtPlot::yRight, QwtPlot::yLeft1, QwtPlot::yRight1, QwtPlot::yLeft2, QwtPlot::yRight2, QwtPlot::yLeft3, QwtPlot::yRight3 }; -LTMPlot::LTMPlot(LTMWindow *parent, MainWindow *main) : - bg(NULL), parent(parent), main(main), highlighter(NULL) +LTMPlot::LTMPlot(LTMWindow *parent, Context *context) : + bg(NULL), parent(parent), context(context), highlighter(NULL) { setInstanceName("Metric Plot"); @@ -64,7 +66,7 @@ LTMPlot::LTMPlot(LTMWindow *parent, MainWindow *main) : configUpdate(); // set basic colors - connect(main->context, SIGNAL(configChanged()), this, SLOT(configUpdate())); + connect(context, SIGNAL(configChanged()), this, SLOT(configUpdate())); } LTMPlot::~LTMPlot() @@ -101,7 +103,7 @@ LTMPlot::setData(LTMSettings *set) settings = set; // For each metric in chart, translate units and name if default uname - LTMTool::translateMetrics(main, main->athlete->home, settings); + LTMTool::translateMetrics(context, context->athlete->home, settings); // crop dates to at least within a year of the data available, but only if we have some data if (settings->data != NULL && (*settings->data).count() != 0) { @@ -780,7 +782,7 @@ LTMPlot::createTODCurveData(LTMSettings *settings, MetricDetail metricDetail, QV foreach (SummaryMetrics rideMetrics, *(settings->data)) { // filter out unwanted rides - if (main->isfiltered && !main->filters.contains(rideMetrics.getFileName())) continue; + if (context->mainWindow->isfiltered && !context->mainWindow->filters.contains(rideMetrics.getFileName())) continue; double value = rideMetrics.getForSymbol(metricDetail.symbol); @@ -790,7 +792,7 @@ LTMPlot::createTODCurveData(LTMSettings *settings, MetricDetail metricDetail, QV // Special computed metrics (LTS/STS) have a null metric pointer if (metricDetail.metric) { // convert from stored metric value to imperial - if (main->athlete->useMetricUnits == false) { + if (context->athlete->useMetricUnits == false) { value *= metricDetail.metric->conversion(); value += metricDetail.metric->conversionSum(); } @@ -856,8 +858,8 @@ LTMPlot::createCurveData(LTMSettings *settings, MetricDetail metricDetail, QVect // filter out unwanted rides but not for PMC type metrics // because that needs to be done in the stress calculator - if (metricDetail.type != METRIC_PM && main->isfiltered && - !main->filters.contains(rideMetrics.getFileName())) continue; + if (metricDetail.type != METRIC_PM && context->mainWindow->isfiltered && + !context->mainWindow->filters.contains(rideMetrics.getFileName())) continue; // day we are on int currentDay = groupForDate(rideMetrics.getRideDate().date(), settings->groupBy); @@ -875,7 +877,7 @@ LTMPlot::createCurveData(LTMSettings *settings, MetricDetail metricDetail, QVect // Special computed metrics (LTS/STS) have a null metric pointer if (metricDetail.metric) { // convert from stored metric value to imperial - if (main->athlete->useMetricUnits == false) { + if (context->athlete->useMetricUnits == false) { value *= metricDetail.metric->conversion(); value += metricDetail.metric->conversionSum(); } @@ -957,13 +959,13 @@ LTMPlot::createPMCCurveData(LTMSettings *settings, MetricDetail metricDetail, // create the Stress Calculation List // FOR ALL RIDE FILES StressCalculator *sc = new StressCalculator( - main->athlete->cyclist, + context->athlete->cyclist, settings->start, settings->end, (appsettings->value(this, GC_STS_DAYS,7)).toInt(), (appsettings->value(this, GC_LTS_DAYS,42)).toInt()); - sc->calculateStress(main, main->athlete->home.absolutePath(), scoreType, settings->ltmTool->isFiltered(), settings->ltmTool->filters()); + sc->calculateStress(context, context->athlete->home.absolutePath(), scoreType, settings->ltmTool->isFiltered(), settings->ltmTool->filters()); // pick out any data that is in the date range selected // convert to SummaryMetric Format used on the plot @@ -1087,7 +1089,7 @@ LTMPlot::pointHover(QwtPlotCurve *curve, int index) c.next(); if (c.value() == curve) { const RideMetric *metric =factory.rideMetric(c.key()); - units = metric ? metric->units(main->athlete->useMetricUnits) : ""; + units = metric ? metric->units(context->athlete->useMetricUnits) : ""; precision = metric ? metric->precision() : 1; // BikeScore, RI and Daniels Points have no units @@ -1181,8 +1183,8 @@ class LTMPlotBackground: public QwtPlotItem const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &rect) const { - const Zones *zones = parent->parent->main->athlete->zones(); - int zone_range_size = parent->parent->main->athlete->zones()->getRangeSize(); + const Zones *zones = parent->parent->context->mainWindow->athlete->zones(); + int zone_range_size = parent->parent->context->mainWindow->athlete->zones()->getRangeSize(); if (zone_range_size >= 0) { //parent->shadeZones() && for (int i = 0; i < zone_range_size; i ++) { @@ -1238,8 +1240,8 @@ class LTMPlotZoneLabel: public QwtPlotItem parent = _parent; zone_number = _zone_number; - const Zones *zones = parent->parent->main->athlete->zones(); - //int zone_range = 0; //parent->parent->mainWindow->zoneRange(); + const Zones *zones = parent->parent->context->mainWindow->athlete->zones(); + //int zone_range = 0; //parent->parent->context->mainWindow->zoneRange(); int zone_range = zones->whichRange(settings->start.addDays((settings->end.date().toJulianDay()-settings->start.date().toJulianDay())/2).date()); // which axis has watts? @@ -1308,7 +1310,7 @@ LTMPlot::refreshMarkers(QDate from, QDate to, int groupby) // seasons and season events if (settings->events) { - foreach (Season s, main->athlete->seasons->seasons) { + foreach (Season s, context->athlete->seasons->seasons) { if (s.type != Season::temporary && s.name != settings->title && s.getStart() >= from && s.getStart() < to) { @@ -1366,7 +1368,7 @@ LTMPlot::refreshZoneLabels(int axisid) } if (axisid == -1) return; // our job is done - no zones to plot - const Zones *zones = main->athlete->zones(); + const Zones *zones = context->athlete->zones(); if (zones == NULL || zones->getRangeSize()==0) return; // no zones to plot diff --git a/src/LTMPlot.h b/src/LTMPlot.h index 0ad86da50..d79d14a20 100644 --- a/src/LTMPlot.h +++ b/src/LTMPlot.h @@ -31,7 +31,7 @@ #include "LTMSettings.h" #include "MetricAggregator.h" -#include "MainWindow.h" +#include "Context.h" class LTMPlotBackground; class LTMWindow; @@ -45,7 +45,7 @@ class LTMPlot : public QwtPlot public: - LTMPlot(LTMWindow *, MainWindow *main); + LTMPlot(LTMWindow *, Context *context); ~LTMPlot(); void setData(LTMSettings *); void setAxisTitle(int axis, QString label); @@ -66,7 +66,7 @@ class LTMPlot : public QwtPlot double minY[10], maxY[10], maxX; // for all possible 10 curves private: - MainWindow *main; + Context *context; LTMSettings *settings; // date range selection diff --git a/src/LTMPopup.cpp b/src/LTMPopup.cpp index 1f0d1f1a0..13e923f96 100644 --- a/src/LTMPopup.cpp +++ b/src/LTMPopup.cpp @@ -17,8 +17,10 @@ */ #include "LTMPopup.h" +#include "MainWindow.h" +#include "Athlete.h" -LTMPopup::LTMPopup(MainWindow *parent) : QWidget(parent), main(parent) +LTMPopup::LTMPopup(Context *context) : QWidget(context->mainWindow), context(context) { // get application settings setAutoFillBackground(false); @@ -135,7 +137,7 @@ LTMPopup::setData(QListdata, const RideMetric *metric, QString t rides->setRowHeight(count, 14); // metrics - QString value = x.getStringForSymbol(metric->symbol(), main->athlete->useMetricUnits); + QString value = x.getStringForSymbol(metric->symbol(), context->athlete->useMetricUnits); h = new QTableWidgetItem(value,QTableWidgetItem::Type); h->setFlags(t->flags() & (~Qt::ItemIsEditable)); h->setTextAlignment(Qt::AlignHCenter); @@ -173,7 +175,7 @@ LTMPopup::setData(QListdata, const RideMetric *metric, QString t } // Metric summary - QString filename = main->athlete->home.absolutePath()+"/ltm-summary.html"; + QString filename = context->athlete->home.absolutePath()+"/ltm-summary.html"; if (!QFile(filename).exists()) filename = ":/html/ltm-summary.html"; // read it in... @@ -247,7 +249,7 @@ LTMPopup::setData(LTMSettings &settings, QDate start, QDate end) // metrics int column = 1; foreach(MetricDetail d, settings.metrics) { - QString value = x.getStringForSymbol(d.symbol, main->athlete->useMetricUnits); + QString value = x.getStringForSymbol(d.symbol, context->athlete->useMetricUnits); h = new QTableWidgetItem(value,QTableWidgetItem::Type); h->setFlags(t->flags() & (~Qt::ItemIsEditable)); h->setTextAlignment(Qt::AlignHCenter); @@ -291,7 +293,7 @@ LTMPopup::setData(LTMSettings &settings, QDate start, QDate end) } // Metric summary - QString filename = main->athlete->home.absolutePath()+"/ltm-summary.html"; + QString filename = context->athlete->home.absolutePath()+"/ltm-summary.html"; if (!QFile(filename).exists()) filename = ":/html/ltm-summary.html"; // read it in... @@ -316,7 +318,7 @@ LTMPopup::rideSelected() if (selected.count() > index) { // update summary - metrics->setText(selected[index].toString(summary, main->athlete->useMetricUnits)); + metrics->setText(selected[index].toString(summary, context->athlete->useMetricUnits)); notes->setText(selected[index].getText("Notes", "")); } diff --git a/src/LTMPopup.h b/src/LTMPopup.h index 9343f7cd2..39d1d299e 100644 --- a/src/LTMPopup.h +++ b/src/LTMPopup.h @@ -20,7 +20,7 @@ #define _GC_LTMPopup_h 1 #include "GoldenCheetah.h" -#include "MainWindow.h" +#include "Context.h" #include "Settings.h" #include "LTMSettings.h" #include "MetricAggregator.h" @@ -37,7 +37,7 @@ class LTMPopup : public QWidget public: - LTMPopup(MainWindow *parent); + LTMPopup(Context *context); void setTitle(QString); // when called from LTM chart @@ -55,7 +55,7 @@ class LTMPopup : public QWidget private: - MainWindow *main; + Context *context; QLabel *title; QTableWidget *rides; QTextEdit *metrics; diff --git a/src/LTMSettings.cpp b/src/LTMSettings.cpp index 8390cbb29..67116a96c 100644 --- a/src/LTMSettings.cpp +++ b/src/LTMSettings.cpp @@ -17,8 +17,9 @@ */ #include "LTMSettings.h" -#include "LTMTool.h" #include "MainWindow.h" +#include "LTMTool.h" +#include "Context.h" #include "LTMChartParser.h" #include @@ -30,8 +31,8 @@ /*---------------------------------------------------------------------- * EDIT CHART DIALOG *--------------------------------------------------------------------*/ -EditChartDialog::EditChartDialog(MainWindow *mainWindow, LTMSettings *settings, QListpresets) : - QDialog(mainWindow, Qt::Dialog), mainWindow(mainWindow), settings(settings), presets(presets) +EditChartDialog::EditChartDialog(Context *context, LTMSettings *settings, QListpresets) : + QDialog(context->mainWindow, Qt::Dialog), context(context), settings(settings), presets(presets) { setWindowTitle(tr("Enter Chart Name")); @@ -90,8 +91,8 @@ EditChartDialog::cancelClicked() /*---------------------------------------------------------------------- * CHART MANAGER DIALOG *--------------------------------------------------------------------*/ -ChartManagerDialog::ChartManagerDialog(MainWindow *mainWindow, QList*presets) : - QDialog(mainWindow, Qt::Dialog), mainWindow(mainWindow), presets(presets) +ChartManagerDialog::ChartManagerDialog(Context *context, QList*presets) : + QDialog(context->mainWindow, Qt::Dialog), context(context), presets(presets) { setWindowTitle(tr("Manage Charts")); diff --git a/src/LTMSettings.h b/src/LTMSettings.h index a46011a5a..2eeffe73e 100644 --- a/src/LTMSettings.h +++ b/src/LTMSettings.h @@ -34,7 +34,7 @@ class LTMTool; class LTMSettings; class SummaryMetrics; -class MainWindow; +class Context; class RideMetric; // group by settings @@ -141,14 +141,14 @@ class EditChartDialog : public QDialog public: - EditChartDialog(MainWindow *, LTMSettings *, QList); + EditChartDialog(Context *, LTMSettings *, QList); public slots: void okClicked(); void cancelClicked(); private: - MainWindow *mainWindow; + Context *context; LTMSettings *settings; QList presets; @@ -163,7 +163,7 @@ class ChartManagerDialog : public QDialog public: - ChartManagerDialog(MainWindow *, QList *); + ChartManagerDialog(Context *, QList *); public slots: void okClicked(); @@ -176,7 +176,7 @@ class ChartManagerDialog : public QDialog void deleteClicked(); private: - MainWindow *mainWindow; + Context *context; QList *presets; QLineEdit *chartName; diff --git a/src/LTMSidebar.cpp b/src/LTMSidebar.cpp index 50a132a37..70dee7ee8 100644 --- a/src/LTMSidebar.cpp +++ b/src/LTMSidebar.cpp @@ -18,6 +18,8 @@ #include "LTMSidebar.h" #include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "Settings.h" #include "Units.h" #include @@ -39,7 +41,7 @@ #include "MetricAggregator.h" #include "SummaryMetrics.h" -LTMSidebar::LTMSidebar(MainWindow *parent, const QDir &home) : QWidget(parent), home(home), main(parent), active(false) +LTMSidebar::LTMSidebar(Context *context, const QDir &home) : QWidget(context->mainWindow), home(home), context(context), active(false) { QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->setContentsMargins(0,0,0,0); @@ -93,7 +95,7 @@ LTMSidebar::LTMSidebar(MainWindow *parent, const QDir &home) : QWidget(parent), #endif eventsWidget->addWidget(eventTree); - seasons = parent->athlete->seasons; + seasons = context->athlete->seasons; resetSeasons(); // reset the season list configChanged(); // will reset the metric tree @@ -120,7 +122,7 @@ LTMSidebar::LTMSidebar(MainWindow *parent, const QDir &home) : QWidget(parent), mainLayout->addWidget(splitter); - splitter->prepare(main->athlete->cyclist, "LTM"); + splitter->prepare(context->athlete->cyclist, "LTM"); // our date ranges connect(dateRangeTree,SIGNAL(itemSelectionChanged()), this, SLOT(dateRangeTreeWidgetSelectionChanged())); @@ -129,7 +131,7 @@ LTMSidebar::LTMSidebar(MainWindow *parent, const QDir &home) : QWidget(parent), connect(dateRangeTree,SIGNAL(itemMoved(QTreeWidgetItem *,int, int)), this, SLOT(dateRangeMoved(QTreeWidgetItem*, int, int))); connect(eventTree,SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(eventPopup(const QPoint &))); // GC signal - connect(main->context, SIGNAL(configChanged()), this, SLOT(configChanged())); + connect(context, SIGNAL(configChanged()), this, SLOT(configChanged())); connect(seasons, SIGNAL(seasonsChanged()), this, SLOT(resetSeasons())); connect(this, SIGNAL(dateRangeChanged(DateRange)), this, SLOT(setSummary(DateRange))); @@ -182,7 +184,7 @@ LTMSidebar::dateRangeTreeWidgetSelectionChanged() // make sure they fit eventTree->header()->resizeSections(QHeaderView::ResizeToContents); - appsettings->setCValue(main->athlete->cyclist, GC_LTM_LAST_DATE_RANGE, dateRange->id().toString()); + appsettings->setCValue(context->athlete->cyclist, GC_LTM_LAST_DATE_RANGE, dateRange->id().toString()); } @@ -206,7 +208,7 @@ LTMSidebar::resetSeasons() for (i=allDateRanges->childCount(); i > 0; i--) { delete allDateRanges->takeChild(0); } - QString id = appsettings->cvalue(main->athlete->cyclist, GC_LTM_LAST_DATE_RANGE, seasons->seasons.at(0).id().toString()).toString(); + QString id = appsettings->cvalue(context->athlete->cyclist, GC_LTM_LAST_DATE_RANGE, seasons->seasons.at(0).id().toString()).toString(); for (i=0; i seasons.count(); i++) { Season season = seasons->seasons.at(i); QTreeWidgetItem *add = new QTreeWidgetItem(allDateRanges, season.getType()); @@ -443,7 +445,7 @@ LTMSidebar::addRange() { Season newOne; - EditSeasonDialog dialog(main, &newOne); + EditSeasonDialog dialog(context, &newOne); if (dialog.exec()) { @@ -466,7 +468,7 @@ LTMSidebar::editRange() if (dateRangeTree->selectedItems().count() != 1) return; int index = allDateRanges->indexOfChild(dateRangeTree->selectedItems().first()); - EditSeasonDialog dialog(main, &seasons->seasons[index]); + EditSeasonDialog dialog(context, &seasons->seasons[index]); if (dialog.exec()) { @@ -509,7 +511,7 @@ LTMSidebar::addEvent() } SeasonEvent myevent("", QDate()); - EditSeasonEventDialog dialog(main, &myevent); + EditSeasonEventDialog dialog(context, &myevent); if (dialog.exec()) { @@ -572,7 +574,7 @@ LTMSidebar::editEvent() QTreeWidgetItem *ours = eventTree->selectedItems().first(); int index = allEvents->indexOfChild(ours); - EditSeasonEventDialog dialog(main, &seasons->seasons[seasonindex].events[index]); + EditSeasonEventDialog dialog(context, &seasons->seasons[seasonindex].events[index]); if (dialog.exec()) { @@ -633,7 +635,7 @@ LTMSidebar::setSummary(DateRange dateRange) to = newTo; // lets get the metrics - QListresults = main->athlete->metricDB->getAllMetricsFor(QDateTime(from,QTime(0,0,0)), QDateTime(to, QTime(24,59,59))); + QListresults = context->athlete->metricDB->getAllMetricsFor(QDateTime(from,QTime(0,0,0)), QDateTime(to, QTime(24,59,59))); // foreach of the metrics get an aggregated value // header of summary @@ -685,15 +687,15 @@ LTMSidebar::setSummary(DateRange dateRange) const RideMetric *metric = RideMetricFactory::instance().rideMetric(metricname); QStringList empty; // filter list not used at present - QString value = SummaryMetrics::getAggregated(main, metricname, results, empty, false, main->athlete->useMetricUnits); + QString value = SummaryMetrics::getAggregated(context, metricname, results, empty, false, context->athlete->useMetricUnits); // Maximum Max and Average Average looks nasty, remove from name for display QString s = metric ? metric->name().replace(QRegExp(tr("^(Average|Max) ")), "") : "unknown"; // don't show units for time values - if (metric && (metric->units(main->athlete->useMetricUnits) == "seconds" || - metric->units(main->athlete->useMetricUnits) == tr("seconds") || - metric->units(main->athlete->useMetricUnits) == "")) { + if (metric && (metric->units(context->athlete->useMetricUnits) == "seconds" || + metric->units(context->athlete->useMetricUnits) == tr("seconds") || + metric->units(context->athlete->useMetricUnits) == "")) { summaryText += QString("") .arg(s) @@ -702,7 +704,7 @@ LTMSidebar::setSummary(DateRange dateRange) } else { summaryText += QString("") .arg(s) - .arg(metric ? metric->units(main->athlete->useMetricUnits) : "unknown") + .arg(metric ? metric->units(context->athlete->useMetricUnits) : "unknown") .arg(value); } } diff --git a/src/LTMSidebar.h b/src/LTMSidebar.h index 0d96e18b9..92151ed6b 100644 --- a/src/LTMSidebar.h +++ b/src/LTMSidebar.h @@ -20,7 +20,7 @@ #define _GC_LTMSidebar_h 1 #include "GoldenCheetah.h" -#include "MainWindow.h" +#include "Context.h" #include "GcSideBarItem.h" #include "Season.h" #include "RideMetric.h" @@ -42,7 +42,7 @@ class LTMSidebar : public QWidget public: - LTMSidebar(MainWindow *parent, const QDir &home); + LTMSidebar(Context *context, const QDir &home); //const Season *currentDateRange() { return dateRange; } //void selectDateRange(int); @@ -82,7 +82,7 @@ class LTMSidebar : public QWidget private: const QDir home; - MainWindow *main; + Context *context; bool active; QDate from, to; // so we don't repeat update... diff --git a/src/LTMTool.cpp b/src/LTMTool.cpp index eca96da08..594385d29 100644 --- a/src/LTMTool.cpp +++ b/src/LTMTool.cpp @@ -18,6 +18,8 @@ #include "LTMTool.h" #include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "Settings.h" #include "Units.h" #include @@ -34,7 +36,7 @@ #include "RideMetadata.h" #include "SpecialFields.h" -LTMTool::LTMTool(MainWindow *parent, const QDir &home, bool multi) : QWidget(parent), home(home), main(parent), active(false), _amFiltered(false) +LTMTool::LTMTool(Context *context, const QDir &home, bool multi) : QWidget(context->mainWindow), home(home), context(context), active(false), _amFiltered(false) { setStyleSheet("QFrame { FrameStyle = QFrame::NoFrame };" "QWidget { background = Qt::white; border:0 px; margin: 2px; };"); @@ -51,7 +53,7 @@ LTMTool::LTMTool(MainWindow *parent, const QDir &home, bool multi) : QWidget(par basicsettingsLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow); #ifdef GC_HAVE_LUCENE - searchBox = new SearchFilterBox(this, main); + searchBox = new SearchFilterBox(this, context); connect(searchBox, SIGNAL(searchClear()), this, SLOT(clearFilter())); connect(searchBox, SIGNAL(searchResults(QStringList)), this, SLOT(setFilter(QStringList))); @@ -155,7 +157,7 @@ LTMTool::LTMTool(MainWindow *parent, const QDir &home, bool multi) : QWidget(par // set default for the user overiddable fields adds.uname = adds.name; adds.units = ""; - adds.uunits = adds.metric->units(main->athlete->useMetricUnits); + adds.uunits = adds.metric->units(context->athlete->useMetricUnits); // default units to metric name if it is blank if (adds.uunits == "") adds.uunits = adds.name; @@ -623,7 +625,7 @@ LTMTool::LTMTool(MainWindow *parent, const QDir &home, bool multi) : QWidget(par // metadata metrics SpecialFields sp; - foreach (FieldDefinition field, main->athlete->rideMetadata()->getFields()) { + foreach (FieldDefinition field, context->athlete->rideMetadata()->getFields()) { if (!sp.isMetric(field.name) && (field.type == 3 || field.type == 4)) { MetricDetail metametric; metametric.type = METRIC_META; @@ -646,7 +648,7 @@ LTMTool::LTMTool(MainWindow *parent, const QDir &home, bool multi) : QWidget(par // measures QList measureDefinitions; QList keywordDefinitions; //NOTE: not used in measures.xml - QString filename = main->athlete->home.absolutePath()+"/measures.xml"; + QString filename = context->athlete->home.absolutePath()+"/measures.xml"; QString colorfield; if (!QFile(filename).exists()) filename = ":/xml/measures.xml"; RideMetadata::readXML(filename, keywordDefinitions, measureDefinitions, colorfield); @@ -711,7 +713,7 @@ LTMTool::LTMTool(MainWindow *parent, const QDir &home, bool multi) : QWidget(par tabs->addTab(metricContainer, tr("Custom")); connect(metricTree,SIGNAL(itemSelectionChanged()), this, SLOT(metricTreeWidgetSelectionChanged())); - connect(main->context, SIGNAL(configChanged()), this, SLOT(configChanged())); + connect(context, SIGNAL(configChanged()), this, SLOT(configChanged())); connect(metricTree,SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(metricTreePopup(const QPoint &))); // switched between one or other @@ -815,7 +817,7 @@ void LTMTool::editMetric() { int index = allMetrics->indexOfChild(activeMetric); - EditMetricDetailDialog dialog(main, &metrics[index]); + EditMetricDetailDialog dialog(context, &metrics[index]); if (dialog.exec()) { // notify of change @@ -827,7 +829,7 @@ void LTMTool::colorPicker() { int index = allMetrics->indexOfChild(activeMetric); - QColorDialog picker(main); + QColorDialog picker(context->mainWindow); picker.setCurrentColor(metrics[index].penColor); // don't use native dialog, since there is a nasty bug causing focus loss @@ -876,8 +878,8 @@ LTMTool::applySettings(LTMSettings *settings) // usemetricUnits changed since charts.xml was // written if (saved && saved->conversion() != 1.0 && - metrics[i].uunits.contains(saved->units(!main->athlete->useMetricUnits))) - metrics[i].uunits.replace(saved->units(!main->athlete->useMetricUnits), saved->units(main->athlete->useMetricUnits)); + metrics[i].uunits.contains(saved->units(!context->athlete->useMetricUnits))) + metrics[i].uunits.replace(saved->units(!context->athlete->useMetricUnits), saved->units(context->athlete->useMetricUnits)); // select it on the tool allMetrics->child(i)->setSelected(true); break; @@ -891,8 +893,8 @@ LTMTool::applySettings(LTMSettings *settings) /*---------------------------------------------------------------------- * EDIT METRIC DETAIL DIALOG *--------------------------------------------------------------------*/ -EditMetricDetailDialog::EditMetricDetailDialog(MainWindow *mainWindow, MetricDetail *metricDetail) : - QDialog(mainWindow, Qt::Dialog), mainWindow(mainWindow), metricDetail(metricDetail) +EditMetricDetailDialog::EditMetricDetailDialog(Context *context, MetricDetail *metricDetail) : + QDialog(context->mainWindow, Qt::Dialog), context(context), metricDetail(metricDetail) { setWindowTitle(tr("Settings")); @@ -1061,7 +1063,7 @@ EditMetricDetailDialog::cancelClicked() void EditMetricDetailDialog::colorClicked() { - QColorDialog picker(mainWindow); + QColorDialog picker(context->mainWindow); picker.setCurrentColor(penColor); // don't use native dialog, since there is a nasty bug causing focus loss @@ -1162,11 +1164,11 @@ LTMTool::metricDetails(QString symbol) } void -LTMTool::translateMetrics(MainWindow *main, const QDir &home, LTMSettings *settings) +LTMTool::translateMetrics(Context *context, const QDir &home, LTMSettings *settings) { static QMap unitsMap; // LTMTool instance is created to have access to metrics catalog - LTMTool* ltmTool = new LTMTool(main, home, false); + LTMTool* ltmTool = new LTMTool(context, home, false); if (unitsMap.isEmpty()) { foreach(MetricDetail metric, ltmTool->metrics) { if (metric.units != "") // translate units diff --git a/src/LTMTool.h b/src/LTMTool.h index 0821ca875..d927fe1a2 100644 --- a/src/LTMTool.h +++ b/src/LTMTool.h @@ -20,7 +20,7 @@ #define _GC_LTMTool_h 1 #include "GoldenCheetah.h" -#include "MainWindow.h" +#include "Context.h" #include "Season.h" #include "RideMetric.h" #include "LTMSettings.h" @@ -49,7 +49,7 @@ class LTMTool : public QWidget public: - LTMTool(MainWindow *parent, const QDir &home, bool Multi = true); + LTMTool(Context *context, const QDir &home, bool Multi = true); //const Season *currentDateRange() { return dateRange; } //void selectDateRange(int); @@ -60,7 +60,7 @@ class LTMTool : public QWidget MetricDetail metricDetails(QTreeWidgetItem *); MetricDetail* metricDetails(QString symbol); void selectMetric(QString symbol); - static void translateMetrics(MainWindow *main, const QDir &home, LTMSettings *settings); + static void translateMetrics(Context *context, const QDir &home, LTMSettings *settings); // allow others to create and update season structures //int newSeason(QString, QDate, QDate, int); @@ -131,7 +131,7 @@ class LTMTool : public QWidget void translateDefaultCharts(QList&charts); const QDir home; - MainWindow *main; + Context *context; bool active; // ignore season changed signals since we triggered them //Seasons *seasons; @@ -160,7 +160,7 @@ class EditMetricDetailDialog : public QDialog public: - EditMetricDetailDialog(MainWindow *, MetricDetail *); + EditMetricDetailDialog(Context *, MetricDetail *); public slots: void colorClicked(); @@ -168,7 +168,7 @@ class EditMetricDetailDialog : public QDialog void cancelClicked(); private: - MainWindow *mainWindow; + Context *context; MetricDetail *metricDetail; QLineEdit *userName, diff --git a/src/LTMWindow.cpp b/src/LTMWindow.cpp index f6f076e04..7d22d7137 100644 --- a/src/LTMWindow.cpp +++ b/src/LTMWindow.cpp @@ -20,7 +20,9 @@ #include "LTMTool.h" #include "LTMPlot.h" #include "LTMSettings.h" -#include "MainWindow.h" +#include "Context.h" +#include "Context.h" +#include "Athlete.h" #include "SummaryMetrics.h" #include "Settings.h" #include "math.h" @@ -35,17 +37,16 @@ #include #include -LTMWindow::LTMWindow(MainWindow *parent) : - GcChartWindow(parent), dirty(true) +LTMWindow::LTMWindow(Context *context) : + GcChartWindow(context), context(context), dirty(true) { - main = parent; setInstanceName("Metric Window"); useToToday = useCustom = false; plotted = DateRange(QDate(01,01,01), QDate(01,01,01)); // the plot QVBoxLayout *mainLayout = new QVBoxLayout; - ltmPlot = new LTMPlot(this, main); + ltmPlot = new LTMPlot(this, context); mainLayout->addWidget(ltmPlot); setChartLayout(mainLayout); @@ -87,7 +88,7 @@ LTMWindow::LTMWindow(MainWindow *parent) : // the popup popup = new GcPane(); - ltmPopup = new LTMPopup(main); + ltmPopup = new LTMPopup(context); QVBoxLayout *popupLayout = new QVBoxLayout(); popupLayout->addWidget(ltmPopup); popup->setLayout(popupLayout); @@ -120,7 +121,7 @@ LTMWindow::LTMWindow(MainWindow *parent) : _canvasPicker = new LTMCanvasPicker(ltmPlot); - ltmTool = new LTMTool(parent, main->athlete->home); + ltmTool = new LTMTool(context, context->athlete->home); // initialise settings.ltmTool = ltmTool; @@ -149,15 +150,15 @@ LTMWindow::LTMWindow(MainWindow *parent) : connect(ltmTool, SIGNAL(useCustomRange(DateRange)), this, SLOT(useCustomRange(DateRange))); connect(ltmTool, SIGNAL(useThruToday()), this, SLOT(useThruToday())); connect(ltmTool, SIGNAL(useStandardRange()), this, SLOT(useStandardRange())); - connect(main, SIGNAL(filterChanged(QStringList&)), this, SLOT(refresh())); + connect(context->mainWindow, SIGNAL(filterChanged(QStringList&)), this, SLOT(refresh())); // connect pickers to ltmPlot connect(_canvasPicker, SIGNAL(pointHover(QwtPlotCurve*, int)), ltmPlot, SLOT(pointHover(QwtPlotCurve*, int))); connect(_canvasPicker, SIGNAL(pointClicked(QwtPlotCurve*, int)), ltmPlot, SLOT(pointClicked(QwtPlotCurve*, int))); - connect(main, SIGNAL(rideAdded(RideItem*)), this, SLOT(refresh(void))); - connect(main, SIGNAL(rideDeleted(RideItem*)), this, SLOT(refresh(void))); - connect(main->context, SIGNAL(configChanged()), this, SLOT(refresh())); + connect(context->mainWindow, SIGNAL(rideAdded(RideItem*)), this, SLOT(refresh(void))); + connect(context->mainWindow, SIGNAL(rideDeleted(RideItem*)), this, SLOT(refresh(void))); + connect(context, SIGNAL(configChanged()), this, SLOT(refresh())); } LTMWindow::~LTMWindow() @@ -212,11 +213,11 @@ LTMWindow::refresh() { // refresh for changes to ridefiles / zones - if (amVisible() == true && main->athlete->metricDB != NULL) { + if (amVisible() == true && context->athlete->metricDB != NULL) { results.clear(); // clear any old data - results = main->athlete->metricDB->getAllMetricsFor(settings.start, settings.end); + results = context->athlete->metricDB->getAllMetricsFor(settings.start, settings.end); measures.clear(); // clear any old data - measures = main->athlete->metricDB->getAllMeasuresFor(settings.start, settings.end); + measures = context->athlete->metricDB->getAllMeasuresFor(settings.start, settings.end); refreshPlot(); repaint(); // title changes color when filters change dirty = false; @@ -290,9 +291,9 @@ LTMWindow::filterChanged() // we need to get data again and apply filter results.clear(); // clear any old data - results = main->athlete->metricDB->getAllMetricsFor(settings.start, settings.end); + results = context->athlete->metricDB->getAllMetricsFor(settings.start, settings.end); measures.clear(); // clear any old data - measures = main->athlete->metricDB->getAllMeasuresFor(settings.start, settings.end); + measures = context->athlete->metricDB->getAllMeasuresFor(settings.start, settings.end); // loop through results removing any not in stringlist.. if (ltmTool->isFiltered()) { @@ -373,10 +374,10 @@ LTMWindow::chartSelected(int selected) void LTMWindow::saveClicked() { - EditChartDialog editor(main, &settings, ltmTool->presets); + EditChartDialog editor(context, &settings, ltmTool->presets); if (editor.exec()) { ltmTool->presets.append(settings); - settings.writeChartXML(main->athlete->home, ltmTool->presets); + settings.writeChartXML(context->athlete->home, ltmTool->presets); ltmTool->presetPicker->insertItem(ltmTool->presets.count()-1, settings.name, ltmTool->presets.count()-1); ltmTool->presetPicker->setCurrentIndex(ltmTool->presets.count()-1); } @@ -386,7 +387,7 @@ void LTMWindow::manageClicked() { QList charts = ltmTool->presets; // get current - ChartManagerDialog editor(main, &charts); + ChartManagerDialog editor(context, &charts); if (editor.exec()) { // wipe the current and add the new ltmTool->presets = charts; @@ -396,7 +397,7 @@ LTMWindow::manageClicked() ltmTool->presetPicker->addItem(ltmTool->presets[i].name, i); // update charts.xml - settings.writeChartXML(main->athlete->home, ltmTool->presets); + settings.writeChartXML(context->athlete->home, ltmTool->presets); } } diff --git a/src/LTMWindow.h b/src/LTMWindow.h index 8650cc1c7..655919a3c 100644 --- a/src/LTMWindow.h +++ b/src/LTMWindow.h @@ -23,6 +23,7 @@ #include #include #include "MainWindow.h" +#include "Context.h" #include "MetricAggregator.h" #include "Season.h" #include "LTMPlot.h" @@ -104,18 +105,18 @@ class LTMWindow : public GcChartWindow public: - LTMWindow(MainWindow *); + LTMWindow(Context *); ~LTMWindow(); LTMToolTip *toolTip() { return picker; } // reveal / filters bool hasReveal() { return true; } #ifdef GC_HAVE_LUCENE - bool isFiltered() const { return (ltmTool->isFiltered() || main->isfiltered); } + bool isFiltered() const { return (ltmTool->isFiltered() || context->mainWindow->isfiltered); } #endif // used by children - MainWindow *main; + Context *context; // get/set properties int chart() const { return ltmTool->presetPicker->currentIndex(); } @@ -178,7 +179,7 @@ class LTMWindow : public GcChartWindow void useThruToday(); private: - // passed from MainWindow + // passed from Context * DateRange plotted; bool useCustom; diff --git a/src/LeftRightBalance.cpp b/src/LeftRightBalance.cpp index 540853e06..7616dd4ed 100644 --- a/src/LeftRightBalance.cpp +++ b/src/LeftRightBalance.cpp @@ -43,7 +43,7 @@ class LeftRightBalance : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { total = count = 0; diff --git a/src/LibUsb.cpp b/src/LibUsb.cpp index 7484d36b9..49d7ddfbc 100644 --- a/src/LibUsb.cpp +++ b/src/LibUsb.cpp @@ -24,7 +24,7 @@ #include #include "LibUsb.h" #include "Settings.h" -#include "MainWindow.h" +#include "Context.h" LibUsb::LibUsb(int type) : type(type) { diff --git a/src/LibUsb.h b/src/LibUsb.h index f37ec5698..89d4ad1ac 100644 --- a/src/LibUsb.h +++ b/src/LibUsb.h @@ -49,7 +49,7 @@ extern "C" { #define TYPE_ANT 0 #define TYPE_FORTIUS 1 -class MainWindow; +class Context; class LibUsb { diff --git a/src/Library.cpp b/src/Library.cpp index b8e0e1beb..30b33289a 100644 --- a/src/Library.cpp +++ b/src/Library.cpp @@ -16,6 +16,8 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ +#include "Athlete.h" +#include "Context.h" #include "Library.h" #include "Settings.h" #include "LibraryParser.h" @@ -93,7 +95,7 @@ Library::initialise(QDir home) } void -Library::importFiles(MainWindow *mainWindow, QStringList files) +Library::importFiles(Context *context, QStringList files) { QStringList videos, workouts; MediaHelper helper; @@ -110,7 +112,7 @@ Library::importFiles(MainWindow *mainWindow, QStringList files) // if it is a workout we parse it to check if (ErgFile::isWorkout(file)) { int mode; - ErgFile *p = new ErgFile(file, mode, mainWindow); + ErgFile *p = new ErgFile(file, mode, context); if (p->isValid()) workouts << file; delete p; } @@ -158,7 +160,7 @@ Library::importFiles(MainWindow *mainWindow, QStringList files) // set target directory QString workoutDir = appsettings->value(NULL, GC_WORKOUTDIR).toString(); if (workoutDir == "") { - QDir root = mainWindow->athlete->home; + QDir root = context->athlete->home; root.cdUp(); workoutDir = root.absolutePath(); } @@ -174,7 +176,7 @@ Library::importFiles(MainWindow *mainWindow, QStringList files) // still add it, it may noit have been scanned... int mode; - ErgFile file(target, mode, mainWindow); + ErgFile file(target, mode, context); trainDB->importWorkout(target, &file); } @@ -182,35 +184,35 @@ Library::importFiles(MainWindow *mainWindow, QStringList files) trainDB->endLUW(); // now write to disk.. any refs we added - LibraryParser::serialize(mainWindow->athlete->home); + LibraryParser::serialize(context->athlete->home); // Tell traintool to select what was imported - if (videos.count()) mainWindow->context->notifySelectVideo(videos[0]); - if (workouts.count()) mainWindow->context->notifySelectWorkout(target); + if (videos.count()) context->notifySelectVideo(videos[0]); + if (workouts.count()) context->notifySelectWorkout(target); } else { // we have a list of files to import, lets kick off the importer... - WorkoutImportDialog *p = new WorkoutImportDialog(mainWindow, files); + WorkoutImportDialog *p = new WorkoutImportDialog(context, files); p->exec(); } } void -Library::removeRef(MainWindow *mainWindow, QString ref) +Library::removeRef(Context *context, QString ref) { // remove a previous reference int index = refs.indexOf(ref); if (index >= 0) { refs.removeAt(index); - LibraryParser::serialize(mainWindow->athlete->home); + LibraryParser::serialize(context->athlete->home); } } // // SEARCHDIALOG -- user select paths and files and run a search // -LibrarySearchDialog::LibrarySearchDialog(MainWindow *mainWindow) : mainWindow(mainWindow) +LibrarySearchDialog::LibrarySearchDialog(Context *context) : context(context) { setAttribute(Qt::WA_DeleteOnClose); setWindowTitle(tr("Search for Workouts and Media")); @@ -406,7 +408,7 @@ LibrarySearchDialog::search() // now write to disk.. - LibraryParser::serialize(mainWindow->athlete->home); + LibraryParser::serialize(context->athlete->home); } // ok, we;ve completed a search without aborting @@ -551,7 +553,7 @@ LibrarySearchDialog::updateDB() // workouts foreach(QString ergFile, workoutsFound) { int mode; - ErgFile file(ergFile, mode, mainWindow); + ErgFile file(ergFile, mode, context); if (file.isValid()) { trainDB->importWorkout(ergFile, &file); } @@ -579,7 +581,7 @@ LibrarySearchDialog::updateDB() // is a workout? if (ErgFile::isWorkout(r)) { int mode; - ErgFile file(r, mode, mainWindow); + ErgFile file(r, mode, context); if (file.isValid()) { trainDB->importWorkout(r, &file); } @@ -644,8 +646,8 @@ LibrarySearch::abort() // // LIBRARY IMPORT DIALOG... // -WorkoutImportDialog::WorkoutImportDialog(MainWindow *main, QStringList files) : - main(main), files(files) +WorkoutImportDialog::WorkoutImportDialog(Context *context, QStringList files) : + context(context), files(files) { setAttribute(Qt::WA_DeleteOnClose); setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint); @@ -667,7 +669,7 @@ WorkoutImportDialog::WorkoutImportDialog(MainWindow *main, QStringList files) : // if it is a workout we parse it to check if (ErgFile::isWorkout(file)) { int mode; - ErgFile *p = new ErgFile(file, mode, main); + ErgFile *p = new ErgFile(file, mode, context); if (p->isValid()) workouts << file; delete p; } @@ -750,12 +752,12 @@ WorkoutImportDialog::import() } // now write to disk.. - LibraryParser::serialize(main->athlete->home); + LibraryParser::serialize(context->athlete->home); // set target directory QString workoutDir = appsettings->value(NULL, GC_WORKOUTDIR).toString(); if (workoutDir == "") { - QDir root = main->athlete->home; + QDir root = context->athlete->home; root.cdUp(); workoutDir = root.absolutePath(); } @@ -769,7 +771,7 @@ WorkoutImportDialog::import() // cannot read or not valid int mode; - ErgFile file(workout, mode, main); + ErgFile file(workout, mode, context); if (!file.isValid()) continue; // get target name diff --git a/src/Library.h b/src/Library.h index add633587..317eab24b 100644 --- a/src/Library.h +++ b/src/Library.h @@ -40,8 +40,8 @@ class Library : QObject static void initialise(QDir); // init static Library *findLibrary(QString); - static void importFiles(MainWindow *mainWindow, QStringList files); - void removeRef(MainWindow *mainWindow, QString ref); + static void importFiles(Context *context, QStringList files); + void removeRef(Context *context, QString ref); }; extern QList libraries; // keep track of all Library search paths for all users @@ -52,7 +52,7 @@ class LibrarySearchDialog : public QDialog Q_OBJECT public: - LibrarySearchDialog(MainWindow *mainWindow); + LibrarySearchDialog(Context *context); private slots: void search(); @@ -68,7 +68,7 @@ class LibrarySearchDialog : public QDialog void updateDB(); private: - MainWindow *mainWindow; + Context *context; Library *library; LibrarySearch *searcher; bool searching; @@ -130,13 +130,13 @@ class WorkoutImportDialog : public QDialog Q_OBJECT public: - WorkoutImportDialog(MainWindow *main, QStringList files); + WorkoutImportDialog(Context *context, QStringList files); public slots: void import(); private: - MainWindow *main; + Context *context; QStringList files; QStringList videos, workouts; diff --git a/src/Lucene.cpp b/src/Lucene.cpp index 321d8c0c3..3869434b5 100644 --- a/src/Lucene.cpp +++ b/src/Lucene.cpp @@ -18,6 +18,8 @@ #include "Lucene.h" #include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" // stdc strings using namespace std; @@ -29,13 +31,13 @@ using namespace lucene::queryParser; using namespace lucene::search; using namespace lucene::store; -Lucene::Lucene(QObject *parent, MainWindow *main) : QObject(parent), main(main) +Lucene::Lucene(QObject *parent, Context *context) : QObject(parent), context(context) { // create the directory if needed - main->athlete->home.mkdir("index"); + context->athlete->home.mkdir("index"); // make index directory if needed - dir = QDir(main->athlete->home.canonicalPath() + "/index"); + dir = QDir(context->athlete->home.canonicalPath() + "/index"); try { @@ -77,11 +79,11 @@ bool Lucene::importRide(SummaryMetrics *, RideFile *ride, QColor , unsigned long QString alltexts; // And all the metadata texts individually - foreach(FieldDefinition field, main->athlete->rideMetadata()->getFields()) { + foreach(FieldDefinition field, context->athlete->rideMetadata()->getFields()) { - if (!main->specialFields.isMetric(field.name) && (field.type < 3 || field.type == 7)) { + if (!context->mainWindow->specialFields.isMetric(field.name) && (field.type < 3 || field.type == 7)) { - std::wstring name = main->specialFields.makeTechName(field.name).toStdWString(); + std::wstring name = context->mainWindow->specialFields.makeTechName(field.name).toStdWString(); std::wstring value = ride->getTag(field.name,"").toStdWString(); alltexts += ride->getTag(field.name,"") + " "; diff --git a/src/Lucene.h b/src/Lucene.h index 3972b105c..b39ba8b61 100644 --- a/src/Lucene.h +++ b/src/Lucene.h @@ -23,7 +23,7 @@ #include #include -#include "MainWindow.h" +#include "Context.h" #include "RideMetadata.h" #include "SummaryMetrics.h" #include "RideFile.h" @@ -43,7 +43,7 @@ class Lucene : public QObject Q_OBJECT public: - Lucene(QObject *parent, MainWindow *main); + Lucene(QObject *parent, Context *context); ~Lucene(); // Create/Delete Metrics @@ -63,7 +63,7 @@ signals: void results(QStringList); private: - MainWindow *main; + Context *context; QDir dir; // CLucene objects diff --git a/src/MainWindow.cpp b/src/MainWindow.cpp index b5016a9a9..6a9563700 100644 --- a/src/MainWindow.cpp +++ b/src/MainWindow.cpp @@ -18,6 +18,8 @@ */ #include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "AboutDialog.h" #include "AddIntervalDialog.h" #include "BestIntervalDialog.h" @@ -207,7 +209,7 @@ MainWindow::MainWindow(const QDir &home) : #endif // Metadata fields - athlete->_rideMetadata = new RideMetadata(this,true); + athlete->_rideMetadata = new RideMetadata(context,true); athlete->_rideMetadata->hide(); #ifdef GC_HAVE_LUCENE @@ -365,7 +367,7 @@ MainWindow::MainWindow(const QDir &home) : head->addWidget(viewsel); #ifdef GC_HAVE_LUCENE - SearchFilterBox *searchBox = new SearchFilterBox(this,this,false); + SearchFilterBox *searchBox = new SearchFilterBox(this,context,false); QCleanlooksStyle *toolStyle = new QCleanlooksStyle(); searchBox->setStyle(toolStyle); searchBox->setFixedWidth(300); @@ -380,7 +382,7 @@ MainWindow::MainWindow(const QDir &home) : setContentsMargins(0,0,0,0); setAcceptDrops(true); - GCColor *GCColorSet = new GCColor(this); // get/keep colorset + GCColor *GCColorSet = new GCColor(context); // get/keep colorset GCColorSet->colorSet(); // shut up the compiler #if (defined Q_OS_MAC) && (defined GC_HAVE_LION) @@ -393,7 +395,7 @@ MainWindow::MainWindow(const QDir &home) : /*---------------------------------------------------------------------- * The help bubble used everywhere *--------------------------------------------------------------------*/ - bubble = new GcBubble(this); + bubble = new GcBubble(context); bubble->hide(); /*---------------------------------------------------------------------- @@ -436,20 +438,20 @@ MainWindow::MainWindow(const QDir &home) : *--------------------------------------------------------------------*/ #ifdef GC_HAVE_LUCENE - athlete->lucene = new Lucene(this, this); // before metricDB attempts to refresh + athlete->lucene = new Lucene(context, context); // before metricDB attempts to refresh #endif - athlete->metricDB = new MetricAggregator(this); // just to catch config updates! + athlete->metricDB = new MetricAggregator(context); // just to catch config updates! athlete->metricDB->refreshMetrics(); // Downloaders - athlete->withingsDownload = new WithingsDownload(this); - athlete->zeoDownload = new ZeoDownload(this); - athlete->calendarDownload = new CalendarDownload(this); + athlete->withingsDownload = new WithingsDownload(context); + athlete->zeoDownload = new ZeoDownload(context); + athlete->calendarDownload = new CalendarDownload(context); // Calendar #ifdef GC_HAVE_ICAL - athlete->rideCalendar = new ICalendar(this); // my local/remote calendar entries - athlete->davCalendar = new CalDAV(this); // remote caldav + athlete->rideCalendar = new ICalendar(context); // my local/remote calendar entries + athlete->davCalendar = new CalDAV(context); // remote caldav athlete->davCalendar->download(); // refresh the diary window #endif @@ -550,7 +552,7 @@ MainWindow::MainWindow(const QDir &home) : #ifdef GC_HAVE_LUCENE // add a search box on far right, but with a little space too - SearchFilterBox *searchBox = new SearchFilterBox(this,this,false); + SearchFilterBox *searchBox = new SearchFilterBox(this,context,false); searchBox->setStyle(toolStyle); searchBox->setFixedWidth(250); head->addWidget(searchBox); @@ -563,11 +565,11 @@ MainWindow::MainWindow(const QDir &home) : /*---------------------------------------------------------------------- * Scope Bar *--------------------------------------------------------------------*/ - trainTool = new TrainTool(this, athlete->home); + trainTool = new TrainTool(context, athlete->home); trainTool->hide(); trainTool->getToolbarButtons()->hide(); // no show yet - scopebar = new GcScopeBar(this, trainTool->getToolbarButtons()); + scopebar = new GcScopeBar(context, trainTool->getToolbarButtons()); connect(scopebar, SIGNAL(selectDiary()), this, SLOT(selectDiary())); connect(scopebar, SIGNAL(selectHome()), this, SLOT(selectHome())); connect(scopebar, SIGNAL(selectAnal()), this, SLOT(selectAnalysis())); @@ -616,12 +618,12 @@ MainWindow::MainWindow(const QDir &home) : treeWidget->setFirstItemColumnSpanned (allRides, true); // UI Ride List (configurable) - listView = new RideNavigator(this, true); + listView = new RideNavigator(context, true); listView->setProperty("nomenu", true); // sidebar items - gcCalendar = new GcCalendar(this); - gcMultiCalendar = new GcMultiCalendar(this); + gcCalendar = new GcCalendar(context); + gcMultiCalendar = new GcMultiCalendar(context); // we need to connect the search box on Linux/Windows #ifdef GC_HAVE_LUCENE @@ -648,8 +650,8 @@ MainWindow::MainWindow(const QDir &home) : } // INTERVALS - intervalSummaryWindow = new IntervalSummaryWindow(this); - intervalWidget = new IntervalTreeView(this); + intervalSummaryWindow = new IntervalSummaryWindow(context); + intervalWidget = new IntervalTreeView(context); intervalWidget->setColumnCount(1); intervalWidget->setIndentation(5); intervalWidget->setSortingEnabled(false); @@ -713,7 +715,7 @@ MainWindow::MainWindow(const QDir &home) : QString name = i.next(); QDateTime dt; if (parseRideFileName(name, &dt)) { - last = new RideItem(RIDE_TYPE, athlete->home.path(), name, dt, athlete->zones(), athlete->hrZones(), this); + last = new RideItem(RIDE_TYPE, athlete->home.path(), name, dt, athlete->zones(), athlete->hrZones(), context); allRides->addChild(last); } } @@ -754,21 +756,21 @@ MainWindow::MainWindow(const QDir &home) : masterControls->addWidget(homeControls); // HOME WINDOW & CONTROLS - homeWindow = new HomeWindow(this, "home", "Home"); + homeWindow = new HomeWindow(context, "home", "Home"); homeControls->addWidget(homeWindow->controls()); homeControls->setCurrentIndex(0); // DIARY WINDOW & CONTROLS - diaryWindow = new HomeWindow(this, "diary", "Diary"); + diaryWindow = new HomeWindow(context, "diary", "Diary"); diaryControls->addWidget(diaryWindow->controls()); // TRAIN WINDOW & CONTROLS - trainWindow = new HomeWindow(this, "train", "Training"); + trainWindow = new HomeWindow(context, "train", "Training"); trainWindow->controls()->hide(); trainControls->addWidget(trainWindow->controls()); // ANALYSIS WINDOW & CONTRAOLS - analWindow = new HomeWindow(this, "analysis", "Analysis"); + analWindow = new HomeWindow(context, "analysis", "Analysis"); analysisControls->addWidget(analWindow->controls()); currentWindow = NULL; @@ -782,10 +784,10 @@ MainWindow::MainWindow(const QDir &home) : showBlankDiary = !(appsettings->cvalue(athlete->cyclist, GC_BLANK_DIARY, false).toBool()); // setup the blank pages - blankStateAnalysisPage = new BlankStateAnalysisPage(this); - blankStateHomePage = new BlankStateHomePage(this); - blankStateDiaryPage = new BlankStateDiaryPage(this); - blankStateTrainPage = new BlankStateTrainPage(this); + blankStateAnalysisPage = new BlankStateAnalysisPage(context); + blankStateHomePage = new BlankStateHomePage(context); + blankStateDiaryPage = new BlankStateDiaryPage(context); + blankStateTrainPage = new BlankStateTrainPage(context); connect(blankStateDiaryPage, SIGNAL(closeClicked()), this, SLOT(closeBlankDiary())); connect(blankStateHomePage, SIGNAL(closeClicked()), this, SLOT(closeBlankHome())); @@ -798,7 +800,7 @@ MainWindow::MainWindow(const QDir &home) : // do controllers after home windows -- they need their first signals caught connect(gcCalendar, SIGNAL(dateRangeChanged(DateRange)), this, SLOT(dateRangeChangedDiary(DateRange))); - ltmSidebar = new LTMSidebar(this, athlete->home); + ltmSidebar = new LTMSidebar(context, athlete->home); connect(ltmSidebar, SIGNAL(dateRangeChanged(DateRange)), this, SLOT(dateRangeChangedLTM(DateRange))); ltmSidebar->dateRangeTreeWidgetSelectionChanged(); // force an update to get first date range shown @@ -1497,7 +1499,7 @@ MainWindow::splitterMoved(int pos, int /*index*/) void MainWindow::showOptions() { - ConfigDialog *cd = new ConfigDialog(athlete->home, athlete->zones_, this); + ConfigDialog *cd = new ConfigDialog(athlete->home, athlete->zones_, context); cd->show(); } @@ -1589,7 +1591,7 @@ MainWindow::closeAll() void MainWindow::aboutDialog() { - AboutDialog *ad = new AboutDialog(this, athlete->home); + AboutDialog *ad = new AboutDialog(context, athlete->home); ad->exec(); } @@ -1601,7 +1603,7 @@ void MainWindow::showTools() void MainWindow::showRhoEstimator() { - ToolsRhoEstimator *tre = new ToolsRhoEstimator(this); + ToolsRhoEstimator *tre = new ToolsRhoEstimator(context); tre->show(); } @@ -1653,7 +1655,7 @@ void MainWindow::manualProcess(QString name) // then call it! RideItem *rideitem = (RideItem*)context->currentRideItem(); if (rideitem) { - ManualDataProcessorDialog *p = new ManualDataProcessorDialog(this, name, rideitem); + ManualDataProcessorDialog *p = new ManualDataProcessorDialog(context, name, rideitem); p->setWindowModality(Qt::ApplicationModal); // don't allow select other ride or it all goes wrong! p->exec(); } @@ -1860,13 +1862,13 @@ MainWindow::dropEvent(QDropEvent *event) if (currentWindow != trainWindow) { // We have something to process then - RideImportWizard *dialog = new RideImportWizard (&urls, athlete->home, this); + RideImportWizard *dialog = new RideImportWizard (&urls, athlete->home, context); dialog->process(); // do it! } else { QStringList filenames; for (int i=0; ihome.path(), name, dt, athlete->zones(), athlete->hrZones(), this); + RideItem *last = new RideItem(RIDE_TYPE, athlete->home.path(), name, dt, athlete->zones(), athlete->hrZones(), context); int index = 0; while (index < allRides->childCount()) { @@ -1997,14 +1999,14 @@ MainWindow::checkCPX(RideItem*ride) void MainWindow::downloadRide() { - (new DownloadRideDialog(this, athlete->home))->show(); + (new DownloadRideDialog(context, athlete->home))->show(); } void MainWindow::manualRide() { - (new ManualRideDialog(this))->show(); + (new ManualRideDialog(context))->show(); } const RideFile * @@ -2026,7 +2028,7 @@ MainWindow::currentRide() void MainWindow::exportBatch() { - BatchExportDialog *d = new BatchExportDialog(this); + BatchExportDialog *d = new BatchExportDialog(context); d->exec(); } @@ -2056,7 +2058,7 @@ MainWindow::exportRide() getSuffix.exactMatch(suffix); QFile file(fileName); - bool result = RideFileFactory::instance().writeRideFile(this, context->currentRide(), file, getSuffix.cap(1)); + bool result = RideFileFactory::instance().writeRideFile(context, context->currentRide(), file, getSuffix.cap(1)); if (result == false) { QMessageBox oops(QMessageBox::Critical, tr("Export Failed"), @@ -2086,7 +2088,7 @@ MainWindow::importFile() lastDir = QFileInfo(fileNames.front()).absolutePath(); appsettings->setValue(GC_SETTINGS_LAST_IMPORT_PATH, lastDir); QStringList fileNamesCopy = fileNames; // QT doc says iterate over a copy - RideImportWizard *import = new RideImportWizard(fileNamesCopy, athlete->home, this); + RideImportWizard *import = new RideImportWizard(fileNamesCopy, athlete->home, context); import->process(); } } @@ -2118,7 +2120,7 @@ MainWindow::revertRide() void MainWindow::splitRide() { - if (context->ride && context->ride->ride() && context->ride->ride()->dataPoints().count()) (new SplitActivityWizard(this))->exec(); + if (context->ride && context->ride->ride() && context->ride->ride()->dataPoints().count()) (new SplitActivityWizard(context))->exec(); else { if (!context->ride || !context->ride->ride()) QMessageBox::critical(this, tr("Split Activity"), tr("No activity selected")); @@ -2156,7 +2158,7 @@ MainWindow::addDevice() { // lets get a new one - AddDeviceWizard *p = new AddDeviceWizard(this); + AddDeviceWizard *p = new AddDeviceWizard(context); p->show(); } @@ -2222,7 +2224,7 @@ MainWindow::uploadRideWithGPSAction() RideItem *item = dynamic_cast(_item); if (item) { // menu is disabled anyway, but belt and braces - RideWithGPSDialog d(this, item); + RideWithGPSDialog d(context, item); d.exec(); } } @@ -2240,7 +2242,7 @@ MainWindow::uploadTtb() RideItem *item = dynamic_cast(_item); if (item) { // menu is disabled anyway, but belt and braces - TtbDialog d(this, item); + TtbDialog d(context, item); d.exec(); } } @@ -2271,7 +2273,7 @@ MainWindow::importWorkout() QStringList fileNamesCopy = fileNames; // QT doc says iterate over a copy // import them via the workoutimporter - Library::importFiles(this, fileNamesCopy); + Library::importFiles(context, fileNamesCopy); } } /*---------------------------------------------------------------------- @@ -2286,7 +2288,7 @@ MainWindow::downloadErgDB() QFileInfo fi(workoutDir); if (fi.exists() && fi.isDir()) { - ErgDBDownloadDialog *d = new ErgDBDownloadDialog(this); + ErgDBDownloadDialog *d = new ErgDBDownloadDialog(context); d->exec(); } else{ QMessageBox::critical(this, tr("Workout Directory Invalid"), @@ -2302,7 +2304,7 @@ MainWindow::downloadErgDB() void MainWindow::manageLibrary() { - LibrarySearchDialog *search = new LibrarySearchDialog(this); + LibrarySearchDialog *search = new LibrarySearchDialog(context); search->exec(); } @@ -2315,7 +2317,7 @@ void MainWindow::uploadTP() { if (context->ride) { - TPUploadDialog uploader(athlete->cyclist, context->currentRide(), this); + TPUploadDialog uploader(athlete->cyclist, context->currentRide(), context); uploader.exec(); } } @@ -2323,7 +2325,7 @@ MainWindow::uploadTP() void MainWindow::downloadTP() { - TPDownloadDialog downloader(this); + TPDownloadDialog downloader(context); downloader.exec(); } #endif @@ -2337,7 +2339,7 @@ MainWindow::addIntervals() { if (context->ride && context->ride->ride() && context->ride->ride()->dataPoints().count()) { - AddIntervalDialog *p = new AddIntervalDialog(this); + AddIntervalDialog *p = new AddIntervalDialog(context); p->setWindowModality(Qt::ApplicationModal); // don't allow select other ride or it all goes wrong! p->exec(); diff --git a/src/MainWindow.h b/src/MainWindow.h index 0b9495ed3..444496770 100644 --- a/src/MainWindow.h +++ b/src/MainWindow.h @@ -88,130 +88,6 @@ class Context; extern QList mainwindows; // keep track of all the MainWindows we have open extern QDesktopWidget *desktop; // how many screens / res etc -class Athlete : public QObject -{ - Q_OBJECT - - public: - - // basic athlete info - QString cyclist; // the cyclist name - bool useMetricUnits; - QDir home; - const Zones *zones() const { return zones_; } - const HrZones *hrZones() const { return hrzones_; } - Zones *zones_; - HrZones *hrzones_; - void setCriticalPower(int cp); - QSqlDatabase db; - MetricAggregator *metricDB; - RideMetadata *_rideMetadata; - Seasons *seasons; - QList cpxCache; - - // athlete's calendar - CalendarDownload *calendarDownload; - WithingsDownload *withingsDownload; - ZeoDownload *zeoDownload; -#ifdef GC_HAVE_ICAL - ICalendar *rideCalendar; - CalDAV *davCalendar; -#endif - - // ride metadata definitions - RideMetadata *rideMetadata() { return _rideMetadata; } - - // indexes / filters -#ifdef GC_HAVE_LUCENE - Lucene *lucene; - NamedSearches *namedSearches; -#endif - Context *context; - - void notifyZonesChanged() { zonesChanged(); } - void notifySeasonsChanged() { seasonsChanged(); } - - signals: - void zonesChanged(); - void seasonsChanged(); - - public slots: - void configChanged(); - -}; - -class Context : public QObject -{ - Q_OBJECT; - - public: - - // ride item - RideItem *rideItem() const { return ride; } - const RideFile *currentRide(); - const RideItem *currentRideItem() { return ride; } - - // last date range selected in diary/home view - DateRange currentDateRange() { return _dr; } - - - // current selections - MainWindow *mainWindow; - Athlete *athlete; - RideItem *ride; // the currently selected ride - DateRange _dr; // the currently selected date range - ErgFile *workout; // the currently selected workout file - long now; // point in time during train session - - // ********************************************* - // APPLICATION EVENTS - // ********************************************* - void notifyConfigChanged(); // used by ConfigDialog to notify MainWindow - // when config has changed - and to get a - // signal emitted to notify its children - - // realtime signals - void notifyTelemetryUpdate(const RealtimeData &rtData) { telemetryUpdate(rtData); } - void notifyErgFileSelected(ErgFile *x) { workout=x; ergFileSelected(x); } - ErgFile *currentErgFile() { return workout; } - void notifyMediaSelected( QString x) { mediaSelected(x); } - void notifySelectVideo(QString x) { selectMedia(x); } - void notifySelectWorkout(QString x) { selectWorkout(x); } - void notifySetNow(long x) { now = x; setNow(x); } - long getNow() { return now; } - void notifyNewLap() { emit newLap(); } - void notifyStart() { emit start(); } - void notifyUnPause() { emit unpause(); } - void notifyPause() { emit pause(); } - void notifyStop() { emit stop(); } - void notifySeek(long x) { emit seek(x); } - - void notifyRideClean() { rideClean(ride); } - void notifyRideDirty() { rideDirty(ride); } - - signals: - - void configChanged(); - - void rideDirty(RideItem*); - void rideClean(RideItem*); - - // realtime - void telemetryUpdate(RealtimeData rtData); - void ergFileSelected(ErgFile *); - void mediaSelected(QString); - void selectWorkout(QString); // ask traintool to select this - void selectMedia(QString); // ask traintool to select this - void setNow(long); - void seek(long); - void newLap(); - void start(); - void unpause(); - void pause(); - void stop(); - -}; - class MainWindow : public QMainWindow { Q_OBJECT diff --git a/src/ManualRideDialog.cpp b/src/ManualRideDialog.cpp index 0fb5aa655..6c5473c04 100644 --- a/src/ManualRideDialog.cpp +++ b/src/ManualRideDialog.cpp @@ -18,6 +18,8 @@ #include "ManualRideDialog.h" #include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "Settings.h" #include #include @@ -42,7 +44,7 @@ ManualRideDialog::deriveFactors() timeKJ = distanceKJ = timeTSS = distanceTSS = timeBS = distanceBS = timeDP = distanceDP = 0.0; // whats the most recent ride? - QList metrics = mainWindow->athlete->metricDB->getAllMetricsFor(QDateTime(), QDateTime()); + QList metrics = context->athlete->metricDB->getAllMetricsFor(QDateTime(), QDateTime()); // do we have any rides? if (metrics.count()) { @@ -57,7 +59,7 @@ ManualRideDialog::deriveFactors() totalseconds = totaldistance = totaltss = totalkj = totalbs = totaldp = 0; // just use the metricDB versions, nice 'n fast - foreach (SummaryMetrics metric, mainWindow->athlete->metricDB->getAllMetricsFor(QDateTime() , QDateTime())) { + foreach (SummaryMetrics metric, context->athlete->metricDB->getAllMetricsFor(QDateTime() , QDateTime())) { // skip those with no time or distance values (not comparing doubles) if (metric.getForSymbol("time_riding") == 0 || metric.getForSymbol("total_distance") == 0) continue; @@ -88,7 +90,7 @@ ManualRideDialog::deriveFactors() // total values, not just last 'n' days -- but avoid divide by zero if (totalseconds && totaldistance) { - if (!mainWindow->athlete->useMetricUnits) totaldistance *= MILES_PER_KM; + if (!context->athlete->useMetricUnits) totaldistance *= MILES_PER_KM; timeBS = (totalbs * 3600) / totalseconds; // BS per hour distanceBS = totalbs / totaldistance; // BS per mile or km timeDP = (totaldp * 3600) / totalseconds; // DP per hour @@ -101,7 +103,7 @@ ManualRideDialog::deriveFactors() // don't use defaults if we have rides in last 'n' days if (rides) { - if (!mainWindow->athlete->useMetricUnits) distance *= MILES_PER_KM; + if (!context->athlete->useMetricUnits) distance *= MILES_PER_KM; timeBS = (bs * 3600) / seconds; // BS per hour distanceBS = bs / distance; // BS per mile or km timeDP = (dp * 3600) / seconds; // DP per hour @@ -114,7 +116,7 @@ ManualRideDialog::deriveFactors() } } -ManualRideDialog::ManualRideDialog(MainWindow *mainWindow) : mainWindow(mainWindow) +ManualRideDialog::ManualRideDialog(Context *context) : context(context) { setAttribute(Qt::WA_DeleteOnClose); setWindowTitle(tr("Manual Activity Entry")); @@ -149,7 +151,7 @@ ManualRideDialog::ManualRideDialog(MainWindow *mainWindow) : mainWindow(mainWind duration->setDisplayFormat("hh:mm:ss"); // ride distance - QString distanceString = QString(tr("Distance (%1):")).arg(mainWindow->athlete->useMetricUnits ? "km" : "miles"); + QString distanceString = QString(tr("Distance (%1):")).arg(context->athlete->useMetricUnits ? "km" : "miles"); QLabel *distanceLabel = new QLabel(distanceString, this); distance = new QDoubleSpinBox(this); distance->setSingleStep(10.0); @@ -482,16 +484,16 @@ ManualRideDialog::okClicked() .arg (rideDateTime.time().minute(), 2, 10, zero) .arg (rideDateTime.time().second(), 2, 10, zero); - QString filename = mainWindow->athlete->home.absolutePath() + "/" + basename + ".json"; + QString filename = context->athlete->home.absolutePath() + "/" + basename + ".json"; QFile out(filename); - bool success = RideFileFactory::instance().writeRideFile(mainWindow, rideFile, out, "json"); + bool success = RideFileFactory::instance().writeRideFile(context, rideFile, out, "json"); delete rideFile; if (success) { // refresh metric db etc - mainWindow->addRide(basename + ".json"); + context->mainWindow->addRide(basename + ".json"); accept(); } else { diff --git a/src/ManualRideDialog.h b/src/ManualRideDialog.h index 79adf9003..87bf7fa13 100644 --- a/src/ManualRideDialog.h +++ b/src/ManualRideDialog.h @@ -24,7 +24,7 @@ #include #include -class MainWindow; +class Context; class ManualRideDialog : public QDialog { @@ -32,7 +32,7 @@ class ManualRideDialog : public QDialog G_OBJECT public: - ManualRideDialog(MainWindow *mainWindow); + ManualRideDialog(Context *context); private slots: void okClicked(); @@ -43,7 +43,7 @@ class ManualRideDialog : public QDialog private: - MainWindow *mainWindow; + Context *context; QVector records; QString filename, filepath; int daysago; // remember last deriveFactors value diff --git a/src/MetadataWindow.cpp b/src/MetadataWindow.cpp index 6ac7d085c..415ebd64a 100644 --- a/src/MetadataWindow.cpp +++ b/src/MetadataWindow.cpp @@ -18,8 +18,8 @@ #include "MetadataWindow.h" -MetadataWindow::MetadataWindow(MainWindow *mainWindow) : - GcChartWindow(mainWindow), mainWindow(mainWindow) +MetadataWindow::MetadataWindow(Context *context) : + GcChartWindow(context), context(context) { setInstanceName("Metadata Window"); setControls(NULL); @@ -28,7 +28,7 @@ MetadataWindow::MetadataWindow(MainWindow *mainWindow) : QVBoxLayout *vlayout = new QVBoxLayout; vlayout->setSpacing(0); - rideMetadata = new RideMetadata(mainWindow); + rideMetadata = new RideMetadata(context); QFont font; font.setPointSize(font.pointSize()); rideMetadata->setFont(font); diff --git a/src/MetadataWindow.h b/src/MetadataWindow.h index 4ccd30c24..e47a74990 100644 --- a/src/MetadataWindow.h +++ b/src/MetadataWindow.h @@ -21,7 +21,7 @@ #include "GoldenCheetah.h" #include "RideMetadata.h" -class MainWindow; +class Context; class MetadataWindow : public GcChartWindow { @@ -30,7 +30,7 @@ class MetadataWindow : public GcChartWindow public: - MetadataWindow(MainWindow *parent); + MetadataWindow(Context *context); protected slots: @@ -38,7 +38,7 @@ class MetadataWindow : public GcChartWindow protected: - MainWindow *mainWindow; + Context *context; RideMetadata *rideMetadata; }; diff --git a/src/MetricAggregator.cpp b/src/MetricAggregator.cpp index 29de71b99..7c63e1c66 100644 --- a/src/MetricAggregator.cpp +++ b/src/MetricAggregator.cpp @@ -16,6 +16,9 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ +#include "MainWindow.h" +#include "Athlete.h" +#include "Context.h" #include "MetricAggregator.h" #include "DBAccess.h" #include "RideFile.h" @@ -34,14 +37,14 @@ #include #include -MetricAggregator::MetricAggregator(MainWindow *main) : QObject(main), main(main) +MetricAggregator::MetricAggregator(Context *context) : QObject(context), context(context) { - colorEngine = new ColorEngine(main); - dbaccess = new DBAccess(main); - connect(main->context, SIGNAL(configChanged()), this, SLOT(update())); - connect(main->context, SIGNAL(rideClean(RideItem*)), this, SLOT(update(void))); - connect(main, SIGNAL(rideAdded(RideItem*)), this, SLOT(addRide(RideItem*))); - connect(main, SIGNAL(rideDeleted(RideItem*)), this, SLOT(update(void))); + colorEngine = new ColorEngine(context); + dbaccess = new DBAccess(context); + connect(context, SIGNAL(configChanged()), this, SLOT(update())); + connect(context, SIGNAL(rideClean(RideItem*)), this, SLOT(update(void))); + connect(context->mainWindow, SIGNAL(rideAdded(RideItem*)), this, SLOT(addRide(RideItem*))); + connect(context->mainWindow, SIGNAL(rideDeleted(RideItem*)), this, SLOT(update(void))); } MetricAggregator::~MetricAggregator() @@ -69,7 +72,7 @@ void MetricAggregator::refreshMetrics() void MetricAggregator::refreshMetrics(QDateTime forceAfterThisDate) { // only if we have established a connection to the database - if (dbaccess == NULL || main->isclean==true) return; + if (dbaccess == NULL || context->mainWindow->isclean==true) return; // first check db structure is still up to date // this is because metadata.xml may add new fields @@ -77,7 +80,7 @@ void MetricAggregator::refreshMetrics(QDateTime forceAfterThisDate) // Get a list of the ride files QRegExp rx = RideFileFactory::instance().rideFileRegExp(); - QStringList filenames = RideFileFactory::instance().listRideFiles(main->athlete->home); + QStringList filenames = RideFileFactory::instance().listRideFiles(context->athlete->home); QStringListIterator i(filenames); // get a Hash map of statistic records and timestamps @@ -98,23 +101,23 @@ void MetricAggregator::refreshMetrics(QDateTime forceAfterThisDate) // Delete statistics for non-existant ride files QHash::iterator d; for (d = dbStatus.begin(); d != dbStatus.end(); ++d) { - if (QFile(main->athlete->home.absolutePath() + "/" + d.key()).exists() == false) { + if (QFile(context->athlete->home.absolutePath() + "/" + d.key()).exists() == false) { dbaccess->deleteRide(d.key()); #ifdef GC_HAVE_LUCENE - main->athlete->lucene->deleteRide(d.key()); + context->athlete->lucene->deleteRide(d.key()); #endif } } - unsigned long zoneFingerPrint = static_cast(main->athlete->zones()->getFingerprint()) - + static_cast(main->athlete->hrZones()->getFingerprint()); // checksum of *all* zone data (HR and Power) + unsigned long zoneFingerPrint = static_cast(context->athlete->zones()->getFingerprint()) + + static_cast(context->athlete->hrZones()->getFingerprint()); // checksum of *all* zone data (HR and Power) // update statistics for ride files which are out of date // showing a progress bar as we go QTime elapsed; elapsed.start(); QString title = tr("Refreshing Ride Statistics...\nStarted"); - QProgressDialog bar(title, tr("Abort"), 0, filenames.count(), main); + QProgressDialog bar(title, tr("Abort"), 0, filenames.count(), context->mainWindow); bar.setWindowModality(Qt::WindowModal); bar.setMinimumDuration(0); bar.show(); @@ -123,7 +126,7 @@ void MetricAggregator::refreshMetrics(QDateTime forceAfterThisDate) QApplication::processEvents(); // get that dialog up! // log of progress - QFile log(main->athlete->home.absolutePath() + "/" + "metric.log"); + QFile log(context->athlete->home.absolutePath() + "/" + "metric.log"); log.open(QIODevice::WriteOnly); log.resize(0); QTextStream out(&log); @@ -131,7 +134,7 @@ void MetricAggregator::refreshMetrics(QDateTime forceAfterThisDate) while (i.hasNext()) { QString name = i.next(); - QFile file(main->athlete->home.absolutePath() + "/" + name); + QFile file(context->athlete->home.absolutePath() + "/" + name); // if it s missing or out of date then update it! status current = dbStatus.value(name); @@ -159,7 +162,7 @@ void MetricAggregator::refreshMetrics(QDateTime forceAfterThisDate) out << "Opening ride: " << name << "\r\n"; // read file and process it if we didn't already... - if (ride == NULL) ride = RideFileFactory::instance().openRideFile(main, file, errors); + if (ride == NULL) ride = RideFileFactory::instance().openRideFile(context, file, errors); out << "File open completed: " << name << "\r\n"; @@ -168,7 +171,7 @@ void MetricAggregator::refreshMetrics(QDateTime forceAfterThisDate) out << "Getting weight: " << name << "\r\n"; ride->getWeight(); out << "Updating statistics: " << name << "\r\n"; - importRide(main->athlete->home, ride, name, zoneFingerPrint, (dbTimeStamp > 0)); + importRide(context->athlete->home, ride, name, zoneFingerPrint, (dbTimeStamp > 0)); } } @@ -177,7 +180,7 @@ void MetricAggregator::refreshMetrics(QDateTime forceAfterThisDate) // if ride wasn't opened it will do it itself // we only want to check so passing check=true // because we don't actually want the results now - RideFileCache updater(main, main->athlete->home.absolutePath() + "/" + name, ride, true); + RideFileCache updater(context, context->athlete->home.absolutePath() + "/" + name, ride, true); // free memory - if needed if (ride) delete ride; @@ -195,10 +198,10 @@ void MetricAggregator::refreshMetrics(QDateTime forceAfterThisDate) #ifdef GC_HAVE_LUCENE #ifndef WIN32 // windows crashes here.... out << "OPTIMISE: " << QDateTime::currentDateTime().toString() + "\r\n"; - main->athlete->lucene->optimise(); + context->athlete->lucene->optimise(); #endif #endif - main->isclean = true; + context->mainWindow->isclean = true; // stop logging out << "SIGNAL DATA CHANGED: " << QDateTime::currentDateTime().toString() + "\r\n"; @@ -216,15 +219,15 @@ void MetricAggregator::refreshMetrics(QDateTime forceAfterThisDate) void MetricAggregator::addRide(RideItem*ride) { if (ride && ride->ride()) { - importRide(main->athlete->home, ride->ride(), ride->fileName, main->athlete->zones()->getFingerprint(), true); - RideFileCache updater(main, main->athlete->home.absolutePath() + "/" + ride->fileName, ride->ride(), true); // update cpx etc + importRide(context->athlete->home, ride->ride(), ride->fileName, context->athlete->zones()->getFingerprint(), true); + RideFileCache updater(context, context->athlete->home.absolutePath() + "/" + ride->fileName, ride->ride(), true); // update cpx etc dataChanged(); // notify models/views } } void MetricAggregator::update() { - main->isclean = false; - if (!main->ismultisave) { + context->mainWindow->isclean = false; + if (!context->mainWindow->ismultisave) { refreshMetrics(); } } @@ -254,7 +257,7 @@ bool MetricAggregator::importRide(QDir path, RideFile *ride, QString fileName, u metrics << factory.metricName(i); // compute all the metrics - QHash computed = RideMetric::computeMetrics(main, ride, main->athlete->zones(), main->athlete->hrZones(), metrics); + QHash computed = RideMetric::computeMetrics(context, ride, context->athlete->zones(), context->athlete->hrZones(), metrics); // get metrics into summaryMetric QMap for(int i = 0; i < factory.metricCount(); ++i) { @@ -263,11 +266,11 @@ bool MetricAggregator::importRide(QDir path, RideFile *ride, QString fileName, u } // what color will this ride be? - QColor color = colorEngine->colorFor(ride->getTag(main->athlete->rideMetadata()->getColorField(), "")); + QColor color = colorEngine->colorFor(ride->getTag(context->athlete->rideMetadata()->getColorField(), "")); dbaccess->importRide(&summaryMetric, ride, color, fingerprint, modify); #ifdef GC_HAVE_LUCENE - main->athlete->lucene->importRide(&summaryMetric, ride, color, fingerprint, modify); + context->athlete->lucene->importRide(&summaryMetric, ride, color, fingerprint, modify); #endif return true; @@ -331,7 +334,7 @@ MetricAggregator::getAllMetricsFor(DateRange dr) QList MetricAggregator::getAllMetricsFor(QDateTime start, QDateTime end) { - if (main->isclean == false) refreshMetrics(); // get them up-to-date + if (context->mainWindow->isclean == false) refreshMetrics(); // get them up-to-date QList empty; @@ -352,7 +355,7 @@ MetricAggregator::getAllMetricsFor(QDateTime start, QDateTime end) SummaryMetrics MetricAggregator::getAllMetricsFor(QString filename) { - if (main->isclean == false) refreshMetrics(); // get them up-to-date + if (context->mainWindow->isclean == false) refreshMetrics(); // get them up-to-date SummaryMetrics results; QColor color; // ignored for now... @@ -393,7 +396,7 @@ MetricAggregator::getAllMeasuresFor(QDateTime start, QDateTime end) SummaryMetrics MetricAggregator::getRideMetrics(QString filename) { - if (main->isclean == false) refreshMetrics(); // get them up-to-date + if (context->mainWindow->isclean == false) refreshMetrics(); // get them up-to-date SummaryMetrics empty; diff --git a/src/MetricAggregator.h b/src/MetricAggregator.h index e30b79733..1c380ef51 100644 --- a/src/MetricAggregator.h +++ b/src/MetricAggregator.h @@ -28,7 +28,7 @@ #include "HrZones.h" #include "RideMetric.h" #include "SummaryMetrics.h" -#include "MainWindow.h" +#include "Context.h" #include "DBAccess.h" #include "Colors.h" @@ -39,7 +39,7 @@ class MetricAggregator : public QObject public: - MetricAggregator(MainWindow *); + MetricAggregator(Context *); ~MetricAggregator(); @@ -64,7 +64,7 @@ class MetricAggregator : public QObject void importMeasure(SummaryMetrics *sm); private: - MainWindow *main; + Context *context; DBAccess *dbaccess; typedef QHash MetricMap; diff --git a/src/ModelPlot.cpp b/src/ModelPlot.cpp index e8331f206..2cfa7e8b8 100644 --- a/src/ModelPlot.cpp +++ b/src/ModelPlot.cpp @@ -19,7 +19,10 @@ #include "ModelPlot.h" #include "ModelWindow.h" #include "IntervalItem.h" -#include "MainWindow.h" +#include "RideItem.h" +#include "Context.h" +#include "Context.h" +#include "Athlete.h" #include "Settings.h" #include "Zones.h" #include "Colors.h" @@ -314,7 +317,7 @@ ModelDataProvider::ModelDataProvider (BasicModelPlot &plot, ModelSettings *setti { // get application settings cranklength = appsettings->value(NULL, GC_CRANKLENGTH, 0.0).toDouble() / 1000.0; - useMetricUnits = plot.main->athlete->useMetricUnits; + useMetricUnits = plot.context->athlete->useMetricUnits; // if there are no settings or incomplete settings // create a null data plot @@ -794,7 +797,7 @@ ModelDataProvider::ModelDataProvider (BasicModelPlot &plot, ModelSettings *setti * *----------------------------------------------------------------------*/ -BasicModelPlot::BasicModelPlot(MainWindow *parent, ModelSettings *settings) : main(parent) +BasicModelPlot::BasicModelPlot(Context *context, ModelSettings *settings) : context(context) { diag_=0; currentStyle = STYLE_BAR; @@ -990,7 +993,7 @@ BasicModelPlot::resetViewPoint() * MODEL PLOT * Nothing special - just a framed BasicModelPlot *----------------------------------------------------------------------*/ -ModelPlot::ModelPlot(MainWindow *parent, ModelSettings *settings) : QFrame(parent), main(parent) +ModelPlot::ModelPlot(Context *context, ModelSettings *settings) : QFrame(context->mainWindow), context(context) { // the distinction between a model plot and a basic model plot // is only to provide a frame for the qwt3d plot (it looks odd @@ -1006,7 +1009,7 @@ ModelPlot::ModelPlot(MainWindow *parent, ModelSettings *settings) : QFrame(paren layout->setContentsMargins(2,2,2,2); setLayout(layout); - connect(main->context, SIGNAL(configChanged()), basicModelPlot, SLOT(configChanged())); + connect(context, SIGNAL(configChanged()), basicModelPlot, SLOT(configChanged())); } void diff --git a/src/ModelPlot.h b/src/ModelPlot.h index 1877c591c..44f08ddbb 100644 --- a/src/ModelPlot.h +++ b/src/ModelPlot.h @@ -22,7 +22,7 @@ #include #include -#include "MainWindow.h" +#include "Context.h" #include @@ -86,9 +86,9 @@ class BasicModelPlot : public SurfacePlot public: - BasicModelPlot(MainWindow *, ModelSettings *); + BasicModelPlot(Context *, ModelSettings *); - MainWindow *main; + Context *context; void setData(ModelSettings *); void resetViewPoint(); @@ -165,7 +165,7 @@ class ModelPlot : public QFrame public: - ModelPlot(MainWindow *, ModelSettings *); + ModelPlot(Context *, ModelSettings *); void setData(ModelSettings *settings); void resetViewPoint(); void setStyle(int); @@ -180,7 +180,7 @@ class ModelPlot : public QFrame void setResolution(int); private: - MainWindow *main; + Context *context; QVBoxLayout *layout; }; diff --git a/src/ModelWindow.cpp b/src/ModelWindow.cpp index 9be01b1a6..3cc7f17d4 100644 --- a/src/ModelWindow.cpp +++ b/src/ModelWindow.cpp @@ -18,7 +18,7 @@ #include "ModelWindow.h" #include "ModelPlot.h" -#include "MainWindow.h" +#include "Context.h" #include "RideItem.h" #include "IntervalItem.h" #include "math.h" @@ -44,8 +44,8 @@ ModelWindow::addStandardChannels(QComboBox *box) box->addItem(tr("Longitude"), MODEL_LONG); } -ModelWindow::ModelWindow(MainWindow *parent, const QDir &home) : - GcChartWindow(parent), home(home), main(parent), ride(NULL), current(NULL) +ModelWindow::ModelWindow(Context *context, const QDir &home) : + GcChartWindow(context), home(home), main(parent), ride(NULL), current(NULL) { setInstanceName("3D Window"); diff --git a/src/ModelWindow.h b/src/ModelWindow.h index a1b75dc7c..25af2a69f 100644 --- a/src/ModelWindow.h +++ b/src/ModelWindow.h @@ -22,10 +22,12 @@ #include #include -#include "MainWindow.h" +#include "Context.h" class ModelPlot; // we don't include the header because it uses namespaces class ModelDataColor; +class IntervalItem; +class RideItem; class ModelSettings { @@ -65,7 +67,7 @@ class ModelWindow : public GcChartWindow public: - ModelWindow(MainWindow *, const QDir &); + ModelWindow(Context *, const QDir &); // reveal bool hasReveal() { return false; } @@ -112,9 +114,9 @@ class ModelWindow : public GcChartWindow protected: - // passed from MainWindow + // passed from Context * QDir home; - MainWindow *main; + Context *context; bool useMetricUnits; bool active; diff --git a/src/NamedSearch.cpp b/src/NamedSearch.cpp index 5c7297753..e54cea32b 100644 --- a/src/NamedSearch.cpp +++ b/src/NamedSearch.cpp @@ -18,7 +18,8 @@ #include "NamedSearch.h" #include "SearchBox.h" -#include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "GcSideBarItem.h" // for iconFromPNG // Escape special characters (JSON compliance) @@ -179,7 +180,7 @@ NamedSearchParser::serialize(QString filename, QListNamedSearches) } -EditNamedSearches::EditNamedSearches(QWidget *parent, MainWindow *main) : QDialog(parent), mainWindow(main), active(false) +EditNamedSearches::EditNamedSearches(QWidget *parent, Context *context) : QDialog(parent), context(context), active(false) { filterIcon = iconFromPNG(":images/toolbar/filter3.png", false); searchIcon = iconFromPNG(":images/toolbar/search3.png", false); @@ -207,7 +208,7 @@ EditNamedSearches::EditNamedSearches(QWidget *parent, MainWindow *main) : QDialo layout->addLayout(row2); QLabel *filter = new QLabel(tr("Filter"), this); row2->addWidget(filter); - editSearch = new SearchBox(mainWindow, this, true); + editSearch = new SearchBox(context, this, true); row2->addWidget(editSearch); // add/update buttons @@ -250,7 +251,7 @@ EditNamedSearches::EditNamedSearches(QWidget *parent, MainWindow *main) : QDialo row4->addWidget(deleteButton); // Populate the list of named searches - foreach(NamedSearch x, mainWindow->athlete->namedSearches->getList()) { + foreach(NamedSearch x, context->athlete->namedSearches->getList()) { QTreeWidgetItem *add = new QTreeWidgetItem(searchList->invisibleRootItem(), 0); add->setIcon(0, x.type == NamedSearch::search ? searchIcon : filterIcon); add->setText(1, x.name); @@ -259,7 +260,7 @@ EditNamedSearches::EditNamedSearches(QWidget *parent, MainWindow *main) : QDialo connect(searchList, SIGNAL(itemSelectionChanged()), this, SLOT(selectionChanged())); // and select the first one - if (mainWindow->athlete->namedSearches->getList().count()) { + if (context->athlete->namedSearches->getList().count()) { searchList->setCurrentItem(searchList->invisibleRootItem()->child(0)); } @@ -275,7 +276,7 @@ EditNamedSearches::selectionChanged() if (active || searchList->currentItem() == NULL) return; int index = searchList->invisibleRootItem()->indexOfChild(searchList->currentItem()); - NamedSearch x = mainWindow->athlete->namedSearches->getList().at(index); + NamedSearch x = context->athlete->namedSearches->getList().at(index); editName->setText(x.name); editSearch->setText(x.text); @@ -292,7 +293,7 @@ EditNamedSearches::addClicked() x.text = editSearch->text(); x.name = editName->text(); x.type = editSearch->getMode(); - mainWindow->athlete->namedSearches->getList().append(x); + context->athlete->namedSearches->getList().append(x); QTreeWidgetItem *add = new QTreeWidgetItem(searchList->invisibleRootItem(), 0); add->setIcon(0, x.type == NamedSearch::search ? searchIcon : filterIcon); @@ -313,9 +314,9 @@ EditNamedSearches::updateClicked() int index = searchList->invisibleRootItem()->indexOfChild(searchList->currentItem()); // update the text - mainWindow->athlete->namedSearches->getList()[index].name = editName->text(); - mainWindow->athlete->namedSearches->getList()[index].type = editSearch->getMode(); - mainWindow->athlete->namedSearches->getList()[index].text = editSearch->text(); + context->athlete->namedSearches->getList()[index].name = editName->text(); + context->athlete->namedSearches->getList()[index].type = editSearch->getMode(); + context->athlete->namedSearches->getList()[index].text = editSearch->text(); QTreeWidgetItem *here = searchList->invisibleRootItem()->child(index); here->setIcon(0, editSearch->getMode() == 0 ? searchIcon : filterIcon); @@ -333,7 +334,7 @@ EditNamedSearches::deleteClicked() active = true; int index = searchList->invisibleRootItem()->indexOfChild(searchList->currentItem()); - mainWindow->athlete->namedSearches->getList().removeAt(index); + context->athlete->namedSearches->getList().removeAt(index); delete searchList->invisibleRootItem()->takeChild(index); active = false; @@ -347,6 +348,6 @@ void EditNamedSearches::reject() { writeSearches(); } void EditNamedSearches::writeSearches() { - mainWindow->athlete->namedSearches->write(); + context->athlete->namedSearches->write(); } diff --git a/src/NamedSearch.h b/src/NamedSearch.h index afd8adf1b..fab6e34e5 100644 --- a/src/NamedSearch.h +++ b/src/NamedSearch.h @@ -87,7 +87,7 @@ class EditNamedSearches : public QDialog G_OBJECT public: - EditNamedSearches(QWidget *parent, MainWindow *main); + EditNamedSearches(QWidget *parent, Context *context); void closeEvent(QCloseEvent* event); // write away on save void writeSearches(); @@ -95,7 +95,7 @@ class EditNamedSearches : public QDialog void reject(); // write away on close private: - MainWindow *mainWindow; + Context *context; bool active; QLineEdit *editName; SearchBox *editSearch; diff --git a/src/NewCyclistDialog.h b/src/NewCyclistDialog.h index c99c98cda..46dfc5b96 100644 --- a/src/NewCyclistDialog.h +++ b/src/NewCyclistDialog.h @@ -20,7 +20,7 @@ #define _NewCyclistDialog_h #include "GoldenCheetah.h" -#include "MainWindow.h" +#include "Context.h" #include "Units.h" #include "Settings.h" @@ -41,7 +41,7 @@ class NewCyclistDialog : public QDialog void cancelClicked(); private: - MainWindow *mainWindow; + Context *context; bool useMetricUnits; QDateEdit *dob; QComboBox *sex; diff --git a/src/Pages.cpp b/src/Pages.cpp index c4263114a..c9b174c64 100644 --- a/src/Pages.cpp +++ b/src/Pages.cpp @@ -16,6 +16,7 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ +#include "Athlete.h" #include #include #include @@ -35,7 +36,7 @@ // // Main Config Page - tabs for each sub-page // -GeneralPage::GeneralPage(MainWindow *main) : main(main) +GeneralPage::GeneralPage(Context *context) : context(context) { // layout without too wide margins QVBoxLayout *mainLayout = new QVBoxLayout(this); @@ -177,9 +178,9 @@ GeneralPage::GeneralPage(MainWindow *main) : main(main) perfManLTSavgValidator = new QIntValidator(7,56,this); // get config or set to defaults - QVariant perfManSTSVal = appsettings->cvalue(main->athlete->cyclist, GC_STS_DAYS); + QVariant perfManSTSVal = appsettings->cvalue(context->athlete->cyclist, GC_STS_DAYS); if (perfManSTSVal.isNull() || perfManSTSVal.toInt() == 0) perfManSTSVal = 7; - QVariant perfManLTSVal = appsettings->cvalue(main->athlete->cyclist, GC_LTS_DAYS); + QVariant perfManLTSVal = appsettings->cvalue(context->athlete->cyclist, GC_LTS_DAYS); if (perfManLTSVal.isNull() || perfManLTSVal.toInt() == 0) perfManLTSVal = 42; perfManSTSavg = new QLineEdit(perfManSTSVal.toString(),this); @@ -188,7 +189,7 @@ GeneralPage::GeneralPage(MainWindow *main) : main(main) perfManLTSavg->setValidator(perfManLTSavgValidator); showSBToday = new QCheckBox(tr("PMC Stress Balance Today"), this); - showSBToday->setChecked(appsettings->cvalue(main->athlete->cyclist, GC_SB_TODAY).toInt()); + showSBToday->setChecked(appsettings->cvalue(context->athlete->cyclist, GC_SB_TODAY).toInt()); configLayout->addWidget(perfManSTSLabel, 9,0, Qt::AlignRight); configLayout->addWidget(perfManSTSavg, 9,1, Qt::AlignLeft); @@ -240,9 +241,9 @@ GeneralPage::saveClicked() appsettings->setValue(GC_ELEVATION_HYSTERESIS, hystedit->text()); // Performance Manager - appsettings->setCValue(main->athlete->cyclist, GC_STS_DAYS, perfManSTSavg->text()); - appsettings->setCValue(main->athlete->cyclist, GC_LTS_DAYS, perfManLTSavg->text()); - appsettings->setCValue(main->athlete->cyclist, GC_SB_TODAY, (int) showSBToday->isChecked()); + appsettings->setCValue(context->athlete->cyclist, GC_STS_DAYS, perfManSTSavg->text()); + appsettings->setCValue(context->athlete->cyclist, GC_LTS_DAYS, perfManLTSavg->text()); + appsettings->setCValue(context->athlete->cyclist, GC_SB_TODAY, (int) showSBToday->isChecked()); // set default stress names if not set: appsettings->setValue(GC_STS_NAME, appsettings->value(this, GC_STS_NAME,tr("Short Term Stress"))); @@ -264,7 +265,7 @@ GeneralPage::browseWorkoutDir() // // Passwords page // -CredentialsPage::CredentialsPage(QWidget *parent, MainWindow *mainWindow) : QScrollArea(parent), mainWindow(mainWindow) +CredentialsPage::CredentialsPage(QWidget *parent, Context *context) : QScrollArea(parent), context(context) { QWidget *main = new QWidget(this); main->setContentsMargins(0,0,0,0); @@ -327,24 +328,24 @@ CredentialsPage::CredentialsPage(QWidget *parent, MainWindow *mainWindow) : QScr gcURL = new QLineEdit(this); - gcURL->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_GCURL, "http://race.goldencheetah.org").toString()); + gcURL->setText(appsettings->cvalue(context->athlete->cyclist, GC_GCURL, "http://race.goldencheetah.org").toString()); gcUser = new QLineEdit(this); - gcUser->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_GCUSER, "").toString()); + gcUser->setText(appsettings->cvalue(context->athlete->cyclist, GC_GCUSER, "").toString()); gcPass = new QLineEdit(this); gcPass->setEchoMode(QLineEdit::Password); - gcPass->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_GCPASS, "").toString()); + gcPass->setText(appsettings->cvalue(context->athlete->cyclist, GC_GCPASS, "").toString()); tpURL = new QLineEdit(this); - tpURL->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_TPURL, "http://www.trainingpeaks.com").toString()); + tpURL->setText(appsettings->cvalue(context->athlete->cyclist, GC_TPURL, "http://www.trainingpeaks.com").toString()); tpUser = new QLineEdit(this); - tpUser->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_TPUSER, "").toString()); + tpUser->setText(appsettings->cvalue(context->athlete->cyclist, GC_TPUSER, "").toString()); tpPass = new QLineEdit(this); tpPass->setEchoMode(QLineEdit::Password); - tpPass->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_TPPASS, "").toString()); + tpPass->setText(appsettings->cvalue(context->athlete->cyclist, GC_TPPASS, "").toString()); tpType = new QComboBox(this); tpType->addItem("Shared Free"); @@ -354,55 +355,55 @@ CredentialsPage::CredentialsPage(QWidget *parent, MainWindow *mainWindow) : QScr tpType->addItem("Coached Premium"); tpType->addItem("Shared Coached Premium"); - tpType->setCurrentIndex(appsettings->cvalue(mainWindow->athlete->cyclist, GC_TPTYPE, "0").toInt()); + tpType->setCurrentIndex(appsettings->cvalue(context->athlete->cyclist, GC_TPTYPE, "0").toInt()); rideWithGPSUser = new QLineEdit(this); - rideWithGPSUser->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_RWGPSUSER, "").toString()); + rideWithGPSUser->setText(appsettings->cvalue(context->athlete->cyclist, GC_RWGPSUSER, "").toString()); rideWithGPSPass = new QLineEdit(this); rideWithGPSPass->setEchoMode(QLineEdit::Password); - rideWithGPSPass->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_RWGPSPASS, "").toString()); + rideWithGPSPass->setText(appsettings->cvalue(context->athlete->cyclist, GC_RWGPSPASS, "").toString()); ttbUser = new QLineEdit(this); - ttbUser->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_TTBUSER, "").toString()); + ttbUser->setText(appsettings->cvalue(context->athlete->cyclist, GC_TTBUSER, "").toString()); ttbPass = new QLineEdit(this); ttbPass->setEchoMode(QLineEdit::Password); - ttbPass->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_TTBPASS, "").toString()); + ttbPass->setText(appsettings->cvalue(context->athlete->cyclist, GC_TTBPASS, "").toString()); wiURL = new QLineEdit(this); - wiURL->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_WIURL, "http://wbsapi.withings.net/").toString()); + wiURL->setText(appsettings->cvalue(context->athlete->cyclist, GC_WIURL, "http://wbsapi.withings.net/").toString()); wiUser = new QLineEdit(this); - wiUser->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_WIUSER, "").toString()); + wiUser->setText(appsettings->cvalue(context->athlete->cyclist, GC_WIUSER, "").toString()); wiPass = new QLineEdit(this); - wiPass->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_WIKEY, "").toString()); + wiPass->setText(appsettings->cvalue(context->athlete->cyclist, GC_WIKEY, "").toString()); zeoURL = new QLineEdit(this); - zeoURL->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_ZEOURL, "http://app-pro.myzeo.com:8080/").toString()); + zeoURL->setText(appsettings->cvalue(context->athlete->cyclist, GC_ZEOURL, "http://app-pro.myzeo.com:8080/").toString()); zeoUser = new QLineEdit(this); - zeoUser->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_ZEOUSER, "").toString()); + zeoUser->setText(appsettings->cvalue(context->athlete->cyclist, GC_ZEOUSER, "").toString()); zeoPass = new QLineEdit(this); zeoPass->setEchoMode(QLineEdit::Password); - zeoPass->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_ZEOPASS, "").toString()); + zeoPass->setText(appsettings->cvalue(context->athlete->cyclist, GC_ZEOPASS, "").toString()); webcalURL = new QLineEdit(this); - webcalURL->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_WEBCAL_URL, "").toString()); + webcalURL->setText(appsettings->cvalue(context->athlete->cyclist, GC_WEBCAL_URL, "").toString()); dvURL = new QLineEdit(this); - QString url = appsettings->cvalue(mainWindow->athlete->cyclist, GC_DVURL, "").toString(); + QString url = appsettings->cvalue(context->athlete->cyclist, GC_DVURL, "").toString(); url.replace("%40", "@"); // remove escape of @ character dvURL->setText(url); dvUser = new QLineEdit(this); - dvUser->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_DVUSER, "").toString()); + dvUser->setText(appsettings->cvalue(context->athlete->cyclist, GC_DVUSER, "").toString()); dvPass = new QLineEdit(this); dvPass->setEchoMode(QLineEdit::Password); - dvPass->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_DVPASS, "").toString()); + dvPass->setText(appsettings->cvalue(context->athlete->cyclist, GC_DVPASS, "").toString()); grid->addWidget(tp, 0,0); grid->addWidget(urlLabel, 1,0); @@ -484,34 +485,34 @@ CredentialsPage::CredentialsPage(QWidget *parent, MainWindow *mainWindow) : QScr void CredentialsPage::saveClicked() { - appsettings->setCValue(mainWindow->athlete->cyclist, GC_GCURL, gcURL->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_GCUSER, gcUser->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_GCPASS, gcPass->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_TPURL, tpURL->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_TPUSER, tpUser->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_TPPASS, tpPass->text()); + appsettings->setCValue(context->athlete->cyclist, GC_GCURL, gcURL->text()); + appsettings->setCValue(context->athlete->cyclist, GC_GCUSER, gcUser->text()); + appsettings->setCValue(context->athlete->cyclist, GC_GCPASS, gcPass->text()); + appsettings->setCValue(context->athlete->cyclist, GC_TPURL, tpURL->text()); + appsettings->setCValue(context->athlete->cyclist, GC_TPUSER, tpUser->text()); + appsettings->setCValue(context->athlete->cyclist, GC_TPPASS, tpPass->text()); //XXX deprecated appsettings->setCValue(mainWindow->cyclist, GC_STRUSER, stravaUser->text()); //XXX deprecated appsettings->setCValue(mainWindow->cyclist, GC_STRPASS, stravaPass->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_RWGPSUSER, rideWithGPSUser->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_RWGPSPASS, rideWithGPSPass->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_TTBUSER, ttbUser->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_TTBPASS, ttbPass->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_TPTYPE, tpType->currentIndex()); + appsettings->setCValue(context->athlete->cyclist, GC_RWGPSUSER, rideWithGPSUser->text()); + appsettings->setCValue(context->athlete->cyclist, GC_RWGPSPASS, rideWithGPSPass->text()); + appsettings->setCValue(context->athlete->cyclist, GC_TTBUSER, ttbUser->text()); + appsettings->setCValue(context->athlete->cyclist, GC_TTBPASS, ttbPass->text()); + appsettings->setCValue(context->athlete->cyclist, GC_TPTYPE, tpType->currentIndex()); //XXX deprecated appsettings->setCValue(mainWindow->cyclist, GC_TWURL, twitterURL->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_WIURL, wiURL->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_WIUSER, wiUser->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_WIKEY, wiPass->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_ZEOURL, zeoURL->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_ZEOUSER, zeoUser->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_ZEOPASS, zeoPass->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_WEBCAL_URL, webcalURL->text()); + appsettings->setCValue(context->athlete->cyclist, GC_WIURL, wiURL->text()); + appsettings->setCValue(context->athlete->cyclist, GC_WIUSER, wiUser->text()); + appsettings->setCValue(context->athlete->cyclist, GC_WIKEY, wiPass->text()); + appsettings->setCValue(context->athlete->cyclist, GC_ZEOURL, zeoURL->text()); + appsettings->setCValue(context->athlete->cyclist, GC_ZEOUSER, zeoUser->text()); + appsettings->setCValue(context->athlete->cyclist, GC_ZEOPASS, zeoPass->text()); + appsettings->setCValue(context->athlete->cyclist, GC_WEBCAL_URL, webcalURL->text()); // escape the at character QString url = dvURL->text(); url.replace("@", "%40"); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_DVURL, url); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_DVUSER, dvUser->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_DVPASS, dvPass->text()); + appsettings->setCValue(context->athlete->cyclist, GC_DVURL, url); + appsettings->setCValue(context->athlete->cyclist, GC_DVUSER, dvUser->text()); + appsettings->setCValue(context->athlete->cyclist, GC_DVPASS, dvPass->text()); //XXX deprecated saveTwitter(); // get secret key if PIN set } @@ -519,7 +520,7 @@ CredentialsPage::saveClicked() // // About me // -RiderPage::RiderPage(QWidget *parent, MainWindow *mainWindow) : QWidget(parent), mainWindow(mainWindow) +RiderPage::RiderPage(QWidget *parent, Context *context) : QWidget(parent), context(context) { QVBoxLayout *all = new QVBoxLayout(this); QGridLayout *grid = new QGridLayout; @@ -530,14 +531,14 @@ RiderPage::RiderPage(QWidget *parent, MainWindow *mainWindow) : QWidget(parent), QLabel *unitlabel = new QLabel(tr("Unit")); QLabel *biolabel = new QLabel(tr("Bio")); - QString weighttext = QString(tr("Weight (%1)")).arg(mainWindow->athlete->useMetricUnits ? tr("kg") : tr("lb")); + QString weighttext = QString(tr("Weight (%1)")).arg(context->athlete->useMetricUnits ? tr("kg") : tr("lb")); weightlabel = new QLabel(weighttext); nickname = new QLineEdit(this); - nickname->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_NICKNAME).toString()); + nickname->setText(appsettings->cvalue(context->athlete->cyclist, GC_NICKNAME).toString()); dob = new QDateEdit(this); - dob->setDate(appsettings->cvalue(mainWindow->athlete->cyclist, GC_DOB).toDate()); + dob->setDate(appsettings->cvalue(context->athlete->cyclist, GC_DOB).toDate()); sex = new QComboBox(this); sex->addItem(tr("Male")); @@ -546,13 +547,13 @@ RiderPage::RiderPage(QWidget *parent, MainWindow *mainWindow) : QWidget(parent), // we set to 0 or 1 for male or female since this // is language independent (and for once the code is easier!) - sex->setCurrentIndex(appsettings->cvalue(mainWindow->athlete->cyclist, GC_SEX).toInt()); + sex->setCurrentIndex(appsettings->cvalue(context->athlete->cyclist, GC_SEX).toInt()); unitCombo = new QComboBox(); unitCombo->addItem(tr("Metric")); unitCombo->addItem(tr("Imperial")); - if (mainWindow->athlete->useMetricUnits) + if (context->athlete->useMetricUnits) unitCombo->setCurrentIndex(0); else unitCombo->setCurrentIndex(1); @@ -561,13 +562,13 @@ RiderPage::RiderPage(QWidget *parent, MainWindow *mainWindow) : QWidget(parent), weight->setMaximum(999.9); weight->setMinimum(0.0); weight->setDecimals(1); - weight->setValue(appsettings->cvalue(mainWindow->athlete->cyclist, GC_WEIGHT).toDouble() * (mainWindow->athlete->useMetricUnits ? 1.0 : LB_PER_KG)); + weight->setValue(appsettings->cvalue(context->athlete->cyclist, GC_WEIGHT).toDouble() * (context->athlete->useMetricUnits ? 1.0 : LB_PER_KG)); bio = new QTextEdit(this); - bio->setText(appsettings->cvalue(mainWindow->athlete->cyclist, GC_BIO).toString()); + bio->setText(appsettings->cvalue(context->athlete->cyclist, GC_BIO).toString()); - if (QFileInfo(mainWindow->athlete->home.absolutePath() + "/" + "avatar.png").exists()) - avatar = QPixmap(mainWindow->athlete->home.absolutePath() + "/" + "avatar.png"); + if (QFileInfo(context->athlete->home.absolutePath() + "/" + "avatar.png").exists()) + avatar = QPixmap(context->athlete->home.absolutePath() + "/" + "avatar.png"); else avatar = QPixmap(":/images/noavatar.png"); @@ -634,24 +635,24 @@ RiderPage::unitChanged(int currentIndex) void RiderPage::saveClicked() { - appsettings->setCValue(mainWindow->athlete->cyclist, GC_NICKNAME, nickname->text()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_DOB, dob->date()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_WEIGHT, weight->value() * (unitCombo->currentIndex() ? KG_PER_LB : 1.0)); + appsettings->setCValue(context->athlete->cyclist, GC_NICKNAME, nickname->text()); + appsettings->setCValue(context->athlete->cyclist, GC_DOB, dob->date()); + appsettings->setCValue(context->athlete->cyclist, GC_WEIGHT, weight->value() * (unitCombo->currentIndex() ? KG_PER_LB : 1.0)); if (unitCombo->currentIndex()==0) - appsettings->setCValue(mainWindow->athlete->cyclist, GC_UNIT, GC_UNIT_METRIC); + appsettings->setCValue(context->athlete->cyclist, GC_UNIT, GC_UNIT_METRIC); else if (unitCombo->currentIndex()==1) - appsettings->setCValue(mainWindow->athlete->cyclist, GC_UNIT, GC_UNIT_IMPERIAL); + appsettings->setCValue(context->athlete->cyclist, GC_UNIT, GC_UNIT_IMPERIAL); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_SEX, sex->currentIndex()); - appsettings->setCValue(mainWindow->athlete->cyclist, GC_BIO, bio->toPlainText()); - avatar.save(mainWindow->athlete->home.absolutePath() + "/" + "avatar.png", "PNG"); + appsettings->setCValue(context->athlete->cyclist, GC_SEX, sex->currentIndex()); + appsettings->setCValue(context->athlete->cyclist, GC_BIO, bio->toPlainText()); + avatar.save(context->athlete->home.absolutePath() + "/" + "avatar.png", "PNG"); } // // Realtime devices page // -DevicePage::DevicePage(QWidget *parent, MainWindow *mainWindow) : QWidget(parent), mainWindow(mainWindow) +DevicePage::DevicePage(QWidget *parent, Context *context) : QWidget(parent), context(context) { QVBoxLayout *mainLayout = new QVBoxLayout(this); @@ -711,7 +712,7 @@ void DevicePage::devaddClicked() { DeviceConfiguration add; - AddDeviceWizard *p = new AddDeviceWizard(mainWindow); + AddDeviceWizard *p = new AddDeviceWizard(context); p->show(); } @@ -1540,19 +1541,19 @@ SummaryMetricsPage::saveClicked() appsettings->setValue(GC_SETTINGS_SUMMARY_METRICS, metrics.join(",")); } -MetadataPage::MetadataPage(MainWindow *main) : main(main) +MetadataPage::MetadataPage(Context *context) : context(context) { QVBoxLayout *layout = new QVBoxLayout(this); // get current config using default file - keywordDefinitions = main->athlete->rideMetadata()->getKeywords(); - fieldDefinitions = main->athlete->rideMetadata()->getFields(); - colorfield = main->athlete->rideMetadata()->getColorField(); + keywordDefinitions = context->athlete->rideMetadata()->getKeywords(); + fieldDefinitions = context->athlete->rideMetadata()->getFields(); + colorfield = context->athlete->rideMetadata()->getColorField(); // setup maintenance pages using current config fieldsPage = new FieldsPage(this, fieldDefinitions); keywordsPage = new KeywordsPage(this, keywordDefinitions); - processorPage = new ProcessorPage(main); + processorPage = new ProcessorPage(context); tabs = new QTabWidget(this); tabs->addTab(fieldsPage, tr("Fields")); @@ -1574,7 +1575,7 @@ MetadataPage::saveClicked() keywordsPage->getDefinitions(keywordDefinitions); // write to metadata.xml - RideMetadata::serialize(main->athlete->home.absolutePath() + "/metadata.xml", keywordDefinitions, fieldDefinitions, colorfield); + RideMetadata::serialize(context->athlete->home.absolutePath() + "/metadata.xml", keywordDefinitions, fieldDefinitions, colorfield); // save processors config processorPage->saveClicked(); @@ -2026,7 +2027,7 @@ FieldsPage::getDefinitions(QList &fieldList) // // Data processors config page // -ProcessorPage::ProcessorPage(MainWindow *main) : main(main) +ProcessorPage::ProcessorPage(Context *context) : context(context) { // get the available processors const DataProcessorFactory &factory = DataProcessorFactory::instance(); @@ -2099,12 +2100,12 @@ ProcessorPage::saveClicked() // // Zone Config page // -ZonePage::ZonePage(MainWindow *main) : main(main) +ZonePage::ZonePage(Context *context) : context(context) { QVBoxLayout *layout = new QVBoxLayout(this); // get current config by reading it in (leave mainwindow zones alone) - QFile zonesFile(main->athlete->home.absolutePath() + "/power.zones"); + QFile zonesFile(context->athlete->home.absolutePath() + "/power.zones"); if (zonesFile.exists()) { zones.read(zonesFile); zonesFile.close(); @@ -2125,7 +2126,7 @@ void ZonePage::saveClicked() { zones.setScheme(schemePage->getScheme()); - zones.write(main->athlete->home); + zones.write(context->athlete->home); } SchemePage::SchemePage(ZonePage* zonePage) : zonePage(zonePage) @@ -2642,12 +2643,12 @@ CPPage::zonesChanged() // // Zone Config page // -HrZonePage::HrZonePage(MainWindow *main) : main(main) +HrZonePage::HrZonePage(Context *context) : context(context) { QVBoxLayout *layout = new QVBoxLayout(this); // get current config by reading it in (leave mainwindow zones alone) - QFile zonesFile(main->athlete->home.absolutePath() + "/hr.zones"); + QFile zonesFile(context->athlete->home.absolutePath() + "/hr.zones"); if (zonesFile.exists()) { zones.read(zonesFile); zonesFile.close(); @@ -2668,7 +2669,7 @@ void HrZonePage::saveClicked() { zones.setScheme(schemePage->getScheme()); - zones.write(main->athlete->home); + zones.write(context->athlete->home); } HrSchemePage::HrSchemePage(HrZonePage* zonePage) : zonePage(zonePage) @@ -3250,7 +3251,7 @@ LTPage::zonesChanged() // // Ride metadata page // -MeasuresPage::MeasuresPage(MainWindow *main) : main(main) +MeasuresPage::MeasuresPage(Context *context) : context(context) { QGridLayout *mainLayout = new QGridLayout(this); @@ -3295,7 +3296,7 @@ MeasuresPage::MeasuresPage(MainWindow *main) : main(main) QList keywordDefinitions; //NOTE: not used in measures.xml // check we have one and use built in if not there - QString filename = main->athlete->home.absolutePath()+"/measures.xml"; + QString filename = context->athlete->home.absolutePath()+"/measures.xml"; QString colorfield; if (!QFile(filename).exists()) filename = ":/xml/measures.xml"; @@ -3445,20 +3446,20 @@ MeasuresPage::saveClicked() getDefinitions(current); // write to measures.xml (uses same format as metadata.xml) - RideMetadata::serialize(main->athlete->home.absolutePath() + "/measures.xml", QList(), current, ""); + RideMetadata::serialize(context->athlete->home.absolutePath() + "/measures.xml", QList(), current, ""); } // // Season Editor // -SeasonsPage::SeasonsPage(QWidget *parent, MainWindow *mainWindow) : QWidget(parent), mainWindow(mainWindow) +SeasonsPage::SeasonsPage(QWidget *parent, Context *context) : QWidget(parent), context(context) { QGridLayout *mainLayout = new QGridLayout(this); QFormLayout *editLayout = new QFormLayout; editLayout->setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint); // get the list - array = mainWindow->athlete->seasons->seasons; + array = context->athlete->seasons->seasons; // Edit widgets nameEdit = new QLineEdit(this); @@ -3677,9 +3678,9 @@ SeasonsPage::saveClicked() } // write to disk - QString file = QString(mainWindow->athlete->home.absolutePath() + "/seasons.xml"); + QString file = QString(context->athlete->home.absolutePath() + "/seasons.xml"); SeasonParser::serialize(file, array); // re-read - mainWindow->athlete->seasons->readSeasons(); + context->athlete->seasons->readSeasons(); } diff --git a/src/Pages.h b/src/Pages.h index 5e64b79e4..246e4036f 100644 --- a/src/Pages.h +++ b/src/Pages.h @@ -55,7 +55,7 @@ class GeneralPage : public QWidget G_OBJECT public: - GeneralPage(MainWindow *main); + GeneralPage(Context *context); void saveClicked(); @@ -63,7 +63,7 @@ class GeneralPage : public QWidget void browseWorkoutDir(); private: - MainWindow *main; + Context *context; QComboBox *langCombo; QComboBox *unitCombo; @@ -96,7 +96,7 @@ class RiderPage : public QWidget public: - RiderPage(QWidget *parent, MainWindow *mainWindow); + RiderPage(QWidget *parent, Context *context); void saveClicked(); public slots: @@ -104,7 +104,7 @@ class RiderPage : public QWidget void unitChanged(int currentIndex); private: - MainWindow *mainWindow; + Context *context; QLineEdit *nickname; QDateEdit *dob; @@ -124,13 +124,13 @@ class CredentialsPage : public QScrollArea public: - CredentialsPage(QWidget *parent, MainWindow *mainWindow); + CredentialsPage(QWidget *parent, Context *context); void saveClicked(); public slots: private: - MainWindow *mainWindow; + Context *context; QLineEdit *tpURL; // url for training peaks.com ... http://www.trainingpeaks.com QLineEdit *tpUser; @@ -200,7 +200,7 @@ class DevicePage : public QWidget G_OBJECT public: - DevicePage(QWidget *, MainWindow *); + DevicePage(QWidget *, Context *); void saveClicked(); QTableView *deviceList; @@ -210,7 +210,7 @@ class DevicePage : public QWidget void devdelClicked(); private: - MainWindow *mainWindow; + Context *context; QList devices; @@ -418,7 +418,7 @@ class ProcessorPage : public QWidget public: - ProcessorPage(MainWindow *main); + ProcessorPage(Context *context); void saveClicked(); public slots: @@ -428,7 +428,7 @@ class ProcessorPage : public QWidget protected: - MainWindow *main; + Context *context; QMap processors; QTreeWidget *processorTree; @@ -445,7 +445,7 @@ class MetadataPage : public QWidget public: - MetadataPage(MainWindow *); + MetadataPage(Context *); void saveClicked(); public slots: @@ -453,7 +453,7 @@ class MetadataPage : public QWidget protected: - MainWindow *main; + Context *context; bool changed; QTabWidget *tabs; @@ -528,7 +528,7 @@ class ZonePage : public QWidget public: - ZonePage(MainWindow *); + ZonePage(Context *); void saveClicked(); //ZoneScheme scheme; @@ -543,7 +543,7 @@ class ZonePage : public QWidget protected: - MainWindow *main; + Context *context; bool changed; QTabWidget *tabs; @@ -615,7 +615,7 @@ class HrZonePage : public QWidget public: - HrZonePage(MainWindow *); + HrZonePage(Context *); void saveClicked(); //ZoneScheme scheme; @@ -630,7 +630,7 @@ public: protected: - MainWindow *main; + Context *context; bool changed; QTabWidget *tabs; @@ -645,7 +645,7 @@ class SeasonsPage : public QWidget public: - SeasonsPage(QWidget *parent, MainWindow *main); + SeasonsPage(QWidget *parent, Context *context); void getDefinitions(QList&); public slots: @@ -660,7 +660,7 @@ class SeasonsPage : public QWidget private: QTreeWidget *seasons; - MainWindow *mainWindow; + Context *context; QLineEdit *nameEdit; QComboBox *typeEdit; @@ -682,7 +682,7 @@ class MeasuresPage : public QWidget public: - MeasuresPage(MainWindow *main); + MeasuresPage(Context *context); void getDefinitions(QList&); public slots: @@ -695,7 +695,7 @@ class MeasuresPage : public QWidget private: - MainWindow *main; + Context *context; QTreeWidget *fields; #ifndef Q_OS_MAC QToolButton *upButton, *downButton; diff --git a/src/PeakPower.cpp b/src/PeakPower.cpp index 73ceb337a..8ab2eb173 100644 --- a/src/PeakPower.cpp +++ b/src/PeakPower.cpp @@ -37,7 +37,7 @@ class PeakPower : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { if (!ride->dataPoints().isEmpty()) { QList results; @@ -338,7 +338,7 @@ class PeakPowerHr : public RideMetric { } void setSecs(double secs) { this->secs=secs; } void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, - const QHash &, const MainWindow *) { + const QHash &, const Context *) { if (!ride->dataPoints().isEmpty()){ QList results; diff --git a/src/PerformanceManagerWindow.cpp b/src/PerformanceManagerWindow.cpp index 8e2e1cbcb..37f10e785 100644 --- a/src/PerformanceManagerWindow.cpp +++ b/src/PerformanceManagerWindow.cpp @@ -1,6 +1,8 @@ #include "PerformanceManagerWindow.h" #include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "PerfPlot.h" #include "Colors.h" #include "StressCalculator.h" @@ -8,8 +10,8 @@ #include -PerformanceManagerWindow::PerformanceManagerWindow(MainWindow *mainWindow) : - GcWindow(mainWindow), mainWindow(mainWindow), active(false), isfiltered(false) +PerformanceManagerWindow::PerformanceManagerWindow(Context *context) : + GcWindow(context), context(context), active(false), isfiltered(false) { setInstanceName("PM Window"); setControls(NULL); @@ -107,14 +109,14 @@ PerformanceManagerWindow::PerformanceManagerWindow(MainWindow *mainWindow) : SLOT(PMpickerMoved(const QPoint &))); connect(metricCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(metricChanged())); - connect(mainWindow->context, SIGNAL(configChanged()), this, SLOT(configChanged())); - connect(mainWindow->context, SIGNAL(configChanged()), perfplot, SLOT(configUpdate())); - connect(mainWindow, SIGNAL(rideAdded(RideItem*)), this, SLOT(replot())); - connect(mainWindow, SIGNAL(rideDeleted(RideItem*)), this, SLOT(replot())); + connect(context, SIGNAL(configChanged()), this, SLOT(configChanged())); + connect(context, SIGNAL(configChanged()), perfplot, SLOT(configUpdate())); + connect(context->mainWindow, SIGNAL(rideAdded(RideItem*)), this, SLOT(replot())); + connect(context->mainWindow, SIGNAL(rideDeleted(RideItem*)), this, SLOT(replot())); //connect(mainWindow, SIGNAL(rideSelected()), this, SLOT(rideSelected())); connect(this, SIGNAL(rideItemChanged(RideItem*)), this, SLOT(rideSelected())); #ifdef GC_HAVE_LUCENE - connect(mainWindow, SIGNAL(filterChanged(QStringList&)), this, SLOT(filterChanged(QStringList&))); + connect(context->mainWindow, SIGNAL(filterChanged(QStringList&)), this, SLOT(filterChanged(QStringList&))); #endif } @@ -129,7 +131,7 @@ void PerformanceManagerWindow::filterChanged(QStringList &list) { filter = list; - isfiltered = mainWindow->isfiltered; + isfiltered = context->mainWindow->isfiltered; days = 0; // force it replot(); repaint(); @@ -162,7 +164,7 @@ void PerformanceManagerWindow::rideSelected() void PerformanceManagerWindow::replot() { - const QTreeWidgetItem *allRides = mainWindow->allRideItems(); + const QTreeWidgetItem *allRides = context->mainWindow->allRideItems(); int newdays, rightIndex, endIndex; RideItem *firstRideItem = NULL; @@ -179,7 +181,7 @@ void PerformanceManagerWindow::replot() } if (firstRideItem) { - int lookahead = (appsettings->cvalue(mainWindow->athlete->cyclist, GC_STS_DAYS,7)).toInt(); + int lookahead = (appsettings->cvalue(context->athlete->cyclist, GC_STS_DAYS,7)).toInt(); QDateTime endTime = std::max(lastRideItem->dateTime, now.currentDateTime()); endTime = endTime.addDays( lookahead ); newdays = firstRideItem->dateTime.daysTo(endTime); @@ -204,15 +206,15 @@ void PerformanceManagerWindow::replot() if (sc) delete sc; sc = new StressCalculator( - mainWindow->athlete->cyclist, + context->athlete->cyclist, firstRideItem->dateTime, endTime, - (appsettings->cvalue(mainWindow->athlete->cyclist, GC_STS_DAYS,7)).toInt(), - (appsettings->cvalue(mainWindow->athlete->cyclist, GC_LTS_DAYS,42)).toInt()); + (appsettings->cvalue(context->athlete->cyclist, GC_STS_DAYS,7)).toInt(), + (appsettings->cvalue(context->athlete->cyclist, GC_LTS_DAYS,42)).toInt()); #ifdef GC_HAVE_LUCENE - sc->calculateStress(mainWindow,mainWindow->athlete->home.absolutePath(),newMetric,isfiltered,filter); + sc->calculateStress(context,context->athlete->home.absolutePath(),newMetric,isfiltered,filter); #else - sc->calculateStress(mainWindow,mainWindow->athlete->home.absolutePath(),newMetric); + sc->calculateStress(context,context->athlete->home.absolutePath(),newMetric); #endif perfplot->setStressCalculator(sc); diff --git a/src/PerformanceManagerWindow.h b/src/PerformanceManagerWindow.h index 72dccc821..c5570470e 100644 --- a/src/PerformanceManagerWindow.h +++ b/src/PerformanceManagerWindow.h @@ -20,7 +20,7 @@ #ifndef _GC_PerformanceManagerWindow_h #define _GC_PerformanceManagerWindow_h 1 #include "GoldenCheetah.h" -#include "MainWindow.h" +#include "Context.h" #include #include @@ -47,7 +47,7 @@ class PerformanceManagerWindow : public GcWindow public: - PerformanceManagerWindow (MainWindow *mainWindow); + PerformanceManagerWindow (Context *context); ~PerformanceManagerWindow (void); int scheme() const { return metricCombo->currentIndex(); } @@ -76,7 +76,7 @@ class PerformanceManagerWindow : public GcWindow QString metric; StressCalculator *sc; - MainWindow *mainWindow; + Context *context; bool active; PerfPlot *perfplot; diff --git a/src/PfPvPlot.cpp b/src/PfPvPlot.cpp index 9d445896c..9d4f4fe9d 100644 --- a/src/PfPvPlot.cpp +++ b/src/PfPvPlot.cpp @@ -19,6 +19,7 @@ #include "PfPvPlot.h" #include "MainWindow.h" +#include "Context.h" #include "RideFile.h" #include "RideItem.h" #include "IntervalItem.h" @@ -117,8 +118,8 @@ public: }; -PfPvPlot::PfPvPlot(MainWindow *mainWindow) - : rideItem (NULL), mainWindow(mainWindow), cp_ (0), cad_ (85), cl_ (0.175), shade_zones(true) +PfPvPlot::PfPvPlot(Context *context) + : rideItem (NULL), context(context), cp_ (0), cad_ (85), cl_ (0.175), shade_zones(true) { setInstanceName("PfPv Plot"); @@ -328,10 +329,10 @@ int PfPvPlot::intervalCount() const { int highlighted; highlighted = 0; - if (mainWindow->allIntervalItems() == NULL) return 0; // not inited yet! + if (context->mainWindow->allIntervalItems() == NULL) return 0; // not inited yet! - for (int i=0; iallIntervalItems()->childCount(); i++) { - IntervalItem *current = dynamic_cast(mainWindow->allIntervalItems()->child(i)); + for (int i=0; imainWindow->allIntervalItems()->childCount(); i++) { + IntervalItem *current = dynamic_cast(context->mainWindow->allIntervalItems()->child(i)); if (current != NULL) { if (current->isSelected() == true) { ++highlighted; @@ -469,9 +470,9 @@ PfPvPlot::showIntervals(RideItem *_rideItem) double aepf = (p1->watts * 60.0) / (p1->cad * cl_ * 2.0 * PI); double cpv = (p1->cad * cl_ * 2.0 * PI) / 60.0; - for (int high=-1, t=0; tallIntervalItems()->childCount(); t++) { + for (int high=-1, t=0; tmainWindow->allIntervalItems()->childCount(); t++) { - IntervalItem *current = dynamic_cast(mainWindow->allIntervalItems()->child(t)); + IntervalItem *current = dynamic_cast(context->mainWindow->allIntervalItems()->child(t)); if ((current != NULL) && current->isSelected()) { ++high; @@ -515,12 +516,12 @@ PfPvPlot::showIntervals(RideItem *_rideItem) // ensure same colors are used for each interval selected int num_intervals_defined=0; QVector intervalmap; - if (mainWindow->allIntervalItems() != NULL) { + if (context->mainWindow->allIntervalItems() != NULL) { - num_intervals_defined = mainWindow->allIntervalItems()->childCount(); + num_intervals_defined = context->mainWindow->allIntervalItems()->childCount(); - for (int g=0; gallIntervalItems()->childCount(); g++) { - IntervalItem *curr = dynamic_cast(mainWindow->allIntervalItems()->child(g)); + for (int g=0; gmainWindow->allIntervalItems()->childCount(); g++) { + IntervalItem *curr = dynamic_cast(context->mainWindow->allIntervalItems()->child(g)); if (curr->isSelected()) intervalmap.append(g); } } @@ -531,9 +532,9 @@ PfPvPlot::showIntervals(RideItem *_rideItem) if (mergeIntervals()) intervalOrder.insert(1,0); else { - for (int i=0; iallIntervalItems()->childCount(); i++) { + for (int i=0; imainWindow->allIntervalItems()->childCount(); i++) { - IntervalItem *current = dynamic_cast(mainWindow->allIntervalItems()->child(i)); + IntervalItem *current = dynamic_cast(context->mainWindow->allIntervalItems()->child(i)); if (current != NULL && current->isSelected() == true) { intervalOrder.insert(current->displaySequence, count++); diff --git a/src/PfPvPlot.h b/src/PfPvPlot.h index 118b7aad0..3657f576b 100644 --- a/src/PfPvPlot.h +++ b/src/PfPvPlot.h @@ -31,7 +31,7 @@ class RideItem; struct RideFilePoint; class QwtPlotCurve; class QwtPlotMarker; -class MainWindow; +class Context; class PfPvPlotZoneLabel; class PfPvPlot : public QwtPlot @@ -42,7 +42,7 @@ class PfPvPlot : public QwtPlot public: - PfPvPlot(MainWindow *mainWindow); + PfPvPlot(Context *context); void refreshZoneItems(); void setData(RideItem *_rideItem); void showIntervals(RideItem *_rideItem); @@ -82,7 +82,7 @@ class PfPvPlot : public QwtPlot protected: int intervalCount() const; - MainWindow *mainWindow; + Context *context; QwtPlotCurve *curve; QList intervalCurves; QwtPlotCurve *cpCurve; diff --git a/src/PfPvWindow.cpp b/src/PfPvWindow.cpp index a176cccb6..ef51d7573 100644 --- a/src/PfPvWindow.cpp +++ b/src/PfPvWindow.cpp @@ -18,6 +18,8 @@ #include "PfPvWindow.h" #include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "PfPvPlot.h" #include "RideItem.h" #include "Settings.h" @@ -63,8 +65,8 @@ PfPvDoubleClickPicker::trackerTextF( const QPointF &pos ) const return QwtText( text ); } -PfPvWindow::PfPvWindow(MainWindow *mainWindow) : - GcChartWindow(mainWindow), mainWindow(mainWindow), current(NULL) +PfPvWindow::PfPvWindow(Context *context) : + GcChartWindow(context), context(context), current(NULL) { setInstanceName("Pf/Pv Window"); @@ -108,7 +110,7 @@ PfPvWindow::PfPvWindow(MainWindow *mainWindow) : // the plot QVBoxLayout *vlayout = new QVBoxLayout; - pfPvPlot = new PfPvPlot(mainWindow); + pfPvPlot = new PfPvPlot(context); vlayout->addWidget(pfPvPlot); setChartLayout(vlayout); @@ -190,10 +192,10 @@ PfPvWindow::PfPvWindow(MainWindow *mainWindow) : //connect(mainWindow, SIGNAL(rideSelected()), this, SLOT(rideSelected())); connect(doubleClickPicker, SIGNAL(doubleClicked(int, int)), this, SLOT(doubleClicked(int, int))); connect(this, SIGNAL(rideItemChanged(RideItem*)), this, SLOT(rideSelected())); - connect(mainWindow, SIGNAL(intervalSelected()), this, SLOT(intervalSelected())); - connect(mainWindow, SIGNAL(intervalsChanged()), this, SLOT(intervalSelected())); - connect(mainWindow->athlete, SIGNAL(zonesChanged()), this, SLOT(zonesChanged())); - connect(mainWindow->context, SIGNAL(configChanged()), pfPvPlot, SLOT(configChanged())); + connect(context->mainWindow, SIGNAL(intervalSelected()), this, SLOT(intervalSelected())); + connect(context->mainWindow, SIGNAL(intervalsChanged()), this, SLOT(intervalSelected())); + connect(context->athlete, SIGNAL(zonesChanged()), this, SLOT(zonesChanged())); + connect(context, SIGNAL(configChanged()), pfPvPlot, SLOT(configChanged())); } void diff --git a/src/PfPvWindow.h b/src/PfPvWindow.h index 09089c825..eec7fede5 100644 --- a/src/PfPvWindow.h +++ b/src/PfPvWindow.h @@ -23,7 +23,7 @@ #include #include -class MainWindow; +class Context; class PfPvPlot; class RideItem; @@ -60,7 +60,7 @@ class PfPvWindow : public GcChartWindow public: - PfPvWindow(MainWindow *mainWindow); + PfPvWindow(Context *context); // reveal bool hasReveal() { return true; } @@ -100,7 +100,7 @@ class PfPvWindow : public GcChartWindow protected: - MainWindow *mainWindow; + Context *context; PfPvPlot *pfPvPlot; QwtPlotZoomer *pfpvZoomer; PfPvDoubleClickPicker *doubleClickPicker; diff --git a/src/PowerHist.cpp b/src/PowerHist.cpp index 4de3c3e2e..d64277920 100644 --- a/src/PowerHist.cpp +++ b/src/PowerHist.cpp @@ -19,6 +19,8 @@ #include "PowerHist.h" #include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "RideItem.h" #include "IntervalItem.h" #include "RideFile.h" @@ -43,11 +45,11 @@ #include "LTMCanvasPicker.h" // for tooltip -PowerHist::PowerHist(MainWindow *mainWindow): +PowerHist::PowerHist(Context *context): minX(0), maxX(0), rideItem(NULL), - mainWindow(mainWindow), + context(context), series(RideFile::watts), lny(false), shade(false), @@ -243,7 +245,7 @@ PowerHist::refreshHRZoneLabels() if (!rideItem) return; if (series == RideFile::hr) { - const HrZones *zones = mainWindow->athlete->hrZones(); + const HrZones *zones = context->athlete->hrZones(); int zone_range = rideItem->hrZoneRange(); // generate labels for existing zones @@ -272,7 +274,7 @@ PowerHist::recalc(bool force) LASTrideItem == rideItem && LASTseries == series && LASTshade == shade && - LASTuseMetricUnits == mainWindow->athlete->useMetricUnits && + LASTuseMetricUnits == context->athlete->useMetricUnits && LASTlny == lny && LASTzoned == zoned && LASTbinw == binw && @@ -289,7 +291,7 @@ PowerHist::recalc(bool force) LASTrideItem = rideItem; LASTseries = series; LASTshade = shade; - LASTuseMetricUnits = mainWindow->athlete->useMetricUnits; + LASTuseMetricUnits = context->athlete->useMetricUnits; LASTlny = lny; LASTzoned = zoned; LASTbinw = binw; @@ -504,28 +506,28 @@ PowerHist::recalc(bool force) // hr scale draw int hrRange; - if (series == RideFile::hr && zoned && rideItem && mainWindow->athlete->hrZones() && - (hrRange=mainWindow->athlete->hrZones()->whichRange(rideItem->dateTime.date())) != -1) { - setAxisScaleDraw(QwtPlot::xBottom, new HrZoneScaleDraw(mainWindow->athlete->hrZones(), hrRange)); + if (series == RideFile::hr && zoned && rideItem && context->athlete->hrZones() && + (hrRange=context->athlete->hrZones()->whichRange(rideItem->dateTime.date())) != -1) { + setAxisScaleDraw(QwtPlot::xBottom, new HrZoneScaleDraw(context->athlete->hrZones(), hrRange)); if (hrRange >= 0) - setAxisScale(QwtPlot::xBottom, -0.99, mainWindow->athlete->hrZones()->numZones(hrRange), 1); + setAxisScale(QwtPlot::xBottom, -0.99, context->athlete->hrZones()->numZones(hrRange), 1); else setAxisScale(QwtPlot::xBottom, -0.99, 0, 1); } // watts zoned for a time range - if (source == Cache && zoned && (series == RideFile::watts || series == RideFile::wattsKg) && mainWindow->athlete->zones()) { - setAxisScaleDraw(QwtPlot::xBottom, new ZoneScaleDraw(mainWindow->athlete->zones(), 0)); - if (mainWindow->athlete->zones()->getRangeSize()) - setAxisScale(QwtPlot::xBottom, -0.99, mainWindow->athlete->zones()->numZones(0), 1); // use zones from first defined range + if (source == Cache && zoned && (series == RideFile::watts || series == RideFile::wattsKg) && context->athlete->zones()) { + setAxisScaleDraw(QwtPlot::xBottom, new ZoneScaleDraw(context->athlete->zones(), 0)); + if (context->athlete->zones()->getRangeSize()) + setAxisScale(QwtPlot::xBottom, -0.99, context->athlete->zones()->numZones(0), 1); // use zones from first defined range } // hr zoned for a time range - if (source == Cache && zoned && series == RideFile::hr && mainWindow->athlete->hrZones()) { - setAxisScaleDraw(QwtPlot::xBottom, new HrZoneScaleDraw(mainWindow->athlete->hrZones(), 0)); - if (mainWindow->athlete->hrZones()->getRangeSize()) - setAxisScale(QwtPlot::xBottom, -0.99, mainWindow->athlete->hrZones()->numZones(0), 1); // use zones from first defined range + if (source == Cache && zoned && series == RideFile::hr && context->athlete->hrZones()) { + setAxisScaleDraw(QwtPlot::xBottom, new HrZoneScaleDraw(context->athlete->hrZones(), 0)); + if (context->athlete->hrZones()->getRangeSize()) + setAxisScale(QwtPlot::xBottom, -0.99, context->athlete->hrZones()->numZones(0), 1); // use zones from first defined range } setAxisMaxMinor(QwtPlot::xBottom, 0); @@ -602,9 +604,9 @@ PowerHist::setData(RideFileCache *cache) longFromDouble(cadArray, cache->distributionArray(RideFile::cad)); longFromDouble(kphArray, cache->distributionArray(RideFile::kph)); - if (!mainWindow->athlete->useMetricUnits) { - double torque_factor = (mainWindow->athlete->useMetricUnits ? 1.0 : 0.73756215); - double speed_factor = (mainWindow->athlete->useMetricUnits ? 1.0 : 0.62137119); + if (!context->athlete->useMetricUnits) { + double torque_factor = (context->athlete->useMetricUnits ? 1.0 : 0.73756215); + double speed_factor = (context->athlete->useMetricUnits ? 1.0 : 0.62137119); for(int i=0; i&results, QString totalMetric, QString d if (isFiltered && !files.contains(x.getFileName())) continue; // and global filter too - if (mainWindow->isfiltered && !mainWindow->filters.contains(x.getFileName())) continue; + if (context->mainWindow->isfiltered && !context->mainWindow->filters.contains(x.getFileName())) continue; // get computed value - double v = x.getForSymbol(distMetric, mainWindow->athlete->useMetricUnits); + double v = x.getForSymbol(distMetric, context->athlete->useMetricUnits); // ignore no temp files if ((distMetric == "average_temp" || distMetric == "max_temp") && v == RideFile::noTemp) continue; @@ -658,7 +660,7 @@ PowerHist::setData(QList&results, QString totalMetric, QString d if (isnan(v) || isinf(v)) v = 0; // seconds to minutes - if (m->units(mainWindow->athlete->useMetricUnits) == tr("seconds")) v /= 60; + if (m->units(context->athlete->useMetricUnits) == tr("seconds")) v /= 60; // apply multiplier v *= multiplier; @@ -686,10 +688,10 @@ PowerHist::setData(QList&results, QString totalMetric, QString d if (isFiltered && !files.contains(x.getFileName())) continue; // and global filter too - if (mainWindow->isfiltered && !mainWindow->filters.contains(x.getFileName())) continue; + if (context->mainWindow->isfiltered && !context->mainWindow->filters.contains(x.getFileName())) continue; // get computed value - double v = x.getForSymbol(distMetric, mainWindow->athlete->useMetricUnits); + double v = x.getForSymbol(distMetric, context->athlete->useMetricUnits); // ignore no temp files if ((distMetric == "average_temp" || distMetric == "max_temp") && v == RideFile::noTemp) continue; @@ -698,7 +700,7 @@ PowerHist::setData(QList&results, QString totalMetric, QString d if (isnan(v) || isinf(v)) v = 0; // seconds to minutes - if (m->units(mainWindow->athlete->useMetricUnits) == tr("seconds")) v /= 60; + if (m->units(context->athlete->useMetricUnits) == tr("seconds")) v /= 60; // apply multiplier v *= multiplier; @@ -710,10 +712,10 @@ PowerHist::setData(QList&results, QString totalMetric, QString d // there will be some loss of precision due to totalising // a double in an int, but frankly that should be minimal // since most values of note are integer based anyway. - double t = x.getForSymbol(totalMetric, mainWindow->athlete->useMetricUnits); + double t = x.getForSymbol(totalMetric, context->athlete->useMetricUnits); // totalise in minutes - if (tm->units(mainWindow->athlete->useMetricUnits) == tr("seconds")) t /= 60; + if (tm->units(context->athlete->useMetricUnits) == tr("seconds")) t /= 60; // sum up metricArray[(int)(v)-min] += t; @@ -734,17 +736,17 @@ PowerHist::setData(QList&results, QString totalMetric, QString d absolutetime = true; // and the plot itself - QString yunits = tm->units(mainWindow->athlete->useMetricUnits); + QString yunits = tm->units(context->athlete->useMetricUnits); if (yunits == tr("seconds")) yunits = tr("minutes"); - QString xunits = m->units(mainWindow->athlete->useMetricUnits); + QString xunits = m->units(context->athlete->useMetricUnits); if (xunits == tr("seconds")) xunits = tr("minutes"); - if (tm->units(mainWindow->athlete->useMetricUnits) != "") + if (tm->units(context->athlete->useMetricUnits) != "") setAxisTitle(yLeft, QString(tr("Total %1 (%2)")).arg(tm->name()).arg(yunits)); else setAxisTitle(yLeft, QString(tr("Total %1")).arg(tm->name())); - if (m->units(mainWindow->athlete->useMetricUnits) != "") + if (m->units(context->athlete->useMetricUnits) != "") setAxisTitle(xBottom, QString(tr("%1 of Activity (%2)")).arg(m->name()).arg(xunits)); else setAxisTitle(xBottom, QString(tr("%1 of Activity")).arg(m->name())); @@ -811,8 +813,8 @@ PowerHist::setData(RideItem *_rideItem, bool force) cadSelectedArray.resize(0); // unit conversion factor for imperial units for selected parameters - double torque_factor = (mainWindow->athlete->useMetricUnits ? 1.0 : 0.73756215); - double speed_factor = (mainWindow->athlete->useMetricUnits ? 1.0 : 0.62137119); + double torque_factor = (context->athlete->useMetricUnits ? 1.0 : 0.73756215); + double speed_factor = (context->athlete->useMetricUnits ? 1.0 : 0.62137119); foreach(const RideFilePoint *p1, ride->dataPoints()) { bool selected = isSelected(p1, ride->recIntSecs()); @@ -893,11 +895,11 @@ PowerHist::setData(RideItem *_rideItem, bool force) } // hr zoned array - int hrZoneRange = mainWindow->athlete->hrZones() ? mainWindow->athlete->hrZones()->whichRange(ride->startTime().date()) : -1; + int hrZoneRange = context->athlete->hrZones() ? context->athlete->hrZones()->whichRange(ride->startTime().date()) : -1; // Only calculate zones if we have a valid range if (hrZoneRange > -1 && (withz || (!withz && p1->hr))) { - hrIndex = mainWindow->athlete->hrZones()->whichZone(hrZoneRange, p1->hr); + hrIndex = context->athlete->hrZones()->whichZone(hrZoneRange, p1->hr); if (hrIndex >= 0 && hrIndex < maxSize) { if (hrIndex >= hrZoneArray.size()) @@ -1027,11 +1029,11 @@ PowerHist::setParameterAxisTitle() break; case RideFile::kph: - axislabel = QString(tr("Speed (%1)")).arg(mainWindow->athlete->useMetricUnits ? tr("kph") : tr("mph")); + axislabel = QString(tr("Speed (%1)")).arg(context->athlete->useMetricUnits ? tr("kph") : tr("mph")); break; case RideFile::nm: - axislabel = QString(tr("Torque (%1)")).arg(mainWindow->athlete->useMetricUnits ? tr("N-m") : tr("ft-lbf")); + axislabel = QString(tr("Torque (%1)")).arg(context->athlete->useMetricUnits ? tr("N-m") : tr("ft-lbf")); break; default: @@ -1076,9 +1078,9 @@ bool PowerHist::shadeHRZones() const } bool PowerHist::isSelected(const RideFilePoint *p, double sample) { - if (mainWindow->allIntervalItems() != NULL) { - for (int i=0; iallIntervalItems()->childCount(); i++) { - IntervalItem *current = dynamic_cast(mainWindow->allIntervalItems()->child(i)); + if (context->mainWindow->allIntervalItems() != NULL) { + for (int i=0; imainWindow->allIntervalItems()->childCount(); i++) { + IntervalItem *current = dynamic_cast(context->mainWindow->allIntervalItems()->child(i)); if (current != NULL) { if (current->isSelected() && p->secs+sample>current->start && p->secsstop) { return true; diff --git a/src/PowerHist.h b/src/PowerHist.h index 351905618..0b0a3366e 100644 --- a/src/PowerHist.h +++ b/src/PowerHist.h @@ -20,8 +20,10 @@ #ifndef _GC_PowerHist_h #define _GC_PowerHist_h 1 #include "GoldenCheetah.h" -#include "RideFile.h" #include "MainWindow.h" +#include "RideFile.h" +#include "Context.h" +#include "Athlete.h" #include "Zones.h" #include "HrZones.h" @@ -35,7 +37,7 @@ class QwtPlotCurve; class QwtPlotGrid; -class MainWindow; +class Context; class RideItem; struct RideFilePoint; class RideFileCache; @@ -96,7 +98,7 @@ class PowerHist : public QwtPlot public: - PowerHist(MainWindow *mainWindow); + PowerHist(Context *context); ~PowerHist(); double minX; @@ -157,7 +159,7 @@ class PowerHist : public QwtPlot // plot settings RideItem *rideItem; - MainWindow *mainWindow; + Context *context; RideFile::SeriesType series; bool lny; bool shade; @@ -398,7 +400,7 @@ public: if (! rideItem) return; - const HrZones *zones = parent->mainWindow->athlete->hrZones(); + const HrZones *zones = parent->context->athlete->hrZones(); int zone_range = rideItem->hrZoneRange(); if (parent->shadeHRZones() && (zone_range >= 0)) { @@ -448,7 +450,7 @@ public: if (! rideItem) return; - const HrZones *zones = parent->mainWindow->athlete->hrZones(); + const HrZones *zones = parent->context->athlete->hrZones(); int zone_range = rideItem->hrZoneRange(); setZ(1.0 + zone_number / 100.0); diff --git a/src/PwxRideFile.cpp b/src/PwxRideFile.cpp index f7c50f6e2..697ec0090 100644 --- a/src/PwxRideFile.cpp +++ b/src/PwxRideFile.cpp @@ -17,6 +17,7 @@ */ #include "PwxRideFile.h" +#include "Athlete.h" #include "Settings.h" #include #include @@ -297,7 +298,7 @@ PwxFileReader::PwxFromDomDoc(QDomDocument doc, QStringList &errors) const } bool -PwxFileReader::writeRideFile(MainWindow *main, const RideFile *ride, QFile &file) const +PwxFileReader::writeRideFile(Context *context, const RideFile *ride, QFile &file) const { QDomText text; // used all over QDomDocument doc; @@ -320,7 +321,7 @@ PwxFileReader::writeRideFile(MainWindow *main, const RideFile *ride, QFile &file // athlete details QDomElement athlete = doc.createElement("athlete"); QDomElement name = doc.createElement("name"); - text = doc.createTextNode(main->athlete->cyclist); name.appendChild(text); + text = doc.createTextNode(context->athlete->cyclist); name.appendChild(text); athlete.appendChild(name); double cyclistweight = ride->getTag("Weight", "0.0").toDouble(); if (cyclistweight) { diff --git a/src/PwxRideFile.h b/src/PwxRideFile.h index d8a976c28..9f3dbf705 100644 --- a/src/PwxRideFile.h +++ b/src/PwxRideFile.h @@ -21,12 +21,12 @@ #include "GoldenCheetah.h" #include "RideFile.h" -#include "MainWindow.h" +#include "Context.h" #include struct PwxFileReader : public RideFileReader { virtual RideFile *openRideFile(QFile &file, QStringList &errors, QList* = 0) const; - bool writeRideFile(MainWindow *, const RideFile *ride, QFile &file) const; + bool writeRideFile(Context *, const RideFile *ride, QFile &file) const; virtual RideFile *PwxFromDomDoc(QDomDocument doc, QStringList &errors) const; bool hasWrite() const { return true; } }; diff --git a/src/QTFullScreen.cpp b/src/QTFullScreen.cpp index 41201399f..cec8c80a3 100644 --- a/src/QTFullScreen.cpp +++ b/src/QTFullScreen.cpp @@ -18,7 +18,7 @@ #include "QTFullScreen.h" -QTFullScreen::QTFullScreen(MainWindow *main) : QObject(main), main(main), isFull(false) +QTFullScreen::QTFullScreen(Context *context) : QObject(main), context(context), isFull(false) { // watch for ESC key being hit when in full screen main->installEventFilter(this); diff --git a/src/QTFullScreen.h b/src/QTFullScreen.h index 0951fe9af..8cc43403f 100644 --- a/src/QTFullScreen.h +++ b/src/QTFullScreen.h @@ -24,7 +24,7 @@ // QT stuff etc #include -#include "MainWindow.h" +#include "Context.h" class QTFullScreen : public QObject { @@ -32,7 +32,7 @@ class QTFullScreen : public QObject public: - QTFullScreen(MainWindow *main); + QTFullScreen(Context *context); // found in the supplied directory void toggle(); @@ -41,7 +41,7 @@ class QTFullScreen : public QObject bool eventFilter(QObject *obj, QEvent *event); private: - MainWindow *main; + Context *context; bool isFull; }; diff --git a/src/QtMacVideoWindow.h b/src/QtMacVideoWindow.h index f86c1f13d..3998a7a75 100644 --- a/src/QtMacVideoWindow.h +++ b/src/QtMacVideoWindow.h @@ -24,7 +24,7 @@ #include #include #include -#include "MainWindow.h" +#include "Context.h" #include "DeviceConfiguration.h" #include "DeviceTypes.h" #include "RealtimeData.h" @@ -87,7 +87,7 @@ class VideoWindow : public GcWindow public: - VideoWindow(MainWindow *, const QDir &); + VideoWindow(Context *, const QDir &); ~VideoWindow(); public slots: @@ -103,9 +103,9 @@ class VideoWindow : public GcWindow void resizeEvent(QResizeEvent *); - // passed from MainWindow + // passed from Context * QDir home; - MainWindow *main; + Context *context; bool hasMovie; // the active movie diff --git a/src/QtMacVideoWindow.mm b/src/QtMacVideoWindow.mm index 2478b48d1..dc6fe124e 100644 --- a/src/QtMacVideoWindow.mm +++ b/src/QtMacVideoWindow.mm @@ -25,6 +25,7 @@ #include #include "QtMacVideoWindow.h" +#include "Context.h" static inline NSString *darwinQStringToNSString (const QString &aString) @@ -33,8 +34,8 @@ static inline NSString *darwinQStringToNSString (const QString &aString) (0, reinterpret_cast (aString.unicode()), aString.length()); } -VideoWindow::VideoWindow(MainWindow *parent, const QDir &home) : -GcWindow(parent), home(home), main(parent), hasMovie(false) +VideoWindow::VideoWindow(Context *context, const QDir &home) : +GcWindow(context), home(home), context(context), hasMovie(false) { setControls(NULL); @@ -50,12 +51,12 @@ GcWindow(parent), home(home), main(parent), hasMovie(false) layout->addWidget(player); - connect(main->context, SIGNAL(stop()), this, SLOT(stopPlayback())); - connect(main->context, SIGNAL(start()), this, SLOT(startPlayback())); - connect(main->context, SIGNAL(pause()), this, SLOT(pausePlayback())); - connect(main->context, SIGNAL(unpause()), this, SLOT(resumePlayback())); - connect(main->context, SIGNAL(seek(long)), this, SLOT(seekPlayback(long))); - connect(main->context, SIGNAL(mediaSelected(QString)), this, SLOT(mediaSelected(QString))); + connect(context, SIGNAL(stop()), this, SLOT(stopPlayback())); + connect(context, SIGNAL(start()), this, SLOT(startPlayback())); + connect(context, SIGNAL(pause()), this, SLOT(pausePlayback())); + connect(context, SIGNAL(unpause()), this, SLOT(resumePlayback())); + connect(context, SIGNAL(seek(long)), this, SLOT(seekPlayback(long))); + connect(context, SIGNAL(mediaSelected(QString)), this, SLOT(mediaSelected(QString))); } @@ -206,7 +207,7 @@ MediaHelper::isMedia(QString filename) return false; } -QtMacMovieView::QtMacMovieView (QWidget *parent) : QMacCocoaViewContainer (0, parent) +QtMacMovieView::QtMacMovieView (QWidget *context) : QMacCocoaViewContainer (0, context) { #if QT_VERSION >= 0x040800 // see QT-BUG 22574, QMacCocoaContainer on 4.8 is "broken" setAttribute(Qt::WA_NativeWindow); diff --git a/src/QxtScheduleViewProxy.h b/src/QxtScheduleViewProxy.h index 99c1204c5..b0d394a28 100644 --- a/src/QxtScheduleViewProxy.h +++ b/src/QxtScheduleViewProxy.h @@ -38,7 +38,7 @@ #include #include "qxtscheduleview.h" -#include "MainWindow.h" +#include "Context.h" #include "RideMetadata.h" #include "Colors.h" #include "Settings.h" @@ -54,12 +54,12 @@ private: QxtScheduleView *rideNavigator; QList *fieldDefinitions; QList columns; // what columns in the sql model - MainWindow *mainWindow; + Context *context; int filenameIndex, durationIndex, dateIndex, summaryIndex; public: - QxtScheduleViewProxy(QWidget *parent, QList *fields, MainWindow *main) : QAbstractProxyModel(parent), fieldDefinitions(fields), mainWindow(main) { + QxtScheduleViewProxy(QWidget *parent, QList *fields, Context *context) : QAbstractProxyModel(parent), fieldDefinitions(fields), mainWindow(main) { setParent(parent); } ~QxtScheduleViewProxy() {} diff --git a/src/RawRideFile.cpp b/src/RawRideFile.cpp index fb799969d..e1175806d 100644 --- a/src/RawRideFile.cpp +++ b/src/RawRideFile.cpp @@ -16,6 +16,7 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ +#include "Context.h" #include "RawRideFile.h" #include "PowerTapUtil.h" #include "Units.h" diff --git a/src/RealtimePlotWindow.cpp b/src/RealtimePlotWindow.cpp index cec33c443..58f43a848 100644 --- a/src/RealtimePlotWindow.cpp +++ b/src/RealtimePlotWindow.cpp @@ -18,9 +18,11 @@ #include "RealtimePlotWindow.h" +#include "MainWindow.h" +#include "Athlete.h" -RealtimePlotWindow::RealtimePlotWindow(MainWindow *mainWindow) : - GcWindow(mainWindow), mainWindow(mainWindow), active(false) +RealtimePlotWindow::RealtimePlotWindow(Context *context) : + GcWindow(context), context(context), active(false) { setContentsMargins(0,0,0,0); setInstanceName("RT Plot"); @@ -90,7 +92,7 @@ RealtimePlotWindow::RealtimePlotWindow(MainWindow *mainWindow) : connect(smoothLineEdit, SIGNAL(editingFinished()), this, SLOT(setSmoothingFromLineEdit())); // get updates.. - connect(mainWindow, SIGNAL(telemetryUpdate(RealtimeData)), this, SLOT(telemetryUpdate(RealtimeData))); + connect(context->mainWindow, SIGNAL(telemetryUpdate(RealtimeData)), this, SLOT(telemetryUpdate(RealtimeData))); // lets initialise all the smoothing variables hrtot = hrindex = cadtot = cadindex = spdtot = spdindex = alttot = altindex = powtot = powindex = 0; @@ -142,7 +144,7 @@ RealtimePlotWindow::telemetryUpdate(RealtimeData rtData) spdtot += spd; spdtot -= spdHist[spdindex]; spdHist[spdindex] = spd; spdindex++; if (spdindex >= rtPlot->smooth) spdindex = 0; spd = spdtot / rtPlot->smooth; - if (!mainWindow->athlete->useMetricUnits) spd *= MILES_PER_KM; + if (!context->athlete->useMetricUnits) spd *= MILES_PER_KM; rtPlot->spdData->addData(spd); // Power diff --git a/src/RealtimePlotWindow.h b/src/RealtimePlotWindow.h index 59590f97f..ceb05c9ab 100644 --- a/src/RealtimePlotWindow.h +++ b/src/RealtimePlotWindow.h @@ -24,7 +24,7 @@ #include // for Q_PROPERTY -#include "MainWindow.h" +#include "Context.h" #include "RideFile.h" // for data series types #include "RealtimePlot.h" #include "RealtimeData.h" // for realtimedata structure @@ -48,7 +48,7 @@ class RealtimePlotWindow : public GcWindow public: - RealtimePlotWindow(MainWindow *mainWindow); + RealtimePlotWindow(Context *context); // get properties - the setters are below int isShowHr() const { return showHr->checkState(); } @@ -80,7 +80,7 @@ class RealtimePlotWindow : public GcWindow private: - MainWindow *mainWindow; + Context *context; RealtimePlot *rtPlot; bool active; diff --git a/src/RideEditor.cpp b/src/RideEditor.cpp index 1aa58d2f0..5d37df0ed 100644 --- a/src/RideEditor.cpp +++ b/src/RideEditor.cpp @@ -20,6 +20,7 @@ #include "LTMOutliers.h" #include "IntervalItem.h" #include "MainWindow.h" +#include "Context.h" #include "Settings.h" #include @@ -54,7 +55,7 @@ static void secsMsecs(double value, int &secs, int &msecs) msecs = round((value - secs) * 100) * 10; } -RideEditor::RideEditor(MainWindow *main) : GcChartWindow(main), data(NULL), ride(NULL), main(main), inLUW(false), colMapper(NULL) +RideEditor::RideEditor(Context *context) : GcChartWindow(context), data(NULL), ride(NULL), context(context), inLUW(false), colMapper(NULL) { setInstanceName("Ride Editor"); setControls(NULL); @@ -139,11 +140,11 @@ RideEditor::RideEditor(MainWindow *main) : GcChartWindow(main), data(NULL), ride mainLayout->addWidget(table); // trap GC signals - connect(main, SIGNAL(intervalSelected()), this, SLOT(intervalSelected())); + connect(context->mainWindow, SIGNAL(intervalSelected()), this, SLOT(intervalSelected())); //connect(main, SIGNAL(rideSelected()), this, SLOT(rideSelected())); connect(this, SIGNAL(rideItemChanged(RideItem*)), this, SLOT(rideSelected())); - connect(main->context, SIGNAL(rideDirty(RideItem*)), this, SLOT(rideDirty())); - connect(main->context, SIGNAL(rideClean(RideItem*)), this, SLOT(rideClean())); + connect(context, SIGNAL(rideDirty(RideItem*)), this, SLOT(rideDirty())); + connect(context, SIGNAL(rideClean(RideItem*)), this, SLOT(rideClean())); // put find tool and anomaly list in the controls findTool = new FindDialog(this); @@ -271,7 +272,7 @@ void RideEditor::saveFile() { if (ride && ride->isDirty()) { - main->saveRideSingleDialog(ride); + context->mainWindow->saveRideSingleDialog(ride); } } @@ -1107,7 +1108,7 @@ void RideEditor::intervalSelected() { // is it for the ride item we are editing? - if (main->context->currentRideItem() == ride) { + if (context->currentRideItem() == ride) { // clear all selections table->selectionModel()->select(QItemSelection(model->index(0,0), @@ -1115,7 +1116,7 @@ RideEditor::intervalSelected() QItemSelectionModel::Clear); // highlight selection and jump to last - foreach(QTreeWidgetItem *x, main->allIntervalItems()->treeWidget()->selectedItems()) { + foreach(QTreeWidgetItem *x, context->mainWindow->allIntervalItems()->treeWidget()->selectedItems()) { IntervalItem *current = (IntervalItem*)x; diff --git a/src/RideEditor.h b/src/RideEditor.h index d43d899ba..404623145 100644 --- a/src/RideEditor.h +++ b/src/RideEditor.h @@ -20,7 +20,7 @@ #define _GC_RideEditor_h 1 #include "GoldenCheetah.h" -#include "MainWindow.h" +#include "Context.h" #include "RideItem.h" #include "RideFile.h" #include "RideFileCommand.h" @@ -47,7 +47,7 @@ class RideEditor : public GcChartWindow public: - RideEditor(MainWindow *); + RideEditor(Context *); // item delegate uses this QTableView *table; @@ -127,7 +127,7 @@ class RideEditor : public GcChartWindow AnomalyDialog *anomalyTool; private: - MainWindow *main; + Context *context; bool inLUW; QList itemselection; diff --git a/src/RideFile.cpp b/src/RideFile.cpp index 2f6c0ba62..1bbcdfb9a 100644 --- a/src/RideFile.cpp +++ b/src/RideFile.cpp @@ -18,6 +18,7 @@ */ #include "RideFile.h" +#include "Athlete.h" #include "DataProcessor.h" #include "RideEditor.h" #include "RideMetadata.h" @@ -97,9 +98,9 @@ RideFile::seriesName(SeriesType series) } QString -RideFile::unitName(SeriesType series, MainWindow *main) +RideFile::unitName(SeriesType series, Context *context) { - bool useMetricUnits = main->athlete->useMetricUnits; + bool useMetricUnits = context->athlete->useMetricUnits; switch (series) { case RideFile::secs: return QString(tr("seconds")); @@ -264,17 +265,17 @@ RideFileFactory::rideFileRegExp() const } bool -RideFileFactory::writeRideFile(MainWindow *main, const RideFile *ride, QFile &file, QString format) const +RideFileFactory::writeRideFile(Context *context, const RideFile *ride, QFile &file, QString format) const { // get the ride file writer for this format RideFileReader *reader = readFuncs_.value(format.toLower()); // write away if (!reader) return false; - else return reader->writeRideFile(main, ride, file); + else return reader->writeRideFile(context, ride, file); } -RideFile *RideFileFactory::openRideFile(MainWindow *main, QFile &file, +RideFile *RideFileFactory::openRideFile(Context *context, QFile &file, QStringList &errors, QList *rideList) const { QString suffix = file.fileName(); @@ -289,7 +290,7 @@ RideFile *RideFileFactory::openRideFile(MainWindow *main, QFile &file, // NULL returned to indicate openRide failed if (result) { - result->mainwindow = main; + result->context = context; if (result->intervals().empty()) result->fillInIntervals(); @@ -320,7 +321,7 @@ RideFile *RideFileFactory::openRideFile(MainWindow *main, QFile &file, // Construct the summary text used on the calendar QString calendarText; - foreach (FieldDefinition field, main->athlete->rideMetadata()->getFields()) { + foreach (FieldDefinition field, context->athlete->rideMetadata()->getFields()) { if (field.diary == true && result->getTag(field.name, "") != "") { calendarText += QString("%1\n") .arg(result->getTag(field.name, "")); @@ -820,7 +821,7 @@ RideFile::getWeight() } // withings? - QList measures = mainwindow->athlete->metricDB->getAllMeasuresFor(QDateTime::fromString("Jan 1 00:00:00 1900"), startTime()); + QList measures = context->athlete->metricDB->getAllMeasuresFor(QDateTime::fromString("Jan 1 00:00:00 1900"), startTime()); int i = measures.count()-1; if (i) { while (i>=0) { @@ -833,7 +834,7 @@ RideFile::getWeight() // global options - weight_ = appsettings->cvalue(mainwindow->athlete->cyclist, GC_WEIGHT, "75.0").toString().toDouble(); // default to 75kg + weight_ = appsettings->cvalue(context->athlete->cyclist, GC_WEIGHT, "75.0").toString().toDouble(); // default to 75kg // if set to zero in global options then override it. // it must not be zero!!! diff --git a/src/RideFile.h b/src/RideFile.h index 47ceb9271..fb0b87764 100644 --- a/src/RideFile.h +++ b/src/RideFile.h @@ -35,7 +35,7 @@ struct RideFileDataPresent; struct RideFileInterval; class EditorData; // attached to a RideFile class RideFileCommand; // for manipulating ride data -class MainWindow; // for context; cyclist, homedir +class Context; // for context; cyclist, homedir // This file defines four classes: // @@ -83,7 +83,8 @@ class RideFile : public QObject // QObject to emit signals public: friend class RideFileCommand; // tells us we were modified - friend class MainWindow; // tells us we were saved + friend class MainWindow; // tells us we were modified + friend class Context; // tells us we were saved // Constructor / Destructor RideFile(); @@ -96,7 +97,7 @@ class RideFile : public QObject // QObject to emit signals typedef enum seriestype SeriesType; static QString seriesName(SeriesType); - static QString unitName(SeriesType, MainWindow *main); + static QString unitName(SeriesType, Context *context); static int decimalsFor(SeriesType series); static double maximumFor(SeriesType series); static double minimumFor(SeriesType series); @@ -153,7 +154,7 @@ class RideFile : public QObject // QObject to emit signals QString getTag(QString name, QString fallback) const { return tags_.value(name, fallback); } void setTag(QString name, QString value) { tags_.insert(name, value); } - MainWindow *mainwindow; + Context *context; double getWeight(); // METRIC OVERRIDES @@ -235,7 +236,7 @@ struct RideFileReader { // if hasWrite capability should re-implement writeRideFile and hasWrite virtual bool hasWrite() const { return false; } - virtual bool writeRideFile(MainWindow *, const RideFile *, QFile &) const { return false; } + virtual bool writeRideFile(Context *, const RideFile *, QFile &) const { return false; } }; class RideFileFactory { @@ -254,8 +255,8 @@ class RideFileFactory { int registerReader(const QString &suffix, const QString &description, RideFileReader *reader); - RideFile *openRideFile(MainWindow *main, QFile &file, QStringList &errors, QList* = 0) const; - bool writeRideFile(MainWindow *main, const RideFile *ride, QFile &file, QString format) const; + RideFile *openRideFile(Context *context, QFile &file, QStringList &errors, QList* = 0) const; + bool writeRideFile(Context *context, const RideFile *ride, QFile &file, QString format) const; QStringList listRideFiles(const QDir &dir) const; QStringList suffixes() const; QStringList writeSuffixes() const; diff --git a/src/RideFileCache.cpp b/src/RideFileCache.cpp index eff6905d0..a67626c06 100644 --- a/src/RideFileCache.cpp +++ b/src/RideFileCache.cpp @@ -18,6 +18,8 @@ #include "RideFileCache.h" #include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "Zones.h" #include "HrZones.h" @@ -30,8 +32,8 @@ static const int maxcache = 25; // lets max out at 25 caches // cache from ride -RideFileCache::RideFileCache(MainWindow *main, QString fileName, RideFile *passedride, bool check) : - main(main), rideFileName(fileName), ride(passedride) +RideFileCache::RideFileCache(Context *context, QString fileName, RideFile *passedride, bool check) : + context(context), rideFileName(fileName), ride(passedride) { // resize all the arrays to zero wattsMeanMax.resize(0); @@ -99,7 +101,7 @@ RideFileCache::RideFileCache(MainWindow *main, QString fileName, RideFile *passe QStringList errors; QFile file(rideFileName); - ride = RideFileFactory::instance().openRideFile(main, file, errors); + ride = RideFileFactory::instance().openRideFile(context, file, errors); if (ride) { ride->getWeight(); // before threads are created @@ -301,11 +303,11 @@ RideFileCache::refreshCache() // invalidate any incore cache of aggregate // that contains this ride in its date range QDate date = ride->startTime().date(); - for (int i=0; iathlete->cpxCache.count();) { - if (date >= main->athlete->cpxCache.at(i)->start && - date <= main->athlete->cpxCache.at(i)->end) { - delete main->athlete->cpxCache.at(i); - main->athlete->cpxCache.removeAt(i); + for (int i=0; iathlete->cpxCache.count();) { + if (date >= context->athlete->cpxCache.at(i)->start && + date <= context->athlete->cpxCache.at(i)->end) { + delete context->athlete->cpxCache.at(i); + context->athlete->cpxCache.removeAt(i); } else i++; } @@ -814,13 +816,13 @@ RideFileCache::computeDistribution(QVector &array, RideFile::SeriesType s if (ride->isDataPresent(baseSeries) == false) return; // get zones that apply, if any - int zoneRange = main->athlete->zones() ? main->athlete->zones()->whichRange(ride->startTime().date()) : -1; - int hrZoneRange = main->athlete->hrZones() ? main->athlete->hrZones()->whichRange(ride->startTime().date()) : -1; + int zoneRange = context->athlete->zones() ? context->athlete->zones()->whichRange(ride->startTime().date()) : -1; + int hrZoneRange = context->athlete->hrZones() ? context->athlete->hrZones()->whichRange(ride->startTime().date()) : -1; - if (zoneRange != -1) CP=main->athlete->zones()->getCP(zoneRange); + if (zoneRange != -1) CP=context->athlete->zones()->getCP(zoneRange); else CP=0; - if (hrZoneRange != -1) LTHR=main->athlete->hrZones()->getLT(hrZoneRange); + if (hrZoneRange != -1) LTHR=context->athlete->hrZones()->getLT(hrZoneRange); else LTHR=0; // setup the array based upon the ride @@ -843,11 +845,11 @@ RideFileCache::computeDistribution(QVector &array, RideFile::SeriesType s // watts time in zone if (series == RideFile::watts && zoneRange != -1) - wattsTimeInZone[main->athlete->zones()->whichZone(zoneRange, dp->value(series))] += ride->recIntSecs(); + wattsTimeInZone[context->athlete->zones()->whichZone(zoneRange, dp->value(series))] += ride->recIntSecs(); // hr time in zone if (series == RideFile::hr && hrZoneRange != -1) - hrTimeInZone[main->athlete->hrZones()->whichZone(hrZoneRange, dp->value(series))] += ride->recIntSecs(); + hrTimeInZone[context->athlete->hrZones()->whichZone(hrZoneRange, dp->value(series))] += ride->recIntSecs(); int offset = lvalue - min; if (offset >= 0 && offset < array.size()) array[offset] += ride->recIntSecs(); @@ -889,13 +891,13 @@ static void distAggregate(QVector &into, QVector &other) } -RideFileCache::RideFileCache(MainWindow *main, QDate start, QDate end, bool filter, QStringList files) - : start(start), end(end), main(main), rideFileName(""), ride(0) +RideFileCache::RideFileCache(Context *context, QDate start, QDate end, bool filter, QStringList files) + : start(start), end(end), context(context), rideFileName(""), ride(0) { // Oh lets get from the cache if we can -- but not if filtered - if (!filter && !main->isfiltered) { - foreach(RideFileCache *p, main->athlete->cpxCache) { + if (!filter && !context->mainWindow->isfiltered) { + foreach(RideFileCache *p, context->athlete->cpxCache) { if (p->start == start && p->end == end) { *this = *p; return; @@ -930,20 +932,20 @@ RideFileCache::RideFileCache(MainWindow *main, QDate start, QDate end, bool filt // set cursor busy whilst we aggregate -- bit of feedback // and less intrusive than a popup box - main->setCursor(Qt::WaitCursor); + context->mainWindow->setCursor(Qt::WaitCursor); // Iterate over the ride files (not the cpx files since they /might/ not // exist, or /might/ be out of date. - foreach (QString rideFileName, RideFileFactory::instance().listRideFiles(main->athlete->home)) { + foreach (QString rideFileName, RideFileFactory::instance().listRideFiles(context->athlete->home)) { QDate rideDate = dateFromFileName(rideFileName); if (((filter == true && files.contains(rideFileName)) || filter == false) && rideDate >= start && rideDate <= end) { // skip globally filtered values - if (main->isfiltered && !main->filters.contains(rideFileName)) continue; + if (context->mainWindow->isfiltered && !context->mainWindow->filters.contains(rideFileName)) continue; // get its cached values (will refresh if needed...) - RideFileCache rideCache(main, main->athlete->home.absolutePath() + "/" + rideFileName); + RideFileCache rideCache(context, context->athlete->home.absolutePath() + "/" + rideFileName); // lets aggregate meanMaxAggregate(wattsMeanMaxDouble, rideCache.wattsMeanMaxDouble, wattsMeanMaxDate, rideDate); @@ -974,15 +976,15 @@ RideFileCache::RideFileCache(MainWindow *main, QDate start, QDate end, bool filt } // set the cursor back to normal - main->setCursor(Qt::ArrowCursor); + context->mainWindow->setCursor(Qt::ArrowCursor); // lets add to the cache for others to re-use -- but not if filtered - if (!main->isfiltered && !filter) { - if (main->athlete->cpxCache.count() > maxcache) { - delete(main->athlete->cpxCache.at(0)); - main->athlete->cpxCache.removeAt(0); + if (!context->mainWindow->isfiltered && !filter) { + if (context->athlete->cpxCache.count() > maxcache) { + delete(context->athlete->cpxCache.at(0)); + context->athlete->cpxCache.removeAt(0); } - main->athlete->cpxCache.append(new RideFileCache(this)); + context->athlete->cpxCache.append(new RideFileCache(this)); } } diff --git a/src/RideFileCache.h b/src/RideFileCache.h index 637f841c0..62632ea74 100644 --- a/src/RideFileCache.h +++ b/src/RideFileCache.h @@ -24,7 +24,7 @@ #include #include -class MainWindow; +class Context; class RideFile; #include "GoldenCheetah.h" @@ -120,11 +120,11 @@ class RideFileCache // the calling class. // to save time you can pass the ride file if you already have it open // and if you don't want the data and just want to check pass check=true - RideFileCache(MainWindow *main, QString filename, RideFile *ride =0, bool check = false); + RideFileCache(Context *context, QString filename, RideFile *ride =0, bool check = false); // Construct a ridefile cache that represents the data // across a date range. This is used to provide aggregated data. - RideFileCache(MainWindow *main, QDate start, QDate end, bool filter = false, QStringList files = QStringList()); + RideFileCache(Context *context, QDate start, QDate end, bool filter = false, QStringList files = QStringList()); // not actually a copy constructor -- but we call it IN the constructor. RideFileCache(RideFileCache *other) { *this = *other; } @@ -157,7 +157,7 @@ class RideFileCache private: - MainWindow *main; + Context *context; QString rideFileName; // filename of ride QString cacheFileName; // filename of cache file RideFile *ride; diff --git a/src/RideFileTableModel.h b/src/RideFileTableModel.h index 732d9e2d6..41cb92b1d 100644 --- a/src/RideFileTableModel.h +++ b/src/RideFileTableModel.h @@ -22,7 +22,7 @@ #include "RideFile.h" #include "RideFileCommand.h" -#include "MainWindow.h" +#include "Context.h" #include // diff --git a/src/RideImportWizard.cpp b/src/RideImportWizard.cpp index 879cfba9a..c0258a852 100644 --- a/src/RideImportWizard.cpp +++ b/src/RideImportWizard.cpp @@ -18,10 +18,12 @@ #include #include +#include "MainWindow.h" #include "RideItem.h" #include "RideFile.h" #include "RideImportWizard.h" -#include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "QuarqRideFile.h" #include #include "Settings.h" @@ -33,24 +35,24 @@ // drag and drop passes urls ... convert to a list of files and call main constructor -RideImportWizard::RideImportWizard(QList *urls, QDir &home, MainWindow *main, QWidget *parent) : QDialog(parent), mainWindow(main) +RideImportWizard::RideImportWizard(QList *urls, QDir &home, Context *context, QWidget *parent) : QDialog(parent), context(context) { setAttribute(Qt::WA_DeleteOnClose); setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint); QList filenames; for (int i=0; icount(); i++) filenames.append(QFileInfo(urls->value(i).toLocalFile()).absoluteFilePath()); - init(filenames, home, mainWindow); + init(filenames, home, context); filenames.clear(); } -RideImportWizard::RideImportWizard(QList files, QDir &home, MainWindow *main, QWidget *parent) : QDialog(parent), mainWindow(main) +RideImportWizard::RideImportWizard(QList files, QDir &home, Context *context, QWidget *parent) : QDialog(parent), context(context) { - init(files, home, mainWindow); + init(files, home, context); } void -RideImportWizard::init(QList files, QDir &home, MainWindow * /*mainWindow*/) +RideImportWizard::init(QList files, QDir &home, Context * /*mainWindow*/) { // initialise dialog box @@ -279,7 +281,7 @@ RideImportWizard::process() QApplication::processEvents(); QList rides; - RideFile *ride = RideFileFactory::instance().openRideFile(mainWindow, thisfile, errors, &rides); + RideFile *ride = RideFileFactory::instance().openRideFile(context, thisfile, errors, &rides); // is this an archive of files? if (rides.count() > 1) { @@ -307,7 +309,7 @@ RideImportWizard::process() QString fulltarget = QDir::tempPath() + "/" + QFileInfo(thisfile).baseName() + QString("-%1.tcx").arg(counter+1); TcxFileReader reader; QFile target(fulltarget); - reader.writeRideFile(mainWindow, extracted, target); + reader.writeRideFile(context, extracted, target); deleteMe.append(fulltarget); delete extracted; @@ -423,7 +425,7 @@ RideImportWizard::process() tableWidget->item(i,3)->setTextAlignment(Qt::AlignHCenter); // put in the middle // show distance by looking at last data point - QString dist = mainWindow->athlete->useMetricUnits + QString dist = context->athlete->useMetricUnits ? QString ("%1 km").arg(km, 0, 'f', 1) : QString ("%1 mi").arg(km * MILES_PER_KM, 0, 'f', 1); tableWidget->item(i,4)->setText(dist); @@ -698,8 +700,8 @@ RideImportWizard::abortClicked() if (label == tr("Abort")) { hide(); - mainWindow->isclean = false; - mainWindow->athlete->metricDB->refreshMetrics(); + context->mainWindow->isclean = false; + context->athlete->metricDB->refreshMetrics(); aborted=true; // terminated. I'll be back. return; } @@ -707,8 +709,8 @@ RideImportWizard::abortClicked() if (label == tr("Finish")) { // phew. our work is done. -- lets force an update stats... hide(); - mainWindow->isclean = false; - mainWindow->athlete->metricDB->refreshMetrics(); + context->mainWindow->isclean = false; + context->athlete->metricDB->refreshMetrics(); done(0); return; } @@ -801,7 +803,7 @@ RideImportWizard::abortClicked() // read the file (again) QStringList errors; QFile thisfile(filenames[i]); - RideFile *ride(RideFileFactory::instance().openRideFile(mainWindow, thisfile, errors)); + RideFile *ride(RideFileFactory::instance().openRideFile(context, thisfile, errors)); // update ridedatetime ride->setStartTime(ridedatetime); @@ -810,11 +812,11 @@ RideImportWizard::abortClicked() if (filenames[i].endsWith(".gc")) { GcFileReader reader; QFile target(fulltarget); - reader.writeRideFile(mainWindow, ride, target); + reader.writeRideFile(context, ride, target); } else { JsonFileReader reader; QFile target(fulltarget); - reader.writeRideFile(mainWindow, ride, target); + reader.writeRideFile(context, ride, target); } // clear @@ -824,7 +826,7 @@ RideImportWizard::abortClicked() tableWidget->item(i,5)->setText(tr("File Overwritten")); } else { tableWidget->item(i,5)->setText(tr("File Saved")); - mainWindow->addRide(QFileInfo(fulltarget).fileName(), true); + context->mainWindow->addRide(QFileInfo(fulltarget).fileName(), true); } } @@ -869,7 +871,7 @@ RideImportWizard::abortClicked() QFile source(filenames[i]); if (source.copy(fulltarget)) { tableWidget->item(i,5)->setText(tr("File Saved")); - mainWindow->addRide(QFileInfo(fulltarget).fileName(), true); // add to tree view + context->mainWindow->addRide(QFileInfo(fulltarget).fileName(), true); // add to tree view // free immediately otherwise all imported rides are cached // and with large imports this can lead to memory exhaustion // BUT! Some charts/windows will hava snaffled away the ridefile diff --git a/src/RideImportWizard.h b/src/RideImportWizard.h index 5b205c5b0..47db8cc59 100644 --- a/src/RideImportWizard.h +++ b/src/RideImportWizard.h @@ -25,7 +25,7 @@ #include #include #include -#include "MainWindow.h" +#include "Context.h" // Dialog class to show filenames, import progress and to capture user input // of ride date and time @@ -37,8 +37,8 @@ class RideImportWizard : public QDialog public: - RideImportWizard(QList *urls, QDir &home, MainWindow *main, QWidget *parent = 0); - RideImportWizard(QList files, QDir &home, MainWindow *main, QWidget *parent = 0); + RideImportWizard(QList *urls, QDir &home, Context *context, QWidget *parent = 0); + RideImportWizard(QList files, QDir &home, Context *context, QWidget *parent = 0); ~RideImportWizard(); int process(); @@ -52,7 +52,7 @@ private slots: void activateSave(); private: - void init(QList files, QDir &home, MainWindow *main); + void init(QList files, QDir &home, Context *context); QList filenames; // list of filenames passed QList blanks; // record of which have a RideFileReader returned date & time QDir home; // target directory @@ -65,7 +65,7 @@ private: QComboBox *todayButton; // set date to today when asking for dates QCheckBox *overFiles; // chance to set overwrite when asking for dates bool overwriteFiles; // flag to overwrite files from checkbox - MainWindow *mainWindow; // caller + Context *context; // caller QStringList deleteMe; // list of temp files created during import }; diff --git a/src/RideItem.cpp b/src/RideItem.cpp index 15a3eefba..4001ab713 100644 --- a/src/RideItem.cpp +++ b/src/RideItem.cpp @@ -20,7 +20,8 @@ #include "RideItem.h" #include "RideMetric.h" #include "RideFile.h" -#include "MainWindow.h" +#include "Context.h" +#include "Context.h" #include "Zones.h" #include "HrZones.h" #include @@ -28,8 +29,8 @@ RideItem::RideItem(int type, QString path, QString fileName, const QDateTime &dateTime, - const Zones *zones, const HrZones *hrZones, MainWindow *main) : - QTreeWidgetItem(type), ride_(NULL), main(main), isdirty(false), isedit(false), path(path), fileName(fileName), + const Zones *zones, const HrZones *hrZones, Context *context) : + QTreeWidgetItem(type), ride_(NULL), context(context), isdirty(false), isedit(false), path(path), fileName(fileName), dateTime(dateTime), zones(zones), hrZones(hrZones) { } @@ -39,7 +40,7 @@ RideFile *RideItem::ride() // open the ride file QFile file(path + "/" + fileName); - ride_ = RideFileFactory::instance().openRideFile(main, file, errors_); + ride_ = RideFileFactory::instance().openRideFile(context, file, errors_); if (ride_ == NULL) return NULL; // failed to read ride setDirty(false); // we're gonna use on-disk so by @@ -48,7 +49,7 @@ RideFile *RideItem::ride() // certainly be referenced by consuming widgets // stay aware of state changes to our ride - // MainWindow saves and RideFileCommand modifies + // Context saves and RideFileCommand modifies connect(ride_, SIGNAL(modified()), this, SLOT(modified())); connect(ride_, SIGNAL(saved()), this, SLOT(saved())); connect(ride_, SIGNAL(reverted()), this, SLOT(reverted())); @@ -102,7 +103,7 @@ RideItem::setDirty(bool val) setFont(i, current); } - main->context->notifyRideDirty(); + context->notifyRideDirty(); } else { @@ -113,7 +114,7 @@ RideItem::setDirty(bool val) setFont(i, current); } - main->context->notifyRideClean(); + context->notifyRideClean(); } } diff --git a/src/RideItem.h b/src/RideItem.h index 5036a28be..6edb4850d 100644 --- a/src/RideItem.h +++ b/src/RideItem.h @@ -26,7 +26,7 @@ class RideFile; class RideEditor; -class MainWindow; +class Context; class Zones; class HrZones; @@ -49,7 +49,7 @@ class RideItem : public QObject, public QTreeWidgetItem //<< for signals/slots QVector time_in_hr_zone; RideFile *ride_; QStringList errors_; - MainWindow *main; // to notify widgets when date/time changes + Context *context; // to notify widgets when date/time changes bool isdirty; public slots: @@ -77,7 +77,7 @@ class RideItem : public QObject, public QTreeWidgetItem //<< for signals/slots RideItem(int type, QString path, QString fileName, const QDateTime &dateTime, - const Zones *zones, const HrZones *hrZones, MainWindow *main); + const Zones *zones, const HrZones *hrZones, Context *context); void setDirty(bool); bool isDirty() { return isdirty; } diff --git a/src/RideMetadata.cpp b/src/RideMetadata.cpp index 57cdc87ca..6905f08c8 100644 --- a/src/RideMetadata.cpp +++ b/src/RideMetadata.cpp @@ -20,6 +20,9 @@ #include "SpecialFields.h" #include "MainWindow.h" +#include "RideItem.h" +#include "Context.h" +#include "Athlete.h" #include "RideSummaryWindow.h" #include "Settings.h" #include "Units.h" @@ -33,8 +36,8 @@ /*---------------------------------------------------------------------- * Master widget for Metadata Entry "on" RideSummaryWindow *--------------------------------------------------------------------*/ -RideMetadata::RideMetadata(MainWindow *parent, bool singlecolumn) : - QWidget(parent), singlecolumn(singlecolumn), main(parent) +RideMetadata::RideMetadata(Context *context, bool singlecolumn) : + QWidget(context->mainWindow), singlecolumn(singlecolumn), context(context) { _ride = _connected = NULL; @@ -70,7 +73,7 @@ RideMetadata::RideMetadata(MainWindow *parent, bool singlecolumn) : configUpdate(); // watch for config changes - connect(main->context, SIGNAL(configChanged()), this, SLOT(configUpdate())); + connect(context, SIGNAL(configChanged()), this, SLOT(configUpdate())); // Extra tab is expensive to update so we only update if it // is visible. In this case we need to trigger refresh when the @@ -113,7 +116,7 @@ RideMetadata::warnDateTime(QDateTime datetime) // now make a regexp for all know ride types foreach(QString suffix, RideFileFactory::instance().suffixes()) { - QString conflict = main->athlete->home.absolutePath() + "/" + targetnosuffix + "." + suffix; + QString conflict = context->athlete->home.absolutePath() + "/" + targetnosuffix + "." + suffix; if (QFile(conflict).exists() && QFileInfo(conflict).fileName() != rideItem()->fileName) { QMessageBox::warning(this, "Date/Time Entry", "An activity already exists with that date/time, if you do not change it then you will overwrite and lose existing data"); return; // only warn on the first conflict! @@ -209,7 +212,7 @@ RideMetadata::configUpdate() setFont(QFont()); // read metadata.xml - QString filename = main->athlete->home.absolutePath()+"/metadata.xml"; + QString filename = context->athlete->home.absolutePath()+"/metadata.xml"; if (!QFile(filename).exists()) filename = ":/xml/metadata.xml"; readXML(filename, keywordDefinitions, fieldDefinitions, colorfield); @@ -408,13 +411,13 @@ FormField::FormField(FieldDefinition field, RideMetadata *meta) : definition(fie if (meta->sp.isMetric(field.name)) { field.type = FIELD_DOUBLE; // whatever they say, we want a double! - units = meta->sp.rideMetric(field.name)->units(meta->main->athlete->useMetricUnits); + units = meta->sp.rideMetric(field.name)->units(meta->context->athlete->useMetricUnits); if (units != "") units = QString(" (%1)").arg(units); } // we need to show what units we use for weight... if (field.name == "Weight" && field.type == FIELD_DOUBLE) { - units = meta->main->athlete->useMetricUnits ? tr(" (kg)") : tr (" (lbs)"); + units = meta->context->athlete->useMetricUnits ? tr(" (kg)") : tr (" (lbs)"); } label = new QLabel(QString("%1%2").arg(meta->sp.displayName(field.name)).arg(units), this); @@ -473,7 +476,7 @@ FormField::FormField(FieldDefinition field, RideMetadata *meta) : definition(fie enabled = new QCheckBox(this); connect(enabled, SIGNAL(stateChanged(int)), this, SLOT(stateChanged(int))); - units = meta->sp.rideMetric(field.name)->units(meta->main->athlete->useMetricUnits); + units = meta->sp.rideMetric(field.name)->units(meta->context->athlete->useMetricUnits); if (units == "seconds") { // we need to use a TimeEdit instead @@ -631,7 +634,7 @@ FormField::editFinished() if (meta->sp.isMetric(definition.name) && enabled->isChecked()) { // convert from imperial to metric if needed - if (!meta->main->athlete->useMetricUnits) { + if (!meta->context->athlete->useMetricUnits) { double value = text.toDouble() * (1/ meta->sp.rideMetric(definition.name)->conversion()); value -= meta->sp.rideMetric(definition.name)->conversionSum(); text = QString("%1").arg(value); @@ -648,7 +651,7 @@ FormField::editFinished() // we need to convert from display value to // stored value for the Weight field: - if (definition.type == FIELD_DOUBLE && definition.name == "Weight" && meta->main->athlete->useMetricUnits == false) { + if (definition.type == FIELD_DOUBLE && definition.name == "Weight" && meta->context->athlete->useMetricUnits == false) { double kg = text.toDouble() / LB_PER_KG; text = QString("%1").arg(kg); } @@ -745,7 +748,7 @@ FormField::metadataChanged() // does it need conversion from metric? if (meta->sp.rideMetric(definition.name)->conversion() != 1.0) { // do we want imperial? - if (!meta->main->athlete->useMetricUnits) { + if (!meta->context->athlete->useMetricUnits) { double newvalue = value.toDouble() * meta->sp.rideMetric(definition.name)->conversion(); newvalue -= meta->sp.rideMetric(definition.name)->conversionSum(); value = QString("%1").arg(newvalue); @@ -783,7 +786,7 @@ FormField::metadataChanged() case FIELD_DOUBLE : // double if (isTime) ((QTimeEdit*)widget)->setTime(QTime(0,0,0,0).addSecs(value.toDouble())); else { - if (definition.name == "Weight" && meta->main->athlete->useMetricUnits == false) { + if (definition.name == "Weight" && meta->context->athlete->useMetricUnits == false) { double lbs = value.toDouble() * LB_PER_KG; value = QString("%1").arg(lbs); } diff --git a/src/RideMetadata.h b/src/RideMetadata.h index 9a74e0c01..bab39a705 100644 --- a/src/RideMetadata.h +++ b/src/RideMetadata.h @@ -20,7 +20,7 @@ #define _GC_RideMetadata_h #include "GoldenCheetah.h" -#include "MainWindow.h" +#include "Context.h" #include "SpecialFields.h" #include #include @@ -35,6 +35,8 @@ #define FIELD_TIME 6 #define FIELD_CHECKBOX 7 +class RideMetadata; + class KeywordDefinition { public: @@ -118,7 +120,7 @@ class RideMetadata : public QWidget RideItem *_ride, *_connected; public: - RideMetadata(MainWindow *, bool singlecolumn = false); + RideMetadata(Context *, bool singlecolumn = false); static void serialize(QString filename, QList, QList, QString colofield); static void readXML(QString filename, QList&, QList&, QString &colorfield); QList getKeywords() { return keywordDefinitions; } @@ -133,7 +135,7 @@ class RideMetadata : public QWidget bool singlecolumn; SpecialFields sp; - MainWindow *main; + Context *context; SpecialTabs specialTabs; public slots: diff --git a/src/RideMetric.cpp b/src/RideMetric.cpp index 9c831cedc..f7a006b09 100644 --- a/src/RideMetric.cpp +++ b/src/RideMetric.cpp @@ -24,7 +24,7 @@ RideMetricFactory *RideMetricFactory::_instance; QVector RideMetricFactory::noDeps; QHash -RideMetric::computeMetrics(const MainWindow *main, const RideFile *ride, const Zones *zones, const HrZones *hrZones, +RideMetric::computeMetrics(const Context *context, const RideFile *ride, const Zones *zones, const HrZones *hrZones, const QStringList &metrics) { int zoneRange = zones->whichRange(ride->startTime().date()); @@ -48,7 +48,7 @@ RideMetric::computeMetrics(const MainWindow *main, const RideFile *ride, const Z if (ready) { RideMetric *m = factory.newMetric(symbol); //if (!ride->dataPoints().isEmpty()) - m->compute(ride, zones, zoneRange, hrZones, hrZoneRange, done, main); + m->compute(ride, zones, zoneRange, hrZones, hrZoneRange, done, context); if (ride->metricOverrides.contains(symbol)) m->override(ride->metricOverrides.value(symbol)); done.insert(symbol, m); diff --git a/src/RideMetric.h b/src/RideMetric.h index 21692f60f..a547ab3e9 100644 --- a/src/RideMetric.h +++ b/src/RideMetric.h @@ -29,10 +29,11 @@ #include #include "RideFile.h" +#include "Context.h" class Zones; class HrZones; -class MainWindow; +class Context; class RideMetric; typedef QSharedPointer RideMetricPtr; @@ -101,7 +102,7 @@ public: const Zones *zones, int zoneRange, const HrZones *hrzones, int hrzoneRange, const QHash &deps, - const MainWindow *main = 0) = 0; + const Context *context = 0) = 0; // Fill in the value of the ride metric using the mapping provided. For // example, average speed might be specified by the mapping @@ -136,7 +137,7 @@ public: virtual RideMetric *clone() const = 0; static QHash - computeMetrics(const MainWindow *main, const RideFile *ride, const Zones *zones, const HrZones *hrZones, + computeMetrics(const Context *context, const RideFile *ride, const Zones *zones, const HrZones *hrZones, const QStringList &metrics); // Initialisers for derived classes to setup basic data diff --git a/src/RideNavigator.cpp b/src/RideNavigator.cpp index b5cb4ccf8..c1692fba3 100644 --- a/src/RideNavigator.cpp +++ b/src/RideNavigator.cpp @@ -16,6 +16,8 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ +#include "Athlete.h" +#include "Context.h" #include "RideNavigator.h" #include "RideNavigatorProxy.h" #include "SearchFilterBox.h" @@ -23,7 +25,7 @@ #include #include -RideNavigator::RideNavigator(MainWindow *parent, bool mainwindow) : main(parent), active(false), _groupBy(-1) +RideNavigator::RideNavigator(Context *context, bool mainwindow) : context(context), active(false), _groupBy(-1) { // get column headings // default column layouts etc @@ -42,7 +44,7 @@ RideNavigator::RideNavigator(MainWindow *parent, bool mainwindow) : main(parent) if (mainwindow) mainLayout->setContentsMargins(0,0,0,0); else mainLayout->setContentsMargins(2,2,2,2); // so we can resize! - sqlModel = new QSqlTableModel(this, main->athlete->metricDB->db()->connection()); + sqlModel = new QSqlTableModel(this, context->athlete->metricDB->db()->connection()); sqlModel->setTable("metrics"); sqlModel->setEditStrategy(QSqlTableModel::OnManualSubmit); sqlModel->select(); @@ -60,7 +62,7 @@ RideNavigator::RideNavigator(MainWindow *parent, bool mainwindow) : main(parent) #ifdef GC_HAVE_LUCENE if (!mainwindow) { - searchFilterBox = new SearchFilterBox(this, main, false); + searchFilterBox = new SearchFilterBox(this, context, false); mainLayout->addWidget(searchFilterBox); } #endif @@ -94,14 +96,14 @@ RideNavigator::RideNavigator(MainWindow *parent, bool mainwindow) : main(parent) resetView(); // refresh when database is updated - connect(main->athlete->metricDB, SIGNAL(dataChanged()), this, SLOT(refresh())); + connect(context->athlete->metricDB, SIGNAL(dataChanged()), this, SLOT(refresh())); // refresh when config changes (metric/imperial?) - connect(main->context, SIGNAL(configChanged()), this, SLOT(refresh())); + connect(context, SIGNAL(configChanged()), this, SLOT(refresh())); // refresh when rides added/removed - connect(main, SIGNAL(rideAdded(RideItem*)), this, SLOT(refresh())); - connect(main, SIGNAL(rideDeleted(RideItem*)), this, SLOT(refresh())); - connect(main->rideTreeWidget(), SIGNAL(itemSelectionChanged()), this, SLOT(rideTreeSelectionChanged())); + connect(context->mainWindow, SIGNAL(rideAdded(RideItem*)), this, SLOT(refresh())); + connect(context->mainWindow, SIGNAL(rideDeleted(RideItem*)), this, SLOT(refresh())); + connect(context->mainWindow->rideTreeWidget(), SIGNAL(itemSelectionChanged()), this, SLOT(rideTreeSelectionChanged())); // selection of a ride by double clicking it, we need to update the ride list connect(tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(selectRide(QModelIndex))); connect(tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(cursorRide())); @@ -194,7 +196,7 @@ RideNavigator::resetView() // add metadata fields... SpecialFields sp; // all the special fields are in here... - foreach(FieldDefinition field, main->athlete->rideMetadata()->getFields()) { + foreach(FieldDefinition field, context->athlete->rideMetadata()->getFields()) { if (!sp.isMetric(field.name) && (field.type < 5 || field.type == 7)) { nameMap.insert(QString("Z%1").arg(sp.makeTechName(field.name)), sp.displayName(field.name)); internalNameMap.insert(field.name, sp.displayName(field.name)); @@ -433,7 +435,7 @@ RideNavigator::eventFilter(QObject *object, QEvent *e) // so we ignore those if (e->type() != QEvent::ToolTip && e->type() != QEvent::Paint && e->type() != QEvent::WinIdChange && e->type() != QEvent::Destroy) { - main->setBubble(""); + context->mainWindow->setBubble(""); } // not for the table? @@ -514,7 +516,7 @@ RideNavigator::eventFilter(QObject *object, QEvent *e) // off view port! if (local.y() <= 0 || local.x() <= 0) { - main->setBubble(""); + context->mainWindow->setBubble(""); return false; } @@ -524,7 +526,7 @@ RideNavigator::eventFilter(QObject *object, QEvent *e) e->accept(); QPoint p = local; p.setX(width()-20); - main->setBubble(hoverFileName, tableView->viewport()->mapToGlobal(p)); + context->mainWindow->setBubble(hoverFileName, tableView->viewport()->mapToGlobal(p)); } } break; @@ -795,7 +797,7 @@ RideNavigator::selectRide(const QModelIndex &index) QModelIndex fileIndex = tableView->model()->index(index.row(), 2, index.parent()); // column 2 for filename ? QString filename = tableView->model()->data(fileIndex, Qt::DisplayRole).toString(); - main->selectRideFile(filename); + context->mainWindow->selectRideFile(filename); } // user cursor moved to ride @@ -825,8 +827,8 @@ RideNavigator::rideTreeSelectionChanged() else active = true; QTreeWidgetItem *which; - if (main->rideTreeWidget()->selectedItems().count()) - which = main->rideTreeWidget()->selectedItems().first(); + if (context->mainWindow->rideTreeWidget()->selectedItems().count()) + which = context->mainWindow->rideTreeWidget()->selectedItems().first(); else // no rides slected which = NULL; @@ -919,8 +921,8 @@ void NavigatorCellDelegate::paint(QPainter *painter, const QStyleOptionViewItem if (metricValue) { // metric / imperial converstion - metricValue *= (rideNavigator->main->athlete->useMetricUnits) ? 1 : m->conversion(); - metricValue += (rideNavigator->main->athlete->useMetricUnits) ? 0 : m->conversionSum(); + metricValue *= (rideNavigator->context->athlete->useMetricUnits) ? 1 : m->conversion(); + metricValue += (rideNavigator->context->athlete->useMetricUnits) ? 0 : m->conversionSum(); // format with the right precision if (m->units(true) == "seconds" || m->units(true) == tr("seconds")) { @@ -1083,5 +1085,5 @@ ColumnChooser::buttonClicked(QString name) void RideNavigator::showTreeContextMenuPopup(const QPoint &pos) { - main->showTreeContextMenuPopup(mapToGlobal(pos)); + context->mainWindow->showTreeContextMenuPopup(mapToGlobal(pos)); } diff --git a/src/RideNavigator.h b/src/RideNavigator.h index 8307b58d5..d339099d0 100644 --- a/src/RideNavigator.h +++ b/src/RideNavigator.h @@ -20,11 +20,11 @@ #define _GC_RideNavigator_h 1 #include "GoldenCheetah.h" -#include "MainWindow.h" +#include "Context.h" #include "MetricAggregator.h" #include "RideMetadata.h" #include "DBAccess.h" -#include "MainWindow.h" +#include "Context.h" #include "GcCalendar.h" #include "Settings.h" #include "Colors.h" @@ -69,7 +69,7 @@ class RideNavigator : public GcWindow friend class ::SearchBox; public: - RideNavigator(MainWindow *, bool mainwindow = false); + RideNavigator(Context *, bool mainwindow = false); ~RideNavigator(); void borderMenu(const QPoint &pos); @@ -77,7 +77,7 @@ class RideNavigator : public GcWindow // so the cell delegate can access QTreeView *tableView; // the view - MainWindow *main; + Context *context; signals: diff --git a/src/RideSummaryWindow.cpp b/src/RideSummaryWindow.cpp index fa8c3177d..71957b5d1 100644 --- a/src/RideSummaryWindow.cpp +++ b/src/RideSummaryWindow.cpp @@ -17,7 +17,8 @@ */ #include "RideSummaryWindow.h" -#include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "RideFile.h" #include "RideItem.h" #include "RideMetric.h" @@ -32,8 +33,8 @@ #include #include -RideSummaryWindow::RideSummaryWindow(MainWindow *mainWindow, bool ridesummary) : - GcChartWindow(mainWindow), mainWindow(mainWindow), ridesummary(ridesummary), useCustom(false), useToToday(false), filtered(false) +RideSummaryWindow::RideSummaryWindow(Context *context, bool ridesummary) : + GcChartWindow(context), context(context), ridesummary(ridesummary), useCustom(false), useToToday(false), filtered(false) { setInstanceName("Ride Summary Window"); setRideItem(NULL); @@ -56,7 +57,7 @@ RideSummaryWindow::RideSummaryWindow(MainWindow *mainWindow, bool ridesummary) : #ifdef GC_HAVE_LUCENE // filter / searchbox - searchBox = new SearchFilterBox(this, mainWindow); + searchBox = new SearchFilterBox(this, context); connect(searchBox, SIGNAL(searchClear()), this, SLOT(clearFilter())); connect(searchBox, SIGNAL(searchResults(QStringList)), this, SLOT(setFilter(QStringList))); cl->addRow(new QLabel(tr("Filter")), searchBox); @@ -84,15 +85,15 @@ RideSummaryWindow::RideSummaryWindow(MainWindow *mainWindow, bool ridesummary) : if (ridesummary) { connect(this, SIGNAL(rideItemChanged(RideItem*)), this, SLOT(rideItemChanged())); - connect(mainWindow->athlete, SIGNAL(zonesChanged()), this, SLOT(refresh())); - connect(mainWindow, SIGNAL(intervalsChanged()), this, SLOT(refresh())); + connect(context->athlete, SIGNAL(zonesChanged()), this, SLOT(refresh())); + connect(context->mainWindow, SIGNAL(intervalsChanged()), this, SLOT(refresh())); } else { connect(this, SIGNAL(dateRangeChanged(DateRange)), this, SLOT(dateRangeChanged(DateRange))); - connect(mainWindow, SIGNAL(rideAdded(RideItem*)), this, SLOT(refresh())); - connect(mainWindow, SIGNAL(rideDeleted(RideItem*)), this, SLOT(refresh())); - connect(mainWindow, SIGNAL(filterChanged(QStringList&)), this, SLOT(refresh())); + connect(context->mainWindow, SIGNAL(rideAdded(RideItem*)), this, SLOT(refresh())); + connect(context->mainWindow, SIGNAL(rideDeleted(RideItem*)), this, SLOT(refresh())); + connect(context->mainWindow, SIGNAL(filterChanged(QStringList&)), this, SLOT(refresh())); // date settings connect(dateSetting, SIGNAL(useCustomRange(DateRange)), this, SLOT(useCustomRange(DateRange))); @@ -192,7 +193,7 @@ RideSummaryWindow::htmlSummary() const if (!ride && !ridesummary) return ""; // didn't parse! - bool useMetricUnits = mainWindow->athlete->useMetricUnits; + bool useMetricUnits = context->athlete->useMetricUnits; // ride summary and there were ridefile read errors? if (ridesummary && !ride) { @@ -291,7 +292,7 @@ RideSummaryWindow::htmlSummary() const worklist += timeInZonesHR; // go calculate them then... - QHash computed = RideMetric::computeMetrics(mainWindow, ride, mainWindow->athlete->zones(), mainWindow->athlete->hrZones(), worklist); + QHash computed = RideMetric::computeMetrics(context, ride, context->athlete->zones(), context->athlete->hrZones(), worklist); for(int i = 0; i < worklist.count(); ++i) { if (worklist[i] != "") { RideMetricPtr m = computed.value(worklist[i]); @@ -302,7 +303,7 @@ RideSummaryWindow::htmlSummary() const } else { // just use the metricDB versions, nice 'n fast - metrics = mainWindow->athlete->metricDB->getRideMetrics(rideItem->fileName); + metrics = context->athlete->metricDB->getRideMetrics(rideItem->fileName); } } @@ -345,7 +346,7 @@ RideSummaryWindow::htmlSummary() const // get the value - from metrics or from data array if (ridesummary) s = s.arg(time_to_string(metrics.getForSymbol(symbol))); - else s = s.arg(SummaryMetrics::getAggregated(mainWindow, symbol, data, filters, filtered, useMetricUnits)); + else s = s.arg(SummaryMetrics::getAggregated(context, symbol, data, filters, filtered, useMetricUnits)); } else { if (m->units(useMetricUnits) != "") s = s.arg(" (" + m->units(useMetricUnits) + ")"); @@ -361,7 +362,7 @@ RideSummaryWindow::htmlSummary() const double pace; if (ridesummary) pace = metrics.getForSymbol(symbol) * (useMetricUnits ? 1 : m->conversion()) + (useMetricUnits ? 0 : m->conversionSum()); - else pace = SummaryMetrics::getAggregated(mainWindow, symbol, data, filters, filtered, useMetricUnits).toDouble(); + else pace = SummaryMetrics::getAggregated(context, symbol, data, filters, filtered, useMetricUnits).toDouble(); s = s.arg(QTime(0,0,0,0).addSecs(pace*60).toString("mm:ss")); @@ -370,7 +371,7 @@ RideSummaryWindow::htmlSummary() const // get the value - from metrics or from data array if (ridesummary) s = s.arg(metrics.getForSymbol(symbol) * (useMetricUnits ? 1 : m->conversion()) + (useMetricUnits ? 0 : m->conversionSum()), 0, 'f', m->precision()); - else s = s.arg(SummaryMetrics::getAggregated(mainWindow, symbol, data, filters, filtered, useMetricUnits)); + else s = s.arg(SummaryMetrics::getAggregated(context, symbol, data, filters, filtered, useMetricUnits)); } } @@ -393,11 +394,11 @@ RideSummaryWindow::htmlSummary() const range = rideItem->zoneRange(); // or for end of daterange plotted for daterange summary - } else if (mainWindow->athlete->zones()) { + } else if (context->athlete->zones()) { // get from end if period - range = mainWindow->athlete->zones()->whichRange(myDateRange.to); - if (range > -1) numzones = mainWindow->athlete->zones()->numZones(range); + range = context->athlete->zones()->whichRange(myDateRange.to); + if (range > -1) numzones = context->athlete->zones()->numZones(range); } @@ -407,10 +408,10 @@ RideSummaryWindow::htmlSummary() const // if using metrics or data if (ridesummary) time_in_zone[i] = metrics.getForSymbol(timeInZones[i]); - else time_in_zone[i] = SummaryMetrics::getAggregated(mainWindow, timeInZones[i], data, filters, filtered, useMetricUnits, true).toDouble(); + else time_in_zone[i] = SummaryMetrics::getAggregated(context, timeInZones[i], data, filters, filtered, useMetricUnits, true).toDouble(); } summary += tr("

Power Zones

"); - summary += mainWindow->athlete->zones()->summarize(range, time_in_zone); //aggregating + summary += context->athlete->zones()->summarize(range, time_in_zone); //aggregating } // @@ -426,11 +427,11 @@ RideSummaryWindow::htmlSummary() const hrrange = rideItem->hrZoneRange(); // or for end of daterange plotted for daterange summary - } else if (mainWindow->athlete->hrZones()) { + } else if (context->athlete->hrZones()) { // get from end if period - hrrange = mainWindow->athlete->hrZones()->whichRange(myDateRange.to); - if (hrrange > -1) numhrzones = mainWindow->athlete->hrZones()->numZones(hrrange); + hrrange = context->athlete->hrZones()->whichRange(myDateRange.to); + if (hrrange > -1) numhrzones = context->athlete->hrZones()->numZones(hrrange); } @@ -441,11 +442,11 @@ RideSummaryWindow::htmlSummary() const // if using metrics or data if (ridesummary) time_in_zone[i] = metrics.getForSymbol(timeInZonesHR[i]); - else time_in_zone[i] = SummaryMetrics::getAggregated(mainWindow, timeInZonesHR[i], data, filters, filtered, useMetricUnits, true).toDouble(); + else time_in_zone[i] = SummaryMetrics::getAggregated(context, timeInZonesHR[i], data, filters, filtered, useMetricUnits, true).toDouble(); } summary += tr("

Heart Rate Zones

"); - summary += mainWindow->athlete->hrZones()->summarize(hrrange, time_in_zone); //aggregating + summary += context->athlete->hrZones()->summarize(hrrange, time_in_zone); //aggregating } // Only get interval summary for a ride summary @@ -468,7 +469,7 @@ RideSummaryWindow::htmlSummary() const bool even = false; foreach (RideFileInterval interval, ride->intervals()) { RideFile f(ride->startTime(), ride->recIntSecs()); - f.mainwindow = mainWindow; // hack, until we refactor athlete and mainwindow + f.context = context; // hack, until we refactor athlete and mainwindow for (int i = ride->intervalBegin(interval); i>= 0 &&i < ride->dataPoints().size(); ++i) { const RideFilePoint *p = ride->dataPoints()[i]; if (p->secs >= interval.stop) @@ -483,7 +484,7 @@ RideSummaryWindow::htmlSummary() const } QHash metrics = - RideMetric::computeMetrics(mainWindow, &f, mainWindow->athlete->zones(), mainWindow->athlete->hrZones(), intervalMetrics); + RideMetric::computeMetrics(context, &f, context->athlete->zones(), context->athlete->hrZones(), intervalMetrics); if (firstRow) { summary += "
"; summary += ""; @@ -535,11 +536,11 @@ RideSummaryWindow::htmlSummary() const // we have after filtering has been applied, otherwise it is just // the number of entries int activities = 0; - if (mainWindow->isfiltered || filtered) { + if (context->mainWindow->isfiltered || filtered) { foreach (SummaryMetrics activity, data) { if (filtered && !filters.contains(activity.getFileName())) continue; - if (mainWindow->isfiltered && !mainWindow->filters.contains(activity.getFileName())) continue; + if (context->mainWindow->isfiltered && !context->mainWindow->filters.contains(activity.getFileName())) continue; activities++; } @@ -554,7 +555,7 @@ RideSummaryWindow::htmlSummary() const else totalCols = rtotalColumn.count(); int metricCols = metricColumn.count() > 7 ? 7 : metricColumn.count(); - if (mainWindow->isfiltered || filtered) { + if (context->mainWindow->isfiltered || filtered) { // "n of x activities" shown in header of list when filtered summary += ("

" + @@ -616,7 +617,7 @@ RideSummaryWindow::htmlSummary() const // apply the filter if there is one active if (filtered && !filters.contains(rideMetrics.getFileName())) continue; - if (mainWindow->isfiltered && !mainWindow->filters.contains(rideMetrics.getFileName())) continue; + if (context->mainWindow->isfiltered && !context->mainWindow->filters.contains(rideMetrics.getFileName())) continue; if (even) summary += "

"; else { @@ -705,15 +706,15 @@ void RideSummaryWindow::dateRangeChanged(DateRange dr) else current = dr; if (useCustom) { - data = mainWindow->athlete->metricDB->getAllMetricsFor(custom); + data = context->athlete->metricDB->getAllMetricsFor(custom); } else if (useToToday) { DateRange use = myDateRange; QDate today = QDate::currentDate(); if (use.to > today) use.to = today; - data = mainWindow->athlete->metricDB->getAllMetricsFor(use); + data = context->athlete->metricDB->getAllMetricsFor(use); - } else data = mainWindow->athlete->metricDB->getAllMetricsFor(myDateRange); + } else data = context->athlete->metricDB->getAllMetricsFor(myDateRange); refresh(); } diff --git a/src/RideSummaryWindow.h b/src/RideSummaryWindow.h index bb0ce6c54..5dd817b22 100644 --- a/src/RideSummaryWindow.h +++ b/src/RideSummaryWindow.h @@ -20,6 +20,7 @@ #define _GC_RideSummaryWindow_h 1 #include "GoldenCheetah.h" #include "MainWindow.h" +#include "Context.h" #include #include @@ -51,7 +52,7 @@ class RideSummaryWindow : public GcChartWindow public: // two modes - summarise ride or summarise date range - RideSummaryWindow(MainWindow *parent, bool ridesummary = true); + RideSummaryWindow(Context *context, bool ridesummary = true); // properties int useSelected() { return dateSetting->mode(); } @@ -69,7 +70,7 @@ class RideSummaryWindow : public GcChartWindow int prevN() { return dateSetting->prevN(); } void setPrevN(int x) { dateSetting->setPrevN(x); } #ifdef GC_HAVE_LUCENE - bool isFiltered() const { if (!ridesummary) return (filtered || mainWindow->isfiltered); + bool isFiltered() const { if (!ridesummary) return (filtered || context->mainWindow->isfiltered); else return false; } // filter QString filter() const { return ridesummary ? "" : searchBox->filter(); } @@ -98,7 +99,7 @@ class RideSummaryWindow : public GcChartWindow QString htmlSummary() const; - MainWindow *mainWindow; + Context *context; QWebView *rideSummary; RideItem *_connected; diff --git a/src/RideWindow.cpp b/src/RideWindow.cpp index 43d9a505e..5c9017f80 100644 --- a/src/RideWindow.cpp +++ b/src/RideWindow.cpp @@ -17,6 +17,7 @@ */ #include "RideWindow.h" +#include "RideItem.h" #include "RealtimeData.h" #include "JsonRideFile.h" @@ -52,17 +53,16 @@ void RideWindow::loadRide() this, SLOT(addJSObjects())); view->setPage(page); // used for testing... - RiderBridge* tr = new RealtimeRider(main); + RiderBridge* tr = new RealtimeRider(context); tr->setRide(ride); rider = tr; addJSObjects(); } -RideWindow::RideWindow(MainWindow * _main) : - GcWindow(_main), +RideWindow::RideWindow(Context *context) : + GcWindow(context), rideLoaded(false) { - main = _main; setInstanceName("Ride Window"); view = new QWebView(); QVBoxLayout *layout = new QVBoxLayout(); diff --git a/src/RideWindow.h b/src/RideWindow.h index 59a102c4e..3e72a80e3 100644 --- a/src/RideWindow.h +++ b/src/RideWindow.h @@ -28,6 +28,8 @@ #include #include "TrainTool.h" #include "RealtimeController.h" +#include "MainWindow.h" +#include "RideItem.h" #include "RideFile.h" class Route @@ -315,10 +317,10 @@ public slots: curPosition = findCurrentPosition(); } public: - RealtimeRider(MainWindow *main) + RealtimeRider(Context *context) { curPosition = 1; - connect(main,SIGNAL(telemetryUpdate(const RealtimeData &)), this,SLOT(telemetryUpdate(const RealtimeData &))); + connect(context->mainWindow,SIGNAL(telemetryUpdate(const RealtimeData &)), this,SLOT(telemetryUpdate(const RealtimeData &))); } }; @@ -330,7 +332,7 @@ protected: RideItem *ride; QWebView *view; bool rideLoaded; - MainWindow *main; + Context *context; virtual void loadRide(); RiderBridge *rider; @@ -343,7 +345,7 @@ protected: qwi->setVisible(true); } public: - explicit RideWindow(MainWindow *); + explicit RideWindow(Context *); signals: public slots: @@ -363,7 +365,7 @@ protected: //EnableWebInspector(view->page()); // turns on the javascript debugger } public: - explicit MapWindow(MainWindow *main) : RideWindow(main) {} + explicit MapWindow(Context *context) : RideWindow(context) {} }; @@ -377,7 +379,7 @@ protected: // EnableWebInspector(view->page()); // turns on the javascript debugger } public: - explicit StreetViewWindow(MainWindow *main) : RideWindow(main) {} + explicit StreetViewWindow(Context *context) : RideWindow(context) {} }; diff --git a/src/RideWithGPSDialog.cpp b/src/RideWithGPSDialog.cpp index 796835483..19cd3c6bb 100644 --- a/src/RideWithGPSDialog.cpp +++ b/src/RideWithGPSDialog.cpp @@ -17,10 +17,8 @@ */ #include "RideWithGPSDialog.h" +#include "Athlete.h" #include "Settings.h" -#include -#include -#include #include "TimeUtils.h" #include "Units.h" @@ -30,8 +28,8 @@ #include "DBAccess.h" #include "TcxRideFile.h" -RideWithGPSDialog::RideWithGPSDialog(MainWindow *mainWindow, RideItem *item) : - mainWindow(mainWindow) +RideWithGPSDialog::RideWithGPSDialog(Context *context, RideItem *item) : + context(context) { RIDE_WITH_GPS_URL = "http://ridewithgps.com"; @@ -187,8 +185,8 @@ RideWithGPSDialog::requestUpload() int size = 0; - QString username = appsettings->cvalue(mainWindow->athlete->cyclist, GC_RWGPSUSER).toString(); - QString password = appsettings->cvalue(mainWindow->athlete->cyclist, GC_RWGPSPASS).toString(); + QString username = appsettings->cvalue(context->athlete->cyclist, GC_RWGPSUSER).toString(); + QString password = appsettings->cvalue(context->athlete->cyclist, GC_RWGPSPASS).toString(); // application/json out += "{\"apikey\": \"p24n3a9e\", "; diff --git a/src/RideWithGPSDialog.h b/src/RideWithGPSDialog.h index 40e0cb56e..4ae8f8074 100644 --- a/src/RideWithGPSDialog.h +++ b/src/RideWithGPSDialog.h @@ -22,7 +22,11 @@ #include #include -#include "MainWindow.h" +#include +#include +#include +#include +#include "Context.h" #include "RideItem.h" class RideWithGPSDialog : public QDialog @@ -31,7 +35,7 @@ class RideWithGPSDialog : public QDialog G_OBJECT public: - RideWithGPSDialog(MainWindow *mainWindow, RideItem *item); + RideWithGPSDialog(Context *context, RideItem *item); signals: @@ -52,7 +56,7 @@ private: QPushButton *searchActivityButton; QPushButton *getActivityButton; QPushButton *cancelButton; - MainWindow *mainWindow; + Context *context; QCheckBox *workoutTimeChk; QCheckBox *timeRidingChk; QCheckBox *totalDistanceChk; diff --git a/src/SaveDialogs.cpp b/src/SaveDialogs.cpp index a54972c36..ccfb31d1b 100644 --- a/src/SaveDialogs.cpp +++ b/src/SaveDialogs.cpp @@ -174,7 +174,7 @@ MainWindow::saveSilent(RideItem *rideItem) // save in GC format JsonFileReader reader; - reader.writeRideFile(this, rideItem->ride(), savedFile); + reader.writeRideFile(context, rideItem->ride(), savedFile); // rename the file and update the rideItem list to reflect the change if (convert) { diff --git a/src/ScatterPlot.cpp b/src/ScatterPlot.cpp index 4ec19d7a9..5da5302f2 100644 --- a/src/ScatterPlot.cpp +++ b/src/ScatterPlot.cpp @@ -18,8 +18,11 @@ #include "ScatterPlot.h" #include "ScatterWindow.h" -#include "IntervalItem.h" #include "MainWindow.h" +#include "IntervalItem.h" +#include "Context.h" +#include "Context.h" +#include "Athlete.h" #include "Settings.h" #include "Zones.h" #include "Colors.h" @@ -147,7 +150,7 @@ QString ScatterPlot::describeType(int type, bool longer, bool useMetricUnits) } } -ScatterPlot::ScatterPlot(MainWindow *parent) : main(parent) +ScatterPlot::ScatterPlot(Context *context) : context(context) { setInstanceName("2D Plot"); all = NULL; @@ -165,7 +168,7 @@ ScatterPlot::ScatterPlot(MainWindow *parent) : main(parent) sd->setTickLength(QwtScaleDiv::MajorTick, 3); setAxisScaleDraw(QwtPlot::yLeft, sd); - connect(main->context, SIGNAL(configChanged()), this, SLOT(configChanged())); + connect(context, SIGNAL(configChanged()), this, SLOT(configChanged())); configChanged(); // use latest colors etc } @@ -200,8 +203,8 @@ void ScatterPlot::setData (ScatterSettings *settings) foreach(const RideFilePoint *point, settings->ride->ride()->dataPoints()) { - double xv = x[points] = pointType(point, settings->x, main->athlete->useMetricUnits, cranklength); - double yv = y[points] = pointType(point, settings->y, main->athlete->useMetricUnits, cranklength); + double xv = x[points] = pointType(point, settings->x, context->athlete->useMetricUnits, cranklength); + double yv = y[points] = pointType(point, settings->y, context->athlete->useMetricUnits, cranklength); // skip zeroes? if (!(settings->ignore && (x[points] == 0 || y[points] == 0))) { @@ -286,8 +289,8 @@ void ScatterPlot::setData (ScatterSettings *settings) QVector intervals; QMap displaySequence; - for (int child=0; childallIntervalItems()->childCount(); child++) { - IntervalItem *current = dynamic_cast(main->allIntervalItems()->child(child)); + for (int child=0; childmainWindow->allIntervalItems()->childCount(); child++) { + IntervalItem *current = dynamic_cast(context->mainWindow->allIntervalItems()->child(child)); if ((current != NULL) && current->isSelected()) { intervals.append(child); displaySequence.insert(current->displaySequence, intervals.count()-1); @@ -312,7 +315,7 @@ void ScatterPlot::setData (ScatterSettings *settings) // which interval is it in? for (int idx=0; idx(main->allIntervalItems()->child(intervals[idx])); + IntervalItem *current = dynamic_cast(context->mainWindow->allIntervalItems()->child(intervals[idx])); if (point->secs+settings->ride->ride()->recIntSecs() > current->start && point->secs< current->stop) { xvals[idx].append(x); @@ -331,7 +334,7 @@ void ScatterPlot::setData (ScatterSettings *settings) QPen pen; QColor intervalColor; - intervalColor.setHsv((255/main->allIntervalItems()->childCount()) * (intervals[idx]), 255,255); + intervalColor.setHsv((255/context->mainWindow->allIntervalItems()->childCount()) * (intervals[idx]), 255,255); pen.setColor(intervalColor); sym.setPen(pen); diff --git a/src/ScatterPlot.h b/src/ScatterPlot.h index 5bab2ecb3..e5ef29690 100644 --- a/src/ScatterPlot.h +++ b/src/ScatterPlot.h @@ -22,11 +22,14 @@ #include #include -#include "MainWindow.h" +#include "Context.h" +#include "IntervalItem.h" +#include "RideItem.h" #include "Units.h" #include "math.h" #include #include +#include #include #define MODEL_NONE 0 @@ -57,7 +60,7 @@ class ScatterPlot : public QwtPlot public: - ScatterPlot(MainWindow *); + ScatterPlot(Context *); void setData(ScatterSettings *); void showTime(ScatterSettings *, int offset, int secs); void setAxisTitle(int axis, QString label); @@ -67,8 +70,8 @@ class ScatterPlot : public QwtPlot protected: - // passed from MainWindow - MainWindow *main; + // passed from Context * + Context *context; bool useMetricUnits; double cranklength; diff --git a/src/ScatterWindow.cpp b/src/ScatterWindow.cpp index 6814e6198..cce32d833 100644 --- a/src/ScatterWindow.cpp +++ b/src/ScatterWindow.cpp @@ -17,12 +17,9 @@ */ #include "ScatterWindow.h" -#include "ScatterPlot.h" #include "MainWindow.h" -#include "RideItem.h" -#include "IntervalItem.h" -#include "math.h" -#include "Units.h" // for MILES_PER_KM +#include "ScatterPlot.h" +#include "Context.h" #include #include @@ -62,8 +59,8 @@ ScatterWindow::addrStandardChannels(QxtStringSpinBox *box) box->setStrings(list); } -ScatterWindow::ScatterWindow(MainWindow *parent, const QDir &home) : - GcChartWindow(parent), home(home), main(parent), ride(NULL), current(NULL) +ScatterWindow::ScatterWindow(Context *context, const QDir &home) : + GcChartWindow(context), home(home), context(context), ride(NULL), current(NULL) { setInstanceName("2D Window"); @@ -105,7 +102,7 @@ ScatterWindow::ScatterWindow(MainWindow *parent, const QDir &home) : setControls(c); // the plot widget - scatterPlot= new ScatterPlot(main); + scatterPlot= new ScatterPlot(context); QVBoxLayout *vlayout = new QVBoxLayout; vlayout->addWidget(scatterPlot); @@ -153,8 +150,8 @@ ScatterWindow::ScatterWindow(MainWindow *parent, const QDir &home) : // now connect up the widgets //connect(main, SIGNAL(rideSelected()), this, SLOT(rideSelected())); connect(this, SIGNAL(rideItemChanged(RideItem*)), this, SLOT(rideSelected())); - connect(main, SIGNAL(intervalSelected()), this, SLOT(intervalSelected())); - connect(main, SIGNAL(intervalsChanged()), this, SLOT(intervalSelected())); + connect(context->mainWindow, SIGNAL(intervalSelected()), this, SLOT(intervalSelected())); + connect(context->mainWindow, SIGNAL(intervalsChanged()), this, SLOT(intervalSelected())); connect(xSelector, SIGNAL(currentIndexChanged(int)), this, SLOT(setData())); connect(ySelector, SIGNAL(currentIndexChanged(int)), this, SLOT(setData())); connect(rxSelector, SIGNAL(valueChanged(int)), this, SLOT(rxSelectorChanged(int))); @@ -294,8 +291,8 @@ ScatterWindow::setData() // any intervals to plot? settings.intervals.clear(); - for (int i=0; iallIntervalItems()->childCount(); i++) { - IntervalItem *current = dynamic_cast(main->allIntervalItems()->child(i)); + for (int i=0; imainWindow->allIntervalItems()->childCount(); i++) { + IntervalItem *current = dynamic_cast(context->mainWindow->allIntervalItems()->child(i)); if (current != NULL && current->isSelected() == true) settings.intervals.append(current); } diff --git a/src/ScatterWindow.h b/src/ScatterWindow.h index 4d14cbaa9..3b80072b4 100644 --- a/src/ScatterWindow.h +++ b/src/ScatterWindow.h @@ -23,7 +23,11 @@ #include #include #include "qxtstringspinbox.h" -#include "MainWindow.h" +#include "Context.h" +#include "RideItem.h" +#include "IntervalItem.h" +#include "math.h" +#include "Units.h" // for MILES_PER_KM class ScatterPlot; // we don't include the header because it uses namespaces @@ -61,7 +65,7 @@ class ScatterWindow : public GcChartWindow public: - ScatterWindow(MainWindow *, const QDir &); + ScatterWindow(Context *, const QDir &); // reveal bool hasReveal() { return true; } @@ -98,9 +102,9 @@ class ScatterWindow : public GcChartWindow protected: - // passed from MainWindow + // passed from Context * QDir home; - MainWindow *main; + Context *context; bool useMetricUnits; bool active; diff --git a/src/SearchBox.cpp b/src/SearchBox.cpp index 06819d1fc..38a070667 100644 --- a/src/SearchBox.cpp +++ b/src/SearchBox.cpp @@ -17,7 +17,8 @@ */ #include "SearchBox.h" -#include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "NamedSearch.h" #include "RideNavigator.h" #include "GcSideBarItem.h" @@ -28,8 +29,8 @@ #include #include -SearchBox::SearchBox(MainWindow *main, QWidget *parent, bool nochooser) - : QLineEdit(parent), main(main), filtered(false), nochooser(nochooser) +SearchBox::SearchBox(Context *context, QWidget *parent, bool nochooser) + : QLineEdit(parent), context(context), filtered(false), nochooser(nochooser) { setFixedHeight(21); //clear button @@ -179,7 +180,7 @@ void SearchBox::clearClicked() void SearchBox::checkMenu() { - if (main->athlete->namedSearches->getList().count() || text() != "") toolButton->show(); + if (context->athlete->namedSearches->getList().count() || text() != "") toolButton->show(); else toolButton->hide(); } @@ -187,9 +188,9 @@ void SearchBox::setMenu() { dropMenu->clear(); if (text() != "") dropMenu->addAction(tr("Add to Favourites")); - if (main->athlete->namedSearches->getList().count()) { + if (context->athlete->namedSearches->getList().count()) { if (text() != "") dropMenu->addSeparator(); - foreach(NamedSearch x, main->athlete->namedSearches->getList()) { + foreach(NamedSearch x, context->athlete->namedSearches->getList()) { dropMenu->addAction(x.name); } dropMenu->addSeparator(); @@ -204,15 +205,15 @@ void SearchBox::runMenu(QAction *x) if (x->text() == tr("Add to Favourites")) addNamed(); else if (x->text() == tr("Manage Favourites")) { - EditNamedSearches *editor = new EditNamedSearches(this, main); + EditNamedSearches *editor = new EditNamedSearches(this, context); editor->move(QCursor::pos()-QPoint(230,-5)); editor->show(); } else if (x->text() == tr("Column Chooser")) { - ColumnChooser *selector = new ColumnChooser(main->listView->logicalHeadings); + ColumnChooser *selector = new ColumnChooser(context->mainWindow->listView->logicalHeadings); selector->show(); } else { - NamedSearch get = main->athlete->namedSearches->get(x->text()); + NamedSearch get = context->mainWindow->athlete->namedSearches->get(x->text()); if (get.name == x->text()) { setMode(static_cast(get.type)); setText(get.text); @@ -282,6 +283,6 @@ SearchBox::addNamed() x.text = this->text(); x.type = mode; x.count = 0; - main->athlete->namedSearches->getList().append(x); + context->mainWindow->athlete->namedSearches->getList().append(x); } } diff --git a/src/SearchBox.h b/src/SearchBox.h index 3d1976cfd..aa97ccb3a 100644 --- a/src/SearchBox.h +++ b/src/SearchBox.h @@ -26,7 +26,7 @@ class QToolButton; class QMenu; -class MainWindow; +class Context; class QLabel; class SearchBox : public QLineEdit @@ -37,7 +37,7 @@ public: enum searchboxmode { Search, Filter }; typedef enum searchboxmode SearchBoxMode; - SearchBox(MainWindow *main, QWidget *parent = 0, bool nochooser=true); + SearchBox(Context *context, QWidget *parent = 0, bool nochooser=true); // either search box or filter box void setMode(SearchBoxMode mode); @@ -78,7 +78,7 @@ signals: void clearFilter(); private: - MainWindow *main; + Context *context; bool filtered; bool nochooser; QToolButton *clearButton, *searchButton, *toolButton; diff --git a/src/SearchFilterBox.cpp b/src/SearchFilterBox.cpp index 890d82e37..e49c25079 100644 --- a/src/SearchFilterBox.cpp +++ b/src/SearchFilterBox.cpp @@ -17,12 +17,12 @@ */ #include "SearchFilterBox.h" -#include "MainWindow.h" +#include "Context.h" #include "Lucene.h" #include "DataFilter.h" #include "SearchBox.h" -SearchFilterBox::SearchFilterBox(QWidget *parent, MainWindow *main, bool nochooser) : QWidget(parent), main(main) +SearchFilterBox::SearchFilterBox(QWidget *parent, Context *context, bool nochooser) : QWidget(parent), context(context) { setContentsMargins(0,0,0,0); @@ -31,11 +31,11 @@ SearchFilterBox::SearchFilterBox(QWidget *parent, MainWindow *main, bool nochoos contents->setContentsMargins(0,0,0,0); // no column chooser if my parent widget is a modal widget - searchbox = new SearchBox(main, this, nochooser); + searchbox = new SearchBox(context, this, nochooser); contents->addWidget(searchbox); - lucene = new Lucene(this, main); - datafilter = new DataFilter(this,main); + lucene = new Lucene(this, context); + datafilter = new DataFilter(this,context); // text searching connect(searchbox, SIGNAL(submitQuery(QString)), lucene, SLOT(search(QString))); diff --git a/src/SearchFilterBox.h b/src/SearchFilterBox.h index 6600a8fac..98a7cdc17 100644 --- a/src/SearchFilterBox.h +++ b/src/SearchFilterBox.h @@ -19,7 +19,7 @@ #ifndef _GC_SearchFilter_h #define _GC_SearchFilter_h -#include "MainWindow.h" +#include "Context.h" #include "SearchBox.h" // for searchboxmode class Lucene; @@ -30,7 +30,7 @@ class SearchFilterBox : public QWidget Q_OBJECT public: - SearchFilterBox(QWidget *parent, MainWindow *main, bool nochooser = true); + SearchFilterBox(QWidget *parent, Context *context, bool nochooser = true); void setMode(SearchBox::SearchBoxMode x) { searchbox->setMode(x); } QString filter(); @@ -44,7 +44,7 @@ signals: void searchClear(); // we stopped search/filtering looking private: - MainWindow *main; + Context *context; Lucene *lucene; DataFilter *datafilter; SearchBox *searchbox; diff --git a/src/Season.cpp b/src/Season.cpp index 4747d65e6..cff824e62 100644 --- a/src/Season.cpp +++ b/src/Season.cpp @@ -17,6 +17,7 @@ */ #include "Season.h" +#include "MainWindow.h" #include #include #include @@ -85,8 +86,8 @@ void Season::setType(int _type) /*---------------------------------------------------------------------- * EDIT SEASON DIALOG *--------------------------------------------------------------------*/ -EditSeasonDialog::EditSeasonDialog(MainWindow *mainWindow, Season *season) : - QDialog(mainWindow, Qt::Dialog), mainWindow(mainWindow), season(season) +EditSeasonDialog::EditSeasonDialog(Context *context, Season *season) : + QDialog(context->mainWindow, Qt::Dialog), context(context), season(season) { setWindowTitle(tr("Edit Date Range")); QVBoxLayout *mainLayout = new QVBoxLayout(this); @@ -170,8 +171,8 @@ EditSeasonDialog::cancelClicked() /*---------------------------------------------------------------------- * EDIT SEASONEVENT DIALOG *--------------------------------------------------------------------*/ -EditSeasonEventDialog::EditSeasonEventDialog(MainWindow *mainWindow, SeasonEvent *event) : - QDialog(mainWindow, Qt::Dialog), mainWindow(mainWindow), event(event) +EditSeasonEventDialog::EditSeasonEventDialog(Context *context, SeasonEvent *event) : + QDialog(context->mainWindow, Qt::Dialog), context(context), event(event) { setWindowTitle(tr("Edit Event")); QVBoxLayout *mainLayout = new QVBoxLayout(this); diff --git a/src/Season.h b/src/Season.h index 28b94dcc1..14c193cc7 100644 --- a/src/Season.h +++ b/src/Season.h @@ -25,7 +25,7 @@ #include #include -#include "MainWindow.h" +#include "Context.h" class SeasonEvent { @@ -83,14 +83,14 @@ class EditSeasonDialog : public QDialog public: - EditSeasonDialog(MainWindow *, Season *); + EditSeasonDialog(Context *, Season *); public slots: void applyClicked(); void cancelClicked(); private: - MainWindow *mainWindow; + Context *context; Season *season; QPushButton *applyButton, *cancelButton; @@ -107,14 +107,14 @@ class EditSeasonEventDialog : public QDialog public: - EditSeasonEventDialog(MainWindow *, SeasonEvent *); + EditSeasonEventDialog(Context *, SeasonEvent *); public slots: void applyClicked(); void cancelClicked(); private: - MainWindow *mainWindow; + Context *context; SeasonEvent *event; QPushButton *applyButton, *cancelButton; diff --git a/src/SpecialFields.cpp b/src/SpecialFields.cpp index 6404898cb..e5ce55973 100644 --- a/src/SpecialFields.cpp +++ b/src/SpecialFields.cpp @@ -30,7 +30,7 @@ SpecialFields::SpecialFields() namesmap.insert("Sport", tr("Sport")); // in WKO and possible others namesmap.insert("Objective", tr("Objective")); // in WKO as "goal" nad possibly others namesmap.insert("Summary", tr("Summary")); // embeds the RideSummary widget - namesmap.insert("Notes", tr("Notes")); // linked to MainWindow::rideNotes + namesmap.insert("Notes", tr("Notes")); // linked to Context::rideNotes namesmap.insert("Keywords", tr("Keywords")); // extracted from Notes / used for highlighting calendar namesmap.insert("Recording Interval", tr("Recording Interval")); // linked to RideFile::recIntSecs namesmap.insert("Weight", tr("Weight")); // in WKO and possibly others diff --git a/src/SpinScanPlotWindow.cpp b/src/SpinScanPlotWindow.cpp index 91391da64..d8301f43b 100644 --- a/src/SpinScanPlotWindow.cpp +++ b/src/SpinScanPlotWindow.cpp @@ -18,9 +18,10 @@ #include "SpinScanPlotWindow.h" +#include "Context.h" -SpinScanPlotWindow::SpinScanPlotWindow(MainWindow *mainWindow) : - GcWindow(mainWindow), mainWindow(mainWindow), active(false) +SpinScanPlotWindow::SpinScanPlotWindow(Context *context) : + GcWindow(context), context(context), active(false) { setContentsMargins(0,0,0,0); setInstanceName("SpinScan Plot"); @@ -77,9 +78,9 @@ SpinScanPlotWindow::SpinScanPlotWindow(MainWindow *mainWindow) : connect(mode, SIGNAL(currentIndexChanged(int)), this, SLOT(styleChanged())); // get updates.. - connect(mainWindow->context, SIGNAL(telemetryUpdate(RealtimeData)), this, SLOT(telemetryUpdate(RealtimeData))); - connect(mainWindow->context, SIGNAL(start()), this, SLOT(start())); - connect(mainWindow->context, SIGNAL(stop()), this, SLOT(stop())); + connect(context, SIGNAL(telemetryUpdate(RealtimeData)), this, SLOT(telemetryUpdate(RealtimeData))); + connect(context, SIGNAL(start()), this, SLOT(start())); + connect(context, SIGNAL(stop()), this, SLOT(stop())); // set to zero stop(); // resets the array diff --git a/src/SpinScanPlotWindow.h b/src/SpinScanPlotWindow.h index 4644687b9..628e801a8 100644 --- a/src/SpinScanPlotWindow.h +++ b/src/SpinScanPlotWindow.h @@ -24,7 +24,7 @@ #include // for Q_PROPERTY -#include "MainWindow.h" +#include "Context.h" #include "RideFile.h" // for data series types #include "SpinScanPolarPlot.h" #include "SpinScanPlot.h" @@ -42,7 +42,7 @@ class SpinScanPlotWindow : public GcWindow public: - SpinScanPlotWindow(MainWindow *mainWindow); + SpinScanPlotWindow(Context *context); public slots: @@ -86,7 +86,7 @@ class SpinScanPlotWindow : public GcWindow uint16_t rtot[24]; int current; - MainWindow *mainWindow; + Context *context; bool active; QStackedWidget *stack; diff --git a/src/SplitActivityWizard.cpp b/src/SplitActivityWizard.cpp index 5b2e51cb2..d536ebc44 100644 --- a/src/SplitActivityWizard.cpp +++ b/src/SplitActivityWizard.cpp @@ -17,6 +17,9 @@ */ #include "SplitActivityWizard.h" +#include "MainWindow.h" +#include "Athlete.h" +#include "Context.h" // Minimum gap in recording to find a natural break to split static const double defaultMinimumGap = 1; // 1 minute @@ -25,7 +28,7 @@ static const double defaultMinimumGap = 1; // 1 minute static const double defaultMinimumSegmentSize = 5; // 5 minutes // Main wizard -SplitActivityWizard::SplitActivityWizard(MainWindow *main) : QWizard(main), main(main) +SplitActivityWizard::SplitActivityWizard(Context *context) : QWizard(context->mainWindow), context(context) { #ifdef Q_OS_MAX setWizardStyle(QWizard::ModernStyle); @@ -42,7 +45,7 @@ SplitActivityWizard::SplitActivityWizard(MainWindow *main) : QWizard(main), main setWindowTitle(tr("Split Activity")); // set ride - unconst since we will wipe it away eventually - rideItem = const_cast(main->context->currentRideItem()); + rideItem = const_cast(context->currentRideItem()); // Set sensible defaults keepOriginal = false; @@ -286,8 +289,8 @@ SplitActivityWizard::setIntervalsList(SplitSelect *selector) double distance = rideItem->ride()->timeToDistance(interval.stop) - rideItem->ride()->timeToDistance(interval.start); add->setText(5, QString("%1 %2") - .arg(distance * (main->athlete->useMetricUnits ? 1 : MILES_PER_KM), 0, 'f', 2) - .arg(main->athlete->useMetricUnits ? "km" : "mi")); + .arg(distance * (context->athlete->useMetricUnits ? 1 : MILES_PER_KM), 0, 'f', 2) + .arg(context->athlete->useMetricUnits ? "km" : "mi")); // interval name add->setText(6, interval.name); @@ -333,7 +336,7 @@ SplitActivityWizard::setFilesList() add->setText(3, time); // set distance - QString dist = main->athlete->useMetricUnits + QString dist = context->athlete->useMetricUnits ? QString ("%1 km").arg(km, 0, 'f', 1) : QString ("%1 mi").arg(km * MILES_PER_KM, 0, 'f', 1); add->setText(4, dist); @@ -380,7 +383,7 @@ SplitActivityWizard::setFilesList() add->setText(3, time); // set distance - QString dist = main->athlete->useMetricUnits + QString dist = context->athlete->useMetricUnits ? QString ("%1 km").arg(km, 0, 'f', 1) : QString ("%1 mi").arg(km * MILES_PER_KM, 0, 'f', 1); add->setText(4, dist); @@ -399,7 +402,7 @@ SplitActivityWizard::setFilesList() QString SplitActivityWizard::hasBackup(QString filename) { - QString backupFilename = main->athlete->home.absolutePath() + "/" + filename + ".bak"; + QString backupFilename = context->athlete->home.absolutePath() + "/" + filename + ".bak"; if (QFile(backupFilename).exists()) { @@ -429,7 +432,7 @@ SplitActivityWizard::conflicts(QDateTime datetime) // now make a regexp for all know ride types foreach(QString suffix, RideFileFactory::instance().suffixes()) { - QString conflict = main->athlete->home.absolutePath() + "/" + targetnosuffix + "." + suffix; + QString conflict = context->athlete->home.absolutePath() + "/" + targetnosuffix + "." + suffix; if (QFile(conflict).exists()) returning << conflict; } return returning; @@ -707,7 +710,7 @@ SplitConfirm::initializePage() // it will always conflict with current ride, so we pick that // up as a special case. // we check against existing rides AND the rides we WILL create - QString originalFileName = wizard->main->athlete->home.absolutePath() + "/" + wizard->rideItem->fileName; + QString originalFileName = wizard->context->athlete->home.absolutePath() + "/" + wizard->rideItem->fileName; QList toBeCreated; foreach(RideFile *ride, wizard->activities) { @@ -804,7 +807,7 @@ SplitConfirm::validatePage() // first do we need to remove the current ride? if (wizard->keepOriginal == false) { - wizard->main->removeCurrentRide(); + wizard->context->mainWindow->removeCurrentRide(); QTreeWidgetItem *current = wizard->files->invisibleRootItem()->child(0); current->setText(5, tr("Removed")); } @@ -814,15 +817,15 @@ SplitConfirm::validatePage() for(int i=0; iactivities.count(); i++) { QTreeWidgetItem *current = wizard->files->invisibleRootItem()->child(i+off); - QString target = wizard->main->athlete->home.absolutePath() + "/" + current->text(0); + QString target = wizard->context->athlete->home.absolutePath() + "/" + current->text(0); JsonFileReader reader; QFile out(target); - reader.writeRideFile(wizard->main, wizard->activities.at(i), out); + reader.writeRideFile(wizard->context, wizard->activities.at(i), out); current->setText(5, tr("Saved")); - wizard->main->addRide(QFileInfo(out).fileName(), true); + wizard->context->mainWindow->addRide(QFileInfo(out).fileName(), true); } // now make this page the last (so we can see what was done) diff --git a/src/SplitActivityWizard.h b/src/SplitActivityWizard.h index b81acdd4b..da4550919 100644 --- a/src/SplitActivityWizard.h +++ b/src/SplitActivityWizard.h @@ -20,7 +20,7 @@ #define _SplitActivityWizard_h #include "GoldenCheetah.h" -#include "MainWindow.h" +#include "Context.h" #include "SmallPlot.h" #include "RideItem.h" #include "RideFile.h" @@ -40,9 +40,9 @@ class SplitActivityWizard : public QWizard Q_OBJECT public: - SplitActivityWizard(MainWindow *main); + SplitActivityWizard(Context *context); - MainWindow *main; + Context *context; bool keepOriginal; RideItem *rideItem; diff --git a/src/StressCalculator.cpp b/src/StressCalculator.cpp index dc4c928ed..e0ec0606a 100644 --- a/src/StressCalculator.cpp +++ b/src/StressCalculator.cpp @@ -1,9 +1,11 @@ +#include "Athlete.h" +#include "MainWindow.h" #include "StressCalculator.h" #include "MetricAggregator.h" #include "RideMetric.h" #include "RideItem.h" -#include "MainWindow.h" +#include "Context.h" #include @@ -63,13 +65,13 @@ double StressCalculator::min(void) { -void StressCalculator::calculateStress(MainWindow *main, QString, const QString &metric, bool isfilter, QStringList filter) +void StressCalculator::calculateStress(Context *context, QString, const QString &metric, bool isfilter, QStringList filter) { // get all metric data from the year 1900 - 3000 QList results; // get metrics - results = main->athlete->metricDB->getAllMetricsFor(QDateTime(QDate(1900,1,1)), QDateTime(QDate(3000,1,1))); + results = context->athlete->metricDB->getAllMetricsFor(QDateTime(QDate(1900,1,1)), QDateTime(QDate(3000,1,1))); if (isfilter) { // remove any we don't have filtered @@ -82,11 +84,11 @@ void StressCalculator::calculateStress(MainWindow *main, QString, const QString } // and honour the global one too! - if (main->isfiltered) { + if (context->mainWindow->isfiltered) { // remove any we don't have filtered QList filteredresults; foreach (SummaryMetrics x, results) { - if (main->filters.contains(x.getFileName())) + if (context->mainWindow->filters.contains(x.getFileName())) filteredresults << x; } results = filteredresults; @@ -105,7 +107,7 @@ void StressCalculator::calculateStress(MainWindow *main, QString, const QString // start date for any season -- since it may be seeded // so lets run through the seasons and set start date // to the very earliest date set - foreach(Season x, main->athlete->seasons->seasons) + foreach(Season x, context->athlete->seasons->seasons) if (x.getStart() < startDate.date()) startDate = QDateTime(x.getStart(), QTime(0,0,0)); @@ -121,7 +123,7 @@ void StressCalculator::calculateStress(MainWindow *main, QString, const QString // clear data add in the seeds ltsvalues.fill(0); stsvalues.fill(0); - foreach(Season x, main->athlete->seasons->seasons) { + foreach(Season x, context->athlete->seasons->seasons) { if (x.getSeed()) { int offset = startDate.date().daysTo(x.getStart()); ltsvalues[offset] = x.getSeed() * -1; diff --git a/src/StressCalculator.h b/src/StressCalculator.h index 667621a0a..775cb2bba 100644 --- a/src/StressCalculator.h +++ b/src/StressCalculator.h @@ -53,7 +53,7 @@ class StressCalculator:public QObject { StressCalculator(QString cyclist, QDateTime startDate, QDateTime endDate, int shortTermDays, int longTermDays); - void calculateStress(MainWindow *, QString, const QString &metric, bool filter = false, QStringList files = QStringList()); + void calculateStress(Context *, QString, const QString &metric, bool filter = false, QStringList files = QStringList()); // x axes: double *getSTSvalues() { return stsvalues.data(); } diff --git a/src/SummaryMetrics.cpp b/src/SummaryMetrics.cpp index ded4f8b54..7428b6fa6 100644 --- a/src/SummaryMetrics.cpp +++ b/src/SummaryMetrics.cpp @@ -18,6 +18,7 @@ #include "SummaryMetrics.h" #include "MainWindow.h" +#include "Context.h" #include "RideMetric.h" #include #include @@ -114,7 +115,7 @@ SummaryMetrics::getUnitsForSymbol(QString symbol, bool UseMetric) const else return QString("units"); } -QString SummaryMetrics::getAggregated(MainWindow *main, QString name, const QList &results, const QStringList &filters, +QString SummaryMetrics::getAggregated(Context *context, QString name, const QList &results, const QStringList &filters, bool filtered, bool useMetricUnits, bool nofmt) { // get the metric details, so we can convert etc @@ -130,7 +131,7 @@ QString SummaryMetrics::getAggregated(MainWindow *main, QString name, const QLis // skip filtered rides if (filtered && !filters.contains(rideMetrics.getFileName())) continue; - if (main->isfiltered && !main->filters.contains(rideMetrics.getFileName())) continue; + if (context->mainWindow->isfiltered && !context->mainWindow->filters.contains(rideMetrics.getFileName())) continue; // get this value double value = rideMetrics.getForSymbol(name); diff --git a/src/SummaryMetrics.h b/src/SummaryMetrics.h index 2baffa90e..e4048e583 100644 --- a/src/SummaryMetrics.h +++ b/src/SummaryMetrics.h @@ -24,7 +24,7 @@ #include #include #include -class MainWindow; +class Context; class SummaryMetrics { Q_DECLARE_TR_FUNCTIONS(SummaryMetrics) @@ -64,7 +64,7 @@ class SummaryMetrics QString getUnitsForSymbol(QString symbol, bool UseMetric) const; // when passed a list of summary metrics and a name return aggregated value as a string - static QString getAggregated(MainWindow *main, QString name, + static QString getAggregated(Context *context, QString name, const QList &results, const QStringList &filters, bool filtered, bool useMetricUnits, bool nofmt = false); diff --git a/src/SummaryWindow.cpp b/src/SummaryWindow.cpp index acfab3d4f..018fb796e 100644 --- a/src/SummaryWindow.cpp +++ b/src/SummaryWindow.cpp @@ -18,8 +18,8 @@ #include "SummaryWindow.h" -SummaryWindow::SummaryWindow(MainWindow *mainWindow) : - GcWindow(mainWindow), mainWindow(mainWindow) +SummaryWindow::SummaryWindow(Context *context) : + GcWindow(context), context(context) { setInstanceName("Summary Window"); setControls(NULL); @@ -32,8 +32,8 @@ SummaryWindow::SummaryWindow(MainWindow *mainWindow) : vlayout->setContentsMargins(1,1,1,1); vlayout->addWidget(splitter); - rideSummary = new RideSummaryWindow(mainWindow); - rideMetadata = new RideMetadata(mainWindow); + rideSummary = new RideSummaryWindow(context); + rideMetadata = new RideMetadata(context); splitter->addWidget(rideSummary); splitter->addWidget(rideMetadata); diff --git a/src/SummaryWindow.h b/src/SummaryWindow.h index 4cb8b26fd..d05f9ccfe 100644 --- a/src/SummaryWindow.h +++ b/src/SummaryWindow.h @@ -23,7 +23,7 @@ #include "RideSummaryWindow.h" #include "RideMetadata.h" -class MainWindow; +class Context; class SummaryWindow : public GcWindow { @@ -32,7 +32,7 @@ class SummaryWindow : public GcWindow public: - SummaryWindow(MainWindow *parent); + SummaryWindow(Context *context); protected slots: @@ -40,7 +40,7 @@ class SummaryWindow : public GcWindow protected: - MainWindow *mainWindow; + Context *context; RideSummaryWindow *rideSummary; RideMetadata *rideMetadata; QSplitter *splitter; diff --git a/src/TPDownloadDialog.cpp b/src/TPDownloadDialog.cpp index 0933801e9..e0fdc4875 100644 --- a/src/TPDownloadDialog.cpp +++ b/src/TPDownloadDialog.cpp @@ -18,6 +18,8 @@ #include "TPDownloadDialog.h" #include "TPDownload.h" #include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "PwxRideFile.h" #include "JsonRideFile.h" #include "RideFile.h" @@ -25,16 +27,16 @@ #include "MetricAggregator.h" #include "Units.h" -TPDownloadDialog::TPDownloadDialog(MainWindow *main) : QDialog(main, Qt::Dialog), main(main), downloading(false), aborted(false) +TPDownloadDialog::TPDownloadDialog(Context *context) : QDialog(context->mainWindow, Qt::Dialog), context(context), downloading(false), aborted(false) { setWindowTitle(tr("Download from TrainingPeaks.com")); athleter = new TPAthlete(this); connect (athleter, SIGNAL(completed(QList >)), this, SLOT(completedAthlete(QList >))); - athleter->list(appsettings->cvalue(main->athlete->cyclist, GC_TPTYPE, "0").toInt(), - appsettings->cvalue(main->athlete->cyclist, GC_TPUSER, "null").toString(), - appsettings->cvalue(main->athlete->cyclist, GC_TPPASS, "null").toString()); + athleter->list(appsettings->cvalue(context->athlete->cyclist, GC_TPTYPE, "0").toInt(), + appsettings->cvalue(context->athlete->cyclist, GC_TPUSER, "null").toString(), + appsettings->cvalue(context->athlete->cyclist, GC_TPPASS, "null").toString()); QWidget::hide(); // don't show just yet... } @@ -289,7 +291,7 @@ TPDownloadDialog::refreshClicked() } // First lets get the ride metrics - if they refresh it takes a while... - rideMetrics = main->athlete->metricDB->getAllMetricsFor(QDateTime(from->date()), QDateTime(to->date())); + rideMetrics = context->athlete->metricDB->getAllMetricsFor(QDateTime(from->date()), QDateTime(to->date())); // First lets kick off a download of ridefile lookups // since that can take a while @@ -297,13 +299,13 @@ TPDownloadDialog::refreshClicked() athleteCombo->itemData(athleteCombo->currentIndex()).toInt(), from->date(), to->date(), - appsettings->cvalue(main->athlete->cyclist, GC_TPUSER, "null").toString(), - appsettings->cvalue(main->athlete->cyclist, GC_TPPASS, "null").toString()); + appsettings->cvalue(context->athlete->cyclist, GC_TPUSER, "null").toString(), + appsettings->cvalue(context->athlete->cyclist, GC_TPPASS, "null").toString()); // Whilst we wait for the results lets fill the map of existing rideFiles // (but ignore seconds since they aren't reliable) rideFiles.clear(); - QStringListIterator i(RideFileFactory::instance().listRideFiles(main->athlete->home)); + QStringListIterator i(RideFileFactory::instance().listRideFiles(context->athlete->home)); for (i.toFront(); i.hasNext();) rideFiles << QFileInfo(i.next()).baseName().mid(0,14); } @@ -333,7 +335,7 @@ TPDownloadDialog::tabChanged(int idx) void TPDownloadDialog::completedWorkout(QList >workouts) { - useMetricUnits = main->athlete->useMetricUnits; + useMetricUnits = context->athlete->useMetricUnits; // // Setup the upload list @@ -654,7 +656,7 @@ TPDownloadDialog::syncNext() curr->setText(7, tr("Downloading")); rideListSync->setCurrentItem(curr); downloader->download( - main->athlete->cyclist, + context->athlete->cyclist, athleteCombo->itemData(athleteCombo->currentIndex()).toInt(), curr->text(1).toInt() ); @@ -665,11 +667,11 @@ TPDownloadDialog::syncNext() // read in the file QStringList errors; - QFile file(main->athlete->home.absolutePath() + "/" + curr->text(1)); - RideFile *ride = RideFileFactory::instance().openRideFile(main, file, errors); + QFile file(context->athlete->home.absolutePath() + "/" + curr->text(1)); + RideFile *ride = RideFileFactory::instance().openRideFile(context, file, errors); if (ride) { - uploader->upload(main, ride); + uploader->upload(context, ride); delete ride; // clean up! QApplication::processEvents(); return true; @@ -727,7 +729,7 @@ TPDownloadDialog::downloadNext() rideList->setCurrentItem(curr); progressLabel->setText(QString(tr("Downloaded %1 of %2")).arg(downloadcounter).arg(downloadtotal)); downloader->download( - main->athlete->cyclist, + context->athlete->cyclist, athleteCombo->itemData(athleteCombo->currentIndex()).toInt(), curr->text(1).toInt() ); @@ -820,11 +822,11 @@ TPDownloadDialog::uploadNext() // read in the file QStringList errors; - QFile file(main->athlete->home.absolutePath() + "/" + curr->text(1)); - RideFile *ride = RideFileFactory::instance().openRideFile(main, file, errors); + QFile file(context->athlete->home.absolutePath() + "/" + curr->text(1)); + RideFile *ride = RideFileFactory::instance().openRideFile(context, file, errors); if (ride) { - uploader->upload(main, ride); + uploader->upload(context, ride); delete ride; // clean up! QApplication::processEvents(); return true; @@ -894,7 +896,7 @@ TPDownloadDialog::saveRide(RideFile *ride, QDomDocument &, QStringList &errors) .arg ( ridedatetime.time().minute(), 2, 10, zero ) .arg ( ridedatetime.time().second(), 2, 10, zero ); - QString filename = main->athlete->home.absolutePath() + "/" + targetnosuffix + ".json"; + QString filename = context->athlete->home.absolutePath() + "/" + targetnosuffix + ".json"; // exists? QFileInfo fileinfo(filename); @@ -905,11 +907,11 @@ TPDownloadDialog::saveRide(RideFile *ride, QDomDocument &, QStringList &errors) JsonFileReader reader; QFile file(filename); - reader.writeRideFile(main, ride, file); + reader.writeRideFile(context, ride, file); // add to the ride list rideFiles<addRide(fileinfo.fileName(), true); + context->mainWindow->addRide(fileinfo.fileName(), true); return true; } diff --git a/src/TPDownloadDialog.h b/src/TPDownloadDialog.h index dcb83ba83..bc210694d 100644 --- a/src/TPDownloadDialog.h +++ b/src/TPDownloadDialog.h @@ -27,7 +27,7 @@ #include "TPUpload.h" #include "MetricAggregator.h" -class MainWindow; +class Context; class TPDownloadDialog : public QDialog { @@ -36,7 +36,7 @@ class TPDownloadDialog : public QDialog public: - TPDownloadDialog(MainWindow *main); + TPDownloadDialog(Context *context); protected: // cached state @@ -60,7 +60,7 @@ class TPDownloadDialog : public QDialog void selectAllSyncChanged(int); private: - MainWindow *main; + Context *context; TPDownload *downloader; TPUpload *uploader; TPAthlete *athleter; diff --git a/src/TPUpload.cpp b/src/TPUpload.cpp index c30ac1660..e63838455 100644 --- a/src/TPUpload.cpp +++ b/src/TPUpload.cpp @@ -17,7 +17,8 @@ */ #include "TPUpload.h" -#include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include #include "Settings.h" #include "RideFile.h" @@ -73,7 +74,7 @@ TPUpload::TPUpload(QObject *parent) : QObject(parent), http(this), uploading(fal } int -TPUpload::upload(MainWindow *main, const RideFile *ride) +TPUpload::upload(Context *context, const RideFile *ride) { // if currently uploading fail! if (uploading == true) return 0; @@ -82,7 +83,7 @@ TPUpload::upload(MainWindow *main, const RideFile *ride) QString uploadfile(QDir::tempPath() + "/tpupload.pwx"); QFile file(uploadfile); PwxFileReader reader; - reader.writeRideFile(main, ride, file); + reader.writeRideFile(context, ride, file); // read the whole thing back and encode as base64binary file.open(QFile::ReadOnly); @@ -97,8 +98,8 @@ TPUpload::upload(MainWindow *main, const RideFile *ride) http.setHost("www.trainingpeaks.com"); http.setAction("http://www.trainingpeaks.com/TPWebServices/ImportFileForUser"); current.setMethod("ImportFileForUser", "http://www.trainingpeaks.com/TPWebServices/"); - current.addMethodArgument("username", "", appsettings->cvalue(main->athlete->cyclist, GC_TPUSER).toString()); - current.addMethodArgument("password", "", appsettings->cvalue(main->athlete->cyclist, GC_TPPASS).toString()); + current.addMethodArgument("username", "", appsettings->cvalue(context->athlete->cyclist, GC_TPUSER).toString()); + current.addMethodArgument("password", "", appsettings->cvalue(context->athlete->cyclist, GC_TPPASS).toString()); current.addMethodArgument("byteData", "", pwxFile); // do it! diff --git a/src/TPUpload.h b/src/TPUpload.h index ed14c66d8..cb8cc11ad 100644 --- a/src/TPUpload.h +++ b/src/TPUpload.h @@ -31,7 +31,7 @@ class TPUpload : public QObject public: TPUpload(QObject *parent = 0); - int upload(MainWindow *main, const RideFile *ride); + int upload(Context *context, const RideFile *ride); signals: void completed(QString); diff --git a/src/TPUploadDialog.cpp b/src/TPUploadDialog.cpp index dbc8cdc3a..c52018ed4 100644 --- a/src/TPUploadDialog.cpp +++ b/src/TPUploadDialog.cpp @@ -16,15 +16,15 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "TPUploadDialog.h" -#include "MainWindow.h" +#include "Context.h" #include "GcRideFile.h" #include "RideItem.h" #include "RideFile.h" #include "TPUpload.h" #include "Settings.h" -TPUploadDialog::TPUploadDialog(QString cyclist, const RideFile *ride, MainWindow *main) : -main(main), cyclist(cyclist), ride(ride) +TPUploadDialog::TPUploadDialog(QString cyclist, const RideFile *ride, Context *context) : +context(context), cyclist(cyclist), ride(ride) { setWindowTitle(tr("Upload to TrainingPeaks.com")); QVBoxLayout *mainLayout = new QVBoxLayout(this); @@ -53,7 +53,7 @@ main(main), cyclist(cyclist), ride(ride) connect(uploader, SIGNAL(completed(QString)),this, SLOT(completed(QString))); uploading = true; - int size = uploader->upload(main, ride); + int size = uploader->upload(context, ride); statusLabel->setText(QString(tr("Uploading ride (%1 bytes)...")).arg(size)); diff --git a/src/TPUploadDialog.h b/src/TPUploadDialog.h index 9cb814df2..a9b09da17 100644 --- a/src/TPUploadDialog.h +++ b/src/TPUploadDialog.h @@ -25,7 +25,7 @@ #include "RideFile.h" #include "TPUpload.h" -class MainWindow; +class Context; class TPUploadDialog : public QDialog { @@ -34,14 +34,14 @@ class TPUploadDialog : public QDialog public: - TPUploadDialog(QString cyclist, const RideFile *ride, MainWindow *main); + TPUploadDialog(QString cyclist, const RideFile *ride, Context *context); public slots: void cancelClicked(); void completed(QString); private: - MainWindow *main; + Context *context; QString cyclist; const RideFile *ride; diff --git a/src/TRIMPPoints.cpp b/src/TRIMPPoints.cpp index af98750d9..faa311432 100644 --- a/src/TRIMPPoints.cpp +++ b/src/TRIMPPoints.cpp @@ -21,7 +21,8 @@ #include "Zones.h" #include "HrZones.h" #include -#include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include // This is Morton/Banister with Green et al coefficient. @@ -56,7 +57,7 @@ class TRIMPPoints : public RideMetric { const Zones *, int, const HrZones *hrZones, int hrZoneRange, const QHash &deps, - const MainWindow *main) + const Context *context) { if (!hrZones || hrZoneRange < 0) { setValue(0); @@ -91,7 +92,7 @@ class TRIMPPoints : public RideMetric { QString athlete; double ksex = 1.92; if ((athlete = rideFile->getTag("Athlete", "unknown")) != "unknown") { - if (appsettings->cvalue(main->athlete->cyclist, GC_SEX).toInt() == 1) ksex = 1.67; // Female + if (appsettings->cvalue(context->athlete->cyclist, GC_SEX).toInt() == 1) ksex = 1.67; // Female else ksex = 1.92; // Male } @@ -131,7 +132,7 @@ public: const Zones *, int, const HrZones *hrZones, int hrZoneRange, const QHash &deps, - const MainWindow *main) + const Context *context) { if (!hrZones || hrZoneRange < 0) { setValue(0); @@ -158,7 +159,7 @@ public: QString athlete; double ksex = 1.92; if ((athlete = rideFile->getTag("Athlete", "unknown")) != "unknown") { - if (appsettings->cvalue(main->athlete->cyclist, GC_SEX).toInt() == 1) ksex = 1.67; // Female + if (appsettings->cvalue(context->athlete->cyclist, GC_SEX).toInt() == 1) ksex = 1.67; // Female else ksex = 1.92; // Male } @@ -201,7 +202,7 @@ public: const Zones *, int, const HrZones *hrZones, int hrZoneRange, const QHash &deps, - const MainWindow *) + const Context *) { assert(deps.contains("average_hr")); const RideMetric *averageHrMetric = deps.value("average_hr"); @@ -326,7 +327,7 @@ class SessionRPE : public RideMetric { const Zones *, int, const HrZones *, int, const QHash &deps, - const MainWindow *) + const Context *) { // use RPE value in ride metadata double rpe = rideFile->getTag("RPE", "0.0").toDouble(); diff --git a/src/TcxRideFile.cpp b/src/TcxRideFile.cpp index c734cd1e7..89b0f4f16 100644 --- a/src/TcxRideFile.cpp +++ b/src/TcxRideFile.cpp @@ -21,7 +21,8 @@ #include "TcxParser.h" #include -#include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "RideMetric.h" #ifndef GC_VERSION @@ -51,7 +52,7 @@ RideFile *TcxFileReader::openRideFile(QFile &file, QStringList &errors, QList computed = RideMetric::computeMetrics(mainWindow, ride, mainWindow->athlete->zones(), mainWindow->athlete->hrZones(), worklist); + QHash computed = RideMetric::computeMetrics(context, ride, context->athlete->zones(), context->athlete->hrZones(), worklist); QDomElement lap_time = doc.createElement("TotalTimeSeconds"); text = doc.createTextNode(QString("%1").arg(computed.value("workout_time")->value(true))); @@ -397,9 +398,9 @@ TcxFileReader::toByteArray(MainWindow *mainWindow, const RideFile *ride, bool wi } bool -TcxFileReader::writeRideFile(MainWindow *mainWindow, const RideFile *ride, QFile &file) const +TcxFileReader::writeRideFile(Context *context, const RideFile *ride, QFile &file) const { - QByteArray xml = toByteArray(mainWindow, ride, true, true, true, true); + QByteArray xml = toByteArray(context, ride, true, true, true, true); if (!file.open(QIODevice::WriteOnly)) return(false); if (file.write(xml) != xml.size()) return(false); diff --git a/src/TcxRideFile.h b/src/TcxRideFile.h index 71467a17e..821c976a9 100644 --- a/src/TcxRideFile.h +++ b/src/TcxRideFile.h @@ -25,8 +25,8 @@ struct TcxFileReader : public RideFileReader { virtual RideFile *openRideFile(QFile &file, QStringList &errors, QList* = 0) const; - QByteArray toByteArray(MainWindow *mainWindow, const RideFile *ride, bool withAlt, bool withWatts, bool withHr, bool withCad) const; - bool writeRideFile(MainWindow *mainWindow, const RideFile *ride, QFile &file) const; + QByteArray toByteArray(Context *context, const RideFile *ride, bool withAlt, bool withWatts, bool withHr, bool withCad) const; + bool writeRideFile(Context *context, const RideFile *ride, QFile &file) const; bool hasWrite() const { return true; } }; diff --git a/src/TimeInZone.cpp b/src/TimeInZone.cpp index 3fa550cde..2dfe3dd13 100644 --- a/src/TimeInZone.cpp +++ b/src/TimeInZone.cpp @@ -45,7 +45,7 @@ class ZoneTime : public RideMetric { void compute(const RideFile *ride, const Zones *zone, int zoneRange, const HrZones *, int, const QHash &, - const MainWindow *) + const Context *) { seconds = 0; // get zone ranges diff --git a/src/ToolsRhoEstimator.cpp b/src/ToolsRhoEstimator.cpp index ea31b1a6d..d0bb81c51 100644 --- a/src/ToolsRhoEstimator.cpp +++ b/src/ToolsRhoEstimator.cpp @@ -20,7 +20,8 @@ #include "ToolsRhoEstimator.h" #include "Settings.h" -#include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "Units.h" #include #include @@ -28,7 +29,7 @@ typedef QDoubleSpinBox* QDoubleSpinBoxPtr; -ToolsRhoEstimator::ToolsRhoEstimator(MainWindow *mainWindow, QWidget *parent) : QDialog(parent), mainWindow(mainWindow) { +ToolsRhoEstimator::ToolsRhoEstimator(Context *context, QWidget *parent) : QDialog(parent), context(context) { // Set the main window title. setWindowTitle(tr("Air Density (Rho) Estimator")); @@ -46,10 +47,10 @@ ToolsRhoEstimator::ToolsRhoEstimator(MainWindow *mainWindow, QWidget *parent) : // forcing them to change their preference in the preferences menu.) QHBoxLayout *rads = new QHBoxLayout; metBut = new QRadioButton(tr("Metric")); - metBut->setChecked(mainWindow->athlete->useMetricUnits); + metBut->setChecked(context->athlete->useMetricUnits); rads->addWidget(metBut); impBut = new QRadioButton(tr("Imperial")); - impBut->setChecked(!mainWindow->athlete->useMetricUnits); + impBut->setChecked(!context->athlete->useMetricUnits); // note that we only need to connect one of the radio button // signals, since changing one also changes the other. connect(impBut, SIGNAL(toggled(bool)), @@ -62,7 +63,7 @@ ToolsRhoEstimator::ToolsRhoEstimator(MainWindow *mainWindow, QWidget *parent) : tempSpinBox = new QDoubleSpinBox(this); tempSpinBox->setDecimals(2); tempSpinBox->setRange(-200, 200); - if (mainWindow->athlete->useMetricUnits) { + if (context->athlete->useMetricUnits) { tempLabel = new QLabel(tr("Temperature (C):")); thl->addWidget(tempLabel); tempSpinBox->setValue(15); @@ -83,7 +84,7 @@ ToolsRhoEstimator::ToolsRhoEstimator(MainWindow *mainWindow, QWidget *parent) : pressSpinBox = new QDoubleSpinBox(this); pressSpinBox->setDecimals(2); pressSpinBox->setRange(0, 2000); - if (mainWindow->athlete->useMetricUnits) { + if (context->athlete->useMetricUnits) { pressLabel = new QLabel(tr("Air Pressure (hPa):")); phl->addWidget(pressLabel); pressSpinBox->setValue(1018); @@ -104,7 +105,7 @@ ToolsRhoEstimator::ToolsRhoEstimator(MainWindow *mainWindow, QWidget *parent) : dewpSpinBox = new QDoubleSpinBox(this); dewpSpinBox->setDecimals(2); dewpSpinBox->setRange(-200, 200); - if (mainWindow->athlete->useMetricUnits) { + if (context->athlete->useMetricUnits) { dewpLabel = new QLabel(tr("Dewpoint (C):")); dhl->addWidget(dewpLabel); dewpSpinBox->setValue(7.5); diff --git a/src/ToolsRhoEstimator.h b/src/ToolsRhoEstimator.h index 0dc86a3b9..1b78241a9 100644 --- a/src/ToolsRhoEstimator.h +++ b/src/ToolsRhoEstimator.h @@ -23,7 +23,7 @@ #include #include -class MainWindow; +class Context; // This class implements a dialog box containing a tool for // helping the user estimate rho, the air density, given @@ -33,10 +33,10 @@ class ToolsRhoEstimator : public QDialog { G_OBJECT public: - ToolsRhoEstimator(MainWindow *mainWindow, QWidget *parent = 0); + ToolsRhoEstimator(Context *context, QWidget *parent = 0); private: - MainWindow *mainWindow; + Context *context; bool useMetricUnits; QRadioButton *metBut; diff --git a/src/TrainTool.cpp b/src/TrainTool.cpp index bd97ce883..4cf1327d5 100644 --- a/src/TrainTool.cpp +++ b/src/TrainTool.cpp @@ -18,6 +18,8 @@ #include "TrainTool.h" #include "MainWindow.h" +#include "Context.h" +#include "Athlete.h" #include "Settings.h" #include "Colors.h" #include "Units.h" @@ -54,7 +56,7 @@ #include "TrainDB.h" #include "Library.h" -TrainTool::TrainTool(MainWindow *parent, const QDir &home) : GcWindow(parent), home(home), main(parent) +TrainTool::TrainTool(Context *context, const QDir &home) : GcWindow(context), home(home), context(context) { setInstanceName("Train Controls"); @@ -273,7 +275,7 @@ TrainTool::TrainTool(MainWindow *parent, const QDir &home) : GcWindow(parent), h connect(forward, SIGNAL(clicked()), this, SLOT(FFwd())); connect(rewind, SIGNAL(clicked()), this, SLOT(Rewind())); connect(lap, SIGNAL(clicked()), this, SLOT(newLap())); - connect(main->context, SIGNAL(newLap()), this, SLOT(resetLapTimer())); + connect(context, SIGNAL(newLap()), this, SLOT(resetLapTimer())); connect(intensitySlider, SIGNAL(valueChanged(int)), this, SLOT(adjustIntensity())); // not used but kept in case re-instated in the future @@ -311,7 +313,7 @@ TrainTool::TrainTool(MainWindow *parent, const QDir &home) : GcWindow(parent), h mediaItem->addWidget(mediaTree); trainSplitter->addWidget(mediaItem); #endif - trainSplitter->prepare(main->athlete->cyclist, "train"); + trainSplitter->prepare(context->athlete->cyclist, "train"); #ifdef Q_OS_MAC // get rid of annoying focus rectangle for sidebar components @@ -327,10 +329,10 @@ TrainTool::TrainTool(MainWindow *parent, const QDir &home) : GcWindow(parent), h #if defined Q_OS_MAC || defined GC_HAVE_VLC connect(mediaTree->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(mediaTreeWidgetSelectionChanged())); - connect(main->context, SIGNAL(selectMedia(QString)), this, SLOT(selectVideo(QString))); + connect(context, SIGNAL(selectMedia(QString)), this, SLOT(selectVideo(QString))); #endif - connect(main->context, SIGNAL(configChanged()), this, SLOT(configChanged())); - connect(main->context, SIGNAL(selectWorkout(QString)), this, SLOT(selectWorkout(QString))); + connect(context, SIGNAL(configChanged()), this, SLOT(configChanged())); + connect(context, SIGNAL(selectWorkout(QString)), this, SLOT(selectWorkout(QString))); connect(trainDB, SIGNAL(dataChanged()), this, SLOT(refresh())); connect(workoutTree->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(workoutTreeWidgetSelectionChanged())); @@ -338,7 +340,7 @@ TrainTool::TrainTool(MainWindow *parent, const QDir &home) : GcWindow(parent), h QVariant workoutDir = appsettings->value(NULL, GC_WORKOUTDIR); // set home - main = parent; + //XXX ??? main = parent; ergFile = NULL; calibrating = false; @@ -434,10 +436,10 @@ TrainTool::workoutPopup() } // connect menu to functions - connect(import, SIGNAL(triggered(void)), main, SLOT(importWorkout(void))); - connect(wizard, SIGNAL(triggered(void)), main, SLOT(showWorkoutWizard(void))); - connect(download, SIGNAL(triggered(void)), main, SLOT(downloadErgDB(void))); - connect(scan, SIGNAL(triggered(void)), main, SLOT(manageLibrary(void))); + connect(import, SIGNAL(triggered(void)), context->mainWindow, SLOT(importWorkout(void))); + connect(wizard, SIGNAL(triggered(void)), context->mainWindow, SLOT(showWorkoutWizard(void))); + connect(download, SIGNAL(triggered(void)), context->mainWindow, SLOT(downloadErgDB(void))); + connect(scan, SIGNAL(triggered(void)), context->mainWindow, SLOT(manageLibrary(void))); // execute the menu menu.exec(trainSplitter->mapToGlobal(QPoint(workoutItem->pos().x()+workoutItem->width()-20, @@ -456,8 +458,8 @@ TrainTool::mediaPopup() menu.addAction(scan); // connect menu to functions - connect(import, SIGNAL(triggered(void)), main, SLOT(importWorkout(void))); - connect(scan, SIGNAL(triggered(void)), main, SLOT(manageLibrary(void))); + connect(import, SIGNAL(triggered(void)), context->mainWindow, SLOT(importWorkout(void))); + connect(scan, SIGNAL(triggered(void)), context->mainWindow, SLOT(manageLibrary(void))); QModelIndex current = mediaTree->currentIndex(); QModelIndex target = vsortModel->mapToSource(current); @@ -530,8 +532,8 @@ TrainTool::configChanged() workoutTree->setCurrentIndex(firstWorkout); // Athlete FTP=285; // default to 285 if zones are not set - int range = main->athlete->zones()->whichRange(QDate::currentDate()); - if (range != -1) FTP = main->athlete->zones()->getCP(range); + int range = context->athlete->zones()->whichRange(QDate::currentDate()); + if (range != -1) FTP = context->athlete->zones()->getCP(range); } @@ -584,7 +586,7 @@ TrainTool::workoutTreeWidgetSelectionChanged() } if (filename == "") { - main->context->notifyErgFileSelected(NULL); + context->notifyErgFileSelected(NULL); return; } @@ -592,21 +594,21 @@ TrainTool::workoutTreeWidgetSelectionChanged() int index = target.row(); if (index == 0) { // ergo mode - main->context->notifyErgFileSelected(NULL); + context->notifyErgFileSelected(NULL); mode = ERG; setLabels(); status &= ~RT_WORKOUT; //ergPlot->setVisible(false); } else if (index == 1) { // slope mode - main->context->notifyErgFileSelected(NULL); + context->notifyErgFileSelected(NULL); mode = CRS; setLabels(); status &= ~RT_WORKOUT; //ergPlot->setVisible(false); } else { // workout mode - ergFile = new ErgFile(filename, mode, main); + ergFile = new ErgFile(filename, mode, context); if (ergFile->isValid()) { status |= RT_WORKOUT; @@ -614,7 +616,7 @@ TrainTool::workoutTreeWidgetSelectionChanged() // success! we have a load file // setup the course profile in the // display! - main->context->notifyErgFileSelected(ergFile); + context->notifyErgFileSelected(ergFile); intensitySlider->setValue(100); lastAppliedIntensity = 100; setLabels(); @@ -623,7 +625,7 @@ TrainTool::workoutTreeWidgetSelectionChanged() // couldn't parse fall back to ERG mode delete ergFile; ergFile = NULL; - main->context->notifyErgFileSelected(NULL); + context->notifyErgFileSelected(NULL); mode = ERG; status &= ~RT_WORKOUT; setLabels(); @@ -684,7 +686,7 @@ TrainTool::deleteVideos() // remove any reference (from drag and drop) Library *l = Library::findLibrary("Media Library"); - if (l) l->removeRef(main, filename); + if (l) l->removeRef(context, filename); // delete from DB trainDB->startLUW(); @@ -728,7 +730,7 @@ TrainTool::mediaTreeWidgetSelectionChanged() QModelIndex current = mediaTree->currentIndex(); QModelIndex target = vsortModel->mapToSource(current); QString filename = videoModel->data(videoModel->index(target.row(), 0), Qt::DisplayRole).toString(); - main->context->notifyMediaSelected(filename); + context->notifyMediaSelected(filename); } /*-------------------------------------------------------------------------------- @@ -759,7 +761,7 @@ void TrainTool::Start() // when start button is pressed #endif // tell the world - main->context->notifyUnPause(); + context->notifyUnPause(); } else if (status&RT_RUNNING) { @@ -781,7 +783,7 @@ void TrainTool::Start() // when start button is pressed #endif // tell the world - main->context->notifyPause(); + context->notifyPause(); } else { @@ -791,7 +793,7 @@ void TrainTool::Start() // when start button is pressed // if we have selected multiple devices lets // configure the series we collect from each one if (deviceTree->selectedItems().count() > 1) { - MultiDeviceDialog *multisetup = new MultiDeviceDialog(main, this); + MultiDeviceDialog *multisetup = new MultiDeviceDialog(context, this); if (multisetup->exec() == false) { return; } @@ -827,7 +829,7 @@ void TrainTool::Start() // when start button is pressed foreach(int dev, devices()) Devices[dev].controller->start(); // tell the world - main->context->notifyStart(); + context->notifyStart(); // we're away! status |=RT_RUNNING; @@ -893,7 +895,7 @@ void TrainTool::Pause() // pause capture to recalibrate #endif // tell the world - main->context->notifyUnPause(); + context->notifyUnPause(); } else { @@ -912,7 +914,7 @@ void TrainTool::Pause() // pause capture to recalibrate #endif // tell the world - main->context->notifyPause(); + context->notifyPause(); } } @@ -956,7 +958,7 @@ void TrainTool::Stop(int deviceStatus) // when stop button is pressed // add to the view - using basename ONLY QString name; name = recordFile->fileName(); - main->addRide(QFileInfo(name).fileName(), true); + context->mainWindow->addRide(QFileInfo(name).fileName(), true); } } @@ -968,15 +970,15 @@ void TrainTool::Stop(int deviceStatus) // when stop button is pressed // get back to normal after it may have been adusted by the user lastAppliedIntensity=100; intensitySlider->setValue(100); - if (main->context->currentErgFile()) main->context->currentErgFile()->reload(); - main->context->notifySetNow(load_msecs); + if (context->currentErgFile()) context->currentErgFile()->reload(); + context->notifySetNow(load_msecs); // reset the play button QIcon playIcon(":images/oxygen/play.png"); play->setIcon(playIcon); // tell the world - main->context->notifyStop(); + context->notifyStop(); // Re-enable gui elements // reset counters etc @@ -1109,7 +1111,7 @@ void TrainTool::guiUpdate() // refreshes the telemetry // virtual speed double crr = 0.004f; // typical for asphalt surfaces double g = 9.81; // g constant 9.81 m/s - double weight = appsettings->cvalue(main->athlete->cyclist, GC_WEIGHT, 0.0).toDouble(); + double weight = appsettings->cvalue(context->athlete->cyclist, GC_WEIGHT, 0.0).toDouble(); double m = weight ? weight + 8 : 83; // default to 75kg weight, plus 8kg bike double sl = slope / 100; // 10% = 0.1 double ad = 1.226f; // default air density at sea level @@ -1138,7 +1140,7 @@ void TrainTool::guiUpdate() // refreshes the telemetry // go update the displays... - main->context->notifyTelemetryUpdate(rtData); // signal everyone to update telemetry + context->notifyTelemetryUpdate(rtData); // signal everyone to update telemetry // set now to current time when not using a workout // but limit to almost every second (account for @@ -1150,7 +1152,7 @@ void TrainTool::guiUpdate() // refreshes the telemetry long rmsecs = round((rtData.getMsecs() + 99) / 100) * 100; // Test for <= 100ms if (!(status&RT_WORKOUT) && ((rmsecs % 1000) <= 100)) { - main->context->notifySetNow(rtData.getMsecs()); + context->notifySetNow(rtData.getMsecs()); } } } @@ -1167,7 +1169,7 @@ void TrainTool::newLap() hrcount = 0; spdcount = 0; - main->context->notifyNewLap(); + context->notifyNewLap(); } } @@ -1238,7 +1240,7 @@ void TrainTool::loadUpdate() if(displayWorkoutLap != curLap) { - main->context->notifyNewLap(); + context->notifyNewLap(); } displayWorkoutLap = curLap; @@ -1247,14 +1249,14 @@ void TrainTool::loadUpdate() Stop(DEVICE_OK); } else { foreach(int dev, devices()) Devices[dev].controller->setLoad(load); - main->context->notifySetNow(load_msecs); + context->notifySetNow(load_msecs); } } else { slope = ergFile->gradientAt(displayWorkoutDistance*1000, curLap); if(displayWorkoutLap != curLap) { - main->context->notifyNewLap(); + context->notifyNewLap(); } displayWorkoutLap = curLap; @@ -1263,7 +1265,7 @@ void TrainTool::loadUpdate() Stop(DEVICE_OK); } else { foreach(int dev, devices()) Devices[dev].controller->setGradient(slope); - main->context->notifySetNow(displayWorkoutDistance * 1000); + context->notifySetNow(displayWorkoutDistance * 1000); } } } @@ -1282,7 +1284,7 @@ void TrainTool::Calibrate() load_period.restart(); if (status & RT_WORKOUT) load_timer->start(LOADRATE); if (status & RT_RECORDING) disk_timer->start(SAMPLERATE); - main->context->notifyUnPause(); // get video started again, amongst other things + context->notifyUnPause(); // get video started again, amongst other things // back to ergo/slope mode and restore load/gradient if (status&RT_MODE_ERGO) { @@ -1320,7 +1322,7 @@ void TrainTool::Calibrate() if (status & RT_WORKOUT) load_timer->stop(); load_msecs += load_period.restart(); - main->context->notifyPause(); // get video started again, amongst other things + context->notifyPause(); // get video started again, amongst other things // only do this for computrainers! foreach(int dev, devices()) @@ -1336,7 +1338,7 @@ void TrainTool::FFwd() if (status&RT_MODE_ERGO) { load_msecs += 10000; // jump forward 10 seconds - main->context->notifySeek(load_msecs); + context->notifySeek(load_msecs); } else displayWorkoutDistance += 1; // jump forward a kilometer in the workout @@ -1349,7 +1351,7 @@ void TrainTool::Rewind() if (status&RT_MODE_ERGO) { load_msecs -=10000; // jump back 10 seconds if (load_msecs < 0) load_msecs = 0; - main->context->notifySeek(load_msecs); + context->notifySeek(load_msecs); } else { displayWorkoutDistance -=1; // jump back a kilometer if (displayWorkoutDistance < 0) displayWorkoutDistance = 0; @@ -1367,7 +1369,7 @@ void TrainTool::FFwdLap() if (status&RT_MODE_ERGO) { lapmarker = ergFile->nextLap(load_msecs); if (lapmarker != -1) load_msecs = lapmarker; // jump forward to lapmarker - main->context->notifySeek(load_msecs); + context->notifySeek(load_msecs); } else { lapmarker = ergFile->nextLap(displayWorkoutDistance*1000); if (lapmarker != -1) displayWorkoutDistance = lapmarker/1000; // jump forward to lapmarker @@ -1379,7 +1381,7 @@ void TrainTool::Higher() { if ((status&RT_RUNNING) == 0) return; - if (main->context->currentErgFile()) { + if (context->currentErgFile()) { // adjust the workout IF intensitySlider->setValue(intensitySlider->value()+5); @@ -1402,7 +1404,7 @@ void TrainTool::Lower() { if ((status&RT_RUNNING) == 0) return; - if (main->context->currentErgFile()) { + if (context->currentErgFile()) { // adjust the workout IF intensitySlider->setValue(intensitySlider->value()-5); @@ -1423,19 +1425,19 @@ void TrainTool::Lower() void TrainTool::setLabels() { - if (main->context->currentErgFile()) { + if (context->currentErgFile()) { intensitySlider->show(); - if (main->context->currentErgFile()->format == CRS) { + if (context->currentErgFile()->format == CRS) { - stress->setText(QString("Elevation %1").arg(main->context->currentErgFile()->ELE, 0, 'f', 0)); - intensity->setText(QString("Grade %1 %").arg(main->context->currentErgFile()->GRADE, 0, 'f', 1)); + stress->setText(QString("Elevation %1").arg(context->currentErgFile()->ELE, 0, 'f', 0)); + intensity->setText(QString("Grade %1 %").arg(context->currentErgFile()->GRADE, 0, 'f', 1)); } else { - stress->setText(QString("TSS %1").arg(main->context->currentErgFile()->TSS, 0, 'f', 0)); - intensity->setText(QString("IF %1").arg(main->context->currentErgFile()->IF, 0, 'f', 3)); + stress->setText(QString("TSS %1").arg(context->currentErgFile()->TSS, 0, 'f', 0)); + intensity->setText(QString("IF %1").arg(context->currentErgFile()->IF, 0, 'f', 3)); } } else { @@ -1448,10 +1450,10 @@ void TrainTool::setLabels() void TrainTool::adjustIntensity() { - if (!main->context->currentErgFile()) return; // no workout selected + if (!context->currentErgFile()) return; // no workout selected // block signals temporarily - main->blockSignals(true); + context->mainWindow->blockSignals(true); // work through the ergFile from NOW // adjusting back from last intensity setting @@ -1461,29 +1463,29 @@ void TrainTool::adjustIntensity() double to = double(intensitySlider->value()) / 100.00; lastAppliedIntensity = intensitySlider->value(); - long starttime = main->context->getNow(); + long starttime = context->getNow(); - bool insertedNow = main->context->getNow() ? false : true; // don't add if at start + bool insertedNow = context->getNow() ? false : true; // don't add if at start // what about gradient courses? ErgFilePoint last; - for(int i = 0; i < main->context->currentErgFile()->Points.count(); i++) { + for(int i = 0; i < context->currentErgFile()->Points.count(); i++) { - if (main->context->currentErgFile()->Points.at(i).x >= starttime) { + if (context->currentErgFile()->Points.at(i).x >= starttime) { if (insertedNow == false) { if (i) { // add a point to adjust from ErgFilePoint add; - add.x = main->context->getNow(); + add.x = context->getNow(); add.val = last.val / from * to; // recalibrate altitude if gradient changing - if (main->context->currentErgFile()->format == CRS) add.y = last.y + ((add.x-last.x) * (add.val/100)); + if (context->currentErgFile()->format == CRS) add.y = last.y + ((add.x-last.x) * (add.val/100)); else add.y = add.val; - main->context->currentErgFile()->Points.insert(i, add); + context->currentErgFile()->Points.insert(i, add); last = add; i++; // move on to next point (i.e. where we were!) @@ -1492,32 +1494,32 @@ void TrainTool::adjustIntensity() insertedNow = true; } - ErgFilePoint *p = &main->context->currentErgFile()->Points[i]; + ErgFilePoint *p = &context->currentErgFile()->Points[i]; // recalibrate altitude if in CRS mode p->val = p->val / from * to; - if (main->context->currentErgFile()->format == CRS) { + if (context->currentErgFile()->format == CRS) { if (i) p->y = last.y + ((p->x-last.x) * (last.val/100)); } else p->y = p->val; } // remember last - last = main->context->currentErgFile()->Points.at(i); + last = context->currentErgFile()->Points.at(i); } // recalculate metrics - main->context->currentErgFile()->calculateMetrics(); + context->currentErgFile()->calculateMetrics(); setLabels(); // unblock signals now we are done - main->blockSignals(false); + context->mainWindow->blockSignals(false); // force replot - main->context->notifySetNow(main->context->getNow()); + context->notifySetNow(context->getNow()); } -MultiDeviceDialog::MultiDeviceDialog(MainWindow *, TrainTool *traintool) : traintool(traintool) +MultiDeviceDialog::MultiDeviceDialog(Context *, TrainTool *traintool) : traintool(traintool) { setAttribute(Qt::WA_DeleteOnClose); setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint); @@ -1609,7 +1611,7 @@ TrainTool::devicePopup() QMenu menu(deviceTree); QAction *addDevice = new QAction(tr("Add Device"), deviceTree); - connect(addDevice, SIGNAL(triggered(void)), main, SLOT(addDevice())); + connect(addDevice, SIGNAL(triggered(void)), context->mainWindow, SLOT(addDevice())); menu.addAction(addDevice); if (deviceTree->selectedItems().size() == 1) { @@ -1627,7 +1629,7 @@ TrainTool::deviceTreeMenuPopup(const QPoint &pos) { QMenu menu(deviceTree); QAction *addDevice = new QAction(tr("Add Device"), deviceTree); - connect(addDevice, SIGNAL(triggered(void)), main, SLOT(addDevice())); + connect(addDevice, SIGNAL(triggered(void)), context->mainWindow, SLOT(addDevice())); menu.addAction(addDevice); if (deviceTree->selectedItems().size() == 1) { @@ -1669,7 +1671,7 @@ TrainTool::deleteDevice() all.writeConfig(list); // tell everyone - main->context->notifyConfigChanged(); + context->notifyConfigChanged(); } // we have been told to select this video (usually because diff --git a/src/TrainTool.h b/src/TrainTool.h index 467457c25..028780e9a 100644 --- a/src/TrainTool.h +++ b/src/TrainTool.h @@ -20,7 +20,7 @@ #define _GC_TrainTool_h 1 #include "GoldenCheetah.h" -#include "MainWindow.h" +#include "Context.h" #include "RealtimeData.h" #include "RealtimePlot.h" #include "DeviceConfiguration.h" @@ -76,7 +76,7 @@ class TrainTool : public GcWindow public: - TrainTool(MainWindow *parent, const QDir &home); + TrainTool(Context *context, const QDir &home); QStringList listWorkoutFiles(const QDir &) const; QList devices(); // convenience function for iterating over active devices @@ -166,7 +166,7 @@ class TrainTool : public GcWindow friend class ::MultiDeviceDialog; const QDir home; - MainWindow *main; + Context *context; GcSplitter *trainSplitter; GcSplitterItem *deviceItem, *workoutItem, @@ -241,7 +241,7 @@ class MultiDeviceDialog : public QDialog G_OBJECT public: - MultiDeviceDialog(MainWindow *, TrainTool *); + MultiDeviceDialog(Context *, TrainTool *); public slots: void applyClicked(); @@ -249,7 +249,7 @@ class MultiDeviceDialog : public QDialog private: - MainWindow *mainWindow; + Context *context; TrainTool *traintool; QComboBox *bpmSelect, // heartrate *wattsSelect, // power diff --git a/src/TreeMapPlot.cpp b/src/TreeMapPlot.cpp index d781fe9de..faf8b2ff3 100644 --- a/src/TreeMapPlot.cpp +++ b/src/TreeMapPlot.cpp @@ -16,6 +16,7 @@ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ +#include "Context.h" #include "TreeMapPlot.h" #include "LTMTool.h" #include "TreeMapWindow.h" @@ -36,8 +37,8 @@ bool TreeMapLessThan(const TreeMap *a, const TreeMap *b) { return (a->value) > (b->value); } -TreeMapPlot::TreeMapPlot(TreeMapWindow *parent, MainWindow *main) - : QWidget (parent), parent(parent), main(main) +TreeMapPlot::TreeMapPlot(TreeMapWindow *parent, Context *context) + : QWidget (parent), parent(parent), context(context) { setInstanceName("TreeMap Plot"); @@ -51,7 +52,7 @@ TreeMapPlot::TreeMapPlot(TreeMapWindow *parent, MainWindow *main) setContentsMargins(0,0,0,0); configUpdate(); // set basic colors - connect(main->context, SIGNAL(configChanged()), this, SLOT(configUpdate())); + connect(context, SIGNAL(configChanged()), this, SLOT(configUpdate())); } TreeMapPlot::~TreeMapPlot() @@ -69,7 +70,7 @@ TreeMapPlot::setData(TMSettings *settings) foreach (SummaryMetrics rideMetrics, *(settings->data)) { // don't plot if filtered - if (main->isfiltered && !main->filters.contains(rideMetrics.getFileName())) continue; + if (context->mainWindow->isfiltered && !context->mainWindow->filters.contains(rideMetrics.getFileName())) continue; double value = rideMetrics.getForSymbol(settings->symbol); QString text1 = rideMetrics.getText(settings->field1, "(unknown)"); diff --git a/src/TreeMapPlot.h b/src/TreeMapPlot.h index 08e362bad..fc0fca041 100644 --- a/src/TreeMapPlot.h +++ b/src/TreeMapPlot.h @@ -24,7 +24,7 @@ #include "MetricAggregator.h" #include "TreeMapWindow.h" -#include "MainWindow.h" +#include "Context.h" // for sorting @@ -240,7 +240,7 @@ class TreeMapPlot : public QWidget public: - TreeMapPlot(TreeMapWindow *, MainWindow *main); + TreeMapPlot(TreeMapWindow *, Context *context); ~TreeMapPlot(); void setData(TMSettings *); @@ -258,7 +258,7 @@ class TreeMapPlot : public QWidget virtual void resizeEvent(QResizeEvent *); private: - MainWindow *main; + Context *context; TMSettings *settings; TreeMap *root; // the tree map data structure diff --git a/src/TreeMapWindow.cpp b/src/TreeMapWindow.cpp index 22bfc0259..bea828334 100644 --- a/src/TreeMapWindow.cpp +++ b/src/TreeMapWindow.cpp @@ -20,7 +20,9 @@ #include "LTMTool.h" #include "TreeMapPlot.h" #include "LTMSettings.h" -#include "MainWindow.h" +#include "Context.h" +#include "Context.h" +#include "Athlete.h" #include "SummaryMetrics.h" #include "Settings.h" #include "math.h" @@ -34,14 +36,14 @@ #include #include -TreeMapWindow::TreeMapWindow(MainWindow *parent) : - GcWindow(parent), main(parent), active(false), dirty(true), useCustom(false), useToToday(false) +TreeMapWindow::TreeMapWindow(Context *context) : + GcWindow(context), context(context), active(false), dirty(true), useCustom(false), useToToday(false) { setInstanceName("Treemap Window"); // the plot mainLayout = new QVBoxLayout; - ltmPlot = new TreeMapPlot(this, main); + ltmPlot = new TreeMapPlot(this, context); mainLayout->addWidget(ltmPlot); mainLayout->setSpacing(0); mainLayout->setContentsMargins(0,0,0,0); @@ -53,7 +55,7 @@ TreeMapWindow::TreeMapWindow(MainWindow *parent) : setControls(c); // read metadata.xml - QString filename = main->athlete->home.absolutePath()+"/metadata.xml"; + QString filename = context->athlete->home.absolutePath()+"/metadata.xml"; QString colorfield; if (!QFile(filename).exists()) filename = ":/xml/metadata.xml"; RideMetadata::readXML(filename, keywordDefinitions, fieldDefinitions, colorfield); @@ -70,7 +72,7 @@ TreeMapWindow::TreeMapWindow(MainWindow *parent) : // setup the popup widget popup = new GcPane(); - ltmPopup = new LTMPopup(main); + ltmPopup = new LTMPopup(context); QVBoxLayout *popupLayout = new QVBoxLayout(); popupLayout->addWidget(ltmPopup); popup->setLayout(popupLayout); @@ -133,11 +135,11 @@ TreeMapWindow::TreeMapWindow(MainWindow *parent) : // config changes or ride file activities cause a redraw/refresh (but only if active) connect(this, SIGNAL(rideItemChanged(RideItem*)), this, SLOT(rideSelected())); - connect(main, SIGNAL(rideAdded(RideItem*)), this, SLOT(refresh(void))); - connect(main, SIGNAL(rideDeleted(RideItem*)), this, SLOT(refresh(void))); - connect(main, SIGNAL(filterChanged(QStringList&)), this, SLOT(refresh(void))); + connect(context->mainWindow, SIGNAL(rideAdded(RideItem*)), this, SLOT(refresh(void))); + connect(context->mainWindow, SIGNAL(rideDeleted(RideItem*)), this, SLOT(refresh(void))); + connect(context->mainWindow, SIGNAL(filterChanged(QStringList&)), this, SLOT(refresh(void))); - connect(main->context, SIGNAL(configChanged()), this, SLOT(refresh())); + connect(context, SIGNAL(configChanged()), this, SLOT(refresh())); // user clicked on a cell in the plot connect(ltmPlot, SIGNAL(clicked(QString,QString)), this, SLOT(cellClicked(QString,QString))); @@ -228,7 +230,7 @@ TreeMapWindow::refresh() // get the data results.clear(); // clear any old data - results = main->athlete->metricDB->getAllMetricsFor(QDateTime(settings.from, QTime(0,0,0)), + results = context->athlete->metricDB->getAllMetricsFor(QDateTime(settings.from, QTime(0,0,0)), QDateTime(settings.to, QTime(0,0,0))); refreshPlot(); diff --git a/src/TreeMapWindow.h b/src/TreeMapWindow.h index 546355e38..1f01a6225 100644 --- a/src/TreeMapWindow.h +++ b/src/TreeMapWindow.h @@ -19,10 +19,11 @@ #ifndef _GC_TreeMapWindow_h #define _GC_TreeMapWindow_h 1 #include "GoldenCheetah.h" +#include "MainWindow.h" #include #include -#include "MainWindow.h" +#include "Context.h" #include "MetricAggregator.h" #include "RideMetadata.h" #include "Season.h" @@ -62,12 +63,12 @@ class TreeMapWindow : public GcWindow public: - MainWindow *main; // used by zones shader - TreeMapWindow(MainWindow *); + Context *context; // used by zones shader + TreeMapWindow(Context *); ~TreeMapWindow(); #ifdef GC_HAVE_LUCENE - bool isFiltered() const { return main->isfiltered; } + bool isFiltered() const { return context->mainWindow->isfiltered; } #endif QString f1() const { return field1->currentText(); } void setf1(QString x) const { field1->setCurrentIndex(field1->findText(x)); } @@ -128,7 +129,7 @@ class TreeMapWindow : public GcWindow void useThruToday(); private: - // passed from MainWindow + // passed from Context * TMSettings settings; DateSettingsEdit *dateSetting; diff --git a/src/TtbDialog.cpp b/src/TtbDialog.cpp index 5e9503574..74ac5fe91 100644 --- a/src/TtbDialog.cpp +++ b/src/TtbDialog.cpp @@ -17,13 +17,9 @@ */ #include "TtbDialog.h" +#include "MainWindow.h" +#include "Athlete.h" #include "Settings.h" -#include -#include -#include -#include -#include -#include #include "TimeUtils.h" #include "Units.h" @@ -85,14 +81,11 @@ protected: }; -TtbDialog::TtbDialog(MainWindow *mainWindow, RideItem *item) : - mainWindow(mainWindow), +TtbDialog::TtbDialog(Context *context, RideItem *item) : + context(context), ride( item ), proMember( false ) { - assert(mainWindow); - assert(ride); - exerciseId = ride->ride()->getTag("TtbExercise", ""); setWindowTitle("Trainingstagebuch"); @@ -146,8 +139,8 @@ TtbDialog::requestSettings() currentRequest = reqSettings; - QString username = appsettings->cvalue(mainWindow->athlete->cyclist, GC_TTBUSER).toString(); - QString password = appsettings->cvalue(mainWindow->athlete->cyclist, GC_TTBPASS).toString(); + QString username = appsettings->cvalue(context->athlete->cyclist, GC_TTBUSER).toString(); + QString password = appsettings->cvalue(context->athlete->cyclist, GC_TTBPASS).toString(); QUrl url( TTB_URL + "/settings/list" ); url.addQueryItem( "view", "xml" ); @@ -170,8 +163,8 @@ TtbDialog::requestSession() currentRequest = reqSession; - QString username = appsettings->cvalue(mainWindow->athlete->cyclist, GC_TTBUSER).toString(); - QString password = appsettings->cvalue(mainWindow->athlete->cyclist, GC_TTBPASS).toString(); + QString username = appsettings->cvalue(context->athlete->cyclist, GC_TTBUSER).toString(); + QString password = appsettings->cvalue(context->athlete->cyclist, GC_TTBPASS).toString(); QUrl url( TTB_URL + "/login/sso" ); url.addQueryItem( "view", "xml" ); @@ -203,12 +196,12 @@ TtbDialog::requestUpload() body->append( textPart ); - QString fname = mainWindow->athlete->home.absoluteFilePath(".ttbupload.tcx" ); + QString fname = context->athlete->home.absoluteFilePath(".ttbupload.tcx" ); QFile *uploadFile = new QFile( fname ); uploadFile->setParent(body); TcxFileReader reader; - reader.writeRideFile( mainWindow, ride->ride(), *uploadFile ); + reader.writeRideFile(context, ride->ride(), *uploadFile ); progressBar->setValue(12); int limit = proMember diff --git a/src/TtbDialog.h b/src/TtbDialog.h index 62977812d..de2ae27e1 100644 --- a/src/TtbDialog.h +++ b/src/TtbDialog.h @@ -22,7 +22,14 @@ #include #include -#include "MainWindow.h" +#include +#include +#include +#include +#include +#include +#include +#include "Context.h" #include "RideItem.h" class TtbDialog : public QDialog @@ -31,7 +38,7 @@ class TtbDialog : public QDialog G_OBJECT public: - TtbDialog(MainWindow *mainWindow, RideItem *item); + TtbDialog(Context *context, RideItem *item); signals: @@ -61,7 +68,7 @@ private: reqUpload, }; - MainWindow *mainWindow; + Context *context; RideItem *ride; QProgressBar *progressBar; diff --git a/src/VideoWindow.cpp b/src/VideoWindow.cpp index dae1c75a8..6ffd65f1a 100644 --- a/src/VideoWindow.cpp +++ b/src/VideoWindow.cpp @@ -17,8 +17,9 @@ */ #include "VideoWindow.h" +#include "Context.h" -VideoWindow::VideoWindow(MainWindow *parent, const QDir &home) : +VideoWindow::VideoWindow(Context *parent, const QDir &home) : GcWindow(parent), home(home), main(parent), m_MediaChanged(false) { setControls(NULL); diff --git a/src/VideoWindow.h b/src/VideoWindow.h index fd83a7c21..3c317f81f 100644 --- a/src/VideoWindow.h +++ b/src/VideoWindow.h @@ -33,7 +33,7 @@ extern "C" { // QT stuff etc #include #include -#include "MainWindow.h" +#include "Context.h" #include "DeviceConfiguration.h" #include "DeviceTypes.h" #include "RealtimeData.h" @@ -68,7 +68,7 @@ class VideoWindow : public GcWindow public: - VideoWindow(MainWindow *, const QDir &); + VideoWindow(Context *, const QDir &); ~VideoWindow(); public slots: @@ -84,9 +84,9 @@ class VideoWindow : public GcWindow void resizeEvent(QResizeEvent *); - // passed from MainWindow + // passed from Context * QDir home; - MainWindow *main; + Context *context; bool m_MediaChanged; diff --git a/src/WattsPerKilogram.cpp b/src/WattsPerKilogram.cpp index ce0750621..4efcba9e3 100644 --- a/src/WattsPerKilogram.cpp +++ b/src/WattsPerKilogram.cpp @@ -45,7 +45,7 @@ class AverageWPK : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &deps, - const MainWindow *) { + const Context *) { // unconst naughty boy RideFile *uride = const_cast(ride); @@ -81,7 +81,7 @@ class PeakWPK : public RideMetric { void compute(const RideFile *ride, const Zones *, int, const HrZones *, int, const QHash &, - const MainWindow *) { + const Context *) { // unconst naughty boy RideFile *uride = const_cast(ride); @@ -300,7 +300,7 @@ class Vo2max : public RideMetric { void compute(const RideFile *, const Zones *, int, const HrZones *, int, const QHash &deps, - const MainWindow *) { + const Context *) { PeakWPK5m *wpk5m = dynamic_cast(deps.value("5m_peak_wpk")); setValue(wpk5m->value(false) * 12 + 3.5); diff --git a/src/WithingsDownload.cpp b/src/WithingsDownload.cpp index 4f4808e20..36d30b06f 100644 --- a/src/WithingsDownload.cpp +++ b/src/WithingsDownload.cpp @@ -17,8 +17,10 @@ */ #include "WithingsDownload.h" +#include "MainWindow.h" +#include "Athlete.h" -WithingsDownload::WithingsDownload(MainWindow *main) : main(main) +WithingsDownload::WithingsDownload(Context *context) : context(context) { nam = new QNetworkAccessManager(this); connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(downloadFinished(QNetworkReply*))); @@ -29,15 +31,15 @@ bool WithingsDownload::download() { QString request = QString("%1/measure?action=getmeas&userid=%2&publickey=%3") - .arg(appsettings->cvalue(main->athlete->cyclist, GC_WIURL, "http://wbsapi.withings.net").toString()) - .arg(appsettings->cvalue(main->athlete->cyclist, GC_WIUSER, "").toString()) - .arg(appsettings->cvalue(main->athlete->cyclist, GC_WIKEY, "").toString()); + .arg(appsettings->cvalue(context->athlete->cyclist, GC_WIURL, "http://wbsapi.withings.net").toString()) + .arg(appsettings->cvalue(context->athlete->cyclist, GC_WIUSER, "").toString()) + .arg(appsettings->cvalue(context->athlete->cyclist, GC_WIKEY, "").toString()); QNetworkReply *reply = nam->get(QNetworkRequest(QUrl(request))); if (reply->error() != QNetworkReply::NoError) { - QMessageBox::warning(main, tr("Withings Data Download"), reply->errorString()); + QMessageBox::warning(context->mainWindow, tr("Withings Data Download"), reply->errorString()); return false; } return true; @@ -57,7 +59,7 @@ WithingsDownload::downloadFinished(QNetworkReply *reply) foreach (WithingsReading x, parser->readings()) { - QList list = main->athlete->metricDB->getAllMeasuresFor(x.when,x.when); + QList list = context->athlete->metricDB->getAllMeasuresFor(x.when,x.when); bool presentOrEmpty = false; for (int i=0;iathlete->metricDB->importMeasure(&add); + context->athlete->metricDB->importMeasure(&add); if (olderDate.isNull() || x.whenmainWindow, tr("Withings Data Download"), status); if (!olderDate.isNull()) { - main->isclean = false; - main->athlete->metricDB->refreshMetrics(olderDate); + context->mainWindow->isclean = false; + context->athlete->metricDB->refreshMetrics(olderDate); } return; } diff --git a/src/WithingsDownload.h b/src/WithingsDownload.h index bdadbf54d..eeb340eb9 100644 --- a/src/WithingsDownload.h +++ b/src/WithingsDownload.h @@ -23,7 +23,7 @@ #include #include #include -#include "MainWindow.h" +#include "Context.h" #include "Settings.h" #include "WithingsParser.h" #include "MetricAggregator.h" @@ -35,14 +35,14 @@ class WithingsDownload : public QObject public: - WithingsDownload(MainWindow *main); + WithingsDownload(Context *context); bool download(); public slots: void downloadFinished(QNetworkReply *reply); private: - MainWindow *main; + Context *context; QNetworkAccessManager *nam; WithingsParser *parser; diff --git a/src/WorkoutPlotWindow.cpp b/src/WorkoutPlotWindow.cpp index 1991f6720..18410b187 100644 --- a/src/WorkoutPlotWindow.cpp +++ b/src/WorkoutPlotWindow.cpp @@ -18,9 +18,10 @@ #include "WorkoutPlotWindow.h" +#include "Context.h" -WorkoutPlotWindow::WorkoutPlotWindow(MainWindow *mainWindow) : - GcWindow(mainWindow), mainWindow(mainWindow) +WorkoutPlotWindow::WorkoutPlotWindow(Context *context) : + GcWindow(context), context(context) { setContentsMargins(0,0,0,0); setInstanceName("RT Plot"); @@ -30,13 +31,13 @@ WorkoutPlotWindow::WorkoutPlotWindow(MainWindow *mainWindow) : QVBoxLayout *layout = new QVBoxLayout(this); layout->setSpacing(0); layout->setContentsMargins(2,2,2,2); - ergPlot = new ErgFilePlot(mainWindow); + ergPlot = new ErgFilePlot(context); layout->addWidget(ergPlot); - connect(mainWindow->context, SIGNAL(setNow(long)), this, SLOT(setNow(long))); - connect(mainWindow->context, SIGNAL(ergFileSelected(ErgFile*)), this, SLOT(ergFileSelected(ErgFile*))); - connect(mainWindow->context, SIGNAL(telemetryUpdate(RealtimeData)), ergPlot, SLOT(performancePlot(RealtimeData))); - connect(mainWindow->context, SIGNAL(start()), ergPlot, SLOT(start())); + connect(context, SIGNAL(setNow(long)), this, SLOT(setNow(long))); + connect(context, SIGNAL(ergFileSelected(ErgFile*)), this, SLOT(ergFileSelected(ErgFile*))); + connect(context, SIGNAL(telemetryUpdate(RealtimeData)), ergPlot, SLOT(performancePlot(RealtimeData))); + connect(context, SIGNAL(start()), ergPlot, SLOT(start())); } void diff --git a/src/WorkoutPlotWindow.h b/src/WorkoutPlotWindow.h index 9afa5ec86..4ca9e66e8 100644 --- a/src/WorkoutPlotWindow.h +++ b/src/WorkoutPlotWindow.h @@ -19,13 +19,12 @@ #ifndef _GC_WorkoutPlotWindow_h #define _GC_WorkoutPlotWindow_h 1 #include "GoldenCheetah.h" -#include "RideWindow.h" #include #include // for Q_PROPERTY -#include "MainWindow.h" +#include "Context.h" #include "RideFile.h" // for data series types #include "ErgFilePlot.h" #include "RealtimeData.h" // for realtimedata structure @@ -40,7 +39,7 @@ class WorkoutPlotWindow : public GcWindow public: - WorkoutPlotWindow(MainWindow *mainWindow); + WorkoutPlotWindow(Context *context); public slots: @@ -50,7 +49,7 @@ class WorkoutPlotWindow : public GcWindow private: - MainWindow *mainWindow; + Context *context; ErgFilePlot *ergPlot; }; diff --git a/src/WorkoutWizard.cpp b/src/WorkoutWizard.cpp index b100bf204..6d68d1429 100644 --- a/src/WorkoutWizard.cpp +++ b/src/WorkoutWizard.cpp @@ -17,6 +17,8 @@ */ #include "WorkoutWizard.h" +#include "Context.h" +#include "Athlete.h" #include "qwt_plot.h" #include "qwt_plot_curve.h" @@ -25,7 +27,7 @@ // hack... Need to get the CP and zones for metrics -MainWindow *hackMW; +Context *hackContext; /// workout plot class WorkoutPlot: public QwtPlot @@ -222,8 +224,8 @@ void WorkoutTypePage::initializePage() relWattageRadioButton = new QRadioButton(tr("% FTP Wattage")); gradientRadioButton = new QRadioButton(tr("Gradient")); - if (hackMW->context->rideItem()) { - QString s = hackMW->context->rideItem()->ride()->startTime().toLocalTime().toString(); + if (hackContext->rideItem()) { + QString s = hackContext->rideItem()->ride()->startTime().toLocalTime().toString(); QString importStr = "Import Selected Ride (" + s + ")"; importRadioButton = new QRadioButton((importStr)); } else { @@ -298,7 +300,7 @@ void AbsWattagePage::updateMetrics() int curSecs = 0; // create rideFile QSharedPointer workout(new RideFile()); - workout->mainwindow = hackMW; + workout->context = hackContext; workout->setRecIntSecs(1); double curMin = 0; for(int i = 0; i < data.size() ; i++) @@ -339,7 +341,7 @@ void AbsWattagePage::updateMetrics() metrics.append("average_power"); metrics.append("skiba_bike_score"); metrics.append("skiba_xpower"); - QHash results = rm->computeMetrics(NULL,&*workout,hackMW->athlete->zones(),hackMW->athlete->hrZones(),metrics); + QHash results = rm->computeMetrics(NULL,&*workout,hackContext->athlete->zones(),hackContext->athlete->hrZones(),metrics); metricsSummary->updateMetrics(metrics,results); } @@ -386,8 +388,8 @@ RelWattagePage::RelWattagePage(QWidget *parent) : WorkoutPage(parent) {} void RelWattagePage::initializePage() { - int zoneRange = hackMW->athlete->zones()->whichRange(QDate::currentDate()); - ftp = hackMW->athlete->zones()->getCP(zoneRange); + int zoneRange = hackContext->athlete->zones()->whichRange(QDate::currentDate()); + ftp = hackContext->athlete->zones()->getCP(zoneRange); setTitle("Workout Wizard"); QString subTitle = "Relative Wattage Workout Wizard, current CP60 = " + QString::number(ftp); @@ -428,7 +430,7 @@ void RelWattagePage::updateMetrics() int curSecs = 0; // create rideFile QSharedPointer workout(new RideFile()); - workout->mainwindow = hackMW; + workout->context = hackContext; workout->setRecIntSecs(1); for(int i = 0; i < data.size() ; i++) { @@ -466,7 +468,7 @@ void RelWattagePage::updateMetrics() metrics.append("average_power"); metrics.append("skiba_bike_score"); metrics.append("skiba_xpower"); - QHash results = rm->computeMetrics(NULL,&*workout,hackMW->athlete->zones(),hackMW->athlete->hrZones(),metrics); + QHash results = rm->computeMetrics(NULL,&*workout,hackContext->athlete->zones(),hackContext->athlete->hrZones(),metrics); metricsSummary->updateMetrics(metrics,results); } @@ -512,9 +514,9 @@ GradientPage::GradientPage(QWidget *parent) : WorkoutPage(parent) {} void GradientPage::initializePage() { - int zoneRange = hackMW->athlete->zones()->whichRange(QDate::currentDate()); - ftp = hackMW->athlete->zones()->getCP(zoneRange); - metricUnits = hackMW->athlete->useMetricUnits; + int zoneRange = hackContext->athlete->zones()->whichRange(QDate::currentDate()); + ftp = hackContext->athlete->zones()->getCP(zoneRange); + metricUnits = hackContext->athlete->useMetricUnits; setTitle("Workout Wizard"); setSubTitle("Manually crate a workout based on gradient (slope) and distance, maxium grade is 5."); @@ -607,14 +609,14 @@ void ImportPage::initializePage() setFinalPage(true); QVBoxLayout *layout = new QVBoxLayout(); plot = new WorkoutPlot(); - metricUnits = hackMW->athlete->useMetricUnits; + metricUnits = hackContext->athlete->useMetricUnits; QString s = (metricUnits ? "KM" : "Miles"); QString distance = QString("Distance (") + s + QString(")"); plot->setXAxisTitle(distance); s = (metricUnits ? "Meters" : "Feet"); QString elevation = QString("elevation (") + s + QString(")"); plot->setYAxisTitle(elevation); - RideItem *rideItem = hackMW->context->rideItem(); + RideItem *rideItem = hackContext->rideItem(); if(rideItem == NULL) return; @@ -740,7 +742,7 @@ void ImportPage::SaveWorkout() WorkoutWizard::WorkoutWizard(QWidget *parent) :QWizard(parent) { - hackMW = (MainWindow *)parent; + hackContext = (Context *)parent; setPage(WW_WorkoutTypePage, new WorkoutTypePage()); setPage(WW_AbsWattagePage, new AbsWattagePage()); setPage(WW_RelWattagePage, new RelWattagePage()); diff --git a/src/WorkoutWizard.h b/src/WorkoutWizard.h index 5c2c01719..2a3730375 100644 --- a/src/WorkoutWizard.h +++ b/src/WorkoutWizard.h @@ -33,7 +33,7 @@ #include #include #include "RideFile.h" -#include "MainWindow.h" +#include "Context.h" #include "GoldenCheetah.h" #include "Settings.h" class QwtPlotCurve; @@ -281,7 +281,7 @@ class GradientPage : public WorkoutPage WorkoutEditorGradient *we; WorkoutMetricsSummary *metricsSummary; - MainWindow *mainWindow; + Context *context; int ftp; bool metricUnits; diff --git a/src/ZeoDownload.cpp b/src/ZeoDownload.cpp index e98eead4c..19071f1e5 100644 --- a/src/ZeoDownload.cpp +++ b/src/ZeoDownload.cpp @@ -17,10 +17,12 @@ */ #include "ZeoDownload.h" +#include "MainWindow.h" +#include "Athlete.h" #include "MetricAggregator.h" #include -ZeoDownload::ZeoDownload(MainWindow *main) : main(main) +ZeoDownload::ZeoDownload(Context *context) : context(context) { nam = new QNetworkAccessManager(this); connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(downloadFinished(QNetworkReply*))); @@ -28,8 +30,8 @@ ZeoDownload::ZeoDownload(MainWindow *main) : main(main) base_api_url = "/zeows/api/v1/sleeperService/"; api_key = "B8B1881541731200E67B902FC933E87E"; // GC key - QString _username = appsettings->cvalue(main->athlete->cyclist, GC_ZEOUSER, "").toString(); - QString _password = appsettings->cvalue(main->athlete->cyclist, GC_ZEOPASS, "").toString(); + QString _username = appsettings->cvalue(context->athlete->cyclist, GC_ZEOUSER, "").toString(); + QString _password = appsettings->cvalue(context->athlete->cyclist, GC_ZEOPASS, "").toString(); usernameAndPasswordEncoded = QString(_username + ":" + _password).toUtf8().toBase64(); } @@ -41,7 +43,7 @@ ZeoDownload::download() allMeasures = 0; // Build the URL to retrieve dates with sleep data. - QString url = appsettings->cvalue(main->athlete->cyclist, GC_ZEOURL, "http://app-pro.myzeo.com:8080").toString() + base_api_url + "getAllDatesWithSleepData" + "?key=" + api_key; + QString url = appsettings->cvalue(context->athlete->cyclist, GC_ZEOURL, "http://app-pro.myzeo.com:8080").toString() + base_api_url + "getAllDatesWithSleepData" + "?key=" + api_key; QNetworkRequest request = QNetworkRequest(QUrl(url)); request.setRawHeader("Authorization", "Basic " + usernameAndPasswordEncoded.toLatin1()); request.setRawHeader("Referer" , "http://www.goldencheetah.org"); @@ -50,7 +52,7 @@ ZeoDownload::download() QNetworkReply *reply = nam->get(request); if (reply->error() != QNetworkReply::NoError) { - QMessageBox::warning(main, tr("Zeo Data Download"), reply->errorString()); + QMessageBox::warning(context->mainWindow, tr("Zeo Data Download"), reply->errorString()); return false; } return true; @@ -102,7 +104,7 @@ ZeoDownload::downloadFinished(QNetworkReply *reply) add.setDateTime(QDateTime(dates.first(), QTime(0,0,0))); add.setText("Sleep index (ZQ)", QString("%1").arg(zq)); add.setText("Sleep time", QString("%1").arg(time)); - main->athlete->metricDB->importMeasure(&add); + context->athlete->metricDB->importMeasure(&add); } dates.removeFirst(); @@ -110,7 +112,7 @@ ZeoDownload::downloadFinished(QNetworkReply *reply) if (!nextDate()) { QString status = QString(tr("%1 new on %2 measurements received.")).arg(newMeasures).arg(allMeasures); - QMessageBox::information(main, tr("Zeo Data Download"), status); + QMessageBox::information(context->mainWindow, tr("Zeo Data Download"), status); } return; } @@ -124,7 +126,7 @@ ZeoDownload::nextDate() QString dateStr = date.toString("yyyy-MM-dd"); QDateTime dateTime = QDateTime(date, QTime(0,0,0)); - QList list = main->athlete->metricDB->getAllMeasuresFor(dateTime,dateTime); + QList list = context->athlete->metricDB->getAllMeasuresFor(dateTime,dateTime); for (int i=0;i0 && sm.getText("Sleep index (ZQ)", "").length()>0) { @@ -137,7 +139,7 @@ ZeoDownload::nextDate() if (!present) { newMeasures ++; // Build the URL to retrieve the stats for date - QString url = appsettings->cvalue(main->athlete->cyclist, GC_ZEOURL, "http://app-pro.myzeo.com:8080").toString() + base_api_url + "getSleepStatsForDate" + "?key=" + api_key + "&date=" + dateStr; + QString url = appsettings->cvalue(context->athlete->cyclist, GC_ZEOURL, "http://app-pro.myzeo.com:8080").toString() + base_api_url + "getSleepStatsForDate" + "?key=" + api_key + "&date=" + dateStr; QNetworkRequest request = QNetworkRequest(QUrl(url)); request.setRawHeader("Authorization", "Basic " + usernameAndPasswordEncoded.toLatin1()); request.setRawHeader("Referer" , "http://www.goldencheetah.org"); @@ -146,7 +148,7 @@ ZeoDownload::nextDate() QNetworkReply *reply = nam->get(request); if (reply->error() != QNetworkReply::NoError) { - QMessageBox::warning(main, tr("Zeo Data Download"), reply->errorString()); + QMessageBox::warning(context->mainWindow, tr("Zeo Data Download"), reply->errorString()); } else return true; } diff --git a/src/ZeoDownload.h b/src/ZeoDownload.h index 5c501ac65..edd79a4a8 100644 --- a/src/ZeoDownload.h +++ b/src/ZeoDownload.h @@ -23,7 +23,7 @@ #include #include #include -#include "MainWindow.h" +#include "Context.h" #include "Settings.h" #include "WithingsParser.h" #include "MetricAggregator.h" @@ -35,14 +35,14 @@ class ZeoDownload : public QObject public: - ZeoDownload(MainWindow *main); + ZeoDownload(Context *context); bool download(); public slots: void downloadFinished(QNetworkReply *reply); private: - MainWindow *main; + Context *context; QNetworkAccessManager *nam; QString host; diff --git a/src/src.pro b/src/src.pro index 8824cba17..2aec9cc8a 100644 --- a/src/src.pro +++ b/src/src.pro @@ -237,6 +237,7 @@ HEADERS += \ ANTMessage.h \ ANTMessages.h \ ANTlocalController.h \ + Athlete.h \ BatchExportDialog.h \ BestIntervalDialog.h \ BinRideFile.h \ @@ -252,6 +253,7 @@ HEADERS += \ Computrainer.h \ Computrainer3dpFile.h \ ConfigDialog.h \ + Context.h \ CpintPlot.h \ CriticalPowerWindow.h \ CsvRideFile.h \ @@ -586,8 +588,7 @@ SOURCES += \ Zones.cpp \ main.cpp \ -RESOURCES = application.qrc \ - RideWindow.qrc +RESOURCES = application.qrc TRANSLATIONS = translations/gc_fr.ts \ translations/gc_ja.ts \
%1: %2
%1(%2): %3
Interval Name