<commit_before>/*
 * Copyright(C) lichuang
 */
#include <map>
#include <list>
#include <arpa/inet.h>  // htonl, ntohl
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include "eventrpc/error_code.h"
#include "eventrpc/base.h"
#include "eventrpc/event.h"
#include "eventrpc/rpc_channel.h"
#include "eventrpc/net_utility.h"
#include "eventrpc/utility.h"
#include "eventrpc/log.h"
namespace eventrpc {
struct MessageResponse {
  gpb::Message* response;
  gpb::Closure* done;
};

struct RpcChannel::Impl : public MessageHandler {
 public:
  Impl(RpcChannel *rpc_channel);

  ~Impl();

  void CallMethod(const gpb::MethodDescriptor* method,
                  gpb::RpcController* controller,
                  const gpb::Message* request,
                  gpb::Message* response,
                  gpb::Closure* done);

  bool HandlePacket(const MessageHeader &header,
                    Buffer* buffer);

  MessageResponse* GetMessageResponse();

  void FreeMessageResponse(MessageResponse *response);

 public:
  RpcChannel *rpc_channel_;
  typedef list<MessageResponse*> MessageResponseList;
  typedef map<uint64, MessageResponseList> MessageResponseMap;
  MessageResponseMap message_response_map_;
  MessageResponseList free_response_list_;
};

RpcChannel::Impl::Impl(RpcChannel *rpc_channel)
  : rpc_channel_(rpc_channel) {
  rpc_channel_->set_message_handler(this);
}

RpcChannel::Impl::~Impl() {
}

void RpcChannel::Impl::CallMethod(const gpb::MethodDescriptor* method,
                                  gpb::RpcController* controller,
                                  const gpb::Message* request,
                                  gpb::Message* response,
                                  gpb::Closure* done) {
  MessageResponse *message_response = GetMessageResponse();
  message_response->response = response;
  message_response->done     = done;
  uint32 opcode = hash_string(method->full_name());
  VLOG_INFO() << "register service: " << method->full_name()
    << ", opcode: " << opcode;
  message_response_map_[opcode].push_back(message_response);
  //rpc_channel_->SendMessage(request);
  rpc_channel_->SendPacket(opcode, request);
}

bool RpcChannel::Impl::HandlePacket(const MessageHeader &header,
                                    Buffer* buffer) {
  MessageResponseMap::iterator iter;
  iter = message_response_map_.find(header.opcode);
  if (iter == message_response_map_.end()) {
    VLOG_ERROR() << "cannot find handler for opcode: " << header.opcode;
    return false;
  }
  MessageResponse *response = iter->second.front();
  iter->second.pop_front();
  string content = buffer->ToString(header.length);
  if (!response->response->ParseFromString(content)) {
    FreeMessageResponse(response);
    return false;
  }
  response->done->Run();
  FreeMessageResponse(response);
  return true;
}

MessageResponse* RpcChannel::Impl::GetMessageResponse() {
  if (free_response_list_.empty()) {
    return new MessageResponse();
  }
  MessageResponse *message_response = free_response_list_.front();
  free_response_list_.pop_front();
  return message_response;
}

void RpcChannel::Impl::FreeMessageResponse(MessageResponse *response) {
  delete response->response;
  delete response->done;
  free_response_list_.push_back(response);
}

RpcChannel::RpcChannel(const string &host, int port)
  : MessageChannel(host, port) {
   impl_ = new Impl(this);
}

RpcChannel::~RpcChannel() {
  delete impl_;
}

void RpcChannel::CallMethod(const gpb::MethodDescriptor* method,
                            gpb::RpcController* controller,
                            const gpb::Message* request,
                            gpb::Message* response,
                            gpb::Closure* done) {
  impl_->CallMethod(method, controller, request, response, done);
}
};
<commit_msg>fix bugs<commit_after>/*
 * Copyright(C) lichuang
 */
#include <map>
#include <list>
#include <arpa/inet.h>  // htonl, ntohl
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include "eventrpc/error_code.h"
#include "eventrpc/base.h"
#include "eventrpc/event.h"
#include "eventrpc/rpc_channel.h"
#include "eventrpc/net_utility.h"
#include "eventrpc/utility.h"
#include "eventrpc/log.h"
namespace eventrpc {
struct MessageResponse {
  gpb::Message* response;
  gpb::Closure* done;
};

struct RpcChannel::Impl : public MessageHandler {
 public:
  Impl(RpcChannel *rpc_channel);

  ~Impl();

  void CallMethod(const gpb::MethodDescriptor* method,
                  gpb::RpcController* controller,
                  const gpb::Message* request,
                  gpb::Message* response,
                  gpb::Closure* done);

  bool HandlePacket(const MessageHeader &header,
                    Buffer* buffer);

  MessageResponse* GetMessageResponse();

  void FreeMessageResponse(MessageResponse *response);

 public:
  RpcChannel *rpc_channel_;
  typedef list<MessageResponse*> MessageResponseList;
  typedef map<uint64, MessageResponseList> MessageResponseMap;
  MessageResponseMap message_response_map_;
  MessageResponseList free_response_list_;
};

RpcChannel::Impl::Impl(RpcChannel *rpc_channel)
  : rpc_channel_(rpc_channel) {
  rpc_channel_->set_message_handler(this);
}

RpcChannel::Impl::~Impl() {
}

void RpcChannel::Impl::CallMethod(const gpb::MethodDescriptor* method,
                                  gpb::RpcController* controller,
                                  const gpb::Message* request,
                                  gpb::Message* response,
                                  gpb::Closure* done) {
  MessageResponse *message_response = GetMessageResponse();
  message_response->response = response;
  message_response->done     = done;
  uint32 opcode = hash_string(method->full_name());
  VLOG_INFO() << "register service: " << method->full_name()
    << ", opcode: " << opcode;
  message_response_map_[opcode].push_back(message_response);
  rpc_channel_->SendPacket(opcode, request);
}

bool RpcChannel::Impl::HandlePacket(const MessageHeader &header,
                                    Buffer* buffer) {
  MessageResponseMap::iterator iter;
  iter = message_response_map_.find(header.opcode);
  if (iter == message_response_map_.end()) {
    VLOG_ERROR() << "cannot find handler for opcode: " << header.opcode;
    return false;
  }
  MessageResponse *response = iter->second.front();
  iter->second.pop_front();
  string content = buffer->ToString(header.length);
  if (!response->response->ParseFromString(content)) {
    FreeMessageResponse(response);
    return false;
  }
  response->done->Run();
  FreeMessageResponse(response);
  return true;
}

MessageResponse* RpcChannel::Impl::GetMessageResponse() {
  if (free_response_list_.empty()) {
    return new MessageResponse();
  }
  MessageResponse *message_response = free_response_list_.front();
  free_response_list_.pop_front();
  return message_response;
}

void RpcChannel::Impl::FreeMessageResponse(MessageResponse *response) {
  free_response_list_.push_back(response);
}

RpcChannel::RpcChannel(const string &host, int port)
  : MessageChannel(host, port) {
   impl_ = new Impl(this);
}

RpcChannel::~RpcChannel() {
  delete impl_;
}

void RpcChannel::CallMethod(const gpb::MethodDescriptor* method,
                            gpb::RpcController* controller,
                            const gpb::Message* request,
                            gpb::Message* response,
                            gpb::Closure* done) {
  impl_->CallMethod(method, controller, request, response, done);
}
};
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed 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 "otbWrapperQtWidgetModel.h"

//Use to create command line from the application parameters
#include "otbWrapperOutputProcessXMLParameter.h"

using std::string;

namespace otb
{

namespace Wrapper
{

QtWidgetModel
::QtWidgetModel(Application* app) :
  m_Application(app),
  m_LogOutput(),
  m_IsRunning(false)
{
  // Init only if not already done
  if(!m_Application->IsInitialized())
    {
    m_Application->Init();
    }

  m_LogOutput = QtLogOutput::New();

  // Attach log output to the Application logger
  m_Application->GetLogger()->AddLogOutput(m_LogOutput);

  m_Timer = new QTimer(this);
  m_Timer->setSingleShot(true);
  m_Timer->setInterval(1000);
  QObject::connect(
    m_Timer,
    SIGNAL( timeout() ),
    this,
    SLOT( TimerDone() )
    );
}

QtWidgetModel::~QtWidgetModel()
{
  if (m_Timer)
    delete m_Timer;
}

void
QtWidgetModel
::NotifyUpdate()
{
  // Update the parameters
  m_Application->UpdateParameters();
  emit UpdateGui();

  // Notify all
  if (!m_IsRunning)
    {
    bool applicationStatus = m_Application->IsApplicationReady();
    emit SetApplicationReady(applicationStatus);
    }
}

void
QtWidgetModel
::ExecuteAndWriteOutputSlot()
{
  // Deactivate the Execute button while processing
  emit SetApplicationReady(false);
  m_IsRunning = true;

  //Buld corresponding command line and display to the Log tab

  //Build XML DOM from m_application
  OutputProcessXMLParameter::Pointer outXMLParam = OutputProcessXMLParameter::New();

  TiXmlElement* XMLAppElement = outXMLParam->ParseApplication(m_Application);

  //Create command line from the XML document
  TiXmlElement * pName, *pParam;
  std::ostringstream cmdLine;

  cmdLine << "";

  if(XMLAppElement)
    {
    pName = XMLAppElement->FirstChildElement("name");

    cmdLine << "otbcli_" << pName->GetText();
#ifdef _WIN32
    cmdLine << ".bat";
#endif
    cmdLine << " ";

    //Parse application parameters
    pParam = XMLAppElement->FirstChildElement("parameter");

    while(pParam)
      {
      //Get pareter key
      cmdLine << "-";
      cmdLine << pParam->FirstChildElement("key")->GetText();
      cmdLine << " ";

      //Some parameters can have multiple values. Test it and handle this
      //specific case
      TiXmlElement * values = pParam->FirstChildElement("values");

      if (values)
        {
        //Loop over value
        TiXmlElement * pValue = values->FirstChildElement("value");
        while(pValue)
          {
          cmdLine << pValue->GetText();
          cmdLine << " ";

          pValue = pValue->NextSiblingElement(); // iteration over multiple values
          }
        }
      else
        {
        //Get parameter value
        cmdLine << pParam->FirstChildElement("value")->GetText();
        cmdLine << " ";

        //In case of OutputImageparameter we need to report output pixel type
        TiXmlElement * pPixType = pParam->FirstChildElement("pixtype");

        if (pPixType)
          {
          cmdLine << pPixType->GetText();
          cmdLine << " ";
          }
        }

      pParam = pParam->NextSiblingElement(); // iteration over parameters
      }

    //Insert a new line character at the end of the command line
    cmdLine << std::endl;

    //Report the command line string to the application logger
    m_Application->GetLogger()->Write(itk::LoggerBase::INFO, cmdLine.str());
    }

  // launch the output image writing
  AppliThread * taskAppli = new AppliThread( m_Application );

  QObject::connect(
    taskAppli,
    SIGNAL( ExceptionRaised( QString ) ),
    // to:
    this,
    SIGNAL( ExceptionRaised( QString ) )
  );

  QObject::connect(
    taskAppli,
    SIGNAL( ApplicationExecutionDone( int ) ),
    // to:
    this,
    SLOT( OnApplicationExecutionDone( int ) )
  );

  QObject::connect(
    taskAppli,
    SIGNAL( finished() ),
    taskAppli,
    SLOT( deleteLater() )
  );

  // Tell the Progress Reporter to begin
  emit SetProgressReportBegin();

  taskAppli->Execute();
}

void
QtWidgetModel
::OnApplicationExecutionDone( int status )
{
  // For the progressReport to close the Progress widget
  // and the GUI to update message
  emit SetProgressReportDone( status );

  if (status >= 0)
    {
    std::ostringstream oss;
    oss << "Execution took "<< m_Application->GetLastExecutionTiming() << " sec";
    SendLogINFO(oss.str());
    }

  // start timer
  m_Timer->start();
}

void
QtWidgetModel
::TimerDone()
{
  m_IsRunning = false;
  // Require GUI update.
  NotifyUpdate();
}

void
QtWidgetModel
::SendLogWARNING( const std::string & mes )
{
  m_Application->GetLogger()->Write( itk::LoggerBase::WARNING, mes );
}

void
QtWidgetModel
::SendLogINFO( const std::string & mes )
{
  m_Application->GetLogger()->Write( itk::LoggerBase::INFO, mes );
}

void
QtWidgetModel
::SendLogDEBUG( const std::string & mes )
{
  m_Application->GetLogger()->Write( itk::LoggerBase::DEBUG, mes );
}

}

}

