<commit_before>//
// Created by Vadim N. on 18/03/2015.
//

#ifndef _BENCHMARK_H_
#define _BENCHMARK_H_

#define YMIR_BENCHMARK(expr) {}

#include <chrono>
#include <ctime>

#include "Inference"

using namespace ymir;

int main(int argc, char* argv[]) {
    std::chrono::system_clock::time_point tp1, tp2;

    time_t vj_single_parse, vdj_single_parse,
            vj_single_prob, vj_single_meta,
            vj_single_infer, vdj_single_prob,
            vdj_single_meta, vdj_single_infer;

    time_t vj_good_parse, vdj_good_parse,
            vj_good_prob, vj_good_meta,
            vj_good_infer, vdj_good_prob,
            vdj_good_meta, vdj_good_infer;

    std::string BENCH_DATA_FOLDER = argv[1];

    RepertoireParser parser;

    //
    // TCR alpha chain repertoire - VJ recombination
    //
    VDJRecombinationGenes vj_single_genes("Vgene",
                                   BENCH_DATA_FOLDER + "trav.txt",
                                   "Jgene",
                                   BENCH_DATA_FOLDER + "traj.txt");

    tp1 = std::chrono::system_clock::now();
    Cloneset cloneset_vj;
    parser.parse(BENCH_DATA_FOLDER + "alpha.500k.new.txt",
                 &cloneset_vj,
                 vj_single_genes,
                 NUCLEOTIDE,
                 VJ_RECOMB,
                 RepertoireParser::AlignmentColumnOptions()
                         .setV(RepertoireParser::USE_PROVIDED)
                         .setJ(RepertoireParser::USE_PROVIDED));
    tp2 = std::chrono::system_clock::now();
    vj_single_parse = std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1);

    //
    // TCR beta chain repertoire - VDJ recombination
    //
    VDJRecombinationGenes vdj_single_genes("Vgene",
                                    BENCH_DATA_FOLDER + "trbv.txt",
                                    "Jgene",
                                    BENCH_DATA_FOLDER + "trbj.txt",
                                    "Dgene",
                                    BENCH_DATA_FOLDER + "trbd.txt");

    tp1 = std::chrono::system_clock::now();
    Cloneset cloneset_vdj;
    parser.parse(BENCH_DATA_FOLDER + "beta.500k.new.txt",
                 &cloneset_vdj,
                 vdj_single_genes,
                 NUCLEOTIDE,
                 VDJ_RECOMB,
                 RepertoireParser::AlignmentColumnOptions()
                         .setV(RepertoireParser::USE_PROVIDED)
                         .setJ(RepertoireParser::USE_PROVIDED)
                         .setD(RepertoireParser::OVERWRITE));
    tp2 = std::chrono::system_clock::now();
    vdj_single_parse = std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1);

    //
    // VJ MAAG
    //
    ProbabilisticAssemblingModel vj_single_model(BENCH_DATA_FOLDER + "../../models/hTRA"); //, EMPTY);

    tp1 = std::chrono::system_clock::now();
    vj_single_model.buildGraphs(cloneset_vj, SAVE_METADATA);
    tp2 = std::chrono::system_clock::now();
    vj_single_meta = std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1);

    tp1 = std::chrono::system_clock::now();
    vj_single_model.computeFullProbabilities(cloneset_vj, NO_METADATA);
    tp2 = std::chrono::system_clock::now();
    vj_single_prob = std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1);

    //
    // VDJ MAAG
    //
    ProbabilisticAssemblingModel vdj_single_model(BENCH_DATA_FOLDER + "../../models/hTRB", EMPTY);

    tp1 = std::chrono::system_clock::now();
//    MAAGRepertoire(vdj_single_model.buildGraphs(cloneset_vdj, SAVE_METADATA));
    vdj_single_model.buildGraphs(cloneset_vdj, SAVE_METADATA);
    tp2 = std::chrono::system_clock::now();
    vdj_single_meta = std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1);

    tp1 = std::chrono::system_clock::now();
    vdj_single_model.computeFullProbabilities(cloneset_vdj, NO_METADATA);
    tp2 = std::chrono::system_clock::now();
    vdj_single_prob = std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1);

    //
    // VJ inference
    //
    tp1 = std::chrono::system_clock::now();
    EMAlgorithm().statisticalInference(cloneset_vj, vj_single_model, EMAlgorithm::AlgorithmParameters().set("niter", 10));
    tp2 = std::chrono::system_clock::now();
    vj_single_infer = std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1);

    //
    // VDJ inference
    //
    tp1 = std::chrono::system_clock::now();
    EMAlgorithm().statisticalInference(cloneset_vdj, vdj_single_model, EMAlgorithm::AlgorithmParameters().set("niter", 10));
    tp2 = std::chrono::system_clock::now();
    vdj_single_infer = std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1);

    //
    // Results
    //
    cout << "========================" << endl << "Results:" << endl;

    cout << endl;
    cout << "TCR alpha repertoire:\tsingle V-J alignment" << endl;
    cout << "TCR beta repertoire:\tsingle V-J alignment, all D alignments" << endl;

    cout << "Parsing VJ, seconds:\t" << vj_single_parse << endl;
    cout << "Parsing VDJ, seconds:\t" << vdj_single_parse << endl;

    cout << "VJ MAAG computing, seconds:\t" << vj_single_prob << endl;
    cout << "VJ MAAG metadata, seconds:\t" << vj_single_meta << endl;
    cout << "VJ inference 10 iter, seconds:\t" << vj_single_infer << endl;

    cout << "VDJ MAAG computing, seconds:\t" << vdj_single_prob << endl;
    cout << "VDJ MAAG metadata, seconds:\t" << vdj_single_meta << endl;
    cout << "VDJ inference 10 iter, seconds:\t" << vdj_single_infer << endl;

    cout << endl;
    cout << "TCR alpha repertoire:\tall good V-J alignments" << endl;
    cout << "TCR beta repertoire:\tall good V-J alignments, all D alignments" << endl;

    cout << "Parsing VJ, seconds:\t" << vj_good_parse << endl;
    cout << "Parsing VDJ, seconds:\t" << vdj_good_parse << endl;

    cout << "VJ MAAG computing, seconds:\t" << vj_good_prob << endl;
    cout << "VJ MAAG metadata, seconds:\t" << vj_good_meta << endl;
    cout << "VJ inference 10 iter, seconds:\t" << vj_good_infer << endl;

    cout << "VDJ MAAG computing, seconds:\t" << vdj_good_prob << endl;
    cout << "VDJ MAAG metadata, seconds:\t" << vdj_good_meta << endl;
    cout << "VDJ inference 10 iter, seconds:\t" << vdj_good_infer << endl;

    return 0;
}

#endif //_BENCHMARK_H_
<commit_msg>fix benchmarks<commit_after>//
// Created by Vadim N. on 18/03/2015.
//

#ifndef _BENCHMARK_H_
#define _BENCHMARK_H_

#define YMIR_BENCHMARK(expr) {}

#include <chrono>
#include <ctime>

#include "Inference"

using namespace ymir;

int main(int argc, char* argv[]) {
    std::chrono::system_clock::time_point tp1, tp2;

    time_t vj_single_parse, vdj_single_parse,
            vj_single_prob, vj_single_meta,
            vj_single_infer, vdj_single_prob,
            vdj_single_meta, vdj_single_infer;

    time_t vj_good_parse, vdj_good_parse,
            vj_good_prob, vj_good_meta,
            vj_good_infer, vdj_good_prob,
            vdj_good_meta, vdj_good_infer;

    std::string BENCH_DATA_FOLDER = argv[1];

    NaiveNucParser parser;

    //
    // TCR alpha chain repertoire - VJ recombination
    //
    VDJRecombinationGenes vj_single_genes("Vgene",
                                   BENCH_DATA_FOLDER + "trav.txt",
                                   "Jgene",
                                   BENCH_DATA_FOLDER + "traj.txt");

    tp1 = std::chrono::system_clock::now();
    Cloneset cloneset_vj;
    parser.openAndParse(BENCH_DATA_FOLDER + "alpha.500k.txt",
                        &cloneset_vj,
                        vj_single_genes,
                        NUCLEOTIDE,
                        VJ_RECOMB,
                        AlignmentColumnOptions()
                                .setV(AlignmentColumnOptions::USE_PROVIDED)
                                .setJ(AlignmentColumnOptions::USE_PROVIDED),
                        VDJAlignerParameters(1, 2));

    tp2 = std::chrono::system_clock::now();
    vj_single_parse = std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1);

    //
    // TCR beta chain repertoire - VDJ recombination
    //
    VDJRecombinationGenes vdj_single_genes("Vgene",
                                    BENCH_DATA_FOLDER + "trbv.txt",
                                    "Jgene",
                                    BENCH_DATA_FOLDER + "trbj.txt",
                                    "Dgene",
                                    BENCH_DATA_FOLDER + "trbd.txt");

    tp1 = std::chrono::system_clock::now();
    Cloneset cloneset_vdj;
    parser.openAndParse(BENCH_DATA_FOLDER + "beta.500k.txt",
                        &cloneset_vdj,
                        vdj_single_genes,
                        NUCLEOTIDE,
                        VDJ_RECOMB,
                        AlignmentColumnOptions()
                                .setV(AlignmentColumnOptions::USE_PROVIDED)
                                .setJ(AlignmentColumnOptions::USE_PROVIDED)
                                .setD(AlignmentColumnOptions::OVERWRITE),
                        VDJAlignerParameters(1, 3));

    tp2 = std::chrono::system_clock::now();
    vdj_single_parse = std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1);

    //
    // VJ MAAG
    //
    ProbabilisticAssemblingModel vj_single_model(BENCH_DATA_FOLDER + "../../models/hTRA"); //, EMPTY);

    tp1 = std::chrono::system_clock::now();
    vj_single_model.buildGraphs(cloneset_vj, SAVE_METADATA);
    tp2 = std::chrono::system_clock::now();
    vj_single_meta = std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1);

    tp1 = std::chrono::system_clock::now();
    vj_single_model.computeFullProbabilities(cloneset_vj, NO_METADATA);
    tp2 = std::chrono::system_clock::now();
    vj_single_prob = std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1);

    //
    // VDJ MAAG
    //
    ProbabilisticAssemblingModel vdj_single_model(BENCH_DATA_FOLDER + "../../models/hTRB", EMPTY);

    tp1 = std::chrono::system_clock::now();
    vdj_single_model.buildGraphs(cloneset_vdj, SAVE_METADATA);
    tp2 = std::chrono::system_clock::now();
    vdj_single_meta = std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1);

    tp1 = std::chrono::system_clock::now();
    vdj_single_model.computeFullProbabilities(cloneset_vdj, NO_METADATA);
    tp2 = std::chrono::system_clock::now();
    vdj_single_prob = std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1);

    //
    // VJ inference
    //
    tp1 = std::chrono::system_clock::now();
    EMAlgorithm().statisticalInference(cloneset_vj, vj_single_model, EMAlgorithm::AlgorithmParameters().set("niter", 10));
    tp2 = std::chrono::system_clock::now();
    vj_single_infer = std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1);

    //
    // VDJ inference
    //
    tp1 = std::chrono::system_clock::now();
    EMAlgorithm().statisticalInference(cloneset_vdj, vdj_single_model, EMAlgorithm::AlgorithmParameters().set("niter", 10));
    tp2 = std::chrono::system_clock::now();
    vdj_single_infer = std::chrono::system_clock::to_time_t(tp2)- std::chrono::system_clock::to_time_t(tp1);

    //
    // Results
    //
    cout << "========================" << endl << "Results:" << endl;

    cout << endl;
    cout << "TCR alpha repertoire:\tsingle V-J alignment" << endl;
    cout << "TCR beta repertoire:\tsingle V-J alignment, all D alignments" << endl;

    cout << "Parsing VJ, seconds:\t" << vj_single_parse << endl;
    cout << "Parsing VDJ, seconds:\t" << vdj_single_parse << endl;

    cout << "VJ MAAG computing, seconds:\t" << vj_single_prob << endl;
    cout << "VJ MAAG metadata, seconds:\t" << vj_single_meta << endl;
    cout << "VJ inference 10 iter, seconds:\t" << vj_single_infer << endl;

    cout << "VDJ MAAG computing, seconds:\t" << vdj_single_prob << endl;
    cout << "VDJ MAAG metadata, seconds:\t" << vdj_single_meta << endl;
    cout << "VDJ inference 10 iter, seconds:\t" << vdj_single_infer << endl;

    cout << endl;
    cout << "TCR alpha repertoire:\tall good V-J alignments" << endl;
    cout << "TCR beta repertoire:\tall good V-J alignments, all D alignments" << endl;

    cout << "Parsing VJ, seconds:\t" << vj_good_parse << endl;
    cout << "Parsing VDJ, seconds:\t" << vdj_good_parse << endl;

    cout << "VJ MAAG computing, seconds:\t" << vj_good_prob << endl;
    cout << "VJ MAAG metadata, seconds:\t" << vj_good_meta << endl;
    cout << "VJ inference 10 iter, seconds:\t" << vj_good_infer << endl;

    cout << "VDJ MAAG computing, seconds:\t" << vdj_good_prob << endl;
    cout << "VDJ MAAG metadata, seconds:\t" << vdj_good_meta << endl;
    cout << "VDJ inference 10 iter, seconds:\t" << vdj_good_infer << endl;

    return 0;
}

