Ejemplo n.º 1
1
HRESULT STDMETHODCALLTYPE BrowserEvents2::Invoke(
        /* [in] */ DISPID dispId,
        /* [in] */ REFIID riid,
        /* [in] */ LCID lcid,
        /* [in] */ WORD wFlags,
        /* [out][in] */ DISPPARAMS *pDispParams,
        /* [out] */ VARIANT *pVarResult,
        /* [out] */ EXCEPINFO *pExcepInfo,
        /* [out] */ UINT *puArgErr) {

    // When returning a result, you must check whether pVarResult
    // is not NULL and initialize it using VariantInit(). If it's
    // NULL then it doesn't expect a result.
    if (riid != IID_NULL)
        return DISP_E_UNKNOWNINTERFACE;
    pExcepInfo = 0;
    puArgErr = 0;
    HRESULT hr;
    json_value* settings = GetApplicationSettings();

    if (dispId == DISPID_NEWWINDOW3) {
        /* When calling window.open() you get an error "Class
           not registered". Before this error appears
           DWebBrowserEvents2::NewWindow3 event is dispatched,
           you need to create the popup window in this event
           and assign the dispatch interface of the new popup
           browser to the first parameter of NewWindow3. */
        LOG_DEBUG << "BrowserEvents2::NewWindow3()";
        if (pDispParams->cArgs != 5) {
            LOG_WARNING << "BrowserEvents2::NewWindow3() failed: "
                    "Expected 5 arguments";
            _ASSERT(false);
            return DISP_E_BADPARAMCOUNT;
        }
        // ppDisp
        _ASSERT(pDispParams->rgvarg[4].vt == (VT_DISPATCH | VT_BYREF));
        // Cancel
        _ASSERT(pDispParams->rgvarg[3].vt == (VT_BOOL | VT_BYREF));
        // dwFlags
        _ASSERT(pDispParams->rgvarg[2].vt == VT_I4);
        // bstrUrlContext
        _ASSERT(pDispParams->rgvarg[1].vt == VT_BSTR);
        // bstrUrl
        _ASSERT(pDispParams->rgvarg[0].vt == VT_BSTR);

        HWND popupHandle = CreatePopupWindow(
                browserWindow_->GetWindowHandle());
        _ASSERT(popupHandle);
        BrowserWindow* browserWindow = GetBrowserWindow(popupHandle);
        if (!browserWindow) {
            LOG_WARNING << "BrowserEvents2::NewWindow3() failed: "
                           "CreatePopupWindow() failed";
            // Cancel parameter. Current navigation should be cancelled.
            *pDispParams->rgvarg[3].pboolVal = VARIANT_TRUE;
            return S_OK;
        }
        const IWebBrowser2Ptr webBrowser2 = browserWindow->GetWebBrowser2();
        IDispatchPtr dispatch;
        hr = webBrowser2->get_Application(&dispatch);
        if (FAILED(hr) || !dispatch) {
            LOG_WARNING << "BrowserEvents2::NewWindow3() failed: "
                           "webBrowser2->get_Application() failed";
            return S_OK;
        }

        *pDispParams->rgvarg[4].ppdispVal = dispatch.Detach();
        *pDispParams->rgvarg[3].pboolVal = VARIANT_FALSE;

        // Following events (DWebBrowserEvents2) will appear
        // after popup creation, they inform about "features"
        // passed to "window.open", such as width, height and others:
        // DISPID_ONTOOLBAR
        // DISPID_ONADDRESSBAR
        // DISPID_WINDOWSETRESIZABLE
        // DISPID_ONMENUBAR
        // DISPID_ONSTATUSBAR
        // DISPID_ONFULLSCREEN
        // DISPID_CLIENTTOHOSTWINDOW
        // DISPID_WINDOWSETWIDTH
        // DISPID_WINDOWSETHEIGHT
        // DISPID_WINDOWSETTOP
        // DISPID_WINDOWSETLEFT
        // DISPID_NAVIGATECOMPLETE2
        return S_OK;
    } else if (dispId == DISPID_WINDOWSETWIDTH) {
        _ASSERT(pDispParams->cArgs == 1);
        _ASSERT(pDispParams->rgvarg[0].vt == VT_I4); // nWidth
        long width = pDispParams->rgvarg[0].lVal;
        // LOG_DEBUG << "BrowserEvents2::WindowSetWidth(): width = "
        //           << width;
        browserWindow_->SetWidth(width);
    } else if (dispId == DISPID_WINDOWSETHEIGHT) {
        _ASSERT(pDispParams->cArgs == 1);
        _ASSERT(pDispParams->rgvarg[0].vt == VT_I4); // nHeight
        long height = pDispParams->rgvarg[0].lVal;
        // LOG_DEBUG << "BrowserEvents2::WindowSetHeight(): height = "
        //           << height;
        browserWindow_->SetHeight(height);
    } else if (dispId == DISPID_WINDOWSETTOP) {
        _ASSERT(pDispParams->cArgs == 1);
        _ASSERT(pDispParams->rgvarg[0].vt == VT_I4); // nTop
        long top = pDispParams->rgvarg[0].lVal;
        // LOG_DEBUG << "BrowserEvents2::WindowSetTop(): top = "
        //           << top;
        browserWindow_->SetTop(top);
    } else if (dispId == DISPID_WINDOWSETLEFT) {
        _ASSERT(pDispParams->cArgs == 1);
        _ASSERT(pDispParams->rgvarg[0].vt == VT_I4); // nLeft
        long left = pDispParams->rgvarg[0].lVal;
        // LOG_DEBUG << "BrowserEvents2::WindowSetLeft(): left = "
        //           << left;
        browserWindow_->SetLeft(left);
    } else if (dispId == DISPID_TITLECHANGE) {
        if (browserWindow_->IsPopup()
                && browserWindow_->IsUsingMetaTitle()) {
            _ASSERT(pDispParams->cArgs == 1);
            _ASSERT(pDispParams->rgvarg[0].vt == VT_BSTR); // Text
            BSTR title = pDispParams->rgvarg[0].bstrVal;
            // LOG_DEBUG << "BrowserEvents2::TitleChange(): "
            //              "setting popup title = " << WideToUtf8(title);
            browserWindow_->SetTitle(title);
        }
    } else if (dispId == DISPID_NAVIGATEERROR) {
        LOG_DEBUG << "BrowserEvents2::NavigateError()";
        if (pDispParams->cArgs != 5) {
            LOG_WARNING << "BrowserEvents2::NavigateError() failed: "
                    "Expected 5 arguments";
            _ASSERT(false);
            return DISP_E_BADPARAMCOUNT;
        }
        // pDisp
        _ASSERT(pDispParams->rgvarg[4].vt == VT_DISPATCH);
        // URL
        _ASSERT(pDispParams->rgvarg[3].vt == (VT_VARIANT | VT_BYREF));
        _ASSERT(pDispParams->rgvarg[3].pvarVal->vt == VT_BSTR);
        // TargetFrameName
        _ASSERT(pDispParams->rgvarg[2].vt == (VT_VARIANT | VT_BYREF));
        _ASSERT(pDispParams->rgvarg[2].pvarVal->vt == VT_BSTR);
        // StatusCode
        _ASSERT(pDispParams->rgvarg[1].vt == (VT_VARIANT | VT_BYREF));
        _ASSERT(pDispParams->rgvarg[1].pvarVal->vt == VT_I4);
        // Cancel
        _ASSERT(pDispParams->rgvarg[0].vt == (VT_BOOL | VT_BYREF));

        const wchar_t* navigateUrl = pDispParams->rgvarg[3].pvarVal->bstrVal;
        int statusCode = pDispParams->rgvarg[1].pvarVal->lVal;

        if (browserWindow_->DisplayErrorPage(navigateUrl, statusCode)) {
            *pDispParams->rgvarg[0].pboolVal = VARIANT_TRUE;
            return S_OK;
        } else {
            *pDispParams->rgvarg[0].pboolVal = VARIANT_FALSE;
            return S_OK;
        }
    } else if (dispId == DISPID_WINDOWCLOSING) {
        // Seems like this event is never being called, it should be
        // called when executing "window.close()", but it's not.
        // Use WM_PARENTNOTIFY instead to be notified when window is closing.
        LOG_DEBUG << "BrowserEvents2::WindowClosing()";
        return S_OK;
        /*
        if (pDispParams->cArgs != 2) {
            LOG_WARNING << "BrowserEvents2::WindowClosing() failed: "
                    "Expected 2 arguments";
            _ASSERT(false);
            return DISP_E_BADPARAMCOUNT;
        }
        // bIsChildWindow
        _ASSERT(pDispParams->rgvarg[1].vt == VT_BOOL);
        // Cancel
        _ASSERT(pDispParams->rgvarg[0].vt == (VT_BOOL | VT_BYREF));

        // VARIANT_FALSE - window is allowed to close..
        *pDispParams->rgvarg[0].pboolVal = VARIANT_FALSE;
        return S_OK;
        */
    }
    return S_OK;
}
Ejemplo n.º 2
0
 void readConfig() {
     boost::shared_ptr<QSettings> settings = GetApplicationSettings();
     double tol = settings->value(GC_DPFG_TOLERANCE, "1.0").toDouble();
     double stop = settings->value(GC_DPFG_STOP, "1.0").toDouble();
     tolerance->setValue(tol);
     beerandburrito->setValue(stop);
 }