namespace otb
{

namespace Wrapper
{

AppliThread
::~AppliThread()
{
  wait();
}

void
AppliThread
::run()
{
  int result = -1;

  try
  {
    result = m_Application->ExecuteAndWriteOutput();
  }
  catch(otb::ApplicationException& err)
  {
    // These are thrown with otbAppLogFATAL, a macro which logs a user
    // friendly error message before throwing. So log exception details only
    // in debug.
    m_Application->GetLogger()->Debug("Caught otb::ApplicationException during application execution:\n");
    m_Application->GetLogger()->Debug(string(err.what()) + "\n");
    emit ExceptionRaised( err.what() );
  }
  catch(otb::ImageFileReaderException& err)
  {
    m_Application->GetLogger()->Debug("Caught otb::ImageFileReaderException during application execution:\n");
    m_Application->GetLogger()->Debug(string(err.what()) + "\n");
    m_Application->GetLogger()->Fatal(string("Cannot open image ") + err.m_Filename + string(". ") + err.GetDescription() + string("\n"));
    emit ExceptionRaised( err.what() );
  }
  catch(itk::ExceptionObject& err)
  {
    m_Application->GetLogger()->Debug("Caught itk::ExceptionObject during application execution:\n");
    m_Application->GetLogger()->Debug(string(err.what()) + "\n");
    m_Application->GetLogger()->Fatal(string(err.GetDescription()) + "\n");
    emit ExceptionRaised( err.what() );
  }
  catch(std::exception& err)
  {
    m_Application->GetLogger()->Fatal(string("Caught std::exception during application execution: ") + err.what() + "\n");
    emit ExceptionRaised( err.what() );
  }
  catch(...)
  {
    m_Application->GetLogger()->Fatal("Caught unknown exception during application execution.\n");
    emit ExceptionRaised("Unknown exception.");
  }

  // Signal OTB-application has ended with result status.
  emit ApplicationExecutionDone( result );
}

}

}
<commit_msg>BUG: mantis 1422: fix stack size for macx<commit_after>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed 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 "otbWrapperQtWidgetModel.h"

//Use to create command line from the application parameters
#include "otbWrapperOutputProcessXMLParameter.h"

using std::string;

namespace otb
{

namespace Wrapper
{

QtWidgetModel
::QtWidgetModel(Application* app) :
  m_Application(app),
  m_LogOutput(),
  m_IsRunning(false)
{
  // Init only if not already done
  if(!m_Application->IsInitialized())
    {
    m_Application->Init();
    }

  m_LogOutput = QtLogOutput::New();

  // Attach log output to the Application logger
  m_Application->GetLogger()->AddLogOutput(m_LogOutput);

  m_Timer = new QTimer(this);
  m_Timer->setSingleShot(true);
  m_Timer->setInterval(1000);
  QObject::connect(
    m_Timer,
    SIGNAL( timeout() ),
    this,
    SLOT( TimerDone() )
    );
}

QtWidgetModel::~QtWidgetModel()
{
  if (m_Timer)
    delete m_Timer;
}

void
QtWidgetModel
::NotifyUpdate()
{
  // Update the parameters
  m_Application->UpdateParameters();
  emit UpdateGui();

  // Notify all
  if (!m_IsRunning)
    {
    bool applicationStatus = m_Application->IsApplicationReady();
    emit SetApplicationReady(applicationStatus);
    }
}

void
QtWidgetModel
::ExecuteAndWriteOutputSlot()
{
  // Deactivate the Execute button while processing
  emit SetApplicationReady(false);
  m_IsRunning = true;

  //Buld corresponding command line and display to the Log tab

  //Build XML DOM from m_application
  OutputProcessXMLParameter::Pointer outXMLParam = OutputProcessXMLParameter::New();

  TiXmlElement* XMLAppElement = outXMLParam->ParseApplication(m_Application);

  //Create command line from the XML document
  TiXmlElement * pName, *pParam;
  std::ostringstream cmdLine;

  cmdLine << "";

  if(XMLAppElement)
    {
    pName = XMLAppElement->FirstChildElement("name");

    cmdLine << "otbcli_" << pName->GetText();
#ifdef _WIN32
    cmdLine << ".bat";
#endif
    cmdLine << " ";

    //Parse application parameters
    pParam = XMLAppElement->FirstChildElement("parameter");

    while(pParam)
      {
      //Get pareter key
      cmdLine << "-";
      cmdLine << pParam->FirstChildElement("key")->GetText();
      cmdLine << " ";

      //Some parameters can have multiple values. Test it and handle this
      //specific case
      TiXmlElement * values = pParam->FirstChildElement("values");

      if (values)
        {
        //Loop over value
        TiXmlElement * pValue = values->FirstChildElement("value");
        while(pValue)
          {
          cmdLine << pValue->GetText();
          cmdLine << " ";

          pValue = pValue->NextSiblingElement(); // iteration over multiple values
          }
        }
      else
        {
        //Get parameter value
        cmdLine << pParam->FirstChildElement("value")->GetText();
        cmdLine << " ";

        //In case of OutputImageparameter we need to report output pixel type
        TiXmlElement * pPixType = pParam->FirstChildElement("pixtype");

        if (pPixType)
          {
          cmdLine << pPixType->GetText();
          cmdLine << " ";
          }
        }

      pParam = pParam->NextSiblingElement(); // iteration over parameters
      }

    //Insert a new line character at the end of the command line
    cmdLine << std::endl;

    //Report the command line string to the application logger
    m_Application->GetLogger()->Write(itk::LoggerBase::INFO, cmdLine.str());
    }

  // launch the output image writing
  AppliThread * taskAppli = new AppliThread( m_Application );
  #ifdef __APPLE__
  /* bug mantis 1422 :
     X Mb *1024*1024 (bytes)
     X = 9 to get 9M stacksize!
   */
  taskAppli->setStackSize(static_cast<uint>(9*1024*1024));
  #endif

  QObject::connect(
    taskAppli,
    SIGNAL( ExceptionRaised( QString ) ),
    // to:
    this,
    SIGNAL( ExceptionRaised( QString ) )
  );

  QObject::connect(
    taskAppli,
    SIGNAL( ApplicationExecutionDone( int ) ),
    // to:
    this,
    SLOT( OnApplicationExecutionDone( int ) )
  );

  QObject::connect(
    taskAppli,
    SIGNAL( finished() ),
    taskAppli,
    SLOT( deleteLater() )
  );

  // Tell the Progress Reporter to begin
  emit SetProgressReportBegin();

  taskAppli->Execute();
}

void
QtWidgetModel
::OnApplicationExecutionDone( int status )
{
  // For the progressReport to close the Progress widget
  // and the GUI to update message
  emit SetProgressReportDone( status );

  if (status >= 0)
    {
    std::ostringstream oss;
    oss << "Execution took "<< m_Application->GetLastExecutionTiming() << " sec";
    SendLogINFO(oss.str());
    }

  // start timer
  m_Timer->start();
}

void
QtWidgetModel
::TimerDone()
{
  m_IsRunning = false;
  // Require GUI update.
  NotifyUpdate();
}

void
QtWidgetModel
::SendLogWARNING( const std::string & mes )
{
  m_Application->GetLogger()->Write( itk::LoggerBase::WARNING, mes );
}

void
QtWidgetModel
::SendLogINFO( const std::string & mes )
{
  m_Application->GetLogger()->Write( itk::LoggerBase::INFO, mes );
}

void
QtWidgetModel
::SendLogDEBUG( const std::string & mes )
{
  m_Application->GetLogger()->Write( itk::LoggerBase::DEBUG, mes );
}

}

}