#endif //_BENCHMARK_H_
<|endoftext|>


<commit_before>// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "ClearElementCommandHandler.h"
#include "errorcodes.h"
#include "../Browser.h"
#include "../Element.h"
#include "../IECommandExecutor.h"
#include "../Generated/atoms.h"
#include "../Script.h"

namespace webdriver {

ClearElementCommandHandler::ClearElementCommandHandler(void) {
}

ClearElementCommandHandler::~ClearElementCommandHandler(void) {
}

void ClearElementCommandHandler::ExecuteInternal(
    const IECommandExecutor& executor,
    const ParametersMap& command_parameters,
    Response* response) {
  ParametersMap::const_iterator id_parameter_iterator = command_parameters.find("id");
  if (id_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "Missing parameter in URL: id");
    return;
  } else {
    int status_code = WD_SUCCESS;
    std::string element_id = id_parameter_iterator->second.asString();

    BrowserHandle browser_wrapper;
    status_code = executor.GetCurrentBrowser(&browser_wrapper);
    if (status_code != WD_SUCCESS) {
      response->SetErrorResponse(status_code, "Unable to get browser");
      return;
    }

    ElementHandle element_wrapper;
    status_code = this->GetElement(executor, element_id, &element_wrapper);
    if (status_code == WD_SUCCESS) {
      // Yes, the clear atom should check this for us, but executing it asynchronously
      // does not return the proper error code when this error condition is encountered.
      // Thus, we'll check the interactable and editable states of the element before
      // attempting to clear it.
      if (!element_wrapper->IsInteractable() || !element_wrapper->IsEditable()) {
        response->SetErrorResponse(EELEMENTNOTENABLED,
                                    "Element must not be hidden, disabled or read-only");
        return;
      }
      // The atom is just the definition of an anonymous
      // function: "function() {...}"; Wrap it in another function so we can
      // invoke it with our arguments without polluting the current namespace.
      std::wstring script_source = L"(function() { return (";
      script_source += atoms::asString(atoms::CLEAR);
      script_source += L")})();";

      Json::Value args(Json::arrayValue);
      args.append(element_wrapper->ConvertToJson());

      HWND async_executor_handle;
      CComPtr<IHTMLDocument2> doc;
      browser_wrapper->GetDocument(&doc);
      Script script_wrapper(doc, script_source);
      status_code = script_wrapper.ExecuteAsync(executor,
                                                args,
                                                ASYNC_SCRIPT_EXECUTION_TIMEOUT_IN_MILLISECONDS,
                                                &async_executor_handle);
      if (status_code != WD_SUCCESS) {
        // Assume that a JavaScript error returned by the atom is that
        // the element is either invisible, disabled, or read-only.
        // This may be a bad assumption, but we currently have no way
        // to get information about exceptions thrown from JS.
        response->SetErrorResponse(EELEMENTNOTENABLED,
                                    "A JavaScript error was encountered clearing the element. The driver assumes this is because the element is hidden, disabled or read-only, and it must not be to clear the element.");
        return;
      }
    } else if (status_code == ENOSUCHELEMENT) {
      response->SetErrorResponse(ERROR_NO_SUCH_ELEMENT, "Invalid internal element ID requested: " + element_id);
      return;
    } else {
      response->SetErrorResponse(status_code, "Element is no longer valid");
      return;
    }

    response->SetSuccessResponse(Json::Value::null);
  }
}

} // namespace webdriver
<commit_msg>Updating clear element command handler to return W3C compliant errors for IE<commit_after>// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "ClearElementCommandHandler.h"
#include "errorcodes.h"
#include "../Browser.h"
#include "../Element.h"
#include "../IECommandExecutor.h"
#include "../Generated/atoms.h"
#include "../Script.h"

namespace webdriver {

ClearElementCommandHandler::ClearElementCommandHandler(void) {
}

ClearElementCommandHandler::~ClearElementCommandHandler(void) {
}

void ClearElementCommandHandler::ExecuteInternal(
    const IECommandExecutor& executor,
    const ParametersMap& command_parameters,
    Response* response) {
  ParametersMap::const_iterator id_parameter_iterator = command_parameters.find("id");
  if (id_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "Missing parameter in URL: id");
    return;
  } else {
    int status_code = WD_SUCCESS;
    std::string element_id = id_parameter_iterator->second.asString();

    BrowserHandle browser_wrapper;
    status_code = executor.GetCurrentBrowser(&browser_wrapper);
    if (status_code != WD_SUCCESS) {
      response->SetErrorResponse(status_code, "Unable to get browser");
      return;
    }

    ElementHandle element_wrapper;
    status_code = this->GetElement(executor, element_id, &element_wrapper);
    if (status_code == WD_SUCCESS) {
      // Yes, the clear atom should check this for us, but executing it asynchronously
      // does not return the proper error code when this error condition is encountered.
      // Thus, we'll check the interactable and editable states of the element before
      // attempting to clear it.
      if (!element_wrapper->IsEditable() || !element_wrapper->IsEnabled()) {
        response->SetErrorResponse(ERROR_INVALID_ELEMENT_STATE,
                                   "Element must not be read-only or disabled");
        return;
      }
      if (!element_wrapper->IsInteractable()) {
        response->SetErrorResponse(ERROR_ELEMENT_NOT_INTERACTABLE,
                                   "Element is not interactable, it must not be hidden and it must be able to receive focus");
        return;
      }

      // The atom is just the definition of an anonymous
      // function: "function() {...}"; Wrap it in another function so we can
      // invoke it with our arguments without polluting the current namespace.
      std::wstring script_source = L"(function() { return (";
      script_source += atoms::asString(atoms::CLEAR);
      script_source += L")})();";

      Json::Value args(Json::arrayValue);
      args.append(element_wrapper->ConvertToJson());

      HWND async_executor_handle;
      CComPtr<IHTMLDocument2> doc;
      browser_wrapper->GetDocument(&doc);
      Script script_wrapper(doc, script_source);
      status_code = script_wrapper.ExecuteAsync(executor,
                                                args,
                                                ASYNC_SCRIPT_EXECUTION_TIMEOUT_IN_MILLISECONDS,
                                                &async_executor_handle);
      if (status_code != WD_SUCCESS) {
        // Assume that a JavaScript error returned by the atom is that
        // the element is either invisible, disabled, or read-only.
        // This may be a bad assumption, but we currently have no way
        // to get information about exceptions thrown from JS.
        response->SetErrorResponse(EELEMENTNOTENABLED,
                                    "A JavaScript error was encountered clearing the element. The driver assumes this is because the element is hidden, disabled or read-only, and it must not be to clear the element.");
        return;
      }
    } else if (status_code == ENOSUCHELEMENT) {
      response->SetErrorResponse(ERROR_NO_SUCH_ELEMENT, "Invalid internal element ID requested: " + element_id);
      return;
    } else {
      response->SetErrorResponse(status_code, "Element is no longer valid");
      return;
    }

    response->SetSuccessResponse(Json::Value::null);
  }
}

} // namespace webdriver
<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// The code in this file is largely based on KDE's KLineEdit class
// as included in KDE 4.5. See there for its authors:
// http://api.kde.org/4.x-api/kdelibs-apidocs/kdeui/html/klineedit_8cpp.html
//
// Copyright 2010      Dennis Nienhüser <earthwings@gentoo.org>
//

#include "RoutingLineEdit.h"
#include "global.h"

#include <QtGui/QApplication>
#include <QtGui/QClipboard>
#include <QtGui/QLabel>
#include <QtGui/QStyle>
#include <QtGui/QMouseEvent>

namespace Marble
{

class RoutingLineEditPrivate
{
public:
    QLabel* m_clearButton;

    QPixmap m_clearPixmap;