Ejemplo n.º 3
0
void BrowserWindow::SetCefBrowser(CefRefPtr<CefBrowser> cefBrowser) {
    // Called from ClientHandler::OnAfterCreated().
    _ASSERT(!cefBrowser_);
    if (cefBrowser_) {
        LOG_ERROR << "BrowserWindow::SetCefBrowser() called, "
                  << "but it is already set";
        return;
    }
    cefBrowser_ = cefBrowser;
    fullscreen_.reset(new Fullscreen(cefBrowser));
    json_value* appSettings = GetApplicationSettings();
    if (!IsPopup()) {
        bool start_fullscreen = (*appSettings)["main_window"]["start_fullscreen"];
        if (start_fullscreen) {
            fullscreen_->ToggleFullscreen();
            CefRefPtr<CefProcessMessage> message = \
                    CefProcessMessage::Create("SetIsFullscreen");
            message->GetArgumentList()->SetBool(0, fullscreen_->IsFullscreen());
            cefBrowser->SendProcessMessage(PID_RENDERER, message);
        }
    }

    // OnSize was called from WM_SIZE, but cefBrowser_ was not yet
    // set, so the window wasn't yet positioned correctly.
    this->OnSize();
}
Ejemplo n.º 4
0
bool BrowserWindow::IsUsingMetaTitle() {
    if (IsPopup()) {
        json_value* settings = GetApplicationSettings();
        std::string fixed_title = (*settings)["popup_window"]["fixed_title"];
        return fixed_title.empty();
    }
    return false;
}
Ejemplo n.º 5
0
HRESULT STDMETHODCALLTYPE HostDispatch::Invoke(
        /* [in] */ DISPID dispId,
        /* [in] */ REFIID riid,
        /* [in] */ LCID lcid,
        /* [in] */ WORD wFlags,
        /* [out][in] */ DISPPARAMS *pDispParams,
        /* [out] */ VARIANT *pVarResult,
        /* [out] */ EXCEPINFO *pExcepInfo,
        /* [out] */ UINT *puArgErr) {

    // When returning a result, you must check whether pVarResult
    // is not NULL and initialize it using VariantInit(). If it's
    // NULL then it doesn't expect a result.

    if (riid != IID_NULL)
        return DISP_E_UNKNOWNINTERFACE;
    pExcepInfo = 0;
    puArgErr = 0;
    json_value* settings = GetApplicationSettings();
    bool silent_operations = (*settings)["msie"]["silent_operations"];

    // DLCTL_* constants:
    // http://msdn.microsoft.com/en-us/library/aa741313(v=vs.85).aspx
    // #Download_Control

    if (dispId == DISPID_AMBIENT_DLCONTROL) {
        LOG_DEBUG << "DISPID_AMBIENT_DLCONTROL";
        // DLCTL_BGSOUNDS - The browsing component will play background
        //                  sounds associated with the document.
        // DLCTL_DLIMAGES - The browsing component will download images from
        //                  the server.
        // DLCTL_VIDEOS - The browsing component will play any video clips
        //                that are contained in the document.
        // DLCTL_PRAGMA_NO_CACHE - The browsing component will force the
        //                         request through to the server and ignore
        //                         the proxy, even if the proxy indicates that
        //                         the data is up to date.
        // DLCTL_RESYNCHRONIZE - The browsing component will ignore what is
        //                       in the cache and ask the server for updated
        //                       information. The cached information will be
        //                       used if the server indicates that the cached
        //                       information is up to date.
        // DLCTL_SILENT - The browsing component will not display any user
        //                interface.
        pVarResult->vt = VT_I4;
        pVarResult->lVal = DLCTL_DLIMAGES | DLCTL_VIDEOS
                | DLCTL_PRAGMA_NO_CACHE | DLCTL_RESYNCHRONIZE;
        if (silent_operations) {
            pVarResult->lVal |= DLCTL_SILENT;
        }
        return S_OK;
    }

    return DISP_E_MEMBERNOTFOUND;
}
Ejemplo n.º 6
0
PowerHist::PowerHist(MainWindow *mainWindow):
    selected(watts),
    shade(false),
    rideItem(NULL),
    mainWindow(mainWindow),
    withz(true),
    unit(0),
    lny(false),
    absolutetime(true)
{

    boost::shared_ptr<QSettings> settings = GetApplicationSettings();
    unit = settings->value(GC_UNIT);

    useMetricUnits = (unit.toString() == "Metric");

    binw = settings->value(GC_HIST_BIN_WIDTH, 5).toInt();
    shade = true;

    // create a background object for shading
    bg = new PowerHistBackground(this);
    bg->attach(this);
    hrbg = new HrHistBackground(this);
    hrbg->attach(this);

    setCanvasBackground(Qt::white);

    setParameterAxisTitle();
    setAxisTitle(yLeft, absolutetime ? tr("Time (minutes)") : tr("Time (percent)"));

    curve = new QwtPlotCurve("");
    curve->setStyle(QwtPlotCurve::Steps);
    curve->setRenderHint(QwtPlotItem::RenderAntialiased);
    curve->attach(this);

    curveSelected = new QwtPlotCurve("");
    curveSelected->setStyle(QwtPlotCurve::Steps);
    curveSelected->setRenderHint(QwtPlotItem::RenderAntialiased);
    curveSelected->attach(this);

    grid = new QwtPlotGrid();
    grid->enableX(false);
    grid->attach(this);

    zoneLabels = QList<PowerHistZoneLabel *>();
    hrzoneLabels = QList<HrHistZoneLabel *>();

    zoomer = new penTooltip(this->canvas());
    canvasPicker = new LTMCanvasPicker(this);
    connect(canvasPicker, SIGNAL(pointHover(QwtPlotCurve*, int)), this, SLOT(pointHover(QwtPlotCurve*, int)));

    configChanged();
}
Ejemplo n.º 7
0
void BrowserWindow::SetTitleFromSettings() {
    if (IsPopup()) {
        json_value* settings = GetApplicationSettings();
        std::wstring popup_title = (*settings)["popup_window"]["fixed_title"];
        if (popup_title.empty())
            popup_title = (*settings)["main_window"]["title"];
        if (popup_title.empty())
            popup_title = Utf8ToWide(GetExecutableName());
        SetTitle(popup_title.c_str());
    }
    // Main window title is set in CreateMainWindow().
}
Ejemplo n.º 8
0
void
AllPlot::configChanged()
{

    double width = 1.0;

    boost::shared_ptr<QSettings> settings = GetApplicationSettings();
    useMetricUnits = (settings->value(GC_UNIT).toString() == "Metric");

    // placeholder for setting antialiasing, will come
    // in with a future patch. For now antialiasing is
    // not enabled since it can slow down plotting on
    // windows and linux platforms.
    if (false) {
        wattsCurve->setRenderHint(QwtPlotItem::RenderAntialiased);
        hrCurve->setRenderHint(QwtPlotItem::RenderAntialiased);
        speedCurve->setRenderHint(QwtPlotItem::RenderAntialiased);
        cadCurve->setRenderHint(QwtPlotItem::RenderAntialiased);
        altCurve->setRenderHint(QwtPlotItem::RenderAntialiased);
        intervalHighlighterCurve->setRenderHint(QwtPlotItem::RenderAntialiased);
    }

    setCanvasBackground(GColor(CPLOTBACKGROUND));
    QPen wattsPen = QPen(GColor(CPOWER));
    wattsPen.setWidth(width);
    wattsCurve->setPen(wattsPen);
    QPen hrPen = QPen(GColor(CHEARTRATE));
    hrPen.setWidth(width);
    hrCurve->setPen(hrPen);
    QPen speedPen = QPen(GColor(CSPEED));
    speedPen.setWidth(width);
    speedCurve->setPen(speedPen);
    QPen cadPen = QPen(GColor(CCADENCE));
    cadPen.setWidth(width);
    cadCurve->setPen(cadPen);
    QPen altPen(GColor(CALTITUDE));
    altPen.setWidth(width);
    altCurve->setPen(altPen);
    QColor brush_color = GColor(CALTITUDEBRUSH);
    brush_color.setAlpha(200);
    altCurve->setBrush(brush_color);   // fill below the line
    QPen ihlPen = QPen(GColor(CINTERVALHIGHLIGHTER));
    ihlPen.setWidth(width);
    intervalHighlighterCurve->setPen(ihlPen);
    QColor ihlbrush = QColor(GColor(CINTERVALHIGHLIGHTER));
    ihlbrush.setAlpha(64);
    intervalHighlighterCurve->setBrush(ihlbrush);   // fill below the line
    this->legend()->remove(intervalHighlighterCurve); // don't show in legend
    QPen gridPen(GColor(CPLOTGRID));
    gridPen.setStyle(Qt::DotLine);
    grid->setPen(gridPen);
}
Ejemplo n.º 9
0
bool
FixTorque::postProcess(RideFile *ride, DataProcessorConfig *config=0)
{
    // does this ride have torque?
    if (ride->areDataPresent()->nm == false) return false;

    // Lets do it then!
    QString ta;
    double nmAdjust;

    if (config == NULL) { // being called automatically
        boost::shared_ptr<QSettings> settings = GetApplicationSettings();
        ta = settings->value(GC_DPTA, "0 nm").toString();
    } else { // being called manually
        ta = ((FixTorqueConfig*)(config))->ta->text();
    }

    // patrick's torque adjustment code
    bool pi = ta.endsWith("pi", Qt::CaseInsensitive);
    if (pi || ta.endsWith("nm", Qt::CaseInsensitive)) {
        nmAdjust = ta.left(ta.length() - 2).toDouble();
        if (pi) {
            nmAdjust *= 0.11298482933;
        }
    } else {
        nmAdjust = ta.toDouble();
    }

    // no adjustment required
    if (nmAdjust == 0) return false;

    // apply the change
    ride->command->startLUW("Adjust Torque");
    for (int i=0; i<ride->dataPoints().count(); i++) {
        RideFilePoint *point = ride->dataPoints()[i];

      if (point->nm != 0) {
            double newnm = point->nm + nmAdjust;
            ride->command->setPointValue(i, RideFile::watts, point->watts * (newnm / point->nm));
            ride->command->setPointValue(i, RideFile::nm, newnm);
        }
    }
    ride->command->endLUW();

    double currentta = ride->getTag("Torque Adjust", "0.0").toDouble();
    ride->setTag("Torque Adjust", QString("%1 nm").arg(currentta + nmAdjust));

    return true;
}
Ejemplo n.º 10
0
void
RealtimeWindow::configUpdate()
{

    // config has been updated! so re-read
    // wipe out all the current entries
    deviceSelector->clear();
    streamSelector->clear();

    // metric or imperial changed?
    boost::shared_ptr<QSettings> settings = GetApplicationSettings();
    QVariant unit = settings->value(GC_UNIT);
    useMetricUnits = (unit.toString() == "Metric");

    // set labels accordingly
    distanceLabel->setText(useMetricUnits ? tr("Distance (KM)") : tr("Distance (Miles)"));
    speedLabel->setText(useMetricUnits ? tr("KPH") : tr("MPH"));
    avgspeedLabel->setText(useMetricUnits ? tr("Avg KPH") : tr("Avg MPH"));

    // get configured devices
    DeviceConfigurations all;

    Devices.clear();
    Devices = all.getList();

    streamSelector->addItem("No streaming", -1);
    for (int i=0; i<Devices.count(); i++) {
        // add streamers
        if (Devices.at(i).type == DEV_GSERVER)
            streamSelector->addItem(Devices.at(i).name, i);

        // add data sources
        deviceSelector->addItem(Devices.at(i).name, i);
    }

    deviceSelector->setCurrentIndex(0);
    streamSelector->setCurrentIndex(0);

    // reconnect - otherwise after no config they still get an error
    if (Devices.count() > 0) {
        disconnect(startButton, SIGNAL(clicked()), this, SLOT(warnnoConfig()));
        disconnect(pauseButton, SIGNAL(clicked()), this, SLOT(warnnoConfig()));
        disconnect(stopButton, SIGNAL(clicked()), this, SLOT(warnnoConfig()));
        connect(startButton, SIGNAL(clicked()), this, SLOT(Start()));
        connect(pauseButton, SIGNAL(clicked()), this, SLOT(Pause()));
        connect(stopButton, SIGNAL(clicked()), this, SLOT(Stop()));
    }
}
Ejemplo n.º 11
0
// serialise/deserialise config
QList<DeviceConfiguration>
DeviceConfigurations::readConfig()
{
    int count;

    boost::shared_ptr<QSettings> settings = GetApplicationSettings();

    // get count of devices
    QVariant configVal = settings->value(GC_DEV_COUNT);
    if (configVal.isNull()) {
        count=0;
    } else {
        count = configVal.toInt();
    }

    // for each device
    for (int i=0; i< count; i++) {

            DeviceConfiguration Entry;

            QString configStr = QString("%1%2").arg(GC_DEV_NAME).arg(i+1);
            configVal = settings->value(configStr);
            Entry.name = configVal.toString();

            configStr = QString("%1%2").arg(GC_DEV_SPEC).arg(i+1);
            configVal = settings->value(configStr);
            Entry.portSpec = configVal.toString();

            configStr = QString("%1%2").arg(GC_DEV_TYPE).arg(i+1);
            configVal = settings->value(configStr);
            Entry.type = configVal.toInt();

            configStr = QString("%1%2").arg(GC_DEV_PROF).arg(i+1);
            configVal = settings->value(configStr);
            Entry.deviceProfile = configVal.toString();

            configStr = QString("%1%2").arg(GC_DEV_DEFI).arg(i+1);
            configVal = settings->value(configStr);
            Entry.isDefaultDownload = configVal.toInt();

            configStr = QString("%1%2").arg(GC_DEV_DEFR).arg(i+1);
            configVal = settings->value(configStr);
            Entry.isDefaultRealtime = configVal.toInt();

            Entries.append(Entry);
    }
    return Entries;
}
Ejemplo n.º 12
0
void
GCColor::readConfig()
{
    boost::shared_ptr<QSettings> settings = GetApplicationSettings();
    // read in config settings and populate the color table
    for (unsigned int i=0; ColorList[i].name != ""; i++) {
        QString colortext = settings->value(ColorList[i].setting, "").toString();
        if (colortext != "") {
            // color definitions are stored as "r:g:b"
            QStringList rgb = colortext.split(":");
            ColorList[i].color = QColor(rgb[0].toInt(),
                                        rgb[1].toInt(),
                                        rgb[2].toInt());
        }
    }
}
Ejemplo n.º 13
0
PfPvPlot::PfPvPlot()
    : rideItem (NULL),
      cp_ (0),
      cad_ (85),
      cl_ (0.175),
      shade_zones(true)
{
    setCanvasBackground(Qt::white);

    setAxisTitle(yLeft, "Average Effective Pedal Force (N)");
    setAxisScale(yLeft, 0, 600);
    setAxisTitle(xBottom, "Circumferential Pedal Velocity (m/s)");
    setAxisScale(xBottom, 0, 3);

    mX = new QwtPlotMarker();
    mX->setLineStyle(QwtPlotMarker::VLine);
    mX->attach(this);

    mY = new QwtPlotMarker();
    mY->setLineStyle(QwtPlotMarker::HLine);
    mY->attach(this);

    cpCurve = new QwtPlotCurve();
    cpCurve->setRenderHint(QwtPlotItem::RenderAntialiased);
    cpCurve->attach(this);

    curve = new QwtPlotCurve();
    QwtSymbol sym;
    sym.setStyle(QwtSymbol::Ellipse);
    sym.setSize(6);
    sym.setPen(QPen(Qt::red));
    sym.setBrush(QBrush(Qt::NoBrush));
    
    curve->setSymbol(sym);
    curve->setStyle(QwtPlotCurve::Dots);
    curve->setRenderHint(QwtPlotItem::RenderAntialiased);
    curve->attach(this);
    
    boost::shared_ptr<QSettings> settings = GetApplicationSettings();
 
    cl_ = settings->value(GC_CRANKLENGTH).toDouble() / 1000.0;

    recalc();
}
Ejemplo n.º 14
0
/*--cef(optional_param=process_type)--*/
void App::OnBeforeCommandLineProcessing(
        const CefString& process_type,
        CefRefPtr<CefCommandLine> command_line) {
    // May be called on any thread?
    if (process_type.empty()) {
        // Browser process.
        json_value* appSettings = GetApplicationSettings();
        json_value switches = (*appSettings)["chrome"]["command_line_switches"];
        if (switches.type == json_object) {
            int length = switches.u.object.length;
            for (int i = 0; i < length; i++) {
                std::string name = switches.u.object.values[i].name;
                std::string value = (*switches.u.object.values[i].value);
                if (name.find("-") == 0) {
                    LOG_WARNING << "Invalid command line switch: " << name;
                    continue;
                }
                if (command_line->HasSwitch(name)) {
                    if (value.empty()) {
                        // Switch already set, do nothing.
                    } else {
                        std::string oldValue = command_line->GetSwitchValue(name);
                        if (oldValue != value) {
                            // Overwrite the switch with a new value.
                            command_line->AppendSwitchWithValue(name, value);
                        }
                    }
                } else {
                    if (value.empty()) {
                        command_line->AppendSwitch(name);
                    } else {
                        command_line->AppendSwitchWithValue(name, value);
                    }
                }
            }
        }
    }
    std::string process_name = "browser";
    if (!process_type.empty()) {
        process_name = process_type;
    }
    LOG_DEBUG << "Command line string for the " << process_name << " process: "
              << command_line->GetCommandLineString().ToString();
}
Ejemplo n.º 15
0
void BrowserWindow::SetIconFromSettings() {
    json_value* settings = GetApplicationSettings();
    const char* iconPath;
    if (IsPopup())
        iconPath = (*settings)["popup_window"]["icon"];
    else
        iconPath = (*settings)["main_window"]["icon"];
    if (iconPath && iconPath[0] != 0) {
        wchar_t iconPathW[MAX_PATH];
        Utf8ToWide(iconPath, iconPathW, _countof(iconPathW));
        int bigX = GetSystemMetrics(SM_CXICON);
        int bigY = GetSystemMetrics(SM_CYICON);
        HANDLE bigIcon = LoadImage(0, iconPathW, IMAGE_ICON, bigX, bigY,
                                   LR_LOADFROMFILE);
        if (bigIcon) {
            SendMessage(windowHandle_, WM_SETICON, ICON_BIG, (LPARAM)bigIcon);
        } else {
            LOG_WARNING << "Setting icon from settings file failed "
                           "(ICON_BIG)";
        }
        int smallX = GetSystemMetrics(SM_CXSMICON);
        int smallY = GetSystemMetrics(SM_CYSMICON);
        HANDLE smallIcon = LoadImage(0, iconPathW, IMAGE_ICON, smallX,
                                     smallY, LR_LOADFROMFILE);
        if (smallIcon) {
            SendMessage(windowHandle_, WM_SETICON, ICON_SMALL, (LPARAM)smallIcon);
        } else {
            LOG_WARNING << "Setting icon from settings file failed "
                           "(ICON_SMALL)";
        }
    } else if (IsPopup()) {
        // CEF did not set icon for the popup window, even though the opener
        // window had an icon set.
        HICON smallIcon = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDR_MAINWINDOW));
        if (smallIcon) {
            SendMessage(windowHandle_, WM_SETICON, ICON_SMALL, (LPARAM)smallIcon);
        } else {
            LOG_WARNING << "LoadIcon(IDR_MAINWINDOW) failed "
                        << "in BrowserWindow::SetIconFromSettings()";
        }
    }
}
Ejemplo n.º 16
0
void BrowserWindow::OnGetMinMaxInfo(UINT uMsg, WPARAM wParam, LPARAM lParam) {
    if (!IsPopup()) {
        json_value* settings = GetApplicationSettings();
        static long minimum_width =
                (*settings)["main_window"]["minimum_size"][0];
        static long minimum_height =
                (*settings)["main_window"]["minimum_size"][1];
        static long maximum_width =
                (*settings)["main_window"]["maximum_size"][0];
        static long maximum_height =
                (*settings)["main_window"]["maximum_size"][1];
        MINMAXINFO* pMMI = (MINMAXINFO*)lParam;
        if (minimum_width)
            pMMI->ptMinTrackSize.x = minimum_width;
        if (minimum_height)
            pMMI->ptMinTrackSize.y = minimum_height;
        if (maximum_width)
            pMMI->ptMaxTrackSize.x = maximum_width;
        if (maximum_height)
            pMMI->ptMaxTrackSize.y = maximum_height;
    }
}
Ejemplo n.º 17
0
NOTIFYICONDATA GetTrayData(HWND hwnd)
{
    static NOTIFYICONDATA tray = {0};
    tray.hWnd = hwnd;
    if (tray.cbSize) {
        return tray;
    }
    json_value* appSettings = GetApplicationSettings();
    std::string main_window_title = (*appSettings)["main_window"]["title"];
    std::string minimize_to_tray_message = (*appSettings)["main_window"]["minimize_to_tray_message"];
    tray.cbSize = sizeof(tray);
    tray.uID = 1;
    tray.uCallbackMessage = WM_TRAY_MESSAGE;
    tray.hIcon = (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(IDR_MAINWINDOW), IMAGE_ICON,
        GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON),
        LR_DEFAULTCOLOR);
    wcscpy_s(tray.szInfo, 256, Utf8ToWide(minimize_to_tray_message).c_str());
    wcscpy_s(tray.szInfoTitle, 64, Utf8ToWide(main_window_title).c_str());
    tray.uFlags = NIF_ICON | NIF_INFO | NIF_MESSAGE;
    tray.dwInfoFlags = NIIF_NONE;
    return tray;
}
Ejemplo n.º 18
0
HWND CreatePopupWindow(HWND parentHandle) {
    json_value* settings = GetApplicationSettings();
    bool center_relative_to_parent =
            (*settings)["popup_window"]["center_relative_to_parent"];

    // Title will be set in BrowserWindow::BrowserWindow().
    // CW_USEDEFAULT cannot be used with WS_POPUP.
    HWND hwnd = CreateWindowEx(0, g_windowClassName,
            0, WS_OVERLAPPEDWINDOW,
            CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
            parentHandle, 0, g_hInstance, 0);
    _ASSERT(hwnd);
    if (center_relative_to_parent) {
        // This won't work properly as real width/height is set later
        // when BrowserEvents2::WindowSetWidth() / WindowSetHeight()
        // are triggered. TODO.
        // CenterWindow(hwnd);
    }
    ShowWindow(hwnd, SW_SHOWNORMAL);
    UpdateWindow(hwnd);
    return hwnd;
}
Ejemplo n.º 19
0
void
DeviceConfigurations::writeConfig(QList<DeviceConfiguration> Configuration)
{
    // loop through the entries in the Configuration QList
    // writing to the GC settings

    int i=0;
    boost::shared_ptr<QSettings> settings = GetApplicationSettings();

    settings->setValue(GC_DEV_COUNT, Configuration.count());
    for (i=0; i < Configuration.count(); i++) {

        // name
        QString configStr = QString("%1%2").arg(GC_DEV_NAME).arg(i+1);
        settings->setValue(configStr, Configuration.at(i).name);

        // type
        configStr = QString("%1%2").arg(GC_DEV_TYPE).arg(i+1);
        settings->setValue(configStr, Configuration.at(i).type);

        // portSpec
        configStr = QString("%1%2").arg(GC_DEV_SPEC).arg(i+1);
        settings->setValue(configStr, Configuration.at(i).portSpec);

        // deviceProfile
        configStr = QString("%1%2").arg(GC_DEV_PROF).arg(i+1);
        settings->setValue(configStr, Configuration.at(i).deviceProfile);

        // isDefaultDownload
        configStr = QString("%1%2").arg(GC_DEV_DEFI).arg(i+1);
        settings->setValue(configStr, Configuration.at(i).isDefaultDownload);

        // isDefaultRealtime
        configStr = QString("%1%2").arg(GC_DEV_DEFR).arg(i+1);
        settings->setValue(configStr, Configuration.at(i).isDefaultRealtime);
    }

}
Ejemplo n.º 20
0
int 
main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    
    //this is the path within the current directory where GC will look for
    //files to allow USB stick support
    QString localLibraryPath="Library/GoldenCheetah";

    //this is the path that used to be used for all platforms
    //now different platforms will use their own path
    //this path is checked first to make things easier for long-time users
    QString oldLibraryPath=QDir::home().path()+"/Library/GoldenCheetah";

    //these are the new platform-dependent library paths