namespace otb
{

namespace Wrapper
{

AppliThread
::~AppliThread()
{
  wait();
}

void
AppliThread
::run()
{
  int result = -1;

  try
  {
    result = m_Application->ExecuteAndWriteOutput();
  }
  catch(otb::ApplicationException& err)
  {
    // These are thrown with otbAppLogFATAL, a macro which logs a user
    // friendly error message before throwing. So log exception details only
    // in debug.
    m_Application->GetLogger()->Debug("Caught otb::ApplicationException during application execution:\n");
    m_Application->GetLogger()->Debug(string(err.what()) + "\n");
    emit ExceptionRaised( err.what() );
  }
  catch(otb::ImageFileReaderException& err)
  {
    m_Application->GetLogger()->Debug("Caught otb::ImageFileReaderException during application execution:\n");
    m_Application->GetLogger()->Debug(string(err.what()) + "\n");
    m_Application->GetLogger()->Fatal(string("Cannot open image ") + err.m_Filename + string(". ") + err.GetDescription() + string("\n"));
    emit ExceptionRaised( err.what() );
  }
  catch(itk::ExceptionObject& err)
  {
    m_Application->GetLogger()->Debug("Caught itk::ExceptionObject during application execution:\n");
    m_Application->GetLogger()->Debug(string(err.what()) + "\n");
    m_Application->GetLogger()->Fatal(string(err.GetDescription()) + "\n");
    emit ExceptionRaised( err.what() );
  }
  catch(std::exception& err)
  {
    m_Application->GetLogger()->Fatal(string("Caught std::exception during application execution: ") + err.what() + "\n");
    emit ExceptionRaised( err.what() );
  }
  catch(...)
  {
    m_Application->GetLogger()->Fatal("Caught unknown exception during application execution.\n");
    emit ExceptionRaised("Unknown exception.");
  }

  // Signal OTB-application has ended with result status.
  emit ApplicationExecutionDone( result );
}

}

}
<|endoftext|>


<commit_before><commit_msg>Added the real SINTreeNode implementation (again)<commit_after>#include "SINTreeNode.h"
#include <cassert>

namespace SIN {
    ////////////////////////////////
    TreeNode::TreeNode(void):
    parent(0x00u), previous(0x00u), next(0x00u)
    { }
    ////////////////////////////////
    TreeNode::~TreeNode(void) { }
    ////////////////////////////////
    TreeNode *TreeNode::operator [](size_t _index) const {
        TreeNode *result = 0x00;
        try {
            result = children.at(_index);
        }
        catch(std::out_of_range) { }
        return result;
    }
    ////////////////////////////////
    size_t TreeNode::NumberOfChildren(void) const {
        return children.size();
    }
    ////////////////////////////////
    TreeNode &TreeNode::operator <<(TreeNode *_kid) {
        _kid->parent = this;
        _kid->next = 0x00u;
        if (NumberOfChildren() > 0) {
            _kid->previous = children.back();
            children.back()->next = _kid;
        }
        else
            _kid->previous = 0x00u;
        children.push_back(_kid);
        return *this;
    }
    ////////////////////////////////
    TreeNode *TreeNode::GetParent(void) const {
        return parent;
    }
    ////////////////////////////////
    void TreeNode::SetParent(TreeNode *_parent) {
        parent = _parent;
    }
    ////////////////////////////////
    TreeNode *TreeNode::GetNext(void) const {
        return next;
    }
    ////////////////////////////////
    void TreeNode::SetNext(TreeNode *_next) {
        next = _next;
    }
    ////////////////////////////////
    TreeNode *TreeNode::GetPrevious(void) const {
        return previous;
    }
    ////////////////////////////////
    void TreeNode::SetPrevious(TreeNode *_previous) {
        previous = _previous;
    }
    ////////////////////////////////
} // namespace SIN
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/component_updater/component_updater_service.h"

#include <algorithm>
#include <string>
#include <vector>

#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/metrics/histogram.h"
#include "base/string_util.h"
#include "build/build_config.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "net/url_request/url_request_context_getter.h"

namespace {
// Default time constants.
const int kDelayOneMinute = 60;
const int kDelayOneHour = kDelayOneMinute * 60;

// Debug values you can pass to --component-updater-debug=value1,value2.
// Speed up component checking.
const char kDebugFastUpdate[] = "fast-update";
// Force out-of-process-xml parsing.
const char kDebugOutOfProcess[] = "out-of-process";
// Add "testrequest=1" parameter to the update check query.
const char kDebugRequestParam[] = "test-request";

bool HasDebugValue(const std::vector<std::string>& vec, const char* test) {
  if (vec.empty())
    return 0;
  return (std::find(vec.begin(), vec.end(), test) != vec.end());
}

// The request extra information is the OS and architecture, this helps
// the server select the right package to be delivered.
const char kExtraInfo[] =
#if defined(OS_MACOSX)
  #if defined(__amd64__)
    "os=mac&arch=x64&prod=chrome&prodversion=";
  #elif defined(__i386__)
     "os=mac&arch=x86&prod=chrome&prodversion=";
  #else
     #error "unknown mac architecture"
  #endif
#elif defined(OS_WIN)
  #if defined(_WIN64)
    "os=win&arch=x64&prod=chrome&prodversion=";
  #elif defined(_WIN32)
    "os=win&arch=x86&prod=chrome&prodversion=";
  #else
    #error "unknown windows architecture"
  #endif
#elif defined(OS_CHROMEOS)
  #if defined(__i386__)
    "os=cros&arch=x86&prod=chrome&prodversion=";
  #elif defined(__arm__)
    "os=cros&arch=arm&prod=chrome&prodversion=";
  #else
    "os=cros&arch=unknown&prod=chrome&prodversion=";
  #endif
#elif defined(OS_LINUX)
  #if defined(__amd64__)
    "os=linux&arch=x64&prod=chrome&prodversion=";
  #elif defined(__i386__)
    "os=linux&arch=x86&prod=chrome&prodversion=";
  #elif defined(__arm__)
    "os=linux&arch=arm&prod=chrome&prodversion=";
  #else
    "os=linux&arch=unknown&prod=chrome&prodversion=";
  #endif
#elif defined(OS_OPENBSD)
  #if defined(__amd64__)
    "os=openbsd&arch=x64";
  #elif defined(__i386__)
    "os=openbsd&arch=x86";
  #else
    "os=openbsd&arch=unknown";
  #endif
#else
    #error "unknown os or architecture"
#endif

}  // namespace

class ChromeConfigurator : public ComponentUpdateService::Configurator {
 public:
  ChromeConfigurator(const CommandLine* cmdline,
                     net::URLRequestContextGetter* url_request_getter);

  virtual ~ChromeConfigurator() {}

  virtual int InitialDelay() OVERRIDE;
  virtual int NextCheckDelay() OVERRIDE;
  virtual int StepDelay() OVERRIDE;
  virtual int MinimumReCheckWait() OVERRIDE;
  virtual GURL UpdateUrl() OVERRIDE;
  virtual const char* ExtraRequestParams() OVERRIDE;
  virtual size_t UrlSizeLimit() OVERRIDE;
  virtual net::URLRequestContextGetter* RequestContext() OVERRIDE;
  virtual bool InProcess() OVERRIDE;
  virtual void OnEvent(Events event, int val) OVERRIDE;

 private:
  net::URLRequestContextGetter* url_request_getter_;
  std::string extra_info_;
  bool fast_update_;
  bool out_of_process_;
  GURL app_update_url_;
};

ChromeConfigurator::ChromeConfigurator(const CommandLine* cmdline,
    net::URLRequestContextGetter* url_request_getter)
      : url_request_getter_(url_request_getter),
        extra_info_(kExtraInfo) {
  // Parse comma-delimited debug flags.
  std::vector<std::string> debug_values;
  Tokenize(cmdline->GetSwitchValueASCII(switches::kComponentUpdaterDebug),
      ",", &debug_values);
  fast_update_ = HasDebugValue(debug_values, kDebugFastUpdate);
  out_of_process_ = HasDebugValue(debug_values, kDebugOutOfProcess);

  // Allow switch to override update URL (piggyback on AppsGalleryUpdateURL).
  if (cmdline->HasSwitch(switches::kAppsGalleryUpdateURL)) {
    app_update_url_ =
        GURL(cmdline->GetSwitchValueASCII(switches::kAppsGalleryUpdateURL));
  } else {
    app_update_url_ = GURL("http://clients2.google.com/service/update2/crx");
  }

  // Make the extra request params, they are necessary so omaha does
  // not deliver components that are going to be rejected at install time.
  extra_info_ += chrome::VersionInfo().Version();
  if (HasDebugValue(debug_values, kDebugRequestParam))
    extra_info_ += "&testrequest=1";
}

int ChromeConfigurator::InitialDelay() {
  return  fast_update_ ? 1 : (6 * kDelayOneMinute);
}

int ChromeConfigurator::NextCheckDelay() {
  return fast_update_ ? 3 : (4 * kDelayOneHour);
}

int ChromeConfigurator::StepDelay() {
  return fast_update_ ? 1 : 4;
}

int ChromeConfigurator::MinimumReCheckWait() {
  return fast_update_ ? 30 : (6 * kDelayOneHour);
}

GURL ChromeConfigurator::UpdateUrl() {
  return app_update_url_;
}

const char* ChromeConfigurator::ExtraRequestParams() {
  return extra_info_.c_str();
}

size_t ChromeConfigurator::UrlSizeLimit() {
  return 1024ul;
}

net::URLRequestContextGetter* ChromeConfigurator::RequestContext() {
  return url_request_getter_;
}

bool ChromeConfigurator::InProcess() {
  return !out_of_process_;
}

void ChromeConfigurator::OnEvent(Events event, int val) {
  switch (event) {
    case kManifestCheck:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.ManifestCheck", val, 100);
      break;
    case kComponentUpdated:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.ComponentUpdated", val, 100);
      break;
    case kManifestError:
      UMA_HISTOGRAM_COUNTS_100("ComponentUpdater.ManifestError", val);
      break;
    case kNetworkError:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.NetworkError", val, 100);
      break;
    case kUnpackError:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.UnpackError", val, 100);
      break;
    case kInstallerError:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.InstallError", val, 100);
      break;
    default:
      NOTREACHED();
      break;
  }
}

ComponentUpdateService::Configurator* MakeChromeComponentUpdaterConfigurator(
    const CommandLine* cmdline, net::URLRequestContextGetter* context_getter) {
  return new ChromeConfigurator(cmdline, context_getter);
}
<commit_msg>Add android component updater configuration.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/component_updater/component_updater_service.h"

#include <algorithm>
#include <string>
#include <vector>

#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/metrics/histogram.h"
#include "base/string_util.h"
#include "build/build_config.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "net/url_request/url_request_context_getter.h"