    RoutingLineEditPrivate( RoutingLineEdit* parent );
};

RoutingLineEditPrivate::RoutingLineEditPrivate( RoutingLineEdit* parent ) :
        m_clearButton( new QLabel( parent ) )
{
    m_clearButton->setCursor( Qt::ArrowCursor );
    m_clearButton->setToolTip( QObject::tr( "Clear" ) );
}

RoutingLineEdit::RoutingLineEdit( QWidget *parent ) :
        QLineEdit( parent ), d( new RoutingLineEditPrivate( this ) )
{
    updateClearButtonIcon( text() );
    updateClearButton();

    // Padding for clear button to avoid text underflow
    QString const direction = layoutDirection() == Qt::LeftToRight ? "right" : "left";
    if ( !MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen ) {
        setStyleSheet( QString( ":enabled { padding-%1: %2; }").arg( direction).arg( 18 ) );
    }

    connect( this, SIGNAL( textChanged( QString ) ), SLOT( updateClearButtonIcon( QString ) ) );
}

RoutingLineEdit::~RoutingLineEdit()
{
    delete d;
}

void RoutingLineEdit::updateClearButtonIcon( const QString& text )
{
    d->m_clearButton->setVisible( text.length() > 0 );
    if ( d->m_clearButton->pixmap() && !d->m_clearButton->pixmap()->isNull() ) {
        return;
    }

    QString const direction = layoutDirection() == Qt::LeftToRight ? "rtl" : "ltr";
    int const size = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen ? 22 : 16;
    QPixmap pixmap = QPixmap( QString( ":/icons/%1x%1/edit-clear-locationbar-%2.png").arg( size ).arg( direction ) );
    d->m_clearButton->setPixmap( pixmap );
}

void RoutingLineEdit::updateClearButton()
{
    const QSize geom = size();
    const int frameWidth = style()->pixelMetric( QStyle::PM_DefaultFrameWidth, 0, this );
    const int pixmapSize = d->m_clearButton->pixmap()->width();

    int y = ( geom.height() - pixmapSize ) / 2;
    if ( layoutDirection() == Qt::LeftToRight ) {
        d->m_clearButton->move( geom.width() - frameWidth - pixmapSize - 1, y );
    } else {
        d->m_clearButton->move( frameWidth + 1, y );
    }
}

void RoutingLineEdit::mouseReleaseEvent( QMouseEvent* e )
{
    if ( d->m_clearButton == childAt( e->pos() ) ) {
        QString newText;
        if ( e->button() == Qt::MidButton ) {
            newText = QApplication::clipboard()->text( QClipboard::Selection );
            setText( newText );
        } else {
            setSelection( 0, text().size() );
            del();
            emit clearButtonClicked();
        }
        emit textChanged( newText );
    }

    QLineEdit::mouseReleaseEvent( e );
}

void RoutingLineEdit::resizeEvent( QResizeEvent * event )
{
    updateClearButton();
    QLineEdit::resizeEvent( event );
}

} // namespace Marble

#include "RoutingLineEdit.moc"
<commit_msg>The line edits on Maemo are huge, we need even larger clear icons.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// The code in this file is largely based on KDE's KLineEdit class
// as included in KDE 4.5. See there for its authors:
// http://api.kde.org/4.x-api/kdelibs-apidocs/kdeui/html/klineedit_8cpp.html
//
// Copyright 2010      Dennis Nienhüser <earthwings@gentoo.org>
//

#include "RoutingLineEdit.h"
#include "global.h"

#include <QtGui/QApplication>
#include <QtGui/QClipboard>
#include <QtGui/QLabel>
#include <QtGui/QStyle>
#include <QtGui/QMouseEvent>

namespace Marble
{

class RoutingLineEditPrivate
{
public:
    QLabel* m_clearButton;

    QPixmap m_clearPixmap;

    RoutingLineEditPrivate( RoutingLineEdit* parent );
};

RoutingLineEditPrivate::RoutingLineEditPrivate( RoutingLineEdit* parent ) :
        m_clearButton( new QLabel( parent ) )
{
    m_clearButton->setCursor( Qt::ArrowCursor );
    m_clearButton->setToolTip( QObject::tr( "Clear" ) );
}

RoutingLineEdit::RoutingLineEdit( QWidget *parent ) :
        QLineEdit( parent ), d( new RoutingLineEditPrivate( this ) )
{
    updateClearButtonIcon( text() );
    updateClearButton();

    // Padding for clear button to avoid text underflow
    QString const direction = layoutDirection() == Qt::LeftToRight ? "right" : "left";
    if ( !MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen ) {
        setStyleSheet( QString( ":enabled { padding-%1: %2; }").arg( direction).arg( 18 ) );
    }

    connect( this, SIGNAL( textChanged( QString ) ), SLOT( updateClearButtonIcon( QString ) ) );
}

RoutingLineEdit::~RoutingLineEdit()
{
    delete d;
}

void RoutingLineEdit::updateClearButtonIcon( const QString& text )
{
    d->m_clearButton->setVisible( text.length() > 0 );
    if ( d->m_clearButton->pixmap() && !d->m_clearButton->pixmap()->isNull() ) {
        return;
    }

    QString const direction = layoutDirection() == Qt::LeftToRight ? "rtl" : "ltr";
    int const size = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen ? 32 : 16;
    QPixmap pixmap = QPixmap( QString( ":/icons/%1x%1/edit-clear-locationbar-%2.png").arg( size ).arg( direction ) );
    d->m_clearButton->setPixmap( pixmap );
}

void RoutingLineEdit::updateClearButton()
{
    const QSize geom = size();
    const int frameWidth = style()->pixelMetric( QStyle::PM_DefaultFrameWidth, 0, this );
    const int pixmapSize = d->m_clearButton->pixmap()->width();

    int y = ( geom.height() - pixmapSize ) / 2;
    if ( layoutDirection() == Qt::LeftToRight ) {
        d->m_clearButton->move( geom.width() - frameWidth - pixmapSize - 1, y );
    } else {
        d->m_clearButton->move( frameWidth + 1, y );
    }
}

void RoutingLineEdit::mouseReleaseEvent( QMouseEvent* e )
{
    if ( d->m_clearButton == childAt( e->pos() ) ) {
        QString newText;
        if ( e->button() == Qt::MidButton ) {
            newText = QApplication::clipboard()->text( QClipboard::Selection );
            setText( newText );
        } else {
            setSelection( 0, text().size() );
            del();
            emit clearButtonClicked();
        }
        emit textChanged( newText );
    }

    QLineEdit::mouseReleaseEvent( e );
}

void RoutingLineEdit::resizeEvent( QResizeEvent * event )
{
    updateClearButton();
    QLineEdit::resizeEvent( event );
}

} // namespace Marble

#include "RoutingLineEdit.moc"
<|endoftext|>


<commit_before>#include "precompiled.h"
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//

// Renderer.cpp: Implements EGL dependencies for creating and destroying Renderer instances.

#include <EGL/eglext.h>
#include "libGLESv2/main.h"
#include "libGLESv2/Program.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/renderer/Renderer11.h"
#include "libGLESv2/utilities.h"
#include "third_party/trace_event/trace_event.h"

#if !defined(ANGLE_ENABLE_D3D11)
// Enables use of the Direct3D 11 API for a default display, when available
#define ANGLE_ENABLE_D3D11 0
#endif

#if !defined(D3DCOMPILER_DLL)
#define D3DCOMPILER_DLL "NO_COMPILER"
#endif

// d3dcompiler is available to Windows Store Apps (winrt) in Windows 8.1
// using Visual Studio 2013
#if defined(ANGLE_PLATFORM_WP8)
    #pragma message("Warning: d3dcompiler dll is not available for Windows Phone 8.0. Must use precompiled shaders.")
#elif defined(ANGLE_PLATFORM_WINRT)
#if (_MSC_VER >= 1800)
    #pragma comment(lib,"d3dcompiler.lib")
#else
    #pragma message("Warning: Visual Studio 2013 and Windows 8.1 required for Windows Store App certification")
    #pragma message("Warning: Visual Studio 2012 d3dcompiler dll is available only for development of a Windows Store App.")
    #pragma message("Warning: d3dcompiler dll is not available for Windows 8.0 Store Apps. Must use precompiled shaders.")
#endif // (_MSC_VER >= 1800)
#else
#include "libGLESv2/renderer/Renderer9.h"
#endif // #if defined(ANGLE_PLATFORM_WINRT)