#if defined(Q_OS_MACX)
    QString libraryPath="Library/GoldenCheetah";
#elif defined(Q_OS_WIN)
    QString libraryPath=QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "GoldenCheetah";
#else
    // Q_OS_LINUX et al
    QString libraryPath=".goldencheetah";
#endif

    //First check to see if the Library folder exists where the executable is (for USB sticks)
    QDir home = QDir();
    //if it does, create an ini file for settings and cd into the library
    if(home.exists(localLibraryPath))
    {
         home.cd(localLibraryPath);
    }
    //if it does not exist, let QSettings handle storing settings
    //also cd to the home directory and look for libraries
    else
    {
        home = QDir::home();
        //check if this users previously stored files in the old library path
        //if they did, use the existing library
        if (home.exists(oldLibraryPath))
        {
            home.cd(oldLibraryPath);
        }
        //otherwise use the new library path
        else
        {
            //first create the path if it does not exist
            if (!home.exists(libraryPath))
            {
                if (!home.mkpath(libraryPath))
                {
                    qDebug()<<"Failed to create library path\n";
                    assert(false);
                }
            }
            home.cd(libraryPath);
        }
    }
    boost::shared_ptr<QSettings> settings;
    settings = GetApplicationSettings();
    QVariant lastOpened = settings->value(GC_SETTINGS_LAST);
    QVariant unit = settings->value(GC_UNIT);
    double crankLength = settings->value(GC_CRANKLENGTH).toDouble();
    if(crankLength<=0) {
       settings->setValue(GC_CRANKLENGTH,172.5);
    }

    bool anyOpened = false;
    if (lastOpened != QVariant()) {
        QStringList list = lastOpened.toStringList();
        QStringListIterator i(list);
        while (i.hasNext()) {
            QString cyclist = i.next();
            if (home.cd(cyclist)) {
                // used by WkoRideFileReader to store notes
                WKO_HOMEDIR = home.absolutePath();
                MainWindow *main = new MainWindow(home);
                main->show();
                home.cdUp();
                anyOpened = true;
            }
        }
    }
    if (!anyOpened) {
        ChooseCyclistDialog d(home, true);
        d.setModal(true);
        if (d.exec() != QDialog::Accepted)
            return 0;
        home.cd(d.choice());
        if (!home.exists())
            assert(false);
        // used by WkoRideFileReader to store notes
        WKO_HOMEDIR = home.absolutePath();
        MainWindow *main = new MainWindow(home);
        main->show();
    }
    return app.exec();
}
Ejemplo n.º 21
0
bool
FixGaps::postProcess(RideFile *ride, DataProcessorConfig *config=0)
{
    // get settings
    double tolerance, stop;
    if (config == NULL) { // being called automatically
        boost::shared_ptr<QSettings> settings = GetApplicationSettings();
        tolerance = settings->value(GC_DPFG_TOLERANCE, "1.0").toDouble();
        stop = settings->value(GC_DPFG_STOP, "1.0").toDouble();
    } else { // being called manually
        tolerance = ((FixGapsConfig*)(config))->tolerance->value();
        stop = ((FixGapsConfig*)(config))->beerandburrito->value();
    }

    // if the number of duration / number of samples
    // equals the recording interval then we don't need
    // to post-process for gaps
    // XXX commented out since it is not always true and
    //     is purely to improve performance
    //if ((ride->recIntSecs() + ride->dataPoints()[ride->dataPoints().count()-1]->secs -
    //    ride->dataPoints()[0]->secs) / (double) ride->dataPoints().count() == ride->recIntSecs())
    //    return false;

    // Additionally, If there are less than 2 dataPoints then there
    // is no way of post processing anyway (e.g. manual workouts)
    if (ride->dataPoints().count() < 2) return false;

    // OK, so there are probably some gaps, lets post process them
    RideFilePoint *last = NULL;
    int dropouts = 0;
    double dropouttime = 0.0;

    // put it all in a LUW
    ride->command->startLUW("Fix Gaps in Recording");

    for (int position = 0; position < ride->dataPoints().count(); position++) {
        RideFilePoint *point = ride->dataPoints()[position];

        if (last == NULL) last = point;
        else {
            double gap = point->secs - last->secs - ride->recIntSecs();

            // if we have gps and we moved, then this isn't a stop
            bool stationary = ((last->lat || last->lon) && (point->lat || point->lon)) // gps is present
                         && last->lat == point->lat && last->lon == point->lon;

            // moved for less than 30 seconds ... interpolate
            if (!stationary && gap > tolerance && gap < stop) {

                // what's needed?
                dropouts++;
                dropouttime += gap;

                int count = gap/ride->recIntSecs();
                double hrdelta = (point->hr - last->hr) / (double) count;
                double pwrdelta = (point->watts - last->watts) / (double) count;
                double kphdelta = (point->kph - last->kph) / (double) count;
                double kmdelta = (point->km - last->km) / (double) count;
                double caddelta = (point->cad - last->cad) / (double) count;
                double altdelta = (point->alt - last->alt) / (double) count;
                double nmdelta = (point->nm - last->nm) / (double) count;
                double londelta = (point->lon - last->lon) / (double) count;
                double latdelta = (point->lat - last->lat) / (double) count;
                double hwdelta = (point->headwind - last->headwind) / (double) count;

                // add the points
                for(int i=0; i<count; i++) {
                    RideFilePoint *add = new RideFilePoint(last->secs+((i+1)*ride->recIntSecs()),
                                                           last->cad+((i+1)*caddelta),
                                                           last->hr + ((i+1)*hrdelta),
                                                           last->km + ((i+1)*kmdelta),
                                                           last->kph + ((i+1)*kphdelta),
                                                           last->nm + ((i+1)*nmdelta),
                                                           last->watts + ((i+1)*pwrdelta),
                                                           last->alt + ((i+1)*altdelta),
                                                           last->lon + ((i+1)*londelta),
                                                           last->lat + ((i+1)*latdelta),
                                                           last->headwind + ((i+1)*hwdelta),
                                                           last->interval);
                    ride->command->insertPoint(position++, add);
                }

            // stationary or greater than 30 seconds... fill with zeroes
            } else if (gap > stop) {

                dropouts++;
                dropouttime += gap;

                int count = gap/ride->recIntSecs();
                double kmdelta = (point->km - last->km) / (double) count;

                // add zero value points
                for(int i=0; i<count; i++) {
                    RideFilePoint *add = new RideFilePoint(last->secs+((i+1)*ride->recIntSecs()),
                                                           0,
                                                           0,
                                                           last->km + ((i+1)*kmdelta),
                                                           0,
                                                           0,
                                                           0,
                                                           0,
                                                           0,
                                                           0,
                                                           0,
                                                           last->interval);
                    ride->command->insertPoint(position++, add);
                }
            }
        }
        last = point;
    }

    // end the Logical unit of work here
    ride->command->endLUW();

    ride->setTag("Dropouts", QString("%1").arg(dropouts));
    ride->setTag("Dropout Time", QString("%1").arg(dropouttime));

    if (dropouts) return true;
    else return false;
}
Ejemplo n.º 22
0
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    LPTSTR lpstrCmdLine, int nCmdShow) {
    g_hInstance = hInstance;
    json_value* appSettings = GetApplicationSettings();
    if (GetApplicationSettingsError().length()) {
        std::string error = GetApplicationSettingsError();
        error.append("\nApplication will terminate immediately. ");
        FatalError(NULL, error);
    }

    // Debugging options.
    bool show_console = (*appSettings)["debugging"]["show_console"];
    bool subprocess_show_console = (*appSettings)["debugging"]["subprocess_show_console"];
    std::string log_level = (*appSettings)["debugging"]["log_level"];
    std::string log_file = (*appSettings)["debugging"]["log_file"];
    log_file = GetAbsolutePath(log_file);
    
    // Initialize logging.
    if (std::wstring(lpstrCmdLine).find(L"--type=") != std::string::npos) {
        // This is a subprocess.
        InitializeLogging(subprocess_show_console, log_level, log_file);
    } else {
        // Main browser process.
        InitializeLogging(show_console, log_level, log_file);
    }

    // Command line arguments
    LPWSTR *argv;
    int argc;
    argv = CommandLineToArgvW(GetCommandLineW(), &argc);
    if (argv) {
        for (int i = 0; i < argc; i++) {
            std::string argument = WideToUtf8(std::wstring(argv[i]));
            size_t pos = argument.find("=");
            if (pos != std::string::npos) {
                std::string name = argument.substr(0, pos);
                std::string value = argument.substr(pos+1, std::string::npos);
                if (name == "--cgi-environment" && value.length()) {
                    g_cgiEnvironmentFromArgv.assign(value);
                }
            }
        }
    } else {
        LOG_WARNING << "CommandLineToArgvW() failed";
    }

    // CEF subprocesses.
    CefMainArgs main_args(hInstance);
    CefRefPtr<App> app(new App);
    int exit_code = CefExecuteProcess(main_args, app.get(), NULL);
    if (exit_code >= 0) {
        ShutdownLogging();
        return exit_code;
    }

    LOG_INFO << "--------------------------------------------------------";
    LOG_INFO << "Started application";

    if (log_file.length())
        LOG_INFO << "Logging to: " << log_file;
    else
        LOG_INFO << "No logging file set";
    LOG_INFO << "Log level = "
             << FILELog::ToString(FILELog::ReportingLevel());

    // Main window title option.
    std::string main_window_title = (*appSettings)["main_window"]["title"];
    if (main_window_title.empty())
        main_window_title = GetExecutableName();

    // Single instance guid option.
    const char* single_instance_guid =
            (*appSettings)["application"]["single_instance_guid"];
    if (single_instance_guid && single_instance_guid[0] != 0) {
        int guidSize = strlen(single_instance_guid) + 1;
        g_singleInstanceApplicationGuid = new wchar_t[guidSize];
        Utf8ToWide(single_instance_guid, g_singleInstanceApplicationGuid,
                   guidSize);
    }
    if (g_singleInstanceApplicationGuid
            && g_singleInstanceApplicationGuid[0] != 0) {
        g_singleInstanceApplication.Initialize(
                g_singleInstanceApplicationGuid);
	    if (g_singleInstanceApplication.IsRunning()) {
            HWND hwnd = FindWindow(g_singleInstanceApplicationGuid, NULL);
            if (hwnd) {
                if (IsIconic(hwnd))
                    ShowWindow(hwnd, SW_RESTORE);
                SetForegroundWindow(hwnd);
                return 0;
            }
        }
    }

    // Window class name.
    if (g_singleInstanceApplicationGuid) {
        swprintf_s(g_windowClassName, _countof(g_windowClassName), L"%s",
                   g_singleInstanceApplicationGuid);
    } else {
        swprintf_s(g_windowClassName, _countof(g_windowClassName), L"%s",
                   Utf8ToWide(GetExecutableName()).c_str());
    }

    if (!StartWebServer()) {
        FatalError(NULL, "Error while starting an internal local server.\n"
                   "Application will terminate immediately.");
    }

    CefSettings cef_settings;

    // log_file
    std::string chrome_log_file = (*appSettings)["chrome"]["log_file"];
    chrome_log_file = GetAbsolutePath(chrome_log_file);
    CefString(&cef_settings.log_file) = chrome_log_file;

    // log_severity
    std::string chrome_log_severity = (*appSettings)["chrome"]["log_severity"];
    cef_log_severity_t log_severity = LOGSEVERITY_DEFAULT;
    if (chrome_log_severity == "verbose") {
        log_severity = LOGSEVERITY_VERBOSE;
    } else if (chrome_log_severity == "info") {
        log_severity = LOGSEVERITY_INFO;
    } else if (chrome_log_severity == "warning") {
        log_severity = LOGSEVERITY_WARNING;
    } else if (chrome_log_severity == "error") {
        log_severity = LOGSEVERITY_ERROR;
    } else if (chrome_log_severity == "error-report") {
        log_severity = LOGSEVERITY_ERROR_REPORT;
    } else if (chrome_log_severity == "disable") {
        log_severity = LOGSEVERITY_DISABLE;
    }
    cef_settings.log_severity = log_severity;

    // cache_path
    std::string cache_path = (*appSettings)["chrome"]["cache_path"];
    cache_path = GetAbsolutePath(cache_path);
    CefString(&cef_settings.cache_path) = cache_path;

    // remote_debugging_port
    // A value of -1 will disable remote debugging.
    int remote_debugging_port = static_cast<long>(
            (*appSettings)["chrome"]["remote_debugging_port"]);
    if (remote_debugging_port == 0) {
        remote_debugging_port = random(49152, 65535+1);
        int i = 100;
        while (((i--) > 0) && remote_debugging_port == GetWebServerPort()) {
            remote_debugging_port = random(49152, 65535+1);
        }
    }
    if (remote_debugging_port > 0) {
        LOG_INFO << "remote_debugging_port = " << remote_debugging_port;
        cef_settings.remote_debugging_port = remote_debugging_port;
    }

    // Sandbox support
    cef_settings.no_sandbox = true;

    CefInitialize(main_args, cef_settings, app.get(), NULL);
    CreateMainWindow(hInstance, nCmdShow, main_window_title);
    CefRunMessageLoop();
    CefShutdown();

    LOG_INFO << "Ended application";
    LOG_INFO << "--------------------------------------------------------";

    ShutdownLogging();

    return 0;
}
Ejemplo n.º 23
0
 void saveConfig() {
     boost::shared_ptr<QSettings> settings = GetApplicationSettings();
     settings->setValue(GC_DPFG_TOLERANCE, tolerance->value());
     settings->setValue(GC_DPFG_STOP, beerandburrito->value());
 }