namespace {
// Default time constants.
const int kDelayOneMinute = 60;
const int kDelayOneHour = kDelayOneMinute * 60;

// Debug values you can pass to --component-updater-debug=value1,value2.
// Speed up component checking.
const char kDebugFastUpdate[] = "fast-update";
// Force out-of-process-xml parsing.
const char kDebugOutOfProcess[] = "out-of-process";
// Add "testrequest=1" parameter to the update check query.
const char kDebugRequestParam[] = "test-request";

bool HasDebugValue(const std::vector<std::string>& vec, const char* test) {
  if (vec.empty())
    return 0;
  return (std::find(vec.begin(), vec.end(), test) != vec.end());
}

// The request extra information is the OS and architecture, this helps
// the server select the right package to be delivered.
const char kExtraInfo[] =
#if defined(OS_MACOSX)
  #if defined(__amd64__)
    "os=mac&arch=x64&prod=chrome&prodversion=";
  #elif defined(__i386__)
     "os=mac&arch=x86&prod=chrome&prodversion=";
  #else
     #error "unknown mac architecture"
  #endif
#elif defined(OS_WIN)
  #if defined(_WIN64)
    "os=win&arch=x64&prod=chrome&prodversion=";
  #elif defined(_WIN32)
    "os=win&arch=x86&prod=chrome&prodversion=";
  #else
    #error "unknown windows architecture"
  #endif
#elif defined(OS_ANDROID)
  #if defined(__i386__)
    "os=android&arch=x86&prod=chrome&prodversion=";
  #elif defined(__arm__)
    "os=android&arch=arm&prod=chrome&prodversion=";
  #else
    "os=android&arch=unknown&prod=chrome&prodversion=";
  #endif
#elif defined(OS_CHROMEOS)
  #if defined(__i386__)
    "os=cros&arch=x86&prod=chrome&prodversion=";
  #elif defined(__arm__)
    "os=cros&arch=arm&prod=chrome&prodversion=";
  #else
    "os=cros&arch=unknown&prod=chrome&prodversion=";
  #endif
#elif defined(OS_LINUX)
  #if defined(__amd64__)
    "os=linux&arch=x64&prod=chrome&prodversion=";
  #elif defined(__i386__)
    "os=linux&arch=x86&prod=chrome&prodversion=";
  #elif defined(__arm__)
    "os=linux&arch=arm&prod=chrome&prodversion=";
  #else
    "os=linux&arch=unknown&prod=chrome&prodversion=";
  #endif
#elif defined(OS_OPENBSD)
  #if defined(__amd64__)
    "os=openbsd&arch=x64";
  #elif defined(__i386__)
    "os=openbsd&arch=x86";
  #else
    "os=openbsd&arch=unknown";
  #endif
#else
    #error "unknown os or architecture"
#endif

}  // namespace

class ChromeConfigurator : public ComponentUpdateService::Configurator {
 public:
  ChromeConfigurator(const CommandLine* cmdline,
                     net::URLRequestContextGetter* url_request_getter);

  virtual ~ChromeConfigurator() {}

  virtual int InitialDelay() OVERRIDE;
  virtual int NextCheckDelay() OVERRIDE;
  virtual int StepDelay() OVERRIDE;
  virtual int MinimumReCheckWait() OVERRIDE;
  virtual GURL UpdateUrl() OVERRIDE;
  virtual const char* ExtraRequestParams() OVERRIDE;
  virtual size_t UrlSizeLimit() OVERRIDE;
  virtual net::URLRequestContextGetter* RequestContext() OVERRIDE;
  virtual bool InProcess() OVERRIDE;
  virtual void OnEvent(Events event, int val) OVERRIDE;

 private:
  net::URLRequestContextGetter* url_request_getter_;
  std::string extra_info_;
  bool fast_update_;
  bool out_of_process_;
  GURL app_update_url_;
};

ChromeConfigurator::ChromeConfigurator(const CommandLine* cmdline,
    net::URLRequestContextGetter* url_request_getter)
      : url_request_getter_(url_request_getter),
        extra_info_(kExtraInfo) {
  // Parse comma-delimited debug flags.
  std::vector<std::string> debug_values;
  Tokenize(cmdline->GetSwitchValueASCII(switches::kComponentUpdaterDebug),
      ",", &debug_values);
  fast_update_ = HasDebugValue(debug_values, kDebugFastUpdate);
  out_of_process_ = HasDebugValue(debug_values, kDebugOutOfProcess);

  // Allow switch to override update URL (piggyback on AppsGalleryUpdateURL).
  if (cmdline->HasSwitch(switches::kAppsGalleryUpdateURL)) {
    app_update_url_ =
        GURL(cmdline->GetSwitchValueASCII(switches::kAppsGalleryUpdateURL));
  } else {
    app_update_url_ = GURL("http://clients2.google.com/service/update2/crx");
  }

  // Make the extra request params, they are necessary so omaha does
  // not deliver components that are going to be rejected at install time.
  extra_info_ += chrome::VersionInfo().Version();
  if (HasDebugValue(debug_values, kDebugRequestParam))
    extra_info_ += "&testrequest=1";
}

int ChromeConfigurator::InitialDelay() {
  return  fast_update_ ? 1 : (6 * kDelayOneMinute);
}

int ChromeConfigurator::NextCheckDelay() {
  return fast_update_ ? 3 : (4 * kDelayOneHour);
}

int ChromeConfigurator::StepDelay() {
  return fast_update_ ? 1 : 4;
}

int ChromeConfigurator::MinimumReCheckWait() {
  return fast_update_ ? 30 : (6 * kDelayOneHour);
}

GURL ChromeConfigurator::UpdateUrl() {
  return app_update_url_;
}

const char* ChromeConfigurator::ExtraRequestParams() {
  return extra_info_.c_str();
}

size_t ChromeConfigurator::UrlSizeLimit() {
  return 1024ul;
}

net::URLRequestContextGetter* ChromeConfigurator::RequestContext() {
  return url_request_getter_;
}

bool ChromeConfigurator::InProcess() {
  return !out_of_process_;
}

void ChromeConfigurator::OnEvent(Events event, int val) {
  switch (event) {
    case kManifestCheck:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.ManifestCheck", val, 100);
      break;
    case kComponentUpdated:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.ComponentUpdated", val, 100);
      break;
    case kManifestError:
      UMA_HISTOGRAM_COUNTS_100("ComponentUpdater.ManifestError", val);
      break;
    case kNetworkError:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.NetworkError", val, 100);
      break;
    case kUnpackError:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.UnpackError", val, 100);
      break;
    case kInstallerError:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.InstallError", val, 100);
      break;
    default:
      NOTREACHED();
      break;
  }
}

ComponentUpdateService::Configurator* MakeChromeComponentUpdaterConfigurator(
    const CommandLine* cmdline, net::URLRequestContextGetter* context_getter) {
  return new ChromeConfigurator(cmdline, context_getter);
}
<|endoftext|>


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

#include <set>

#include "base/memory/scoped_ptr.h"
#include "chrome/browser/platform_util.h"
#include "chrome/browser/ui/views/constrained_window_views.h"
#include "components/web_modal/native_web_contents_modal_dialog_manager.h"
#include "components/web_modal/web_contents_modal_dialog_manager.h"
#include "content/public/browser/web_contents_view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/widget/widget_observer.h"
#include "ui/views/window/dialog_delegate.h"

#if defined(USE_AURA)
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/window.h"
#include "ui/views/corewm/visibility_controller.h"
#include "ui/views/corewm/window_animations.h"
#include "ui/views/corewm/window_modality_controller.h"
#endif

#if defined(USE_ASH)
#include "ash/ash_constants.h"
#include "ash/shell.h"
#include "ash/wm/custom_frame_view_ash.h"
#endif

using web_modal::NativeWebContentsModalDialog;
using web_modal::NativeWebContentsModalDialogManager;
using web_modal::NativeWebContentsModalDialogManagerDelegate;

namespace {

class NativeWebContentsModalDialogManagerViews
    : public NativeWebContentsModalDialogManager,
      public views::WidgetObserver {
 public:
  NativeWebContentsModalDialogManagerViews(
      NativeWebContentsModalDialogManagerDelegate* native_delegate)
      : native_delegate_(native_delegate) {
  }

  virtual ~NativeWebContentsModalDialogManagerViews() {
    for (std::set<views::Widget*>::iterator it = observed_widgets_.begin();
         it != observed_widgets_.end();
         ++it) {
      (*it)->RemoveObserver(this);
    }
  }

  // NativeWebContentsModalDialogManager overrides
  virtual void ManageDialog(NativeWebContentsModalDialog dialog) OVERRIDE {
    views::Widget* widget = GetWidget(dialog);
    widget->AddObserver(this);
    observed_widgets_.insert(widget);
    widget->set_movement_disabled(true);

#if defined(USE_AURA)
    // TODO(wittman): remove once the new visual style is complete
    widget->GetNativeWindow()->SetProperty(aura::client::kConstrainedWindowKey,
                                           true);

    if (views::DialogDelegate::UseNewStyle()) {
      views::corewm::SetWindowVisibilityAnimationType(
          widget->GetNativeWindow(),
          views::corewm::WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE);
    }
#endif

#if defined(USE_ASH)
    gfx::NativeView parent = platform_util::GetParent(widget->GetNativeView());
    views::corewm::SetChildWindowVisibilityChangesAnimated(parent);
    // No animations should get performed on the window since that will re-order
    // the window stack which will then cause many problems.
    if (parent && parent->parent()) {
      parent->parent()->SetProperty(aura::client::kAnimationsDisabledKey, true);
    }

    // TODO(wittman): remove once the new visual style is complete
    widget->GetNativeWindow()->SetProperty(ash::kConstrainedWindowKey, true);
    views::corewm::SetModalParent(
        widget->GetNativeWindow(),
        platform_util::GetParent(widget->GetNativeView()));
#endif
  }

  virtual void ShowDialog(NativeWebContentsModalDialog dialog) OVERRIDE {
    views::Widget* widget = GetWidget(dialog);
#if defined(USE_AURA)
    scoped_ptr<views::corewm::SuspendChildWindowVisibilityAnimations> suspend;
    if (views::DialogDelegate::UseNewStyle() &&
        shown_widgets_.find(widget) != shown_widgets_.end()) {
      suspend.reset(new views::corewm::SuspendChildWindowVisibilityAnimations(
          widget->GetNativeWindow()->parent()));
    }
#endif
    widget->Show();
    FocusDialog(dialog);
#if defined(USE_AURA)
    if (views::DialogDelegate::UseNewStyle()) {
      widget->GetNativeWindow()->parent()->StackChildAbove(
          widget->GetNativeWindow(),
          native_delegate_->GetWebContents()->GetView()->GetNativeView());
    }

    shown_widgets_.insert(widget);
#endif
  }

  virtual void HideDialog(NativeWebContentsModalDialog dialog) OVERRIDE {
    views::Widget* widget = GetWidget(dialog);
#if defined(USE_AURA)
    scoped_ptr<views::corewm::SuspendChildWindowVisibilityAnimations> suspend;
    if (views::DialogDelegate::UseNewStyle()) {
      suspend.reset(new views::corewm::SuspendChildWindowVisibilityAnimations(
          widget->GetNativeWindow()->parent()));
    }
#endif
    widget->Hide();
  }

  virtual void CloseDialog(NativeWebContentsModalDialog dialog) OVERRIDE {
    GetWidget(dialog)->Close();
  }

  virtual void FocusDialog(NativeWebContentsModalDialog dialog) OVERRIDE {
    views::Widget* widget = GetWidget(dialog);
    if (widget->widget_delegate() &&
        widget->widget_delegate()->GetInitiallyFocusedView())
      widget->widget_delegate()->GetInitiallyFocusedView()->RequestFocus();
#if defined(USE_ASH)
    // We don't necessarily have a RootWindow yet.
    if (widget->GetNativeView()->GetRootWindow())
      widget->GetNativeView()->Focus();
#endif
  }

  virtual void PulseDialog(NativeWebContentsModalDialog dialog) OVERRIDE {
  }

  // views::WidgetObserver overrides

  // NOTE(wittman): OnWidgetClosing is overriden to ensure that, when the widget
  // is explicitly closed, the destruction occurs within the same call
  // stack. This avoids event races that lead to non-deterministic destruction
  // ordering in e.g. the print preview dialog. OnWidgetDestroying is overridden
  // because OnWidgetClosing is *only* invoked on explicit close, not when the
  // widget is implicitly destroyed due to its parent being closed. This
  // situation occurs with app windows.  WidgetClosing removes the observer, so
  // only one of these two functions is ever invoked for a given widget.
  virtual void OnWidgetClosing(views::Widget* widget) OVERRIDE {
    WidgetClosing(widget);
  }

  virtual void OnWidgetDestroying(views::Widget* widget) OVERRIDE {
    WidgetClosing(widget);
  }

 private:
  static views::Widget* GetWidget(NativeWebContentsModalDialog dialog) {
    views::Widget* widget = views::Widget::GetWidgetForNativeWindow(dialog);
    DCHECK(widget);
    return widget;
  }

  void WidgetClosing(views::Widget* widget) {
#if defined(USE_ASH)
    gfx::NativeView view = platform_util::GetParent(widget->GetNativeView());
    // Allow the parent to animate again.
    if (view && view->parent())
      view->parent()->ClearProperty(aura::client::kAnimationsDisabledKey);
#endif
    widget->RemoveObserver(this);
    native_delegate_->WillClose(widget->GetNativeView());
    observed_widgets_.erase(widget);
#if defined(USE_AURA)
    shown_widgets_.erase(widget);
#endif
  }

  NativeWebContentsModalDialogManagerDelegate* native_delegate_;
  std::set<views::Widget*> observed_widgets_;
  std::set<views::Widget*> shown_widgets_;

  DISALLOW_COPY_AND_ASSIGN(NativeWebContentsModalDialogManagerViews);
};

}  // namespace