namespace rx
{

Renderer::Renderer(egl::Display *display) : mDisplay(display)
{
    mD3dCompilerModule = NULL;
    mD3DCompileFunc = NULL;
    mHasCompiler = TRUE;
}

Renderer::~Renderer()
{
    if (mD3dCompilerModule)
    {
        FreeLibrary(mD3dCompilerModule);
        mD3dCompilerModule = NULL;
    }
}

bool Renderer::initializeCompiler()
{
    TRACE_EVENT0("gpu", "initializeCompiler");
#if defined(ANGLE_PLATFORM_WP8)
    mD3dCompilerModule = NULL;
    mD3DCompileFunc = NULL;
    mHasCompiler = false;
    return true;
#endif //#if defined(ANGLE_PLATFORM_WP8)

#if defined(ANGLE_PLATFORM_WINRT) && (_MSC_VER >= 1800)
    ERR("No D3D compiler module available - must use precompiled shaders\n");
    mD3dCompilerModule = NULL;
    mD3DCompileFunc = reinterpret_cast<pCompileFunc>(D3DCompile);
    mHasCompiler = true;
    return true;
#endif // #if defined(ANGLE_PLATFORM_WINRT) && (_MSC_VER >= 1800)

#if defined(ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES)
    // Find a D3DCompiler module that had already been loaded based on a predefined list of versions.
    static TCHAR* d3dCompilerNames[] = ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES;

    for (size_t i = 0; i < ArraySize(d3dCompilerNames); ++i)
    {
        if (GetModuleHandleEx(0, d3dCompilerNames[i], &mD3dCompilerModule))
        {
            break;
        }
    }
#else
    // Load the version of the D3DCompiler DLL associated with the Direct3D version ANGLE was built with.
#if defined(ANGLE_PLATFORM_WINRT)
    mD3dCompilerModule = LoadPackagedLibrary((LPCWSTR)D3DCOMPILER_DLL, 0);
    if (!mD3dCompilerModule)
    {
        ERR("No D3D compiler module found - must use precompiled shaders\n");
        mD3DCompileFunc = NULL;
        mHasCompiler = false;
        return true;
    }
#else
    mD3dCompilerModule = LoadLibrary(D3DCOMPILER_DLL);
#endif //
#endif  // ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES

    if (!mD3dCompilerModule)
    {
        ERR("No D3D compiler module found - aborting!\n");
        mHasCompiler = FALSE;
        return false;
    }

    mD3DCompileFunc = reinterpret_cast<pCompileFunc>(GetProcAddress(mD3dCompilerModule, "D3DCompile"));
    ASSERT(mD3DCompileFunc);

    return mD3DCompileFunc != NULL;
}

#if !defined(ANGLE_PLATFORM_WP8)
// Compiles HLSL code into executable binaries
ShaderBlob *Renderer::compileToBinary(gl::InfoLog &infoLog, const char *hlsl, const char *profile, UINT optimizationFlags, bool alternateFlags)
{
    if (!hlsl)
    {
        return NULL;
    }

    HRESULT result = S_OK;
    UINT flags = 0;
    std::string sourceText;
    if (gl::perfActive())
    {
        flags |= D3DCOMPILE_DEBUG;

#ifdef NDEBUG
        flags |= optimizationFlags;
#else
        flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
#endif

        std::string sourcePath = getTempPath();
        sourceText = std::string("#line 2 \"") + sourcePath + std::string("\"\n\n") + std::string(hlsl);
        writeFile(sourcePath.c_str(), sourceText.c_str(), sourceText.size());
    }
    else
    {
        flags |= optimizationFlags;
        sourceText = hlsl;
    }

    // Sometimes D3DCompile will fail with the default compilation flags for complicated shaders when it would otherwise pass with alternative options.
    // Try the default flags first and if compilation fails, try some alternatives.
    const static UINT extraFlags[] =
    {
        0,
        D3DCOMPILE_AVOID_FLOW_CONTROL,
        D3DCOMPILE_PREFER_FLOW_CONTROL
    };

    const static char * const extraFlagNames[] =
    {
        "default",
        "avoid flow control",
        "prefer flow control"
    };

    int attempts = alternateFlags ? ArraySize(extraFlags) : 1;
    pD3DCompile compileFunc = reinterpret_cast<pD3DCompile>(mD3DCompileFunc);
    for (int i = 0; i < attempts; ++i)
    {
        ID3DBlob *errorMessage = NULL;
        ID3DBlob *binary = NULL;

        result = compileFunc(hlsl, strlen(hlsl), gl::g_fakepath, NULL, NULL,
                             "main", profile, flags | extraFlags[i], 0, &binary, &errorMessage);
        if (errorMessage)
        {
            const char *message = (const char*)errorMessage->GetBufferPointer();

            infoLog.appendSanitized(message);
            TRACE("\n%s", hlsl);
            TRACE("\n%s", message);

            errorMessage->Release();
            errorMessage = NULL;
        }

        if (SUCCEEDED(result))
        {
            return (ShaderBlob*)binary;
        }
        else
        {
#if defined(ANGLE_PLATFORM_WINRT)
            if (result == E_OUTOFMEMORY)
#else
            if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY)
#endif // #if defined(ANGLE_PLATFORM_WINRT)
            {
                return gl::error(GL_OUT_OF_MEMORY, (ShaderBlob*) NULL);
            }

            infoLog.append("Warning: D3D shader compilation failed with ");
            infoLog.append(extraFlagNames[i]);
            infoLog.append(" flags.");
            if (i + 1 < attempts)
            {
                infoLog.append(" Retrying with ");
                infoLog.append(extraFlagNames[i + 1]);
                infoLog.append(".\n");
            }
        }
    }
    return NULL;
}
#endif // #if !defined(ANGLE_PLATFORM_WP8)

}

extern "C"
{

rx::Renderer *glCreateRenderer(egl::Display *display, AngleNativeWindowHDC hDc, EGLNativeDisplayType displayId)
{
    rx::Renderer *renderer = NULL;
    EGLint status = EGL_BAD_ALLOC;

#if defined(ANGLE_PLATFORM_WINRT)
	renderer = new rx::Renderer11(display, hDc);
	if (renderer)
	{
		status = renderer->initialize();
	}

	return status == EGL_SUCCESS ? renderer : NULL;
#else
    if (ANGLE_ENABLE_D3D11 ||
        displayId == EGL_D3D11_ELSE_D3D9_DISPLAY_ANGLE ||
        displayId == EGL_D3D11_ONLY_DISPLAY_ANGLE)
    {
        renderer = new rx::Renderer11(display, hDc);

        if (renderer)
        {
            status = renderer->initialize();
        }

        if (status == EGL_SUCCESS)
        {
            return renderer;
        }
        else if (displayId == EGL_D3D11_ONLY_DISPLAY_ANGLE)
        {
            return NULL;
        }

        // Failed to create a D3D11 renderer, try creating a D3D9 renderer
        delete renderer;
    }
#endif

#if !defined(ANGLE_PLATFORM_WINRT)
    bool softwareDevice = (displayId == EGL_SOFTWARE_DISPLAY_ANGLE);
    renderer = new rx::Renderer9(display, hDc, softwareDevice);
#endif //#if !defined(ANGLE_PLATFORM_WINRT)

    if (renderer)
    {
        status = renderer->initialize();
    }

    if (status == EGL_SUCCESS)
    {
        return renderer;
    }

    return NULL;
}

void glDestroyRenderer(rx::Renderer *renderer)
{
    delete renderer;
}

}<commit_msg>use LoadLibrary for WINAPI_PARTITION_DESKTOP<commit_after>#include "precompiled.h"
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//

// Renderer.cpp: Implements EGL dependencies for creating and destroying Renderer instances.

#include <EGL/eglext.h>
#include "libGLESv2/main.h"
#include "libGLESv2/Program.h"
#include "libGLESv2/renderer/Renderer.h"
#include "libGLESv2/renderer/Renderer11.h"
#include "libGLESv2/utilities.h"
#include "third_party/trace_event/trace_event.h"

#if !defined(ANGLE_ENABLE_D3D11)
// Enables use of the Direct3D 11 API for a default display, when available
#define ANGLE_ENABLE_D3D11 0
#endif

#if !defined(D3DCOMPILER_DLL)
#define D3DCOMPILER_DLL "NO_COMPILER"
#endif

// d3dcompiler is available to Windows Store Apps (winrt) in Windows 8.1
// using Visual Studio 2013
#if defined(ANGLE_PLATFORM_WP8)
    #pragma message("Warning: d3dcompiler dll is not available for Windows Phone 8.0. Must use precompiled shaders.")
#elif defined(ANGLE_PLATFORM_WINRT)
#if (_MSC_VER >= 1800)
    #pragma comment(lib,"d3dcompiler.lib")
#else
    #pragma message("Warning: Visual Studio 2013 and Windows 8.1 required for Windows Store App certification")
    #pragma message("Warning: Visual Studio 2012 d3dcompiler dll is available only for development of a Windows Store App.")
    #pragma message("Warning: d3dcompiler dll is not available for Windows 8.0 Store Apps. Must use precompiled shaders.")
#endif // (_MSC_VER >= 1800)
#else
#include "libGLESv2/renderer/Renderer9.h"
#endif // #if defined(ANGLE_PLATFORM_WINRT)

namespace rx
{

Renderer::Renderer(egl::Display *display) : mDisplay(display)
{
    mD3dCompilerModule = NULL;
    mD3DCompileFunc = NULL;
    mHasCompiler = TRUE;
}

Renderer::~Renderer()
{
    if (mD3dCompilerModule)
    {
        FreeLibrary(mD3dCompilerModule);
        mD3dCompilerModule = NULL;
    }
}

bool Renderer::initializeCompiler()
{
    TRACE_EVENT0("gpu", "initializeCompiler");
#if defined(ANGLE_PLATFORM_WP8)
    mD3dCompilerModule = NULL;
    mD3DCompileFunc = NULL;
    mHasCompiler = false;
    return true;
#endif //#if defined(ANGLE_PLATFORM_WP8)

#if defined(ANGLE_PLATFORM_WINRT) && (_MSC_VER >= 1800)
    ERR("No D3D compiler module available - must use precompiled shaders\n");
    mD3dCompilerModule = NULL;
    mD3DCompileFunc = reinterpret_cast<pCompileFunc>(D3DCompile);
    mHasCompiler = true;
    return true;
#endif // #if defined(ANGLE_PLATFORM_WINRT) && (_MSC_VER >= 1800)

#if defined(ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES)
    // Find a D3DCompiler module that had already been loaded based on a predefined list of versions.
    static TCHAR* d3dCompilerNames[] = ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES;

    for (size_t i = 0; i < ArraySize(d3dCompilerNames); ++i)
    {
        if (GetModuleHandleEx(0, d3dCompilerNames[i], &mD3dCompilerModule))
        {
            break;
        }
    }
#else
    // Load the version of the D3DCompiler DLL associated with the Direct3D version ANGLE was built with.
#if defined(ANGLE_PLATFORM_WINRT)
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
    mD3dCompilerModule = LoadLibrary(D3DCOMPILER_DLL);
#else
    mD3dCompilerModule = LoadPackagedLibrary((LPCWSTR)D3DCOMPILER_DLL, 0);
#endif
    if (!mD3dCompilerModule)
    {
        ERR("No D3D compiler module found - must use precompiled shaders\n");
        mD3DCompileFunc = NULL;
        mHasCompiler = false;
        return true;
    }
#else
    mD3dCompilerModule = LoadLibrary(D3DCOMPILER_DLL);
#endif //
#endif  // ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES

    if (!mD3dCompilerModule)
    {
        ERR("No D3D compiler module found - aborting!\n");
        mHasCompiler = FALSE;
        return false;
    }

    mD3DCompileFunc = reinterpret_cast<pCompileFunc>(GetProcAddress(mD3dCompilerModule, "D3DCompile"));
    ASSERT(mD3DCompileFunc);

    return mD3DCompileFunc != NULL;
}

#if !defined(ANGLE_PLATFORM_WP8)
// Compiles HLSL code into executable binaries
ShaderBlob *Renderer::compileToBinary(gl::InfoLog &infoLog, const char *hlsl, const char *profile, UINT optimizationFlags, bool alternateFlags)
{
    if (!hlsl)
    {
        return NULL;
    }

    HRESULT result = S_OK;
    UINT flags = 0;
    std::string sourceText;
    if (gl::perfActive())
    {
        flags |= D3DCOMPILE_DEBUG;

#ifdef NDEBUG
        flags |= optimizationFlags;
#else
        flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
#endif

        std::string sourcePath = getTempPath();
        sourceText = std::string("#line 2 \"") + sourcePath + std::string("\"\n\n") + std::string(hlsl);
        writeFile(sourcePath.c_str(), sourceText.c_str(), sourceText.size());
    }
    else
    {
        flags |= optimizationFlags;
        sourceText = hlsl;
    }

    // Sometimes D3DCompile will fail with the default compilation flags for complicated shaders when it would otherwise pass with alternative options.
    // Try the default flags first and if compilation fails, try some alternatives.
    const static UINT extraFlags[] =
    {
        0,
        D3DCOMPILE_AVOID_FLOW_CONTROL,
        D3DCOMPILE_PREFER_FLOW_CONTROL
    };

    const static char * const extraFlagNames[] =
    {
        "default",
        "avoid flow control",
        "prefer flow control"
    };

    int attempts = alternateFlags ? ArraySize(extraFlags) : 1;
    pD3DCompile compileFunc = reinterpret_cast<pD3DCompile>(mD3DCompileFunc);
    for (int i = 0; i < attempts; ++i)
    {
        ID3DBlob *errorMessage = NULL;
        ID3DBlob *binary = NULL;

        result = compileFunc(hlsl, strlen(hlsl), gl::g_fakepath, NULL, NULL,
                             "main", profile, flags | extraFlags[i], 0, &binary, &errorMessage);
        if (errorMessage)
        {
            const char *message = (const char*)errorMessage->GetBufferPointer();

            infoLog.appendSanitized(message);
            TRACE("\n%s", hlsl);
            TRACE("\n%s", message);

            errorMessage->Release();
            errorMessage = NULL;
        }

        if (SUCCEEDED(result))
        {
            return (ShaderBlob*)binary;
        }
        else
        {
#if defined(ANGLE_PLATFORM_WINRT)
            if (result == E_OUTOFMEMORY)
#else
            if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY)
#endif // #if defined(ANGLE_PLATFORM_WINRT)
            {
                return gl::error(GL_OUT_OF_MEMORY, (ShaderBlob*) NULL);
            }

            infoLog.append("Warning: D3D shader compilation failed with ");
            infoLog.append(extraFlagNames[i]);
            infoLog.append(" flags.");
            if (i + 1 < attempts)
            {
                infoLog.append(" Retrying with ");
                infoLog.append(extraFlagNames[i + 1]);
                infoLog.append(".\n");
            }
        }
    }
    return NULL;
}
#endif // #if !defined(ANGLE_PLATFORM_WP8)

}