Ejemplo n.º 24
0
RealtimeWindow::RealtimeWindow(MainWindow *parent, TrainTool *trainTool, const QDir &home)  : QWidget(parent)
{

    // set home
    this->home = home;
    this->trainTool = trainTool;
    main = parent;
    deviceController = NULL;
    streamController = NULL;
    ergFile = NULL;

    // metric or imperial?
    boost::shared_ptr<QSettings> settings = GetApplicationSettings();
    QVariant unit = settings->value(GC_UNIT);
    useMetricUnits = (unit.toString() == "Metric");

    // main layout for the window
    main_layout = new QVBoxLayout(this);
    timer_layout = new QGridLayout();

    // BUTTONS AND LCDS
    button_layout = new QHBoxLayout();
    option_layout = new QHBoxLayout();
    controls_layout = new QVBoxLayout();

    deviceSelector = new QComboBox(this);
    streamSelector = new QComboBox(this);

    // get configured devices
    DeviceConfigurations all;
    Devices = all.getList();

    streamSelector->addItem("No streaming", -1);
    for (int i=0; i<Devices.count(); i++) {

        // add streamers
        if ( Devices.at(i).type == DEV_GSERVER ||
             Devices.at(i).type == DEV_GCLIENT )
            streamSelector->addItem(Devices.at(i).name, i);

        // add data sources
        deviceSelector->addItem(Devices.at(i).name, i);
    }

    deviceSelector->setCurrentIndex(0);
    streamSelector->setCurrentIndex(0);

    recordSelector = new QCheckBox(this);
    recordSelector->setText(tr("Save"));
    recordSelector->setChecked(Qt::Checked);

    startButton = new QPushButton(tr("Start"), this);
    startButton->setMaximumHeight(100);
    pauseButton = new QPushButton(tr("Pause"), this);
    pauseButton->setMaximumHeight(100);
    stopButton = new QPushButton(tr("Stop"), this);
    stopButton->setMaximumHeight(100);

    button_layout->addWidget(startButton);
    button_layout->addWidget(pauseButton);
    button_layout->addWidget(stopButton);
    option_layout->addWidget(deviceSelector);
    option_layout->addSpacing(10);
    option_layout->addWidget(recordSelector);
    option_layout->addSpacing(10);
    option_layout->addWidget(streamSelector);

    // XXX NETWORK STREAMING DISABLED IN THIS RELEASE SO HIDE THE COMBO
    streamSelector->hide();

    option_layout->addSpacing(10);
    controls_layout->addItem(option_layout);
    controls_layout->addItem(button_layout);

    // handle config changes
    connect(main, SIGNAL(configChanged()), this, SLOT(configUpdate()));

    connect(deviceSelector, SIGNAL(currentIndexChanged(int)), this, SLOT(SelectDevice(int)));
    connect(recordSelector, SIGNAL(clicked()), this, SLOT(SelectRecord()));
    connect(streamSelector, SIGNAL(currentIndexChanged(int)), this, SLOT(SelectStream(int)));
    connect(trainTool, SIGNAL(workoutSelected()), this, SLOT(SelectWorkout()));

    if (Devices.count() > 0) {
        connect(startButton, SIGNAL(clicked()), this, SLOT(Start()));
        connect(pauseButton, SIGNAL(clicked()), this, SLOT(Pause()));
        connect(stopButton, SIGNAL(clicked()), this, SLOT(Stop()));
    } else {
        connect(startButton, SIGNAL(clicked()), this, SLOT(warnnoConfig()));
        connect(pauseButton, SIGNAL(clicked()), this, SLOT(warnnoConfig()));
        connect(stopButton, SIGNAL(clicked()), this, SLOT(warnnoConfig()));
    }
    powerLabel = new QLabel(tr("WATTS"), this);
    powerLabel->setAlignment(Qt::AlignHCenter | Qt::AlignBottom);
    heartrateLabel = new QLabel(tr("BPM"), this);
    heartrateLabel->setAlignment(Qt::AlignHCenter | Qt::AlignBottom);
    speedLabel = new QLabel(useMetricUnits ? tr("KPH") : tr("MPH"), this);
    speedLabel->setAlignment(Qt::AlignHCenter | Qt::AlignBottom);
    cadenceLabel = new QLabel(tr("RPM"), this);
    cadenceLabel->setAlignment(Qt::AlignHCenter | Qt::AlignBottom);
    lapLabel = new QLabel(tr("Lap/Interval"), this);
    lapLabel->setAlignment(Qt::AlignHCenter | Qt::AlignBottom);
    loadLabel = new QLabel(tr("Load WATTS"), this);
    loadLabel->setAlignment(Qt::AlignHCenter | Qt::AlignBottom);
    distanceLabel = new QLabel(useMetricUnits ? tr("Distance (KM)") : tr("Distance (Miles)"), this);
    distanceLabel->setAlignment(Qt::AlignHCenter | Qt::AlignBottom);

    avgpowerLabel = new QLabel(tr("Avg WATTS"), this);
    avgpowerLabel->setAlignment(Qt::AlignHCenter | Qt::AlignBottom);
    avgheartrateLabel = new QLabel(tr("Avg BPM"), this);
    avgheartrateLabel->setAlignment(Qt::AlignHCenter | Qt::AlignBottom);
    avgspeedLabel = new QLabel(useMetricUnits ? tr("Avg KPH") : tr("Avg MPH"), this);
    avgspeedLabel->setAlignment(Qt::AlignHCenter | Qt::AlignBottom);
    avgcadenceLabel = new QLabel(tr("Avg RPM"), this);
    avgcadenceLabel->setAlignment(Qt::AlignHCenter | Qt::AlignBottom);
    avgloadLabel = new QLabel(tr("Avg Load WATTS"), this);
    avgloadLabel->setAlignment(Qt::AlignHCenter | Qt::AlignBottom);

    laptimeLabel = new QLabel(tr("LAP TIME"), this);
    laptimeLabel->setAlignment(Qt::AlignHCenter | Qt::AlignBottom);
    timeLabel = new QLabel(tr("TIME"), this);
    timeLabel->setAlignment(Qt::AlignHCenter | Qt::AlignBottom);

    powerLCD = new QLCDNumber(this); powerLCD->setSegmentStyle(QLCDNumber::Filled);
    heartrateLCD = new QLCDNumber(this); heartrateLCD->setSegmentStyle(QLCDNumber::Filled);
    speedLCD = new QLCDNumber(this); speedLCD->setSegmentStyle(QLCDNumber::Filled);
    cadenceLCD = new QLCDNumber(this); cadenceLCD->setSegmentStyle(QLCDNumber::Filled);
    lapLCD = new QLCDNumber(this); lapLCD->setSegmentStyle(QLCDNumber::Filled);
    loadLCD = new QLCDNumber(this); loadLCD->setSegmentStyle(QLCDNumber::Filled);
    distanceLCD = new QLCDNumber(this); distanceLCD->setSegmentStyle(QLCDNumber::Filled);

    avgpowerLCD = new QLCDNumber(this); avgpowerLCD->setSegmentStyle(QLCDNumber::Filled);
    avgheartrateLCD = new QLCDNumber(this); avgheartrateLCD->setSegmentStyle(QLCDNumber::Filled);
    avgspeedLCD = new QLCDNumber(this); avgspeedLCD->setSegmentStyle(QLCDNumber::Filled);
    avgcadenceLCD = new QLCDNumber(this); avgcadenceLCD->setSegmentStyle(QLCDNumber::Filled);
    avgloadLCD = new QLCDNumber(this); avgloadLCD->setSegmentStyle(QLCDNumber::Filled);

    laptimeLCD = new QLCDNumber(this); laptimeLCD->setSegmentStyle(QLCDNumber::Filled);
    laptimeLCD->setNumDigits(9);
    timeLCD = new QLCDNumber(this); timeLCD->setSegmentStyle(QLCDNumber::Filled);
    timeLCD->setNumDigits(9);

    gridLayout = new QGridLayout();
    gridLayout->addWidget(powerLabel, 1, 0);
    gridLayout->addWidget(cadenceLabel, 1, 1);
    gridLayout->addWidget(heartrateLabel, 1, 2);
    gridLayout->addWidget(speedLabel, 1, 3);
    gridLayout->addWidget(distanceLabel, 1, 4);
    gridLayout->addWidget(lapLabel, 1, 5);
    gridLayout->addWidget(powerLCD, 2, 0);
    gridLayout->addWidget(cadenceLCD, 2, 1);
    gridLayout->addWidget(heartrateLCD, 2, 2);
    gridLayout->addWidget(speedLCD, 2, 3);
    gridLayout->addWidget(distanceLCD, 2, 4);
    gridLayout->addWidget(lapLCD, 2, 5);
    gridLayout->addWidget(avgpowerLabel, 3, 0);
    gridLayout->addWidget(avgcadenceLabel, 3, 1);
    gridLayout->addWidget(avgheartrateLabel, 3, 2);
    gridLayout->addWidget(avgspeedLabel, 3, 3);
    gridLayout->addWidget(avgloadLabel, 3, 4);
    gridLayout->addWidget(loadLabel, 3, 5);
    gridLayout->addWidget(loadLCD, 4, 5);
    gridLayout->addWidget(avgpowerLCD, 4, 0);
    gridLayout->addWidget(avgcadenceLCD, 4, 1);
    gridLayout->addWidget(avgheartrateLCD, 4, 2);
    gridLayout->addWidget(avgspeedLCD, 4, 3);
    gridLayout->addWidget(avgloadLCD, 4, 4);
    gridLayout->setRowStretch(2, 4);
    gridLayout->setRowStretch(4, 3);

    // timers etc
    timer_layout->addWidget(timeLabel, 0, 0);
    timer_layout->addWidget(laptimeLabel, 0, 3);
    timer_layout->addWidget(timeLCD, 1, 0);
    timer_layout->addItem(controls_layout, 1,1);
    timer_layout->addWidget(laptimeLCD, 1, 3);
    timer_layout->setRowStretch(0, 1);
    timer_layout->setRowStretch(1, 4);

    // REALTIME PLOT
    rtPlot = new RealtimePlot();
    connect(main, SIGNAL(configChanged()), rtPlot, SLOT(configChanged()));

    // COURSE PLOT
    ergPlot = new ErgFilePlot(0);
    ergPlot->setVisible(false);

    // LAYOUT

    main_layout->addWidget(ergPlot);
    main_layout->addItem(timer_layout);
    main_layout->addItem(gridLayout);
    main_layout->addWidget(rtPlot);

    displaymode=2;
    main_layout->setStretch(0,1);
    main_layout->setStretch(1,1);
    main_layout->setStretch(2,2);
    main_layout->setStretch(3, displaymode);


    // now the GUI is setup lets sort our control variables
    gui_timer = new QTimer(this);
    disk_timer = new QTimer(this);
    stream_timer = new QTimer(this);
    load_timer = new QTimer(this);

    session_time = QTime();
    session_elapsed_msec = 0;
    lap_time = QTime();
    lap_elapsed_msec = 0;

    recordFile = NULL;
    status = 0;
    status |= RT_RECORDING;         // recording is on by default! - add others here
    status |= RT_MODE_ERGO;         // ergo mode by default
    displayWorkoutLap = displayLap = 0;
    pwrcount = 0;
    cadcount = 0;
    hrcount = 0;
    spdcount = 0;
    lodcount = 0;
    load_msecs = total_msecs = lap_msecs = 0;
    displayWorkoutDistance = displayDistance = displayPower = displayHeartRate =
    displaySpeed = displayCadence = displayGradient = displayLoad = 0;
    avgPower= avgHeartRate= avgSpeed= avgCadence= avgLoad= 0;

    connect(gui_timer, SIGNAL(timeout()), this, SLOT(guiUpdate()));
    connect(disk_timer, SIGNAL(timeout()), this, SLOT(diskUpdate()));
    connect(stream_timer, SIGNAL(timeout()), this, SLOT(streamUpdate()));
    connect(load_timer, SIGNAL(timeout()), this, SLOT(loadUpdate()));

    // setup the controller based upon currently selected device
    setDeviceController();
    rtPlot->replot();
}
Ejemplo n.º 25
0
void
RealtimeWindow::SelectWorkout()
{
    int mode;

    // wip away the current selected workout
    if (ergFile) {
        delete ergFile;
        ergFile = NULL;
    }

    // which one is selected?
    if (trainTool->currentWorkout() == NULL || trainTool->currentWorkout()->type() != WORKOUT_TYPE) return;

    // is it the auto mode?
    int index = trainTool->workoutItems()->indexOfChild((QTreeWidgetItem *)trainTool->currentWorkout());
    if (index == 0) {
        // ergo mode
        mode = ERG;
        status &= ~RT_WORKOUT;
        ergPlot->setVisible(false);
    } else if (index == 1) {
        // slope mode
        mode = CRS;
        status &= ~RT_WORKOUT;
        ergPlot->setVisible(false);
    } else {
        // workout mode
        boost::shared_ptr<QSettings> settings = GetApplicationSettings();
        QVariant workoutDir = settings->value(GC_WORKOUTDIR);
        QString fileName = workoutDir.toString() + "/" + trainTool->currentWorkout()->text(0); // filename

        // Get users CP for relative watts calculations
        QDate today = QDate::currentDate();
        double Cp=285;                       // default to 285 if zones are not set
        int range = main->zones()->whichRange(today);
        if (range != -1) Cp = main->zones()->getCP(range);

        ergFile = new ErgFile(fileName, mode, Cp);
        if (ergFile->isValid()) {

            status |= RT_WORKOUT;

            // success! we have a load file
            // setup the course profile in the
            // display!
            ergPlot->setData(ergFile);
            ergPlot->setVisible(true);
            ergPlot->replot();
        }
    }

    // set the device to the right mode
    if (mode == ERG || mode == MRC) {
        status |= RT_MODE_ERGO;
        status &= ~RT_MODE_SPIN;
        if (deviceController != NULL) deviceController->setMode(RT_MODE_ERGO);
        // set the labels on the gui
        loadLabel->setText(tr("Load WATTS"));
        avgloadLabel->setText(tr("Avg Load WATTS"));
    } else { // SLOPE MODE
        status |= RT_MODE_SPIN;
        status &= ~RT_MODE_ERGO;
        if (deviceController != NULL) deviceController->setMode(RT_MODE_SPIN);
        // set the labels on the gui
        loadLabel->setText(tr("Gradient PERCENT"));
        avgloadLabel->setText(tr("Avg Gradient PERCENT"));
    }
}
Ejemplo n.º 26
0
bool StartWebServer() {
    LOG_INFO << "Starting Mongoose " << mg_version() << " web server";
    json_value* appSettings = GetApplicationSettings();

    // 404_handler
    std::string _404_handler = (*appSettings)["web_server"]["404_handler"];

    // Ip address and port. If port was set to 0, then real port
    // will be known only after the webserver was started.
    std::string ipAddress = (*appSettings)["web_server"]["listen_on"][0];
    std::string port = (*appSettings)["web_server"]["listen_on"][1];
    long portInt = (*appSettings)["web_server"]["listen_on"][1];
    if (portInt)
        port = IntToString(portInt);
    if (ipAddress.empty()) {
        ipAddress = "127.0.0.1";
    }
    if (port.empty()) {
        port = "0";
    }

    // WWW directory from settings.
    std::string wwwDirectory = (*appSettings)["web_server"]["www_directory"];
    if (wwwDirectory.empty()) {
        wwwDirectory = "www";
    }
    wwwDirectory = GetAbsolutePath(wwwDirectory);
    LOG_INFO << "WWW directory: " << wwwDirectory;

    // Index files from settings.
    const json_value indexFilesArray = (*appSettings)["web_server"]["index_files"];
    std::string indexFiles;
    for (int i = 0; i < 32; i++) {
        const char* file = indexFilesArray[i];
        if (strlen(file)) {
            if (indexFiles.length())
                indexFiles.append(",");
            indexFiles.append(file);
        }
    }
    if (indexFiles.empty())
        indexFiles = "index.html,index.php";
    LOG_INFO << "Index files: " << indexFiles;

    // CGI interpreter from settings.
    std::string cgiInterpreter = (*appSettings)["web_server"]["cgi_interpreter"];
    if (cgiInterpreter.empty()) {
        cgiInterpreter = "php\\php-cgi.exe";
    }
    cgiInterpreter = GetAbsolutePath(cgiInterpreter);
    LOG_INFO << "CGI interpreter: " << cgiInterpreter;

    // CGI extensions from settings.
    const json_value cgiExtensions =
            (*appSettings)["web_server"]["cgi_extensions"];
    std::string cgiPattern;
    for (int i = 0; i < 32; i++) {
        const char* extension = cgiExtensions[i];
        if (strlen(extension)) {
            if (cgiPattern.length())
                cgiPattern.append("|");
            cgiPattern.append("**.").append(extension).append("$");
        }
    }
    if (cgiPattern.empty())
        cgiPattern = "**.php$";
    LOG_INFO << "CGI pattern: " << cgiPattern;

    // Hide files patterns.
    const json_value hide_files = (*appSettings)["web_server"]["hide_files"];
    std::string hide_files_patterns = "";
    for (int i = 0; i < 100; i++) {
        const char* pattern = hide_files[i];
        if (strlen(pattern)) {
            if (hide_files_patterns.length())
                hide_files_patterns.append("|");
            hide_files_patterns.append("**/").append(pattern).append("$");
        }
    }
    LOG_INFO << "Hide files patterns: " << hide_files_patterns;

    // Temp directory.
    std::string cgi_temp_dir = (*appSettings)["web_server"]["cgi_temp_dir"];
    cgi_temp_dir = GetAbsolutePath(cgi_temp_dir);
    if (!cgi_temp_dir.length() || !DirectoryExists(cgi_temp_dir)) {
        if (cgi_temp_dir.length()) {
            LOG_WARNING << "cgi_temp_dir directory does not exist: "
                        << cgi_temp_dir;
        }
        cgi_temp_dir.assign(GetAnsiTempDirectory());
    }

    // CGI environment variables.
    std::string cgiEnvironment = "";
    cgiEnvironment.append("TMP=").append(cgi_temp_dir).append(",");
    cgiEnvironment.append("TEMP=").append(cgi_temp_dir).append(",");
    cgiEnvironment.append("TMPDIR=").append(cgi_temp_dir).append(",");
    // Mongoose sets SERVER_NAME to "mydomain.com"
    cgiEnvironment.append("SERVER_NAME=").append(ipAddress).append(",");
    // Let users identify whether web app runs in a normal browser
    // or a phpdesktop browser.
    cgiEnvironment.append("PHPDESKTOP_VERSION=").append(GetPhpDesktopVersion());
    // Environment from application args
    if (g_cgiEnvironmentFromArgv.length()) {
        cgiEnvironment.append(",").append(g_cgiEnvironmentFromArgv);
    }
    LOG_INFO << "CGI environment variables set: " << cgiEnvironment;

    // Mongoose web server.
    std::string listening_ports = ipAddress + ":" + port;
    const char* options[] = {
        "document_root", wwwDirectory.c_str(),
        "listening_ports", listening_ports.c_str(),
        "index_files", indexFiles.c_str(),
        "cgi_interpreter", cgiInterpreter.c_str(),
        "cgi_pattern", cgiPattern.c_str(),
        "cgi_environment", cgiEnvironment.c_str(),
        "404_handler", _404_handler.c_str(),
        "hide_files_patterns", hide_files_patterns.c_str(),
        NULL
    };

    // Globals.
    g_wwwDirectory = wwwDirectory;
    g_cgiInterpreter = cgiInterpreter;

    mg_callbacks callbacks = {0};
    callbacks.log_message = &log_message;
    callbacks.end_request = &end_request;
    g_mongooseContext = mg_start(&callbacks, NULL, options);
    if (g_mongooseContext == NULL)
        return false;

    // When port was set to 0 then a random free port was assigned.
    g_webServerPort = mg_get_listening_port(g_mongooseContext);
    g_webServerIpAddress = ipAddress;
    g_webServerUrl = "http://" + ipAddress + ":" + IntToString(g_webServerPort) + "/";
    LOG_INFO << "Web server url: " << g_webServerUrl;

    return true;
}
Ejemplo n.º 27
0
void PerfPlot::plot() {

    boost::shared_ptr<QSettings> settings = GetApplicationSettings();

    int  num, tics;
    tics = 42;

    setAxisScale(yLeft, _sc->min(), _sc->max());
    num = xmax - xmin;

    /*
       fprintf(stderr,"PerfPlot::plot: xmin = %d xmax = %d num = %d\n",
       xmin, xmax, num);
       */

    // set axis scale
    if (num < 15) {
	tics = 1;
    } else if (num < 71) {
	tics  = 7;
    } else if (num < 141) {
	tics  = 14;
    } else if (num < 364) {
	tics  = 27;
    }
    setAxisScale(xBottom, xmin, xmax,tics);

    setAxisScaleDraw(QwtPlot::xBottom, new TimeScaleDraw(startDate));

    if (DAYcurve) {
	DAYcurve->detach();
	delete DAYcurve;
    }
    DAYcurve = new QwtPlotCurve(tr("Daily"));
    DAYcurve->setRenderHint(QwtPlotItem::RenderAntialiased);
    QPen daypen = QPen(GColor(CDAILYSTRESS));
    daypen.setWidth(1.0);
    DAYcurve->setPen(daypen);
    DAYcurve->setStyle(QwtPlotCurve::Sticks);

    // XXX Note: the days are offset by 1 without the -1 in the 
    //           line below  --------------+
    //                                     |
    //                                     V
    DAYcurve->setData(_sc->getDays()+xmin -1 ,_sc->getDAYvalues()+xmin,num);
    DAYcurve->setYAxis(yRight);
    DAYcurve->attach(this);

    if (STScurve) {
	STScurve->detach();
	delete STScurve;
    }
    STScurve = new QwtPlotCurve(settings->value(GC_STS_NAME,tr("Short Term Stress")).toString());
    STScurve->setRenderHint(QwtPlotItem::RenderAntialiased);
    QPen stspen = QPen(GColor(CSTS));
    stspen.setWidth(2.0);
    STScurve->setPen(stspen);
    STScurve->setData(_sc->getDays()+xmin,_sc->getSTSvalues()+xmin,num);
    STScurve->attach(this);


    if (LTScurve) {
	LTScurve->detach();
	delete LTScurve;
    }
    LTScurve = new QwtPlotCurve(settings->value(GC_LTS_NAME,tr("Long Term Stress")).toString());
    LTScurve->setRenderHint(QwtPlotItem::RenderAntialiased);
    QPen ltspen = QPen(GColor(CLTS));
    ltspen.setWidth(2.0);
    LTScurve->setPen(ltspen);
    LTScurve->setData(_sc->getDays()+xmin,_sc->getLTSvalues()+xmin,num);
    LTScurve->attach(this);


    if (SBcurve) {
	SBcurve->detach();
	delete SBcurve;
    }
    SBcurve = new QwtPlotCurve(settings->value(GC_SB_NAME,tr("Stress Balance")).toString());
    SBcurve->setRenderHint(QwtPlotItem::RenderAntialiased);
    QPen sbpen = QPen(GColor(CSB));
    sbpen.setWidth(2.0);
    SBcurve->setPen(sbpen);
    SBcurve->setData(_sc->getDays()+xmin,_sc->getSBvalues()+xmin,num);
    SBcurve->attach(this);

    replot();

}
Ejemplo n.º 28
0
int
main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    //this is the path within the current directory where GC will look for
    //files to allow USB stick support
    QString localLibraryPath="Library/GoldenCheetah";

    //this is the path that used to be used for all platforms
    //now different platforms will use their own path
    //this path is checked first to make things easier for long-time users
    QString oldLibraryPath=QDir::home().path()+"/Library/GoldenCheetah";

    //these are the new platform-dependent library paths