namespace web_modal {

NativeWebContentsModalDialogManager* WebContentsModalDialogManager::
CreateNativeManager(
    NativeWebContentsModalDialogManagerDelegate* native_delegate) {
  return new NativeWebContentsModalDialogManagerViews(native_delegate);
}

}  // namespace web_modal
<commit_msg>Fix a crash when detaching a tab with a tab-modal dialog in the win-aura build.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <set>

#include "base/memory/scoped_ptr.h"
#include "chrome/browser/platform_util.h"
#include "chrome/browser/ui/views/constrained_window_views.h"
#include "components/web_modal/native_web_contents_modal_dialog_manager.h"
#include "components/web_modal/web_contents_modal_dialog_manager.h"
#include "content/public/browser/web_contents_view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/widget/widget_observer.h"
#include "ui/views/window/dialog_delegate.h"

#if defined(USE_AURA)
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/window.h"
#include "ui/views/corewm/visibility_controller.h"
#include "ui/views/corewm/window_animations.h"
#include "ui/views/corewm/window_modality_controller.h"
#endif

// TODO(wittman): this code should not depend on ash.
#if defined(USE_ASH)
#include "ash/ash_constants.h"
#include "ash/shell.h"
#include "ash/wm/custom_frame_view_ash.h"
#endif

using web_modal::NativeWebContentsModalDialog;
using web_modal::NativeWebContentsModalDialogManager;
using web_modal::NativeWebContentsModalDialogManagerDelegate;

namespace {

class NativeWebContentsModalDialogManagerViews
    : public NativeWebContentsModalDialogManager,
      public views::WidgetObserver
#if defined(USE_AURA)
      , public aura::WindowObserver
#endif
                                   {
 public:
  NativeWebContentsModalDialogManagerViews(
      NativeWebContentsModalDialogManagerDelegate* native_delegate)
      : native_delegate_(native_delegate) {
#if defined(USE_AURA)
    native_delegate_->GetWebContents()->GetView()->GetNativeView()->
        AddObserver(this);
#endif
  }

  virtual ~NativeWebContentsModalDialogManagerViews() {
    for (std::set<views::Widget*>::iterator it = observed_widgets_.begin();
         it != observed_widgets_.end();
         ++it) {
      (*it)->RemoveObserver(this);
    }
  }

  // NativeWebContentsModalDialogManager overrides
  virtual void ManageDialog(NativeWebContentsModalDialog dialog) OVERRIDE {
    views::Widget* widget = GetWidget(dialog);
    widget->AddObserver(this);
    observed_widgets_.insert(widget);
    widget->set_movement_disabled(true);

#if defined(USE_AURA)
    // TODO(wittman): remove once the new visual style is complete
    widget->GetNativeWindow()->SetProperty(aura::client::kConstrainedWindowKey,
                                           true);

    if (views::DialogDelegate::UseNewStyle()) {
      views::corewm::SetWindowVisibilityAnimationType(
          widget->GetNativeWindow(),
          views::corewm::WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE);
    }
#endif

#if defined(USE_ASH)
    gfx::NativeView parent = platform_util::GetParent(widget->GetNativeView());
    views::corewm::SetChildWindowVisibilityChangesAnimated(parent);
    // No animations should get performed on the window since that will re-order
    // the window stack which will then cause many problems.
    if (parent && parent->parent()) {
      parent->parent()->SetProperty(aura::client::kAnimationsDisabledKey, true);
    }

    // TODO(wittman): remove once the new visual style is complete
    widget->GetNativeWindow()->SetProperty(ash::kConstrainedWindowKey, true);
    views::corewm::SetModalParent(
        widget->GetNativeWindow(),
        platform_util::GetParent(widget->GetNativeView()));
#endif
  }

  virtual void ShowDialog(NativeWebContentsModalDialog dialog) OVERRIDE {
    views::Widget* widget = GetWidget(dialog);
#if defined(USE_AURA)
    scoped_ptr<views::corewm::SuspendChildWindowVisibilityAnimations> suspend;
    if (views::DialogDelegate::UseNewStyle() &&
        shown_widgets_.find(widget) != shown_widgets_.end()) {
      suspend.reset(new views::corewm::SuspendChildWindowVisibilityAnimations(
          widget->GetNativeWindow()->parent()));
    }
#endif
    widget->Show();
    FocusDialog(dialog);
#if defined(USE_AURA)
    if (views::DialogDelegate::UseNewStyle()) {
      widget->GetNativeWindow()->parent()->StackChildAbove(
          widget->GetNativeWindow(),
          native_delegate_->GetWebContents()->GetView()->GetNativeView());
    }

    shown_widgets_.insert(widget);
#endif
  }

  virtual void HideDialog(NativeWebContentsModalDialog dialog) OVERRIDE {
    views::Widget* widget = GetWidget(dialog);
#if defined(USE_AURA)
    scoped_ptr<views::corewm::SuspendChildWindowVisibilityAnimations> suspend;
    if (views::DialogDelegate::UseNewStyle()) {
      suspend.reset(new views::corewm::SuspendChildWindowVisibilityAnimations(
          widget->GetNativeWindow()->parent()));
    }
#endif
    widget->Hide();
  }

  virtual void CloseDialog(NativeWebContentsModalDialog dialog) OVERRIDE {
    GetWidget(dialog)->Close();
  }

  virtual void FocusDialog(NativeWebContentsModalDialog dialog) OVERRIDE {
    views::Widget* widget = GetWidget(dialog);
    if (widget->widget_delegate() &&
        widget->widget_delegate()->GetInitiallyFocusedView())
      widget->widget_delegate()->GetInitiallyFocusedView()->RequestFocus();
#if defined(USE_ASH)
    // We don't necessarily have a RootWindow yet.
    if (widget->GetNativeView()->GetRootWindow())
      widget->GetNativeView()->Focus();
#endif
  }

  virtual void PulseDialog(NativeWebContentsModalDialog dialog) OVERRIDE {
  }

  // views::WidgetObserver overrides

  // NOTE(wittman): OnWidgetClosing is overriden to ensure that, when the widget
  // is explicitly closed, the destruction occurs within the same call
  // stack. This avoids event races that lead to non-deterministic destruction
  // ordering in e.g. the print preview dialog. OnWidgetDestroying is overridden
  // because OnWidgetClosing is *only* invoked on explicit close, not when the
  // widget is implicitly destroyed due to its parent being closed. This
  // situation occurs with app windows.  WidgetClosing removes the observer, so
  // only one of these two functions is ever invoked for a given widget.
  virtual void OnWidgetClosing(views::Widget* widget) OVERRIDE {
    WidgetClosing(widget);
  }

  virtual void OnWidgetDestroying(views::Widget* widget) OVERRIDE {
    WidgetClosing(widget);
  }

 private:
#if defined(USE_AURA)
  // aura::WindowObserver overrides
  virtual void OnWindowHierarchyChanged(
      const aura::WindowObserver::HierarchyChangeParams& params) OVERRIDE {
    // We are called during the teardown of the WebContents' view by which time
    // GetWebContents() will return NULL. We can safely ignore this case.
    if (!native_delegate_->GetWebContents())
      return;
    if (params.target ==
        native_delegate_->GetWebContents()->GetView()->GetNativeView()) {
      std::set<views::Widget*>::const_iterator it = observed_widgets_.begin();
      for (; it != observed_widgets_.end(); ++it)
        params.new_parent->AddChild((*it)->GetNativeWindow());
    }
  }
#endif

  static views::Widget* GetWidget(NativeWebContentsModalDialog dialog) {
    views::Widget* widget = views::Widget::GetWidgetForNativeWindow(dialog);
    DCHECK(widget);
    return widget;
  }

  void WidgetClosing(views::Widget* widget) {
#if defined(USE_ASH)
    gfx::NativeView view = platform_util::GetParent(widget->GetNativeView());
    // Allow the parent to animate again.
    if (view && view->parent())
      view->parent()->ClearProperty(aura::client::kAnimationsDisabledKey);
#endif
    widget->RemoveObserver(this);
    native_delegate_->WillClose(widget->GetNativeView());
    observed_widgets_.erase(widget);
#if defined(USE_AURA)
    shown_widgets_.erase(widget);
#endif
  }

  NativeWebContentsModalDialogManagerDelegate* native_delegate_;
  std::set<views::Widget*> observed_widgets_;
  std::set<views::Widget*> shown_widgets_;

  DISALLOW_COPY_AND_ASSIGN(NativeWebContentsModalDialogManagerViews);
};

}  // namespace