extern "C"
{

rx::Renderer *glCreateRenderer(egl::Display *display, AngleNativeWindowHDC hDc, EGLNativeDisplayType displayId)
{
    rx::Renderer *renderer = NULL;
    EGLint status = EGL_BAD_ALLOC;

#if defined(ANGLE_PLATFORM_WINRT)
	renderer = new rx::Renderer11(display, hDc);
	if (renderer)
	{
		status = renderer->initialize();
	}

	return status == EGL_SUCCESS ? renderer : NULL;
#else
    if (ANGLE_ENABLE_D3D11 ||
        displayId == EGL_D3D11_ELSE_D3D9_DISPLAY_ANGLE ||
        displayId == EGL_D3D11_ONLY_DISPLAY_ANGLE)
    {
        renderer = new rx::Renderer11(display, hDc);

        if (renderer)
        {
            status = renderer->initialize();
        }

        if (status == EGL_SUCCESS)
        {
            return renderer;
        }
        else if (displayId == EGL_D3D11_ONLY_DISPLAY_ANGLE)
        {
            return NULL;
        }

        // Failed to create a D3D11 renderer, try creating a D3D9 renderer
        delete renderer;
    }
#endif

#if !defined(ANGLE_PLATFORM_WINRT)
    bool softwareDevice = (displayId == EGL_SOFTWARE_DISPLAY_ANGLE);
    renderer = new rx::Renderer9(display, hDc, softwareDevice);
#endif //#if !defined(ANGLE_PLATFORM_WINRT)

    if (renderer)
    {
        status = renderer->initialize();
    }

    if (status == EGL_SUCCESS)
    {
        return renderer;
    }

    return NULL;
}

void glDestroyRenderer(rx::Renderer *renderer)
{
    delete renderer;
}

}<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "tcpportsgatherer.h"
#include "qtcassert.h"

#include <QDebug>
#include <QFile>
#include <QProcess>
#include <QStringList>

#ifdef Q_OS_WIN
#include <QLibrary>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#endif

#if defined(Q_OS_WIN) && defined(Q_CC_MINGW)

// Missing declarations for MinGW. This requires MinGW with gcc 4.6.
typedef enum { } MIB_TCP_STATE;

typedef struct _MIB_TCP6ROW {
    MIB_TCP_STATE State;
    IN6_ADDR LocalAddr;
    DWORD dwLocalScopeId;
    DWORD dwLocalPort;
    IN6_ADDR RemoteAddr;
    DWORD dwRemoteScopeId;
    DWORD dwRemotePort;
} MIB_TCP6ROW, *PMIB_TCP6ROW;

typedef struct _MIB_TCP6TABLE {
    DWORD dwNumEntries;
    MIB_TCP6ROW table[ANY_SIZE];
} MIB_TCP6TABLE, *PMIB_TCP6TABLE;

#endif // defined(Q_OS_WIN) && defined(Q_CC_MINGW)

namespace Utils {
namespace Internal {

class TcpPortsGathererPrivate
{
public:
    TcpPortsGathererPrivate(TcpPortsGatherer::ProtocolFlags protocolFlags)
        : protocolFlags(protocolFlags) {}

    TcpPortsGatherer::ProtocolFlags protocolFlags;
    PortList usedPorts;

    void updateWin(TcpPortsGatherer::ProtocolFlags protocolFlags);
    void updateLinux(TcpPortsGatherer::ProtocolFlags protocolFlags);
    void updateNetstat(TcpPortsGatherer::ProtocolFlags protocolFlags);
};

#ifdef Q_OS_WIN
template <typename Table >
QSet<int> usedTcpPorts(ULONG (__stdcall *Func)(Table*, PULONG, BOOL))
{
    Table *table = static_cast<Table*>(malloc(sizeof(Table)));
    DWORD dwSize = sizeof(Table);

    // get the necessary size into the dwSize variable
    DWORD dwRetVal = Func(table, &dwSize, false);
    if (dwRetVal == ERROR_INSUFFICIENT_BUFFER) {
        free(table);
        table = static_cast<Table*>(malloc(dwSize));
    }

    // get the actual data
    QSet<int> result;
    dwRetVal = Func(table, &dwSize, false);
    if (dwRetVal == NO_ERROR) {
        for (quint32 i = 0; i < table->dwNumEntries; i++) {
            quint16 port = ntohs(table->table[i].dwLocalPort);
            if (!result.contains(port))
                result.insert(port);
        }
    } else {
        qWarning() << "TcpPortsGatherer: GetTcpTable failed with" << dwRetVal;
    }

    free(table);
    return result;
}
#endif

void TcpPortsGathererPrivate::updateWin(TcpPortsGatherer::ProtocolFlags protocolFlags)
{
#ifdef Q_OS_WIN
    QSet<int> ports;

    if (protocolFlags & TcpPortsGatherer::IPv4Protocol)
        ports.unite(usedTcpPorts<MIB_TCPTABLE>(GetTcpTable));

    //Dynamically load symbol for GetTcp6Table for systems that dont have support for IPV6,
    //eg Windows XP
    typedef ULONG (__stdcall *GetTcp6TablePtr)(PMIB_TCP6TABLE, PULONG, BOOL);
    static GetTcp6TablePtr getTcp6TablePtr = 0;

    if (!getTcp6TablePtr)
        getTcp6TablePtr = (GetTcp6TablePtr)QLibrary::resolve(QLatin1String("Iphlpapi.dll"),
                                                             "GetTcp6Table");

    if (getTcp6TablePtr && (protocolFlags & TcpPortsGatherer::IPv6Protocol))
        ports.unite(usedTcpPorts<MIB_TCP6TABLE>(getTcp6TablePtr));

    foreach (int port, ports) {
        if (!usedPorts.contains(port))
            usedPorts.addPort(port);
    }
#endif
    Q_UNUSED(protocolFlags);
}

void TcpPortsGathererPrivate::updateLinux(TcpPortsGatherer::ProtocolFlags protocolFlags)
{
    QStringList filePaths;
    if (protocolFlags & TcpPortsGatherer::IPv4Protocol)
        filePaths.append(QLatin1String("/proc/net/tcp"));
    if (protocolFlags & TcpPortsGatherer::IPv6Protocol)
        filePaths.append(QLatin1String("/proc/net/tcp6"));

    foreach (const QString &filePath, filePaths) {
        QFile file(filePath);
        if (!file.open(QFile::ReadOnly | QFile::Text)) {
            qWarning() << "TcpPortsGatherer: Cannot open file"
                       << filePath << ":" << file.errorString();
            continue;
        }

        if (file.atEnd()) // read first line describing the output
            file.readLine();

        static QRegExp pattern(QLatin1String("^\\s*" // start of line, whitespace
                                             "\\d+:\\s*" // integer, colon, space
                                             "[0-9A-Fa-f]+:" // hexadecimal number (ip), colon
                                             "([0-9A-Fa-f]+)"  // hexadecimal number (port!)
                                             ));
        while (!file.atEnd()) {
            QByteArray line = file.readLine();
            if (pattern.indexIn(line) != -1) {
                bool isNumber;
                quint16 port = pattern.cap(1).toUShort(&isNumber, 16);
                QTC_ASSERT(isNumber, continue);
                if (!usedPorts.contains(port))
                    usedPorts.addPort(port);
            } else {
                qWarning() << "TcpPortsGatherer: File" << filePath << "has unexpected format.";
                continue;
            }
        }
    }
}

// Only works with FreeBSD version of netstat like we have on Mac OS X
void TcpPortsGathererPrivate::updateNetstat(TcpPortsGatherer::ProtocolFlags protocolFlags)
{
    QStringList netstatArgs;

    netstatArgs.append(QLatin1String("-a"));     // show also sockets of server processes
    netstatArgs.append(QLatin1String("-n"));     // show network addresses as numbers
    netstatArgs.append(QLatin1String("-p"));
    netstatArgs.append(QLatin1String("tcp"));
    if (protocolFlags != TcpPortsGatherer::AnyIPProcol) {
        netstatArgs.append(QLatin1String("-f")); // limit to address family
        if (protocolFlags == TcpPortsGatherer::IPv4Protocol)
            netstatArgs.append(QLatin1String("inet"));
        else
            netstatArgs.append(QLatin1String("inet6"));
    }

    QProcess netstatProcess;
    netstatProcess.start(QLatin1String("netstat"), netstatArgs);
    if (!netstatProcess.waitForFinished(30000)) {
        qWarning() << "TcpPortsGatherer: netstat did not return in time.";
        return;
    }

    QList<QByteArray> output = netstatProcess.readAllStandardOutput().split('\n');
    foreach (const QByteArray &line, output) {
        static QRegExp pattern(QLatin1String("^tcp[46]+" // "tcp", followed by "4", "6", "46"
                                             "\\s+\\d+"           // whitespace, number (Recv-Q)
                                             "\\s+\\d+"           // whitespace, number (Send-Q)
                                             "\\s+(\\S+)"));       // whitespace, Local Address
        if (pattern.indexIn(line) != -1) {
            QString localAddress = pattern.cap(1);

            // Examples of local addresses:
            // '*.56501' , '*.*' 'fe80::1%lo0.123'
            int portDelimiterPos = localAddress.lastIndexOf(".");
            if (portDelimiterPos == -1)
                continue;

            localAddress = localAddress.mid(portDelimiterPos + 1);
            bool isNumber;
            quint16 port = localAddress.toUShort(&isNumber);
            if (!isNumber)
                continue;

            if (!usedPorts.contains(port))
                usedPorts.addPort(port);
        }
    }
}

} // namespace Internal

/*!
  \class Utils::TcpPortsGatherer

  \brief Gather the list of local TCP ports already in use.

  Query the system for the list of local TCP ports already in use. This information can be used
  to select a port for use in a range.
*/

TcpPortsGatherer::TcpPortsGatherer(TcpPortsGatherer::ProtocolFlags protocolFlags)
    : d(new Internal::TcpPortsGathererPrivate(protocolFlags))
{
    update();
}

TcpPortsGatherer::~TcpPortsGatherer()
{
    delete d;
}

void TcpPortsGatherer::update()
{
    d->usedPorts = PortList();

#if defined(Q_OS_WIN)
    d->updateWin(d->protocolFlags);
#elif defined(Q_OS_LINUX)
    d->updateLinux(d->protocolFlags);
#else
    d->updateNetstat(d->protocolFlags);
#endif
}

PortList TcpPortsGatherer::usedPorts() const
{
    return d->usedPorts;
}

/*!
  Select a port out of \a freePorts that is not yet used.

  Returns the port, or 0 if no free port is available.
  */
quint16 TcpPortsGatherer::getNextFreePort(PortList *freePorts)
{
    QTC_ASSERT(freePorts, return 0);
    while (freePorts->hasMore()) {
        const int port = freePorts->getNext();
        if (!d->usedPorts.contains(port))
            return port;
    }
    return 0;
}

} // namespace Utils
<commit_msg>tcpportsgatherer.cpp: Fix compilation with MinGW/gcc 4.7.1.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "tcpportsgatherer.h"
#include "qtcassert.h"