#if defined(Q_OS_MACX)
    QString libraryPath="Library/GoldenCheetah";
#elif defined(Q_OS_WIN)
    QString libraryPath=QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/GoldenCheetah";
#else
    // Q_OS_LINUX et al
    QString libraryPath=".goldencheetah";
#endif

    //First check to see if the Library folder exists where the executable is (for USB sticks)
    QDir home = QDir();
    //if it does, create an ini file for settings and cd into the library
    if(home.exists(localLibraryPath))
    {
         home.cd(localLibraryPath);
    }
    //if it does not exist, let QSettings handle storing settings
    //also cd to the home directory and look for libraries
    else
    {
        home = QDir::home();
        //check if this users previously stored files in the old library path
        //if they did, use the existing library
        if (home.exists(oldLibraryPath))
        {
            home.cd(oldLibraryPath);
        }
        //otherwise use the new library path
        else
        {
            //first create the path if it does not exist
            if (!home.exists(libraryPath))
            {
                if (!home.mkpath(libraryPath))
                {
                    qDebug()<<"Failed to create library path\n";
                    assert(false);
                }
            }
            home.cd(libraryPath);
        }
    }
    boost::shared_ptr<QSettings> settings;
    settings = GetApplicationSettings();

#ifdef ENABLE_METRICS_TRANSLATION
    // install QT Translator to enable QT Dialogs translation
    QTranslator qtTranslator;
    qtTranslator.load("qt_" + QLocale::system().name(),
             QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    app.installTranslator(&qtTranslator);
#endif

    // Language setting (default to system locale)
    QVariant lang = settings->value(GC_LANG, QLocale::system().name());

    // Load specific translation
    QTranslator gcTranslator;
    gcTranslator.load(":translations/gc_" + lang.toString() + ".qm");
    app.installTranslator(&gcTranslator);
 
#ifdef ENABLE_METRICS_TRANSLATION
    RideMetricFactory::instance().initialize();
#endif

    QVariant lastOpened = settings->value(GC_SETTINGS_LAST);
    QVariant unit = settings->value(GC_UNIT);
#ifdef ENABLE_METRICS_TRANSLATION
    if (unit.isNull()) { // Default to system locale
        unit = QLocale::system().measurementSystem() == QLocale::MetricSystem ? "Metric" : "Imperial";
        settings->setValue(GC_UNIT, unit);
    }
#endif
    double crankLength = settings->value(GC_CRANKLENGTH).toDouble();
    if(crankLength<=0) {
       settings->setValue(GC_CRANKLENGTH,172.5);
    }

    bool anyOpened = false;
    if (lastOpened != QVariant()) {
        QStringList list = lastOpened.toStringList();
        QStringListIterator i(list);
        while (i.hasNext()) {
            QString cyclist = i.next();
            if (home.cd(cyclist)) {
                // used by WkoRideFileReader to store notes
                WKO_HOMEDIR = home.absolutePath();
                MainWindow *mainWindow = new MainWindow(home);
                mainWindow->show();
                home.cdUp();
                anyOpened = true;
            }
        }
    }
    if (!anyOpened) {
        ChooseCyclistDialog d(home, true);
        d.setModal(true);
        if (d.exec() != QDialog::Accepted)
            return 0;
        home.cd(d.choice());
        if (!home.exists())
            assert(false);
        // used by WkoRideFileReader to store notes
        WKO_HOMEDIR = home.absolutePath();
        MainWindow *mainWindow = new MainWindow(home);
        mainWindow->show();
    }
    return app.exec();
}
Ejemplo n.º 29
0
AllPlotWindow::AllPlotWindow(MainWindow *mainWindow) :
    QWidget(mainWindow), current(NULL), mainWindow(mainWindow), active(false), stale(true)
{
    boost::shared_ptr<QSettings> settings = GetApplicationSettings();
    QVBoxLayout *vlayout = new QVBoxLayout;

    QHBoxLayout *showLayout = new QHBoxLayout;
    QLabel *showLabel = new QLabel(tr("Show:"), this);
    showLayout->addWidget(showLabel);

    showStack = new QCheckBox(tr("Stacked view"), this);

    if (settings->value(GC_RIDE_PLOT_STACK).toInt())
        showStack->setCheckState(Qt::Checked);
    else
        showStack->setCheckState(Qt::Unchecked);
    showLayout->addWidget(showStack);

    stackWidth = 15;

    QLabel *labelspacer = new QLabel(this);
    labelspacer->setFixedWidth(5);
    showLayout->addWidget(labelspacer);

    stackZoomUp = new QwtArrowButton(1, Qt::UpArrow,this);
    stackZoomUp->setFixedHeight(15);
    stackZoomUp->setFixedWidth(15);
    stackZoomUp->setEnabled(false);
    stackZoomUp->setContentsMargins(0,0,0,0);
    stackZoomUp->setFlat(true);
    showLayout->addWidget(stackZoomUp);

    stackZoomDown = new QwtArrowButton(1, Qt::DownArrow,this);
    stackZoomDown->setFixedHeight(15);
    stackZoomDown->setFixedWidth(15);
    stackZoomDown->setEnabled(false);
    stackZoomDown->setContentsMargins(0,0,0,0);
    stackZoomDown->setFlat(true);
    showLayout->addWidget(stackZoomDown);

    QCheckBox *showGrid = new QCheckBox(tr("Grid"), this);
    showGrid->setCheckState(Qt::Checked);
    showLayout->addWidget(showGrid);

    showHr = new QCheckBox(tr("Heart Rate"), this);
    showHr->setCheckState(Qt::Checked);
    showLayout->addWidget(showHr);

    showSpeed = new QCheckBox(tr("Speed"), this);
    showSpeed->setCheckState(Qt::Checked);
    showLayout->addWidget(showSpeed);

    showCad = new QCheckBox(tr("Cadence"), this);
    showCad->setCheckState(Qt::Checked);
    showLayout->addWidget(showCad);

    showAlt = new QCheckBox(tr("Altitude"), this);
    showAlt->setCheckState(Qt::Checked);
    showLayout->addWidget(showAlt);

    showPower = new QComboBox();
    showPower->addItem(tr("Power + shade"));
    showPower->addItem(tr("Power - shade"));
    showPower->addItem(tr("No Power"));
    showLayout->addWidget(showPower);

    // shade zones defaults will come in with a
    // future patch. For now we have place holder
    // to update when new config arrives
    if (true) showPower->setCurrentIndex(0);
    else showPower->setCurrentIndex(1);

    QHBoxLayout *smoothLayout = new QHBoxLayout;
    QComboBox *comboDistance = new QComboBox();
    comboDistance->addItem(tr("X Axis Shows Time"));
    comboDistance->addItem(tr("X Axis Shows Distance"));
    smoothLayout->addWidget(comboDistance);

    QLabel *smoothLabel = new QLabel(tr("Smoothing (secs)"), this);
    smoothLineEdit = new QLineEdit(this);
    smoothLineEdit->setFixedWidth(40);

    smoothLayout->addWidget(smoothLabel);
    smoothLayout->addWidget(smoothLineEdit);
    smoothSlider = new QSlider(Qt::Horizontal);
    smoothSlider->setTickPosition(QSlider::TicksBelow);
    smoothSlider->setTickInterval(10);
    smoothSlider->setMinimum(1);
    smoothSlider->setMaximum(600);
    smoothLineEdit->setValidator(new QIntValidator(smoothSlider->minimum(),
                                                   smoothSlider->maximum(),
                                                   smoothLineEdit));
    smoothLayout->addWidget(smoothSlider);

    allPlot = new AllPlot(this, mainWindow);
    smoothSlider->setValue(allPlot->smooth);
    smoothLineEdit->setText(QString("%1").arg(allPlot->smooth));

    allZoomer = new QwtPlotZoomer(allPlot->canvas());
    allZoomer->setRubberBand(QwtPicker::RectRubberBand);
    allZoomer->setRubberBandPen(GColor(CPLOTSELECT));
    allZoomer->setSelectionFlags(QwtPicker::DragSelection
                                 | QwtPicker::CornerToCorner);
    allZoomer->setTrackerMode(QwtPicker::AlwaysOff);
    allZoomer->setEnabled(true);

    // TODO: Hack for OS X one-button mouse
    // allZoomer->initMousePattern(1);

    // RightButton: zoom out by 1
    // Ctrl+RightButton: zoom out to full size
    allZoomer->setMousePattern(QwtEventPattern::MouseSelect2,
                               Qt::RightButton, Qt::ControlModifier);
    allZoomer->setMousePattern(QwtEventPattern::MouseSelect3,
                               Qt::RightButton);

    allPanner = new QwtPlotPanner(allPlot->canvas());
    allPanner->setMouseButton(Qt::MidButton);

    // TODO: zoomer doesn't interact well with automatic axis resizing

    // tooltip on hover over point
    allPlot->tooltip = new LTMToolTip(QwtPlot::xBottom, QwtPlot::yLeft,
                               QwtPicker::PointSelection,
                               QwtPicker::VLineRubberBand,
                               QwtPicker::AlwaysOn,
                               allPlot->canvas(),
                               "");
    allPlot->tooltip->setSelectionFlags(QwtPicker::PointSelection | QwtPicker::RectSelection | QwtPicker::DragSelection);
    allPlot->tooltip->setRubberBand(QwtPicker::VLineRubberBand);
    allPlot->tooltip->setMousePattern(QwtEventPattern::MouseSelect1, Qt::LeftButton, Qt::ShiftModifier);
    allPlot->tooltip->setTrackerPen(QColor(Qt::black));
    QColor inv(Qt::white);
    inv.setAlpha(0);
    allPlot->tooltip->setRubberBandPen(inv);
    allPlot->tooltip->setEnabled(true);

    allPlot->_canvasPicker = new LTMCanvasPicker(allPlot);
    connect(allPlot->_canvasPicker, SIGNAL(pointHover(QwtPlotCurve*, int)), allPlot, SLOT(pointHover(QwtPlotCurve*, int)));
    connect(allPlot->tooltip, SIGNAL(moved(const QPoint &)), this, SLOT(plotPickerMoved(const QPoint &)));
    connect(allPlot->tooltip, SIGNAL(appended(const QPoint &)), this, SLOT(plotPickerSelected(const QPoint &)));

    QwtPlotMarker* allMarker1 = new QwtPlotMarker();
    allMarker1->setLineStyle(QwtPlotMarker::VLine);
    allMarker1->attach(allPlot);
    allMarker1->setLabelAlignment(Qt::AlignTop|Qt::AlignRight);
    allPlot->allMarker1=allMarker1;

    QwtPlotMarker* allMarker2 = new QwtPlotMarker();
    allMarker2->setLineStyle(QwtPlotMarker::VLine);
    allMarker2->attach(allPlot);
    allMarker2->setLabelAlignment(Qt::AlignTop|Qt::AlignRight);
    allPlot->allMarker2=allMarker2;

    //
    // stack view
    //
    stackFrame = new QScrollArea();
    stackFrame->hide();
    stackPlotLayout = new QVBoxLayout();
    stackWidget = new QWidget();
    stackWidget->setLayout(stackPlotLayout);
    stackFrame->setWidgetResizable(true);
    stackFrame->setWidget(stackWidget);

    //
    // allPlot view
    //
    QVBoxLayout *allPlotLayout = new QVBoxLayout;
    allPlotFrame = new QScrollArea();

    spanSlider = new QxtSpanSlider(Qt::Horizontal);
    spanSlider->setHandleMovementMode(QxtSpanSlider::NoOverlapping);
    spanSlider->setLowerValue(0);
    spanSlider->setUpperValue(15);

    QFont small;
    small.setPointSize(6);

    scrollLeft = new QPushButton("<");
    scrollLeft->setFont(small);
    scrollLeft->setAutoRepeat(true);
    scrollLeft->setFixedHeight(16);
    scrollLeft->setFixedWidth(16);
    scrollLeft->setContentsMargins(0,0,0,0);

    scrollRight = new QPushButton(">");
    scrollRight->setFont(small);
    scrollRight->setAutoRepeat(true);
    scrollRight->setFixedHeight(16);
    scrollRight->setFixedWidth(16);
    scrollRight->setContentsMargins(0,0,0,0);

#ifdef Q_OS_MAC
    // BUG in QMacStyle and painting of spanSlider
    // so we use a plain style to avoid it, but only
    // on a MAC, since win and linux are fine
    QCleanlooksStyle *style = new QCleanlooksStyle();
    spanSlider->setStyle(style);
    scrollLeft->setStyle(style);
    scrollRight->setStyle(style);
#endif

    fullPlot = new AllPlot(this, mainWindow);
    fullPlot->grid->enableY(false);
    fullPlot->setCanvasBackground(GColor(CPLOTTHUMBNAIL));
    fullPlot->setCanvasLineWidth(0);
    fullPlot->enableAxis(QwtPlot::yLeft, false);
    fullPlot->enableAxis(QwtPlot::yLeft2, false);
    fullPlot->enableAxis(QwtPlot::yRight, false);
    fullPlot->enableAxis(QwtPlot::yRight2, false);
    fullPlot->enableAxis(QwtPlot::xBottom, false);
    fullPlot->legend()->clear();
    //fullPlot->setTitle("");
    fullPlot->setContentsMargins(0,0,0,0);

    allPlotLayout->addWidget(allPlot);
    allPlotFrame->setLayout(allPlotLayout);

    // controls...
    controlsLayout = new QGridLayout;
    controlsLayout->addWidget(fullPlot, 0,1);
    controlsLayout->addWidget(spanSlider, 1,1);
    controlsLayout->addWidget(scrollLeft,1,0);
    controlsLayout->addWidget(scrollRight,1,2);
    controlsLayout->setRowStretch(0, 10);
    controlsLayout->setRowStretch(1, 1);
    controlsLayout->setContentsMargins(0,0,0,0);
#ifdef Q_OS_MAC
    // macs  dpscing is weird
    //controlsLayout->setSpacing(5);
#else
    controlsLayout->setSpacing(0);
#endif

    vlayout->addWidget(allPlotFrame);
    vlayout->addWidget(stackFrame);
    vlayout->addLayout(controlsLayout);
    vlayout->addLayout(showLayout);
    vlayout->addLayout(smoothLayout);
    vlayout->setStretch(0,100);
    vlayout->setStretch(1,100);
    vlayout->setStretch(2,15);
    vlayout->setStretch(3,1);
    vlayout->setStretch(4,1);
    vlayout->setSpacing(1);
    setLayout(vlayout);

    // common controls
    connect(showPower, SIGNAL(currentIndexChanged(int)), this, SLOT(setShowPower(int)));
    connect(showHr, SIGNAL(stateChanged(int)), this, SLOT(setShowHr(int)));
    connect(showSpeed, SIGNAL(stateChanged(int)), this, SLOT(setShowSpeed(int)));
    connect(showCad, SIGNAL(stateChanged(int)), this, SLOT(setShowCad(int)));
    connect(showAlt, SIGNAL(stateChanged(int)), this, SLOT(setShowAlt(int)));
    connect(showGrid, SIGNAL(stateChanged(int)), this, SLOT(setShowGrid(int)));
    connect(showStack, SIGNAL(stateChanged(int)), this, SLOT(showStackChanged(int)));
    connect(comboDistance, SIGNAL(currentIndexChanged(int)), this, SLOT(setByDistance(int)));
    connect(smoothSlider, SIGNAL(valueChanged(int)), this, SLOT(setSmoothingFromSlider()));
    connect(smoothLineEdit, SIGNAL(editingFinished()), this, SLOT(setSmoothingFromLineEdit()));

    // normal view
    connect(spanSlider, SIGNAL(lowerPositionChanged(int)), this, SLOT(zoomChanged()));
    connect(spanSlider, SIGNAL(upperPositionChanged(int)), this, SLOT(zoomChanged()));

    // stacked view
    connect(stackZoomUp, SIGNAL(clicked()), this, SLOT(setStackZoomUp()));
    connect(stackZoomDown, SIGNAL(clicked()), this, SLOT(setStackZoomDown()));
    connect(scrollLeft, SIGNAL(clicked()), this, SLOT(moveLeft()));
    connect(scrollRight, SIGNAL(clicked()), this, SLOT(moveRight()));

    // GC signals
    connect(mainWindow, SIGNAL(rideSelected()), this, SLOT(rideSelected()));
    connect(mainWindow, SIGNAL(rideDirty()), this, SLOT(rideSelected()));
    connect(mainWindow, SIGNAL(zonesChanged()), this, SLOT(zonesChanged()));
    connect(mainWindow, SIGNAL(intervalsChanged()), this, SLOT(intervalsChanged()));
    connect(mainWindow, SIGNAL(intervalSelected()), this, SLOT(intervalSelected()));
    connect(mainWindow, SIGNAL(configChanged()), allPlot, SLOT(configChanged()));
    connect(mainWindow, SIGNAL(configChanged()), this, SLOT(configChanged()));
}
Ejemplo n.º 30
0
AllPlot::AllPlot(AllPlotWindow *parent, MainWindow *mainWindow):
    QwtPlot(parent),
    rideItem(NULL),
    unit(0),
    shade_zones(true),
    showPowerState(3),
    showHrState(Qt::Checked),
    showSpeedState(Qt::Checked),
    showCadState(Qt::Checked),
    showAltState(Qt::Checked),
    bydist(false),
    parent(parent)
{
    boost::shared_ptr<QSettings> settings = GetApplicationSettings();
    unit = settings->value(GC_UNIT);

    referencePlot = NULL;

    useMetricUnits = (unit.toString() == "Metric");

    // options for turning off/on shading on all plot
    // will come in with a future patch, for now we
    // enable zone shading by default, since this is
    // the current default behaviour
    if (false) shade_zones = false;
    else shade_zones = true;

    smooth = settings->value(GC_RIDE_PLOT_SMOOTHING).toInt();
    if (smooth < 1) smooth = 1;

    // create a background object for shading
    bg = new AllPlotBackground(this);
    bg->attach(this);

    insertLegend(new QwtLegend(), QwtPlot::BottomLegend);
    setCanvasBackground(GColor(CPLOTBACKGROUND));

    setXTitle();

    wattsCurve = new QwtPlotCurve(tr("Power"));

    hrCurve = new QwtPlotCurve(tr("Heart Rate"));
    hrCurve->setYAxis(yLeft2);

    speedCurve = new QwtPlotCurve(tr("Speed"));
    speedCurve->setYAxis(yRight);

    cadCurve = new QwtPlotCurve(tr("Cadence"));
    cadCurve->setYAxis(yLeft2);

    altCurve = new QwtPlotCurve(tr("Altitude"));
    // altCurve->setRenderHint(QwtPlotItem::RenderAntialiased);
    altCurve->setYAxis(yRight2);

    intervalHighlighterCurve = new QwtPlotCurve();
    intervalHighlighterCurve->setYAxis(yLeft);
    intervalHighlighterCurve->setData(IntervalPlotData(this, mainWindow));
    intervalHighlighterCurve->attach(this);
    this->legend()->remove(intervalHighlighterCurve); // don't show in legend

    grid = new QwtPlotGrid();
    grid->enableX(false);
    grid->attach(this);

    // get rid of nasty blank space on right of the plot
    plotLayout()->setAlignCanvasToScales(true);

    configChanged(); // set colors
}