namespace web_modal {

NativeWebContentsModalDialogManager* WebContentsModalDialogManager::
CreateNativeManager(
    NativeWebContentsModalDialogManagerDelegate* native_delegate) {
  return new NativeWebContentsModalDialogManagerViews(native_delegate);
}

}  // namespace web_modal
<|endoftext|>


<commit_before>#include <iomanip>

#include <boost/regex.hpp>

#include "sessionhelper.hpp"

SessionHelper::SessionHelper(const std::string &address)
{
  _session.connect(address);
}

SessionHelper::~SessionHelper()
{
  _session.close();
}

bool SessionHelper::getServiceSync(const std::string &serviceName, ServiceHelper &out)
{
  qi::FutureSync<qi::ObjectPtr> future = _session.service(serviceName);

  if (future.hasError())
  {
    std::cout << "\terror : " << future.error() << std::endl;
    return false;
  }

  out = future.value();
  return true;
}

void SessionHelper::_showServiceInfo(const qi::ServiceInfo &infos, bool verbose, bool number)
{
  if (!verbose)
  {
    if (number)
      std::cout << "[" << infos.serviceId() << "]";
    std::cout << infos.name() << std::endl;
    return ;
  }

  std::cout << "    service: " << infos.name() << std::endl
            << "         id: " << infos.serviceId() << std::endl
            << "    machine: " << infos.machineId() << std::endl
            << "    process: " << infos.processId() << std::endl
            << "  endpoints: " << std::endl;

  for (qi::UrlVector::const_iterator it_urls = infos.endpoints().begin(); it_urls != infos.endpoints().end(); ++it_urls)
    std::cout << "             " << it_urls->str() << std::endl;

  ServiceHelper service;

  if (!getServiceSync(infos.name(), service))
    return ;
  qi::details::printMetaObject(std::cout, service.objPtr()->metaObject());
}

void SessionHelper::showServiceInfo(const std::string &serviceName, bool verbose, bool number)
{
  std::vector<qi::ServiceInfo> servs = _session.services();

  unsigned int i;
  for (i = 0; i < servs.size(); ++i)
    if (servs[i].name() == serviceName)
      break;
  if (i == servs.size())
    return ;

  _showServiceInfo(servs[i], verbose, number);
}

void SessionHelper::showServiceInfo(unsigned int serviceId, bool verbose, bool number)
{
  std::vector<qi::ServiceInfo> servs = _session.services();

  unsigned int i;
  for (i = 0; i < servs.size(); ++i)
    if (servs[i].serviceId() == serviceId)
      break;
  if (i == servs.size())
    return ;

  _showServiceInfo(servs[i], verbose, number);
}

bool isNumber(const std::string &str)
{
  for (unsigned int i = 0; i < str.length(); ++i)
  {
    if (!::isdigit(str[i]))
      return false;
  }
  return true;
}

void SessionHelper::xShowServicesInfo(const std::vector<std::string> &patternVec, bool verbose, bool number)
{
  std::vector<qi::ServiceInfo> servs = _session.services();
  std::vector<std::string> matchServs;

  for (unsigned int u = 0; u < patternVec.size(); ++u)
  {
    if (isNumber(patternVec[u]))
      matchServs.push_back(patternVec[u]);
    else
    {
      boost::basic_regex<char> reg(patternVec[u]);
      for (unsigned int i = 0; i < servs.size(); ++i)
      {
        if (boost::regex_match(servs[i].name(), reg))
          matchServs.push_back(servs[i].name());
      }
    }
  }
  showServicesInfo(matchServs, verbose, number);
}

void SessionHelper::showServicesInfo(const std::vector<std::string> &serviceList, bool verbose, bool number)
{
  for (unsigned int i = 0; i < serviceList.size(); ++i)
  {
    if (isNumber(serviceList[i]))
      showServiceInfo(::atoi(serviceList[i].c_str()), verbose, number);
    else
      showServiceInfo(serviceList[i], verbose, number);
    if (verbose)
      if (i + 1 != serviceList.size())
        std::cout << "========================================================================" << std::endl;
  }
}

void SessionHelper::showServicesInfo(bool verbose, bool number)
{
  std::vector<qi::ServiceInfo> servs = _session.services();

  for (unsigned int i = 0; i < servs.size(); ++i)
  {
    _showServiceInfo(servs[i], verbose, number);
    if (verbose)
      if (i + 1 != servs.size())
        std::cout << "========================================================================" << std::endl;
  }
}

qi::FutureSync<void> SessionHelper::connect(const qi::Url &serviceDirectoryURL)
{
  return _session.connect(serviceDirectoryURL);
}

qi::FutureSync<void> SessionHelper::close()
{
  return _session.close();
}

qi::FutureSync< qi::ObjectPtr > SessionHelper::service(const std::string &service, const std::string &protocol)
{
  return _session.service(service, protocol);
}

qi::FutureSync< std::vector<qi::ServiceInfo> > SessionHelper::services(qi::Session::ServiceLocality locality)
{
  return _session.services(locality);
}
<commit_msg>qicli: major perf improvement when using regexp<commit_after>#include <iomanip>

#include <boost/regex.hpp>

#include "sessionhelper.hpp"

SessionHelper::SessionHelper(const std::string &address)
{
  _session.connect(address);
}

SessionHelper::~SessionHelper()
{
  _session.close();
}

bool SessionHelper::getServiceSync(const std::string &serviceName, ServiceHelper &out)
{
  qi::FutureSync<qi::ObjectPtr> future = _session.service(serviceName);

  if (future.hasError())
  {
    std::cout << "\terror : " << future.error() << std::endl;
    return false;
  }

  out = future.value();
  return true;
}

void SessionHelper::_showServiceInfo(const qi::ServiceInfo &infos, bool verbose, bool number)
{
  if (!verbose)
  {
    if (number)
      std::cout << "[" << infos.serviceId() << "]";
    std::cout << infos.name() << std::endl;
    return ;
  }

  std::cout << "    service: " << infos.name() << std::endl
            << "         id: " << infos.serviceId() << std::endl
            << "    machine: " << infos.machineId() << std::endl
            << "    process: " << infos.processId() << std::endl
            << "  endpoints: " << std::endl;

  for (qi::UrlVector::const_iterator it_urls = infos.endpoints().begin(); it_urls != infos.endpoints().end(); ++it_urls)
    std::cout << "             " << it_urls->str() << std::endl;

  ServiceHelper service;

  if (!getServiceSync(infos.name(), service))
    return ;
  qi::details::printMetaObject(std::cout, service.objPtr()->metaObject());
}

void SessionHelper::showServiceInfo(const std::string &serviceName, bool verbose, bool number)
{
  std::vector<qi::ServiceInfo> servs = _session.services();

  unsigned int i;
  for (i = 0; i < servs.size(); ++i)
    if (servs[i].name() == serviceName)
      break;
  if (i == servs.size())
    return ;

  _showServiceInfo(servs[i], verbose, number);
}

void SessionHelper::showServiceInfo(unsigned int serviceId, bool verbose, bool number)
{
  std::vector<qi::ServiceInfo> servs = _session.services();

  unsigned int i;
  for (i = 0; i < servs.size(); ++i)
    if (servs[i].serviceId() == serviceId)
      break;
  if (i == servs.size())
    return ;

  _showServiceInfo(servs[i], verbose, number);
}

bool isNumber(const std::string &str)
{
  for (unsigned int i = 0; i < str.length(); ++i)
  {
    if (!::isdigit(str[i]))
      return false;
  }
  return true;
}

void SessionHelper::xShowServicesInfo(const std::vector<std::string> &patternVec, bool verbose, bool number)
{
  std::vector<qi::ServiceInfo> servs = _session.services();
  std::vector<std::string> matchServs;

  for (unsigned int u = 0; u < patternVec.size(); ++u)
  {
    if (isNumber(patternVec[u]))
      matchServs.push_back(patternVec[u]);
    else
    {
      boost::basic_regex<char> reg(patternVec[u]);
      for (unsigned int i = 0; i < servs.size(); ++i)
      {
        if (boost::regex_match(servs[i].name(), reg))
          matchServs.push_back(servs[i].name());
      }
    }
  }
  showServicesInfo(matchServs, verbose, number);
}

void SessionHelper::showServicesInfo(const std::vector<std::string> &serviceList, bool verbose, bool number)
{
  std::vector<qi::ServiceInfo> servs = _session.services();

  for (unsigned int i = 0; i < servs.size(); ++i)
  {
    for (unsigned int u = 0; u < serviceList.size(); ++u)
    {
      if ((isNumber(serviceList[u]) && static_cast<unsigned int>(::atoi(serviceList[u].c_str())) == servs[i].serviceId())
          || serviceList[u] == servs[i].name())
      {
        _showServiceInfo(servs[i], verbose, number);
        if (verbose)
            std::cout << "========================================================================" << std::endl;
      }
    }
  }
}

void SessionHelper::showServicesInfo(bool verbose, bool number)
{
  std::vector<qi::ServiceInfo> servs = _session.services();

  for (unsigned int i = 0; i < servs.size(); ++i)
  {
    _showServiceInfo(servs[i], verbose, number);
    if (verbose)
      if (i + 1 != servs.size())
        std::cout << "========================================================================" << std::endl;
  }
}

qi::FutureSync<void> SessionHelper::connect(const qi::Url &serviceDirectoryURL)
{
  return _session.connect(serviceDirectoryURL);
}

qi::FutureSync<void> SessionHelper::close()
{
  return _session.close();
}

qi::FutureSync< qi::ObjectPtr > SessionHelper::service(const std::string &service, const std::string &protocol)
{
  return _session.service(service, protocol);
}