#include <QDebug>
#include <QFile>
#include <QProcess>
#include <QStringList>

#ifdef Q_OS_WIN
#include <QLibrary>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#endif

#if defined(Q_OS_WIN) && defined(Q_CC_MINGW)

// Missing declarations for MinGW. This requires MinGW with gcc 4.6.
#if __GNUC__ == 4 && __GNUC_MINOR__ < 7
typedef enum { } MIB_TCP_STATE;
#endif

typedef struct _MIB_TCP6ROW {
    MIB_TCP_STATE State;
    IN6_ADDR LocalAddr;
    DWORD dwLocalScopeId;
    DWORD dwLocalPort;
    IN6_ADDR RemoteAddr;
    DWORD dwRemoteScopeId;
    DWORD dwRemotePort;
} MIB_TCP6ROW, *PMIB_TCP6ROW;

typedef struct _MIB_TCP6TABLE {
    DWORD dwNumEntries;
    MIB_TCP6ROW table[ANY_SIZE];
} MIB_TCP6TABLE, *PMIB_TCP6TABLE;

#endif // defined(Q_OS_WIN) && defined(Q_CC_MINGW)

namespace Utils {
namespace Internal {

class TcpPortsGathererPrivate
{
public:
    TcpPortsGathererPrivate(TcpPortsGatherer::ProtocolFlags protocolFlags)
        : protocolFlags(protocolFlags) {}

    TcpPortsGatherer::ProtocolFlags protocolFlags;
    PortList usedPorts;

    void updateWin(TcpPortsGatherer::ProtocolFlags protocolFlags);
    void updateLinux(TcpPortsGatherer::ProtocolFlags protocolFlags);
    void updateNetstat(TcpPortsGatherer::ProtocolFlags protocolFlags);
};

#ifdef Q_OS_WIN
template <typename Table >
QSet<int> usedTcpPorts(ULONG (__stdcall *Func)(Table*, PULONG, BOOL))
{
    Table *table = static_cast<Table*>(malloc(sizeof(Table)));
    DWORD dwSize = sizeof(Table);

    // get the necessary size into the dwSize variable
    DWORD dwRetVal = Func(table, &dwSize, false);
    if (dwRetVal == ERROR_INSUFFICIENT_BUFFER) {
        free(table);
        table = static_cast<Table*>(malloc(dwSize));
    }

    // get the actual data
    QSet<int> result;
    dwRetVal = Func(table, &dwSize, false);
    if (dwRetVal == NO_ERROR) {
        for (quint32 i = 0; i < table->dwNumEntries; i++) {
            quint16 port = ntohs(table->table[i].dwLocalPort);
            if (!result.contains(port))
                result.insert(port);
        }
    } else {
        qWarning() << "TcpPortsGatherer: GetTcpTable failed with" << dwRetVal;
    }

    free(table);
    return result;
}
#endif

void TcpPortsGathererPrivate::updateWin(TcpPortsGatherer::ProtocolFlags protocolFlags)
{
#ifdef Q_OS_WIN
    QSet<int> ports;

    if (protocolFlags & TcpPortsGatherer::IPv4Protocol)
        ports.unite(usedTcpPorts<MIB_TCPTABLE>(GetTcpTable));

    //Dynamically load symbol for GetTcp6Table for systems that dont have support for IPV6,
    //eg Windows XP
    typedef ULONG (__stdcall *GetTcp6TablePtr)(PMIB_TCP6TABLE, PULONG, BOOL);
    static GetTcp6TablePtr getTcp6TablePtr = 0;

    if (!getTcp6TablePtr)
        getTcp6TablePtr = (GetTcp6TablePtr)QLibrary::resolve(QLatin1String("Iphlpapi.dll"),
                                                             "GetTcp6Table");

    if (getTcp6TablePtr && (protocolFlags & TcpPortsGatherer::IPv6Protocol))
        ports.unite(usedTcpPorts<MIB_TCP6TABLE>(getTcp6TablePtr));

    foreach (int port, ports) {
        if (!usedPorts.contains(port))
            usedPorts.addPort(port);
    }
#endif
    Q_UNUSED(protocolFlags);
}

void TcpPortsGathererPrivate::updateLinux(TcpPortsGatherer::ProtocolFlags protocolFlags)
{
    QStringList filePaths;
    if (protocolFlags & TcpPortsGatherer::IPv4Protocol)
        filePaths.append(QLatin1String("/proc/net/tcp"));
    if (protocolFlags & TcpPortsGatherer::IPv6Protocol)
        filePaths.append(QLatin1String("/proc/net/tcp6"));

    foreach (const QString &filePath, filePaths) {
        QFile file(filePath);
        if (!file.open(QFile::ReadOnly | QFile::Text)) {
            qWarning() << "TcpPortsGatherer: Cannot open file"
                       << filePath << ":" << file.errorString();
            continue;
        }

        if (file.atEnd()) // read first line describing the output
            file.readLine();

        static QRegExp pattern(QLatin1String("^\\s*" // start of line, whitespace
                                             "\\d+:\\s*" // integer, colon, space
                                             "[0-9A-Fa-f]+:" // hexadecimal number (ip), colon
                                             "([0-9A-Fa-f]+)"  // hexadecimal number (port!)
                                             ));
        while (!file.atEnd()) {
            QByteArray line = file.readLine();
            if (pattern.indexIn(line) != -1) {
                bool isNumber;
                quint16 port = pattern.cap(1).toUShort(&isNumber, 16);
                QTC_ASSERT(isNumber, continue);
                if (!usedPorts.contains(port))
                    usedPorts.addPort(port);
            } else {
                qWarning() << "TcpPortsGatherer: File" << filePath << "has unexpected format.";
                continue;
            }
        }
    }
}

// Only works with FreeBSD version of netstat like we have on Mac OS X
void TcpPortsGathererPrivate::updateNetstat(TcpPortsGatherer::ProtocolFlags protocolFlags)
{
    QStringList netstatArgs;

    netstatArgs.append(QLatin1String("-a"));     // show also sockets of server processes
    netstatArgs.append(QLatin1String("-n"));     // show network addresses as numbers
    netstatArgs.append(QLatin1String("-p"));
    netstatArgs.append(QLatin1String("tcp"));
    if (protocolFlags != TcpPortsGatherer::AnyIPProcol) {
        netstatArgs.append(QLatin1String("-f")); // limit to address family
        if (protocolFlags == TcpPortsGatherer::IPv4Protocol)
            netstatArgs.append(QLatin1String("inet"));
        else
            netstatArgs.append(QLatin1String("inet6"));
    }

    QProcess netstatProcess;
    netstatProcess.start(QLatin1String("netstat"), netstatArgs);
    if (!netstatProcess.waitForFinished(30000)) {
        qWarning() << "TcpPortsGatherer: netstat did not return in time.";
        return;
    }

    QList<QByteArray> output = netstatProcess.readAllStandardOutput().split('\n');
    foreach (const QByteArray &line, output) {
        static QRegExp pattern(QLatin1String("^tcp[46]+" // "tcp", followed by "4", "6", "46"
                                             "\\s+\\d+"           // whitespace, number (Recv-Q)
                                             "\\s+\\d+"           // whitespace, number (Send-Q)
                                             "\\s+(\\S+)"));       // whitespace, Local Address
        if (pattern.indexIn(line) != -1) {
            QString localAddress = pattern.cap(1);

            // Examples of local addresses:
            // '*.56501' , '*.*' 'fe80::1%lo0.123'
            int portDelimiterPos = localAddress.lastIndexOf(".");
            if (portDelimiterPos == -1)
                continue;

            localAddress = localAddress.mid(portDelimiterPos + 1);
            bool isNumber;
            quint16 port = localAddress.toUShort(&isNumber);
            if (!isNumber)
                continue;

            if (!usedPorts.contains(port))
                usedPorts.addPort(port);
        }
    }
}

} // namespace Internal

/*!
  \class Utils::TcpPortsGatherer

  \brief Gather the list of local TCP ports already in use.

  Query the system for the list of local TCP ports already in use. This information can be used
  to select a port for use in a range.
*/

TcpPortsGatherer::TcpPortsGatherer(TcpPortsGatherer::ProtocolFlags protocolFlags)
    : d(new Internal::TcpPortsGathererPrivate(protocolFlags))
{
    update();
}

TcpPortsGatherer::~TcpPortsGatherer()
{
    delete d;
}

void TcpPortsGatherer::update()
{
    d->usedPorts = PortList();

#if defined(Q_OS_WIN)
    d->updateWin(d->protocolFlags);
#elif defined(Q_OS_LINUX)
    d->updateLinux(d->protocolFlags);
#else
    d->updateNetstat(d->protocolFlags);
#endif
}

PortList TcpPortsGatherer::usedPorts() const
{
    return d->usedPorts;
}

/*!
  Select a port out of \a freePorts that is not yet used.

  Returns the port, or 0 if no free port is available.
  */
quint16 TcpPortsGatherer::getNextFreePort(PortList *freePorts)
{
    QTC_ASSERT(freePorts, return 0);
    while (freePorts->hasMore()) {
        const int port = freePorts->getNext();
        if (!d->usedPorts.contains(port))
            return port;
    }
    return 0;
}

} // namespace Utils
<|endoftext|>


<commit_before>/*

*/

#include "lineFollowing.h"
#include "../control.h"

using namespace std;
using namespace cv;

void detect_lines(Mat &original_frame, double scale_factor);

#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection"
void line_main() {
//  printf("Hello, this is Caleb\n");
//  no this is patric

  VideoCapture cap("../../tests/videos/top_down_1.m4v");
  if (!cap.isOpened())  // check if we succeeded
    return;

//  Mat edges;
  for (; ;) {
    Mat frame;
    cap >> frame; // get a new frame from camera

    detect_lines(frame, .2);

    if (waitKey(30) >= 0) break;

  }
  // the camera will be deinitialized automatically in VideoCapture destructor

  return;
}
#pragma clang diagnostic pop

void detect_lines(Mat &original_frame, double scale_factor) {

  Mat hsv;
  Mat mask;
  Mat image;

  resize(original_frame, image, Size(), scale_factor, scale_factor); //Potentially scale down the frame

  cvtColor(image, hsv, CV_BGR2HSV); // Image is now HSV

  double minH = 50;
  double minS = 20;
  double minV = 150;
  double maxH = 125;
  double maxS = 100;
  double maxV = 255;

  Scalar lower(minH, minS, minV);
  Scalar upper(maxH, maxS, maxV);
  inRange(hsv, lower, upper, mask); // Create a mask of only the desired color

  vector<Vec4i> lines;
  HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 50, 10); // Find all lines in the image

  printf("Adding in %d lines\n", (int) lines.size());
  for (size_t i = 0; i < lines.size(); i++) {
    Vec4i l = lines[i];
    line(image, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 1, CV_AA);
    // break;
  }
//    if (lines.size() < 1) continue;

//  imshow("line_window", image);
  resize(image, original_frame, Size(), 1/scale_factor, 1/scale_factor);
}

LineFollowing::LineFollowing(Control *control) {
  namedWindow("line_window", CV_WINDOW_NORMAL);
  control_ptr = control;
  return;
}

void LineFollowing::close() {
  return;
}

void LineFollowing::fly() {

  control_ptr->velocities.vx = 0;
  control_ptr->velocities.vy = 0;
  control_ptr->velocities.vz = 0;
  control_ptr->velocities.vr = 0;

  detect_lines(control_ptr->image, 0.3);

  return;
}
<commit_msg>changing hough<commit_after>/*

*/

#include "lineFollowing.h"
#include "../control.h"

using namespace std;
using namespace cv;

void detect_lines(Mat &original_frame, double scale_factor);

#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection"

void line_main() {
//  printf("Hello, this is Caleb\n");
//  no this is patric

  VideoCapture cap("../../tests/videos/top_down_1.m4v");
  if (!cap.isOpened())  // check if we succeeded
    return;

//  Mat edges;
  for (; ;) {
    Mat frame;
    cap >> frame; // get a new frame from camera

    detect_lines(frame, .2);

    if (waitKey(30) >= 0) break;

  }
  // the camera will be deinitialized automatically in VideoCapture destructor

  return;
}

#pragma clang diagnostic pop

void detect_lines(Mat &original_frame, double scale_factor) {

  Mat hsv;
  Mat mask;
  Mat image;

  resize(original_frame, image, Size(), scale_factor, scale_factor); //Potentially scale down the frame

  cvtColor(image, hsv, CV_BGR2HSV); // Image is now HSV

  double minH = 50;
  double minS = 20;
  double minV = 150;
  double maxH = 125;
  double maxS = 100;
  double maxV = 255;

  Scalar lower(minH, minS, minV);
  Scalar upper(maxH, maxS, maxV);
  inRange(hsv, lower, upper, mask); // Create a mask of only the desired color

  vector<Vec4i> lines;
  HoughLines(mask, lines, 1, CV_PI / 180, 100, 0, 0);
//  HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 50, 10); // Find all lines in the image

  printf("Adding in %d lines\n", (int) lines.size());
  for (size_t i = 0; i < lines.size(); i++) {
    float rho = lines[i][0], theta = lines[i][1];
    Point pt1, pt2;
    double a = cos(theta), b = sin(theta);
    double x0 = a * rho, y0 = b * rho;
    pt1.x = cvRound(x0 + 1000 * (-b));
    pt1.y = cvRound(y0 + 1000 * (a));
    pt2.x = cvRound(x0 - 1000 * (-b));
    pt2.y = cvRound(y0 - 1000 * (a));
    line(image, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);
  }
//    if (lines.size() < 1) continue;

//  imshow("line_window", image);
  resize(image, original_frame, Size(), 1 / scale_factor, 1 / scale_factor);
}

LineFollowing::LineFollowing(Control *control) {
  namedWindow("line_window", CV_WINDOW_NORMAL);
  control_ptr = control;
  return;
}

void LineFollowing::close() {
  return;
}

void LineFollowing::fly() {

  control_ptr->velocities.vx = 0;
  control_ptr->velocities.vy = 0;
  control_ptr->velocities.vz = 0;
  control_ptr->velocities.vr = 0;

  detect_lines(control_ptr->image, 0.3);

  return;
}
<|endoftext|>


<commit_before>// - Tested
#define RMM_AAR
#define RMM_CAS
#define RMM_CASEVAC
#define CRB_TWNMGR
#define CRB_FLIPPABLE
#define RMM_JIPMARKERS
#define RMM_LOGBOOK
#define R3F_LOGISTICS
#define RMM_RECRUITMENT
#define RMM_REVIVE
#define RMM_TASKS
#define RMM_TYRES
#define WHB_MULTISPAWN

// WIP
//#define GC_PACK_COW
#define TN_LHDELEVATOR
<commit_msg>- Disable LHD Elevator until fixed<commit_after>// - Tested
#define RMM_AAR
#define RMM_CAS
#define RMM_CASEVAC
#define CRB_TWNMGR
#define CRB_FLIPPABLE
#define RMM_JIPMARKERS
#define RMM_LOGBOOK
#define R3F_LOGISTICS
#define RMM_RECRUITMENT
#define RMM_REVIVE
#define RMM_TASKS
#define RMM_TYRES
#define WHB_MULTISPAWN

// WIP
//#define GC_PACK_COW
//#define TN_LHDELEVATOR
<|endoftext|>


<commit_before><commit_msg>rhbz#994886 update unit in draw. obj. props toolbar<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: colmgr.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 09:05:10 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _COLMGR_HXX
#define _COLMGR_HXX

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif

#ifndef _FMTCLDS_HXX //autogen
#include <fmtclds.hxx>
#endif

SW_DLLPUBLIC void FitToActualSize(SwFmtCol& rCol, USHORT nWidth);

class SW_DLLPUBLIC SwColMgr
{
public:
        // lActWidth wird aus den Edits des Seitendialogs
        // direkt uebergeben
    SwColMgr(const SfxItemSet &rSet, USHORT nActWidth = USHRT_MAX);
    ~SwColMgr();

    inline USHORT       GetCount() const;
    void                SetCount(USHORT nCount, USHORT nGutterWidth);
    USHORT              GetGutterWidth(USHORT nPos = USHRT_MAX) const;
    void                SetGutterWidth(USHORT nWidth, USHORT nPos = USHRT_MAX);

    USHORT              GetColWidth(USHORT nIdx) const;
    void                SetColWidth(USHORT nIdx, USHORT nWidth);

    inline BOOL         IsAutoWidth() const;
    void                SetAutoWidth(BOOL bOn = TRUE, USHORT lGutterWidth = 0);

    inline BOOL         HasLine() const;
    inline void         SetNoLine();

    inline void         SetLineWidthAndColor(ULONG nWidth, const Color& rCol);
    inline ULONG        GetLineWidth() const;
    inline const Color& GetLineColor() const;

    inline SwColLineAdj GetAdjust() const;
    inline void         SetAdjust(SwColLineAdj);

    short               GetLineHeightPercent() const;
    void                SetLineHeightPercent(short nPercent);

    inline void         NoCols();
    void                Update();

    const SwFmtCol&     GetColumns() const { return aFmtCol; }

    void                SetActualWidth(USHORT nW);
    USHORT              GetActualSize() const { return nWidth; }

private:

    SwFmtCol            aFmtCol;
    USHORT              nWidth;
};

// INLINE METHODE --------------------------------------------------------

inline  USHORT SwColMgr::GetCount() const
{
    return aFmtCol.GetNumCols();
}
inline void         SwColMgr::SetLineWidthAndColor(ULONG nWidth, const Color& rCol)
{
    aFmtCol.SetLineWidth(nWidth);
    aFmtCol.SetLineColor(rCol);
}
inline ULONG        SwColMgr::GetLineWidth() const
{
    return aFmtCol.GetLineWidth();
}
inline const Color& SwColMgr::GetLineColor() const
{
    return aFmtCol.GetLineColor();
}
inline  SwColLineAdj SwColMgr::GetAdjust() const
{
    return aFmtCol.GetLineAdj();
}
inline  void SwColMgr::SetAdjust(SwColLineAdj eAdj)
{
    aFmtCol.SetLineAdj(eAdj);
}
inline BOOL SwColMgr::IsAutoWidth() const
{
    return aFmtCol.IsOrtho();
}
inline void SwColMgr::SetAutoWidth(BOOL bOn, USHORT nGutterWidth)
{
    aFmtCol.SetOrtho(bOn, nGutterWidth, nWidth);
}
inline void SwColMgr::NoCols()
{
    aFmtCol.GetColumns().DeleteAndDestroy(0, aFmtCol.GetColumns().Count());
}
inline BOOL SwColMgr::HasLine() const
{
    return GetAdjust() != COLADJ_NONE;
}
inline void SwColMgr::SetNoLine()
{
    SetAdjust(COLADJ_NONE);
}

#endif
<commit_msg>INTEGRATION: CWS swwarnings (1.3.710); FILE MERGED 2007/02/27 09:07:09 os 1.3.710.1: #i69287# warnings removed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: colmgr.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 11:55:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _COLMGR_HXX
#define _COLMGR_HXX

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif

#ifndef _FMTCLDS_HXX //autogen
#include <fmtclds.hxx>
#endif

SW_DLLPUBLIC void FitToActualSize(SwFmtCol& rCol, USHORT nWidth);

class SW_DLLPUBLIC SwColMgr
{
public:
        // lActWidth wird aus den Edits des Seitendialogs
        // direkt uebergeben
    SwColMgr(const SfxItemSet &rSet, USHORT nActWidth = USHRT_MAX);
    ~SwColMgr();