qi::FutureSync< std::vector<qi::ServiceInfo> > SessionHelper::services(qi::Session::ServiceLocality locality)
{
  return _session.services(locality);
}
<|endoftext|>


<commit_before>/* Copyright (C) 2015 haha01haha01

* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "lib_api.h"

namespace HaRail {

	GTFSDataSource *HaRailAPI::gds = nullptr;
	HaException HaRailAPI::last_err("", HaException::CRITICAL_ERROR);

	bool HaRailAPI::loadData(int date, int start_time, string data_root)
	{
		try {
			if (gds) {
				delete gds;
				gds = nullptr;
			}
			gds = new GTFSDataSource(data_root, Utils::padWithZeroes(Utils::int2str(date), 6));
			gds->initStations();
			gds->initTrains();
			return true;
		}
		catch (HaException e)  {
			if (gds) {
				delete gds;
				gds = nullptr;
			}
			last_err = e;
			return false;
		}
		catch (...) {
			last_err = HaException("Unknown Error", HaException::CRITICAL_ERROR);
			return false;
		}
	}

	string HaRailAPI::getLastError()
	{
		return last_err.what();
	}

    vector<int> HaRailAPI::getAllFollowingRoutes(int start_time, int start_station_id, int dest_station_id)
	{
		vector<int> result{ 1 };
		bool found_some_route = false;
		try {
			while (true) {
				vector<Train *> route{};
				Graph::getBestRouteSimple(gds, gds->getStationById(start_station_id), start_time, gds->getStationById(dest_station_id), route);
				encodeRouteSimple(route, result);
				found_some_route = true;
			}
		}
		catch (HaException e) {
		    if (e.getType() == HaException::INVALID_ROUTE_ERROR && found_some_route) {
		        // This is fine, we just reached end of day
		        return result;
		    }
			last_err = e;
			return vector<int> { 0 };
		}
		catch (...) {
			last_err = HaException("Unknown Error", HaException::CRITICAL_ERROR);
			return vector<int> { 0 };
		}
	}

	vector<int> HaRailAPI::getRoutes(int start_time, int start_station_id, int dest_station_id)
	{
		try {
			vector<Train *> shortest_route;
			vector<Train *> best_route;
			Graph::getBestRoutes(gds, gds->getStationById(start_station_id), start_time, gds->getStationById(dest_station_id), shortest_route, best_route);
			if (shortest_route == best_route) {
				vector<int> result{ 1 };
				encodeRoute(best_route, result);
				return result;
			}
			else {
				vector<int> result{ 2 };
				encodeRoute(shortest_route, result);
				encodeRoute(best_route, result);
				return result;
			}
		}
		catch (HaException e) {
			last_err = e;
			return vector<int> { 0 };
		}
		catch (...) {
			last_err = HaException("Unknown Error", HaException::CRITICAL_ERROR);
			return vector<int> { 0 };
		}
	}

	void HaRailAPI::encodeRoute(const vector<Train *>& route, vector<int>& out_vec)
	{
		vector<int> temp_vec;
		Train *last_train = nullptr;
		int trains = 0;
		for (Train *train : route) {
			if (!last_train || train->getTrainId() != last_train->getTrainId()) {
				// Boarding new train
				if (last_train) {
					temp_vec.push_back(last_train->getDest()->getStationId());
					temp_vec.push_back(last_train->getDestTime());
				}
				++trains;
				temp_vec.push_back(train->getTrainId());
				temp_vec.push_back(train->getSource()->getStationId());
				temp_vec.push_back(train->getSourceTime());
			}
			last_train = train;
		}
		temp_vec.push_back(last_train->getDest()->getStationId());
		temp_vec.push_back(last_train->getDestTime());

		out_vec.reserve(out_vec.size() + 1 + temp_vec.size());
		out_vec.push_back(trains);
		for (int curr : temp_vec) {
			out_vec.push_back(curr);
		}
	}

    void HaRailAPI::encodeRouteSimple(const vector<Train *>& route, vector<int>& out_vec)
    {
        out_vec.push_back(Graph::getRouteStartTime(route));
        out_vec.push_back(Graph::getRouteEndTime(route));
        out_vec.push_back(Graph::countTrainSwitches(route));
    }

    string HaRailAPI::getRoutesStr(int start_time, int start_station_id, int dest_station_id)
	{
		try {
			vector<Train *> shortest_route;
			vector<Train *> best_route;
			Graph::getBestRoutes(gds, gds->getStationById(start_station_id), start_time, gds->getStationById(dest_station_id), shortest_route, best_route);
			stringstream ss;
			Graph::printBestRoutes(shortest_route, best_route, ss);
			return ss.str();
		}
		catch (HaException e) {
			return e.what();
		}
		catch (...) {
			return "Unknown Error";
		}
	}

	vector<int> HaRailAPI::getWholeTrainPath(int train_id)
	{
		try {
			int trains = 0;
			vector<int> result{ 1, trains };
			for (Train * train : gds->getTrains()) {
				if (train->getTrainId() == train_id) {
					++trains;
					result.push_back(train->getSource()->getStationId());
					result.push_back(train->getSourceTime());
					result.push_back(train->getDest()->getStationId());
					result.push_back(train->getDestTime());
				}
			}
			result[1] = trains;
			return result;
		}
		catch (HaException e) {
			last_err = e;
			return vector<int> { 0 };
		}
		catch (...) {
			last_err = HaException("Unknown Error", HaException::CRITICAL_ERROR);
			return vector<int> { 0 };
		}
	}
}
<commit_msg>Bugfix<commit_after>/* Copyright (C) 2015 haha01haha01

* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "lib_api.h"

namespace HaRail {

	GTFSDataSource *HaRailAPI::gds = nullptr;
	HaException HaRailAPI::last_err("", HaException::CRITICAL_ERROR);

	bool HaRailAPI::loadData(int date, int start_time, string data_root)
	{
		try {
			if (gds) {
				delete gds;
				gds = nullptr;
			}
			gds = new GTFSDataSource(data_root, Utils::padWithZeroes(Utils::int2str(date), 6));
			gds->initStations();
			gds->initTrains();
			return true;
		}
		catch (HaException e)  {
			if (gds) {
				delete gds;
				gds = nullptr;
			}
			last_err = e;
			return false;
		}
		catch (...) {
			last_err = HaException("Unknown Error", HaException::CRITICAL_ERROR);
			return false;
		}
	}

	string HaRailAPI::getLastError()
	{
		return last_err.what();
	}

    vector<int> HaRailAPI::getAllFollowingRoutes(int start_time, int start_station_id, int dest_station_id)
	{
		vector<int> result{ 1 };
		bool found_some_route = false;
		try {
			while (true) {
				vector<Train *> route{};
				Graph::getBestRouteSimple(gds, gds->getStationById(start_station_id), start_time, gds->getStationById(dest_station_id), route);
				encodeRouteSimple(route, result);
				start_time = Graph::getRouteStartTime(route) + 1;
				found_some_route = true;
			}
		}
		catch (HaException e) {
		    if (e.getType() == HaException::INVALID_ROUTE_ERROR && found_some_route) {
		        // This is fine, we just reached end of day
		        return result;
		    }
			last_err = e;
			return vector<int> { 0 };
		}
		catch (...) {
			last_err = HaException("Unknown Error", HaException::CRITICAL_ERROR);
			return vector<int> { 0 };
		}
	}

	vector<int> HaRailAPI::getRoutes(int start_time, int start_station_id, int dest_station_id)
	{
		try {
			vector<Train *> shortest_route;
			vector<Train *> best_route;
			Graph::getBestRoutes(gds, gds->getStationById(start_station_id), start_time, gds->getStationById(dest_station_id), shortest_route, best_route);
			if (shortest_route == best_route) {
				vector<int> result{ 1 };
				encodeRoute(best_route, result);
				return result;
			}
			else {
				vector<int> result{ 2 };
				encodeRoute(shortest_route, result);
				encodeRoute(best_route, result);
				return result;
			}
		}
		catch (HaException e) {
			last_err = e;
			return vector<int> { 0 };
		}
		catch (...) {
			last_err = HaException("Unknown Error", HaException::CRITICAL_ERROR);
			return vector<int> { 0 };
		}
	}

	void HaRailAPI::encodeRoute(const vector<Train *>& route, vector<int>& out_vec)
	{
		vector<int> temp_vec;
		Train *last_train = nullptr;
		int trains = 0;
		for (Train *train : route) {
			if (!last_train || train->getTrainId() != last_train->getTrainId()) {
				// Boarding new train
				if (last_train) {
					temp_vec.push_back(last_train->getDest()->getStationId());
					temp_vec.push_back(last_train->getDestTime());
				}
				++trains;
				temp_vec.push_back(train->getTrainId());
				temp_vec.push_back(train->getSource()->getStationId());
				temp_vec.push_back(train->getSourceTime());
			}
			last_train = train;
		}
		temp_vec.push_back(last_train->getDest()->getStationId());
		temp_vec.push_back(last_train->getDestTime());

		out_vec.reserve(out_vec.size() + 1 + temp_vec.size());
		out_vec.push_back(trains);
		for (int curr : temp_vec) {
			out_vec.push_back(curr);
		}
	}

    void HaRailAPI::encodeRouteSimple(const vector<Train *>& route, vector<int>& out_vec)
    {
        out_vec.push_back(Graph::getRouteStartTime(route));
        out_vec.push_back(Graph::getRouteEndTime(route));
        out_vec.push_back(Graph::countTrainSwitches(route));
    }

    string HaRailAPI::getRoutesStr(int start_time, int start_station_id, int dest_station_id)
	{
		try {
			vector<Train *> shortest_route;
			vector<Train *> best_route;
			Graph::getBestRoutes(gds, gds->getStationById(start_station_id), start_time, gds->getStationById(dest_station_id), shortest_route, best_route);
			stringstream ss;
			Graph::printBestRoutes(shortest_route, best_route, ss);
			return ss.str();
		}
		catch (HaException e) {
			return e.what();
		}
		catch (...) {
			return "Unknown Error";
		}
	}

	vector<int> HaRailAPI::getWholeTrainPath(int train_id)
	{
		try {
			int trains = 0;
			vector<int> result{ 1, trains };
			for (Train * train : gds->getTrains()) {
				if (train->getTrainId() == train_id) {
					++trains;
					result.push_back(train->getSource()->getStationId());
					result.push_back(train->getSourceTime());
					result.push_back(train->getDest()->getStationId());
					result.push_back(train->getDestTime());
				}
			}
			result[1] = trains;
			return result;
		}
		catch (HaException e) {
			last_err = e;
			return vector<int> { 0 };
		}
		catch (...) {
			last_err = HaException("Unknown Error", HaException::CRITICAL_ERROR);
			return vector<int> { 0 };
		}
	}
}
<|endoftext|>


<commit_before>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2021-present David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#pragma once

#include <DO/Sara/Core/Image.hpp>
#include <DO/Sara/Core/Math/JenkinsTraub.hpp>
#include <DO/Sara/Core/Math/NewtonRaphson.hpp>
#include <DO/Sara/Core/Pixel/PixelTraits.hpp>

#include <DO/Sara/MultiViewGeometry/Camera/PinholeCamera.hpp>

namespace DO::Sara {

  template <typename T>
  struct RadialRationalCorrectionFunction
  {
    Eigen::Matrix<T, 2, 1> k;
    Eigen::Matrix<T, 2, 1> distortion_center;

    auto operator()(const Eigen::Matrix<T, 2, 1>& xd) const
        -> Eigen::Matrix<T, 2, 1>
    {
      const auto r2 = (xd - distortion_center).squaredNorm();
      const auto r4 = r2 * r2;
      const auto distortion_factor = 1 / (1 + k(0) * r2 + k(1) * r4);
      const auto& c = distortion_center;
      return c + distortion_factor * (xd - c);
    }

    auto inverse(const Eigen::Matrix<T, 2, 1>& xu) const
        -> Eigen::Matrix<T, 2, 1>
    {
      const auto& c = distortion_center;
      const auto ru = (xu - c).squaredNorm();

      auto P = UnivariatePolynomial<T>{4};
      P[0] = 1;
      P[1] = -1;
      P[2] = ru * k(0);
      P[3] = 0;
      P[4] = ru * k(1);

      auto solver = NewtonRaphson<T>{P};
      const auto rd = solver(ru);

      return c + rd / ru * (xu - c);
    }
  };

  template <typename T>
  struct RadialPolynomialCorrectionFunction
  {
    Eigen::Matrix<T, 2, 1> k;
    Eigen::Matrix<T, 2, 1> distortion_center;

    auto operator()(const Eigen::Matrix<T, 2, 1>& xd) const
        -> Eigen::Matrix<T, 2, 1>
    {
      const auto r2 = (xd - distortion_center).squaredNorm();
      const auto r4 = r2 * r2;
      const auto distortion_factor = 1 + k(0) * r2 + k(1) * r4;
      const auto& c = distortion_center;
      return c + distortion_factor * (xd - c);
    }

    auto inverse(const Eigen::Matrix<T, 2, 1>& xu, int max_iter = 20,
                 T eps = T{1e-6}) const -> Eigen::Matrix<T, 2, 1>
    {
      const auto& c = distortion_center;
      const auto ru = (xu - c).squaredNorm();

      auto corrected_radius = [this](T rd) {
        const auto rd2 = rd * rd;
        const auto rd3 = rd2 * rd;
        const auto rd5 = rd2 * rd3;
        return rd + k(0) * rd3 + k(1) * rd5;
      };

      auto rd_min = T{};
      auto rd_max = 2 * ru;
      // Find a smaller upper bound by exploiting monotonicity.
      auto corrected_rd = corrected_radius(rd_max);
      while (corrected_radius(rd_max) < ru)
      {
        rd_min = rd_max;
        rd_max = 2 * rd_max;
      }

      // Apply bisection.
      auto rd_estimate = static_cast<T>(0.5) * (rd_min + rd_max);
      auto ru_at_rd_estimate = corrected_radius(rd_estimate);
      auto iter = 0;
      while (iter < max_iter &&
             std::abs(ru_at_rd_estimate - ru) > eps)
      {
        if (ru_at_rd_estimate < ru)
          rd_min = ru_at_rd_estimate;
        else
          rd_max = ru_at_rd_estimate;

        rd_estimate = T{0.5} * (rd_min + rd_max);

        ++iter;
      }

      return c + rd_estimate / ru * (xu - c);
    }
  };

  template <typename T, typename CorrectionFunction>
  struct CameraCorrectionModel : PinholeCamera<T>
  {
    static constexpr auto eps = static_cast<T>(1e-8);

    using correction_function_type = CorrectionFunction;

    //! @brief Types.
    using base_type = PinholeCamera<T>;
    using vector2_type = typename base_type::vector2_type;
    using vector3_type = typename base_type::vector3_type;
    using matrix2_type = Eigen::Matrix<T, 2, 2>;
    using matrix3_type = typename base_type::matrix3_type;

    using base_type::image_sizes;
    using base_type::K;
    using base_type::K_inverse;

    // Correction model.
    correction_function_type correction_function;

    inline auto undistort(const vector2_type& xd) const -> vector2_type
    {
      return correction_function.apply(xd);
    }

    inline auto distort(const vector2_type& xu) const -> vector2_type
    {
      return correction_function.apply_inverse(xu);
    }

    inline auto project(const vector3_type& x) const -> vector2_type
    {
      const Eigen::Vector2f pixel_coords = (K * x).hnormalized();
      return correction_function.apply_inverse(pixel_coords);
    }

    inline auto backproject(const vector2_type& x) const -> vector3_type
    {
      const auto xu = correction_function.apply(x);
      return K_inverse * xu.homogeneous();
    }
  };

}  // namespace DO::Sara
<commit_msg>MAINT: save work.<commit_after>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2021-present David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#pragma once

#include <DO/Sara/Core/Image.hpp>
#include <DO/Sara/Core/Math/JenkinsTraub.hpp>
#include <DO/Sara/Core/Math/NewtonRaphson.hpp>
#include <DO/Sara/Core/Pixel/PixelTraits.hpp>

#include <DO/Sara/MultiViewGeometry/Camera/PinholeCamera.hpp>

namespace DO::Sara {

  template <typename T>
  struct RadialRationalCorrectionFunction
  {
    Eigen::Matrix<T, 2, 1> k;
    Eigen::Matrix<T, 2, 1> distortion_center;

    auto apply(const Eigen::Matrix<T, 2, 1>& xd) const -> Eigen::Matrix<T, 2, 1>
    {
      const auto r2 = (xd - distortion_center).squaredNorm();
      const auto r4 = r2 * r2;
      const auto distortion_factor = 1 / (1 + k(0) * r2 + k(1) * r4);
      const auto& c = distortion_center;
      return c + distortion_factor * (xd - c);
    }

    auto apply_inverse(const Eigen::Matrix<T, 2, 1>& xu, int max_iter = 20,
                       T eps = T{1e-6}) const -> Eigen::Matrix<T, 2, 1>
    {
      const auto& c = distortion_center;
      const auto ru = (xu - c).norm();
      if (ru < std::numeric_limits<T>::epsilon())
        return xu;

      auto P = UnivariatePolynomial<T>{4};
      P[0] = 1;
      P[1] = -1 / ru;
      P[2] = k(0);
      P[3] = 0;
      P[4] = k(1);

      auto solver = NewtonRaphson<T>{P};
      const auto rd = solver(ru, max_iter, eps);

      return c + rd / ru * (xu - c);
    }
  };

  template <typename T>
  struct RadialPolynomialCorrectionFunction
  {
    Eigen::Matrix<T, 2, 1> k;
    Eigen::Matrix<T, 2, 1> distortion_center;

    auto apply(const Eigen::Matrix<T, 2, 1>& xd) const -> Eigen::Matrix<T, 2, 1>
    {
      const auto r2 = (xd - distortion_center).squaredNorm();
      const auto r4 = r2 * r2;
      const auto distortion_factor = 1 + k(0) * r2 + k(1) * r4;
      const auto& c = distortion_center;
      return c + distortion_factor * (xd - c);
    }

    auto apply_inverse(const Eigen::Matrix<T, 2, 1>& xu, int max_iter = 20,
                       T eps = T{1e-6}) const -> Eigen::Matrix<T, 2, 1>
    {
      const auto& c = distortion_center;
      const auto ru = (xu - c).squaredNorm();

      auto corrected_radius = [this](T rd) {
        const auto rd2 = rd * rd;
        const auto rd3 = rd2 * rd;
        const auto rd5 = rd2 * rd3;
        return rd + k(0) * rd3 + k(1) * rd5;
      };

      auto rd_min = T{};
      auto rd_max = 2 * ru;
      // Find a smaller upper bound by exploiting monotonicity.
      auto corrected_rd = corrected_radius(rd_max);
      while (corrected_radius(rd_max) < ru)
      {
        rd_min = rd_max;
        rd_max = 2 * rd_max;
      }

      // Apply bisection.
      auto rd_estimate = static_cast<T>(0.5) * (rd_min + rd_max);
      auto ru_at_rd_estimate = corrected_radius(rd_estimate);
      auto iter = 0;
      while (iter < max_iter && std::abs(ru_at_rd_estimate - ru) > eps)
      {
        if (ru_at_rd_estimate < ru)
          rd_min = ru_at_rd_estimate;
        else
          rd_max = ru_at_rd_estimate;

        rd_estimate = T{0.5} * (rd_min + rd_max);

        ++iter;
      }

      return c + rd_estimate / ru * (xu - c);
    }
  };

  template <typename T, typename CorrectionFunction>
  struct CameraCorrectionModel : PinholeCamera<T>
  {
    static constexpr auto eps = static_cast<T>(1e-8);

    using correction_function_type = CorrectionFunction;

    //! @brief Types.
    using base_type = PinholeCamera<T>;
    using vector2_type = typename base_type::vector2_type;
    using vector3_type = typename base_type::vector3_type;
    using matrix2_type = Eigen::Matrix<T, 2, 2>;
    using matrix3_type = typename base_type::matrix3_type;

    using base_type::image_sizes;
    using base_type::K;
    using base_type::K_inverse;

    // Correction model.
    correction_function_type correction_function;

    inline auto undistort(const vector2_type& xd) const -> vector2_type
    {
      return correction_function.apply(xd);
    }

    inline auto distort(const vector2_type& xu) const -> vector2_type
    {
      return correction_function.apply_inverse(xu);
    }

    inline auto project(const vector3_type& x) const -> vector2_type
    {
      const Eigen::Vector2f pixel_coords = (K * x).hnormalized();
      return correction_function.apply_inverse(pixel_coords);
    }

    inline auto backproject(const vector2_type& x) const -> vector3_type
    {
      const auto xu = correction_function.apply(x);
      return K_inverse * xu.homogeneous();
    }
  };

}  // namespace DO::Sara
<|endoftext|>