    inline USHORT       GetCount() const;
    void                SetCount(USHORT nCount, USHORT nGutterWidth);
    USHORT              GetGutterWidth(USHORT nPos = USHRT_MAX) const;
    void                SetGutterWidth(USHORT nWidth, USHORT nPos = USHRT_MAX);

    USHORT              GetColWidth(USHORT nIdx) const;
    void                SetColWidth(USHORT nIdx, USHORT nWidth);

    inline BOOL         IsAutoWidth() const;
    void                SetAutoWidth(BOOL bOn = TRUE, USHORT lGutterWidth = 0);

    inline BOOL         HasLine() const;
    inline void         SetNoLine();

    inline void         SetLineWidthAndColor(ULONG nWidth, const Color& rCol);
    inline ULONG        GetLineWidth() const;
    inline const Color& GetLineColor() const;

    inline SwColLineAdj GetAdjust() const;
    inline void         SetAdjust(SwColLineAdj);

    short               GetLineHeightPercent() const;
    void                SetLineHeightPercent(short nPercent);

    inline void         NoCols();
    void                Update();

    const SwFmtCol&     GetColumns() const { return aFmtCol; }

    void                SetActualWidth(USHORT nW);
    USHORT              GetActualSize() const { return nWidth; }

private:

    SwFmtCol            aFmtCol;
    USHORT              nWidth;
};

// INLINE METHODE --------------------------------------------------------

inline  USHORT SwColMgr::GetCount() const
{
    return aFmtCol.GetNumCols();
}
inline void         SwColMgr::SetLineWidthAndColor(ULONG nLWidth, const Color& rCol)
{
    aFmtCol.SetLineWidth(nLWidth);
    aFmtCol.SetLineColor(rCol);
}
inline ULONG        SwColMgr::GetLineWidth() const
{
    return aFmtCol.GetLineWidth();
}
inline const Color& SwColMgr::GetLineColor() const
{
    return aFmtCol.GetLineColor();
}
inline  SwColLineAdj SwColMgr::GetAdjust() const
{
    return aFmtCol.GetLineAdj();
}
inline  void SwColMgr::SetAdjust(SwColLineAdj eAdj)
{
    aFmtCol.SetLineAdj(eAdj);
}
inline BOOL SwColMgr::IsAutoWidth() const
{
    return aFmtCol.IsOrtho();
}
inline void SwColMgr::SetAutoWidth(BOOL bOn, USHORT nGutterWidth)
{
    aFmtCol.SetOrtho(bOn, nGutterWidth, nWidth);
}
inline void SwColMgr::NoCols()
{
    aFmtCol.GetColumns().DeleteAndDestroy(0, aFmtCol.GetColumns().Count());
}
inline BOOL SwColMgr::HasLine() const
{
    return GetAdjust() != COLADJ_NONE;
}
inline void SwColMgr::SetNoLine()
{
    SetAdjust(COLADJ_NONE);
}

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: swlbox.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2004-08-23 09:01:33 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SWLBOX_HXX
#define _SWLBOX_HXX

#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif

#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif

class SwBoxEntry;
class Window;

SV_DECL_PTRARR_DEL(SwEntryLst, SwBoxEntry*, 10, 10)

/*--------------------------------------------------------------------
     Beschreibung: SwBoxEntry
 --------------------------------------------------------------------*/

class SW_DLLPUBLIC SwBoxEntry
{
    friend class SwComboBox;

    BOOL    bModified : 1;
    BOOL    bNew : 1;

public:
    SwBoxEntry(const String& aName, USHORT nId=0);
    SwBoxEntry(const SwBoxEntry& rOrg);
    SwBoxEntry();

    String  aName;
    USHORT  nId;
};

/*--------------------------------------------------------------------
     Beschreibung: fuer ComboBoxen
 --------------------------------------------------------------------*/

enum SwComboBoxStyle
{
    CBS_UPPER       = 0x01,
    CBS_LOWER       = 0x02,
    CBS_ALL         = 0x04,
    CBS_FILENAME    = 0x08,
#ifdef WIN
    CBS_SW_FILENAME = CBS_FILENAME | CBS_LOWER
#else
    CBS_SW_FILENAME = CBS_FILENAME
#endif
};

class SW_DLLPUBLIC SwComboBox : public ComboBox
{
    SwEntryLst              aEntryLst;
    SwEntryLst              aDelEntryLst;
    SwBoxEntry              aDefault;
    USHORT                  nStyle;

    SW_DLLPRIVATE void                  InitComboBox();
    SW_DLLPRIVATE void                  InsertSorted(SwBoxEntry* pEntry);

public:
    SwComboBox(Window* pParent, const ResId& rId,
               USHORT nStyleBits = CBS_ALL);
    ~SwComboBox();

    virtual void            KeyInput( const KeyEvent& rKEvt );

    void                    InsertEntry(const SwBoxEntry&);

    void                    RemoveEntry(USHORT nPos);

    USHORT                  GetEntryPos(const SwBoxEntry& rEntry) const;
    const SwBoxEntry&       GetEntry(USHORT) const;

    USHORT                  GetRemovedCount() const;
    const SwBoxEntry&       GetRemovedEntry(USHORT nPos) const;

    USHORT                  GetStyle() const            { return nStyle;    }
    void                    SetStyle(const USHORT nSt)  { nStyle = nSt;     }

    String                  GetText() const;
};

#endif /* _SWLBOX_HXX */
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.596); FILE MERGED 2005/09/05 13:45:38 rt 1.3.596.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: swlbox.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 10:03:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SWLBOX_HXX
#define _SWLBOX_HXX

#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif

#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif

class SwBoxEntry;
class Window;

SV_DECL_PTRARR_DEL(SwEntryLst, SwBoxEntry*, 10, 10)

/*--------------------------------------------------------------------
     Beschreibung: SwBoxEntry
 --------------------------------------------------------------------*/

class SW_DLLPUBLIC SwBoxEntry
{
    friend class SwComboBox;

    BOOL    bModified : 1;
    BOOL    bNew : 1;

public:
    SwBoxEntry(const String& aName, USHORT nId=0);
    SwBoxEntry(const SwBoxEntry& rOrg);
    SwBoxEntry();

    String  aName;
    USHORT  nId;
};

/*--------------------------------------------------------------------
     Beschreibung: fuer ComboBoxen
 --------------------------------------------------------------------*/

enum SwComboBoxStyle
{
    CBS_UPPER       = 0x01,
    CBS_LOWER       = 0x02,
    CBS_ALL         = 0x04,
    CBS_FILENAME    = 0x08,
#ifdef WIN
    CBS_SW_FILENAME = CBS_FILENAME | CBS_LOWER
#else
    CBS_SW_FILENAME = CBS_FILENAME
#endif
};

class SW_DLLPUBLIC SwComboBox : public ComboBox
{
    SwEntryLst              aEntryLst;
    SwEntryLst              aDelEntryLst;
    SwBoxEntry              aDefault;
    USHORT                  nStyle;

    SW_DLLPRIVATE void                  InitComboBox();
    SW_DLLPRIVATE void                  InsertSorted(SwBoxEntry* pEntry);

public:
    SwComboBox(Window* pParent, const ResId& rId,
               USHORT nStyleBits = CBS_ALL);
    ~SwComboBox();

    virtual void            KeyInput( const KeyEvent& rKEvt );

    void                    InsertEntry(const SwBoxEntry&);

    void                    RemoveEntry(USHORT nPos);

    USHORT                  GetEntryPos(const SwBoxEntry& rEntry) const;
    const SwBoxEntry&       GetEntry(USHORT) const;

    USHORT                  GetRemovedCount() const;
    const SwBoxEntry&       GetRemovedEntry(USHORT nPos) const;

    USHORT                  GetStyle() const            { return nStyle;    }
    void                    SetStyle(const USHORT nSt)  { nStyle = nSt;     }

    String                  GetText() const;
};

#endif /* _SWLBOX_HXX */
<|endoftext|>


<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License

Copyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "flusspferd/getopt.hpp"
#include "flusspferd/object.hpp"
#include "flusspferd/array.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/property_iterator.hpp"
#include <iostream>
#include <map>

using namespace flusspferd;

void flusspferd::load_getopt_module(object container) {
  object exports = container.get_property_object("exports");

  flusspferd::create_native_function(exports, "getopt", &flusspferd::getopt);
}

struct optspec {
  std::map<std::string, int> options;

  optspec(object const &spec) {
    for (property_iterator it = spec.begin(); it != spec.end(); ++it) {
      std::string name = it->to_std_string();

      int data = 0;

      options.insert(std::make_pair(name, data));
      std::cout << name << std::endl;

      object item = spec.get_property_object(name);

      if (!item.is_null()) {
        value aliases = item.get_property("alias");
        if (aliases.is_undefined_or_null())
          aliases = item.get_property("aliases");

        if (aliases.is_string()) {
          options.insert(std::make_pair(aliases.to_std_string(), data));
        } else if (aliases.is_object()) {
          object aliases_o = aliases.get_object();

        }
      }
    }
  }
};

object flusspferd::getopt(
  object spec_, boost::optional<array const &> const &arguments_)
{
  if (!arguments_) {
    object sys = flusspferd::global().call("require", "system").to_object();
    array args(sys.get_property_object("args"));
    return getopt(spec_, args);
  }

  array const &arguments = arguments_.get();

  optspec spec(spec_);

  // TODO

  return flusspferd::object();
}
<commit_msg>core/getopt: tiny little change<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License

Copyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "flusspferd/getopt.hpp"
#include "flusspferd/object.hpp"
#include "flusspferd/array.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/property_iterator.hpp"
#include <iostream>
#include <map>

using namespace flusspferd;

void flusspferd::load_getopt_module(object container) {
  object exports = container.get_property_object("exports");

  flusspferd::create_native_function(exports, "getopt", &flusspferd::getopt);
}

struct optspec {
  std::map<std::string, int> options;

  optspec(object const &spec) {
    for (property_iterator it = spec.begin(); it != spec.end(); ++it) {
      std::string name = it->to_std_string();

      int data = 0;

      options.insert(std::make_pair(name, data));
      std::cout << name << std::endl;

      object item = spec.get_property_object(name);

      if (!item.is_null()) {
        value aliases = item.get_property("alias");
        if (aliases.is_undefined_or_null())
          aliases = item.get_property("aliases");

        if (!aliases.is_array()) {
          options.insert(std::make_pair(aliases.to_std_string(), data));
        } else {
          array aliases_a(aliases.get_object());

        }
      }
    }
  }
};

object flusspferd::getopt(
  object spec_, boost::optional<array const &> const &arguments_)
{
  if (!arguments_) {
    object sys = flusspferd::global().call("require", "system").to_object();
    array args(sys.get_property_object("args"));
    return getopt(spec_, args);
  }

  array const &arguments = arguments_.get();

  optspec spec(spec_);

  // TODO

  return flusspferd::object();
}
<|endoftext|>