void SetTimeoutCommandHandler::ExecuteInternal(
    const IECommandExecutor& executor,
    const ParametersMap& command_parameters,
    Response* response) {
  ParametersMap::const_iterator type_parameter_iterator = command_parameters.find("type");
  ParametersMap::const_iterator ms_parameter_iterator = command_parameters.find("ms");
  if (type_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(400, "Missing parameter: type");
    return;
  } else if (ms_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(400, "Missing parameter: ms");
    return;
  } else {
    std::string timeout_type = type_parameter_iterator->second.asString();
    int timeout = ms_parameter_iterator->second.asInt();
    IECommandExecutor& mutable_executor = const_cast<IECommandExecutor&>(executor);
    if (timeout_type == "implicit") {
      mutable_executor.set_implicit_wait_timeout(timeout);
    } else if (timeout_type == "script") {
      mutable_executor.set_async_script_timeout(timeout);
    } else if (timeout_type == "page load") {
        mutable_executor.set_page_load_timeout(timeout);
    } else {
      response->SetErrorResponse(EUNHANDLEDERROR, "Invalid timeout type specified: " + timeout_type);
      return;
    }
    response->SetSuccessResponse(Json::Value::null);
  }
}
void GetElementPropertyCommandHandler::ExecuteInternal(
    const IECommandExecutor& executor,
    const ParametersMap& command_parameters,
    Response* response) {
  ParametersMap::const_iterator id_parameter_iterator = command_parameters.find("id");
  ParametersMap::const_iterator name_parameter_iterator = command_parameters.find("name");
  if (id_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "Missing parameter in URL: id");
    return;
  } else if (name_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "Missing parameter in URL: name");
    return;
  } else {
    std::string element_id = id_parameter_iterator->second.asString();
    std::string name = name_parameter_iterator->second.asString();

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

    ElementHandle element_wrapper;
    status_code = this->GetElement(executor, element_id, &element_wrapper);
    if (status_code == WD_SUCCESS) {
      std::string value = "";
      bool is_null;
      status_code = element_wrapper->GetPropertyValue(name,
                                                      &value,
                                                      &is_null);
      if (status_code != WD_SUCCESS) {
        response->SetErrorResponse(status_code, "Unable to get property");
        return;
      } else {
        if (is_null) {
          response->SetSuccessResponse(Json::Value::null);
          return;
        } else {
          response->SetSuccessResponse(value);
          return;
        }
      }
    } else {
      response->SetErrorResponse(ERROR_STALE_ELEMENT_REFERENCE, "Element is no longer valid");
      return;
    }
  }
}
void SetWindowPositionCommandHandler::ExecuteInternal(
    const IECommandExecutor& executor,
    const ParametersMap& command_parameters,
    Response* response) {
  ParametersMap::const_iterator id_parameter_iterator = command_parameters.find("windowHandle");
  ParametersMap::const_iterator x_parameter_iterator = command_parameters.find("x");
  ParametersMap::const_iterator y_parameter_iterator = command_parameters.find("y");
  if (id_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(400, "Missing parameter in URL: windowHandle");
    return;
  } else if (x_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(400, "Missing parameter: x");
    return;
  } else if (y_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(400, "Missing parameter: y");
    return;
  } else {
    int status_code = WD_SUCCESS;
    int x = x_parameter_iterator->second.asInt();
    int y = y_parameter_iterator->second.asInt();
    std::string window_id = id_parameter_iterator->second.asString();

    BrowserHandle browser_wrapper;
    if (window_id == "current") {
      status_code = executor.GetCurrentBrowser(&browser_wrapper);
    } else {
      status_code = executor.GetManagedBrowser(window_id, &browser_wrapper);
    }
    if (status_code != WD_SUCCESS) {
      response->SetErrorResponse(status_code, "Error retrieving window with handle " + window_id);
      return;
    }

    HWND window_handle = browser_wrapper->GetTopLevelWindowHandle();
    POINT desired_location;
    desired_location.x = x;
    desired_location.y = y;
      
    BOOL set_window_pos_result = ::SetWindowPos(window_handle, NULL, desired_location.x, desired_location.y, 0, 0, SWP_NOSIZE);
    if (!set_window_pos_result) {
      response->SetErrorResponse(EUNHANDLEDERROR,
                                  "Unexpected error setting window size (SetWindowPos API failed)");
      return;
    }

    response->SetSuccessResponse(Json::Value::null);
  }
}
void ActionsCommandHandler::ExecuteInternal(
    const IECommandExecutor& executor,
    const ParametersMap& command_parameters,
    Response* response) {
  BrowserHandle browser_wrapper;
  int status_code = executor.GetCurrentBrowser(&browser_wrapper);
  if (status_code != WD_SUCCESS) {
    response->SetErrorResponse(status_code, "Unable to get current browser");
    return;
  }
  ParametersMap::const_iterator actions_parameter_iterator = command_parameters.find("actions");
  if (actions_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "Missing parameter: actions");
    return;
  }
  if (!actions_parameter_iterator->second.isArray()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "Actions value is not an array");
    return;
  }
  std::string error_info = "";
  status_code = executor.input_manager()->PerformInputSequence(browser_wrapper,
                                                               actions_parameter_iterator->second,
                                                               &error_info);
  if (status_code != WD_SUCCESS) {
    if (status_code == EMOVETARGETOUTOFBOUNDS) {
      response->SetErrorResponse(status_code, error_info);
    } else {
      response->SetErrorResponse(status_code, "Unexpected error performing action sequence.");
    }
    return;
  }
  response->SetSuccessResponse(Json::Value::null);
}
void DeleteCookieCommandHandler::ExecuteInternal(
    const IECommandExecutor& executor,
    const ParametersMap& command_parameters,
    Response* response) {
  ParametersMap::const_iterator name_parameter_iterator = command_parameters.find("name");
  if (name_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "Missing parameter in URL: name");
    return;
  }

  std::string cookie_name = name_parameter_iterator->second.asString();
  BrowserHandle browser_wrapper;
  int status_code = executor.GetCurrentBrowser(&browser_wrapper);
  if (status_code != WD_SUCCESS) {
    response->SetErrorResponse(status_code, "Unable to get browser");
    return;
  }

  BrowserCookie cookie;
  cookie.set_name(cookie_name);
  browser_wrapper->cookie_manager()->DeleteCookie(
      browser_wrapper->GetCurrentUrl(),
      cookie);
  if (status_code != WD_SUCCESS) {
    response->SetErrorResponse(status_code, "Unable to delete cookie");
    return;
  }

  response->SetSuccessResponse(Json::Value::null);
}
void IsElementSelectedCommandHandler::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 {
    std::string element_id = id_parameter_iterator->second.asString();

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

    ElementHandle element_wrapper;
    status_code = this->GetElement(executor, element_id, &element_wrapper);
    if (status_code == WD_SUCCESS) {
      bool is_selected = element_wrapper->IsSelected();
      response->SetSuccessResponse(is_selected);
    } else {
      response->SetErrorResponse(ERROR_STALE_ELEMENT_REFERENCE, "Element is no longer valid");
      return;
    }
  }
}
Example #7
0
void BayesFilter::parseParameters(const ParametersMap & parameters)
{
	ParametersMap::const_iterator iter;
	if((iter=parameters.find(Parameters::kBayesVirtualPlacePriorThr())) != parameters.end())
	{
		this->setVirtualPlacePrior(std::atof((*iter).second.c_str()));
	}
	if((iter=parameters.find(Parameters::kBayesPredictionLC())) != parameters.end())
	{
		this->setPredictionLC((*iter).second);
	}
	if((iter=parameters.find(Parameters::kBayesFullPredictionUpdate())) != parameters.end())
	{
		_fullPredictionUpdate = uStr2Bool((*iter).second.c_str());
	}

}
Json::Value IECommandHandler::RecreateJsonParameterObject(const ParametersMap& command_parameters) {
    Json::Value result;
    ParametersMap::const_iterator param_iterator = command_parameters.begin();
    for (; param_iterator != command_parameters.end(); ++param_iterator) {
        std::string key = param_iterator->first;
        Json::Value value = param_iterator->second;
        result[key] = value;
    }
    return result;
}
void GetElementTextCommandHandler::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 {
    std::string element_id = id_parameter_iterator->second.asString();

    BrowserHandle browser_wrapper;
    int 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) {
      // 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::GET_TEXT);
      script_source += L")})();";

      CComPtr<IHTMLDocument2> doc;
      browser_wrapper->GetDocument(&doc);
      Script script_wrapper(doc, script_source, 1);
      script_wrapper.AddArgument(element_wrapper->element());
      status_code = script_wrapper.Execute();

      if (status_code == WD_SUCCESS) {
        std::string text = "";
        bool is_null = script_wrapper.ConvertResultToString(&text);
        response->SetSuccessResponse(text);
        return;
      } else {
        response->SetErrorResponse(status_code,
                                    "Unable to get element text");
        return;
      }
    } else {
      response->SetErrorResponse(ERROR_STALE_ELEMENT_REFERENCE, "Element is no longer valid");
      return;
    }
  }
}
void Camera::parseParameters(const ParametersMap & parameters)
{
	UDEBUG("");
	ParametersMap::const_iterator iter;
	//Keypoint detector
	KeypointDetector::DetectorType detector = KeypointDetector::kDetectorUndef;
	if((iter=parameters.find(Parameters::kKpDetectorStrategy())) != parameters.end())
	{
		detector = (KeypointDetector::DetectorType)std::atoi((*iter).second.c_str());
	}

	if(detector!=KeypointDetector::kDetectorUndef)
	{
		ULOGGER_DEBUG("new detector strategy %d", int(detector));
		if(_keypointDetector)
		{
			delete _keypointDetector;
			_keypointDetector = 0;
		}
		if(_keypointDescriptor)
		{
			delete _keypointDescriptor;
			_keypointDescriptor = 0;
		}
		switch(detector)
		{
		case KeypointDetector::kDetectorSift:
			_keypointDetector = new SIFTDetector(parameters);
			_keypointDescriptor = new SIFTDescriptor(parameters);
			break;
		case KeypointDetector::kDetectorSurf:
		default:
			_keypointDetector = new SURFDetector(parameters);
			_keypointDescriptor = new SURFDescriptor(parameters);
			break;
		}
	}
	else
	{
		if(_keypointDetector)
		{
			_keypointDetector->parseParameters(parameters);
		}
		if(_keypointDescriptor)
		{
			_keypointDescriptor->parseParameters(parameters);
		}
	}
}
bool SetWindowRectCommandHandler::GetNumericParameter(
    const ParametersMap& command_parameters,
    const std::string& argument_name,
    int* argument_value,
    std::string* error_message) {
  ParametersMap::const_iterator parameter_iterator = command_parameters.find(argument_name);
  if (parameter_iterator != command_parameters.end()) {
    if (!parameter_iterator->second.isNumeric()) {
      *error_message = argument_name + " must be a numeric parameter.";
      return false;
    }
    int value = parameter_iterator->second.asInt();
    if (value < 0) {
      *error_message = argument_name + " must be a numeric parameter greater than zero.";
      return false;
    }

    *argument_value = value;
    return true;
  }
  return true;
}
Example #12
0
void ParametersToolBox::setupUi(const ParametersMap & parameters)
{
	parameters_ = parameters;
	QWidget * currentItem = 0;
	QStringList groups;
	for(ParametersMap::const_iterator iter=parameters.begin();
			iter!=parameters.end();
			++iter)
	{
		QStringList splitted = QString::fromStdString(iter->first).split('/');
		QString group = splitted.first();

		QString name = splitted.last();
		if(currentItem == 0 || currentItem->objectName().compare(group) != 0)
		{
			groups.push_back(group);
			QScrollArea * area = new QScrollArea(this);
			stackedWidget_->addWidget(area);
			currentItem = new QWidget();
			currentItem->setObjectName(group);
			QVBoxLayout * layout = new QVBoxLayout(currentItem);
			layout->setSizeConstraint(QLayout::SetMinimumSize);
			layout->setContentsMargins(0,0,0,0);
			layout->setSpacing(0);
			area->setWidget(currentItem);

			addParameter(layout, iter->first, iter->second);
		}
		else
		{
			addParameter((QVBoxLayout*)currentItem->layout(), iter->first, iter->second);
		}
	}
	comboBox_->addItems(groups);
	connect(comboBox_, SIGNAL(currentIndexChanged(int)), stackedWidget_, SLOT(setCurrentIndex(int)));

	updateParametersVisibility();
}
void ExecuteAsyncScriptCommandHandler::ExecuteInternal(
    const IECommandExecutor& executor,
    const ParametersMap& command_parameters,
    Response* response) {
  ParametersMap::const_iterator script_parameter_iterator = command_parameters.find("script");
  ParametersMap::const_iterator args_parameter_iterator = command_parameters.find("args");
  if (script_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "Missing parameter: script");
    return;
  } else if (args_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "Missing parameter: args");
    return;
  } else {
    wchar_t page_id_buffer[GUID_STRING_LEN] = {0};
    GUID page_id_guid;
    ::CoCreateGuid(&page_id_guid);
    ::StringFromGUID2(page_id_guid, page_id_buffer, GUID_STRING_LEN);
    std::wstring page_id = &page_id_buffer[0];

    wchar_t pending_id_buffer[GUID_STRING_LEN] = {0};
    GUID pending_id_guid;
    ::CoCreateGuid(&pending_id_guid);
    ::StringFromGUID2(pending_id_guid, pending_id_buffer, GUID_STRING_LEN);
    std::wstring pending_id = &pending_id_buffer[0];

    Json::Value json_args = args_parameter_iterator->second;

    int timeout_value = executor.async_script_timeout();
    std::wstring timeout = std::to_wstring(static_cast<long long>(timeout_value));

    std::wstring script_body = StringUtilities::ToWString(script_parameter_iterator->second.asString());

    std::wstring async_script = L"(function() { return function(){\n";
    async_script += L"document.__$webdriverAsyncExecutor = {\n";
    async_script += L"  pageId: '" + page_id + L"',\n";
    async_script += L"  asyncTimeout: 0\n";
    async_script += L"};\n";
    async_script += L"var timeoutId = window.setTimeout(function() {\n";
    async_script += L"  window.setTimeout(function() {\n";
    async_script += L"    document.__$webdriverAsyncExecutor.asyncTimeout = 1;\n";
    async_script += L"  }, 0);\n";
    async_script += L"}," + timeout + L");\n";
    async_script += L"var callback = function(value) {\n";
    async_script += L"  document.__$webdriverAsyncExecutor.asyncTimeout = 0;\n";
    async_script += L"  document.__$webdriverAsyncExecutor.asyncScriptResult = value;\n";
    async_script += L"  window.clearTimeout(timeoutId);\n";
    async_script += L"};\n";
    async_script += L"var argsArray = Array.prototype.slice.call(arguments);\n";
    async_script += L"argsArray.push(callback);\n";
    async_script += L"if (document.__$webdriverAsyncExecutor.asyncScriptResult !== undefined) {\n";
    async_script += L"  delete document.__$webdriverAsyncExecutor.asyncScriptResult;\n";
    async_script += L"}\n";
    async_script += L"(function() {" + script_body + L"}).apply(null, argsArray);\n";
    async_script += L"};})();";

    std::wstring polling_script = L"(function() { return function(){\n";
    polling_script += L"var pendingId = '" + pending_id + L"';\n";
    polling_script += L"if ('__$webdriverAsyncExecutor' in document) {\n";
    polling_script += L"  if (document.__$webdriverAsyncExecutor.pageId != '" + page_id + L"') {\n";
    polling_script += L"    return [pendingId, -1];\n";
    polling_script += L"  } else if ('asyncScriptResult' in document.__$webdriverAsyncExecutor) {\n";
    polling_script += L"    var value = document.__$webdriverAsyncExecutor.asyncScriptResult;\n";
    polling_script += L"    delete document.__$webdriverAsyncExecutor.asyncScriptResult;\n";
    polling_script += L"    return value;\n";
    polling_script += L"  } else {\n";
    polling_script += L"    return [pendingId, document.__$webdriverAsyncExecutor.asyncTimeout];\n";
    polling_script += L"  }\n";
    polling_script += L"} else {\n";
    polling_script += L"  return [pendingId, -1];\n";
    polling_script += L"}\n";
    polling_script += L"};})();";

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

    CComPtr<IHTMLDocument2> doc;
    browser_wrapper->GetDocument(&doc);
    Script async_script_wrapper(doc, async_script, json_args.size());
    status_code = this->PopulateArgumentArray(executor,
                                              async_script_wrapper,
                                              json_args);
    if (status_code != WD_SUCCESS) {
      response->SetErrorResponse(status_code,
                                  "Error setting arguments for script");
      return;
    }

    status_code = async_script_wrapper.Execute();

    if (status_code != WD_SUCCESS) {
      response->SetErrorResponse(status_code,
                                  "JavaScript error in async script.");
      return;
    } else {
      Script polling_script_wrapper(doc, polling_script, 0);
      while (true) {
        Json::Value polling_result;
        status_code = polling_script_wrapper.Execute();
        if (status_code != WD_SUCCESS) {
          // Assume that if the polling script errors, it's because
          // of a page reload. Note that experience shows this to
          // happen most frequently when a refresh occurs, since
          // the document object is not yet ready for accessing.
          // However, this is still a big assumption,and could be faulty.
          response->SetErrorResponse(EUNEXPECTEDJSERROR,
                                      "Page reload detected during async script");
          break;
        }

        polling_script_wrapper.ConvertResultToJsonValue(executor, &polling_result);
          
        Json::UInt index = 0;
        std::string narrow_pending_id = StringUtilities::ToString(pending_id);
        if (polling_result.isArray() &&
            polling_result.size() == 2 && 
            polling_result[index].isString() && 
            polling_result[index].asString() == narrow_pending_id) {
          int timeout_flag = polling_result[1].asInt();
          if (timeout_flag < 0) {
            response->SetErrorResponse(EUNEXPECTEDJSERROR,
                                        "Page reload detected during async script");
            break;
          }
          if (timeout_flag > 0) {
            response->SetErrorResponse(ESCRIPTTIMEOUT,
                                        "Timeout expired waiting for async script");
            break;
          }
        } else {
          response->SetSuccessResponse(polling_result);
          break;
        }
      }

      return;
    }
  }
}
void FindElementCommandHandler::ExecuteInternal(
    const IECommandExecutor& executor,
    const ParametersMap& command_parameters,
    Response* response) {
  ParametersMap::const_iterator using_parameter_iterator = command_parameters.find("using");
  ParametersMap::const_iterator value_parameter_iterator = command_parameters.find("value");
  if (using_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "Missing parameter: using");
    return;
  }
  if (!using_parameter_iterator->second.isString()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "using parameter must be a string");
    return;
  }
  if (value_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "Missing parameter: value");
    return;
  }
  if (!value_parameter_iterator->second.isString()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "value parameter must be a string");
    return;
  }

  std::string mechanism = using_parameter_iterator->second.asString();
  std::string value = value_parameter_iterator->second.asString();

  if (mechanism != "css selector" &&
      mechanism != "tag name" &&
      mechanism != "link text" &&
      mechanism != "partial link text" &&
      mechanism != "xpath") {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "using parameter value '" + mechanism + "' is not a valid value");
    return;
  }

  BrowserHandle browser_wrapper;
  int status_code = executor.GetCurrentBrowser(&browser_wrapper);
  if (status_code != WD_SUCCESS) {
    response->SetErrorResponse(status_code, "Currently focused window has been closed.");
    return;
  }

  int timeout = static_cast<int>(executor.implicit_wait_timeout());
  clock_t end = clock() + (timeout / 1000 * CLOCKS_PER_SEC);
  if (timeout > 0 && timeout < 1000) {
    end += 1 * CLOCKS_PER_SEC;
  }

  status_code = WD_SUCCESS;
  Json::Value found_element;
  do {
    status_code = executor.LocateElement(ElementHandle(),
                                         mechanism,
                                         value,
                                         &found_element);
    if (status_code == WD_SUCCESS) {
      response->SetSuccessResponse(found_element);
      return;
    }
    if (status_code == ENOSUCHWINDOW) {
      response->SetErrorResponse(ERROR_NO_SUCH_WINDOW, "Unable to find element on closed window");
      return;
    }
    if (status_code != ENOSUCHELEMENT) {
      response->SetErrorResponse(status_code, found_element.asString());
      return;
    }

    // Release the thread so that the browser doesn't starve.
    ::Sleep(FIND_ELEMENT_WAIT_TIME_IN_MILLISECONDS);
  } while (clock() < end);

  response->SetErrorResponse(ERROR_NO_SUCH_ELEMENT, 
      "Unable to find element with " + mechanism + " == " + value);
  return;
}
void ExecuteAsyncScriptCommandHandler::ExecuteInternal(
    const IECommandExecutor& executor,
    const ParametersMap& command_parameters,
    Response* response) {
  ParametersMap::const_iterator script_parameter_iterator = command_parameters.find("script");
  ParametersMap::const_iterator args_parameter_iterator = command_parameters.find("args");
  if (script_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT,
                               "Missing parameter: script");
    return;
  }

  if (!script_parameter_iterator->second.isString()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT,
                               "script parameter must be a string");
    return;
  }

  if (args_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT,
                               "Missing parameter: args");
    return;
  }

  if (!args_parameter_iterator->second.isArray()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT,
                               "args parameter must be an array");
    return;
  }

  std::vector<wchar_t> page_id_buffer(GUID_STRING_LEN);
  GUID page_id_guid;
  ::CoCreateGuid(&page_id_guid);
  ::StringFromGUID2(page_id_guid, &page_id_buffer[0], GUID_STRING_LEN);
  std::wstring page_id = &page_id_buffer[0];

  std::vector<wchar_t> pending_id_buffer(GUID_STRING_LEN);
  GUID pending_id_guid;
  ::CoCreateGuid(&pending_id_guid);
  ::StringFromGUID2(pending_id_guid, &pending_id_buffer[0], GUID_STRING_LEN);
  std::wstring pending_id = &pending_id_buffer[0];

  Json::Value json_args = args_parameter_iterator->second;

  unsigned long long timeout_value = executor.async_script_timeout();
  std::wstring timeout = std::to_wstring(static_cast<long long>(timeout_value));

  std::wstring script_body = StringUtilities::ToWString(script_parameter_iterator->second.asString());

  std::wstring async_script = L"(function() { return function(){\n";
  async_script += L"document.__$webdriverAsyncExecutor = {\n";
  async_script += L"  pageId: '" + page_id + L"',\n";
  async_script += L"  asyncTimeout: 0\n";
  async_script += L"};\n";
  async_script += L"var timeoutId = window.setTimeout(function() {\n";
  async_script += L"  window.setTimeout(function() {\n";
  async_script += L"    document.__$webdriverAsyncExecutor.asyncTimeout = 1;\n";
  async_script += L"  }, 0);\n";
  async_script += L"}," + timeout + L");\n";
  async_script += L"var callback = function(value) {\n";
  async_script += L"  document.__$webdriverAsyncExecutor.asyncTimeout = 0;\n";
  async_script += L"  document.__$webdriverAsyncExecutor.asyncScriptResult = value;\n";
  async_script += L"  window.clearTimeout(timeoutId);\n";
  async_script += L"};\n";
  async_script += L"var argsArray = Array.prototype.slice.call(arguments);\n";
  async_script += L"argsArray.push(callback);\n";
  async_script += L"if (document.__$webdriverAsyncExecutor.asyncScriptResult !== undefined) {\n";
  async_script += L"  delete document.__$webdriverAsyncExecutor.asyncScriptResult;\n";
  async_script += L"}\n";
  async_script += L"(function() {\n" + script_body + L"\n}).apply(null, argsArray);\n";
  async_script += L"};})();";

  std::wstring polling_script = L"(function() { return function(){\n";
  polling_script += L"var pendingId = '" + pending_id + L"';\n";
  polling_script += L"if ('__$webdriverAsyncExecutor' in document) {\n";
  polling_script += L"  if (document.__$webdriverAsyncExecutor.pageId != '" + page_id + L"') {\n";
  polling_script += L"    return {'status': 'reload', 'id': pendingId, 'value': -1};\n";
  polling_script += L"  } else if ('asyncScriptResult' in document.__$webdriverAsyncExecutor) {\n";
  polling_script += L"    var value = document.__$webdriverAsyncExecutor.asyncScriptResult;\n";
  polling_script += L"    delete document.__$webdriverAsyncExecutor.asyncScriptResult;\n";
  polling_script += L"    return {'status': 'complete', 'id': pendingId, 'value': value};\n";
  polling_script += L"  } else if (document.__$webdriverAsyncExecutor.asyncTimeout == 0) {\n";
  polling_script += L"    return {'status': 'pending', 'id': pendingId, 'value': document.__$webdriverAsyncExecutor.asyncTimeout};\n";
  polling_script += L"  } else {\n";
  polling_script += L"    return {'status': 'timeout', 'id': pendingId, 'value': document.__$webdriverAsyncExecutor.asyncTimeout};\n";
  polling_script += L"  }\n";
  polling_script += L"} else {\n";
  polling_script += L"  return {'status': 'reload', 'id': pendingId, 'value': -1};\n";
  polling_script += L"}\n";
  polling_script += L"};})();";

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

  CComPtr<IHTMLDocument2> doc;
  browser_wrapper->GetDocument(&doc);

  HWND async_executor_handle;
  Script async_script_wrapper(doc, async_script);
  async_script_wrapper.set_polling_source_code(polling_script);
  status_code = async_script_wrapper.ExecuteAsync(executor,
                                                  json_args,
                                                  &async_executor_handle);
  browser_wrapper->set_script_executor_handle(async_executor_handle);

  if (status_code != WD_SUCCESS) {
    response->SetErrorResponse(status_code, "JavaScript error");
  }
}
void ClickElementCommandHandler::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) {
      if (executor.input_manager()->enable_native_events()) {
        if (this->IsOptionElement(element_wrapper)) {
          std::string option_click_error = "";
          status_code = this->ExecuteAtom(this->GetClickAtom(),
                                          browser_wrapper,
                                          element_wrapper,
                                          &option_click_error);
          if (status_code != WD_SUCCESS) {
            response->SetErrorResponse(status_code, "Cannot click on option element. " + option_click_error);
            return;
          }
        } else {
          Json::Value move_action;
          move_action["type"] = "pointerMove";
          move_action["origin"] = element_wrapper->ConvertToJson();
          move_action["duration"] = 0;

          Json::Value down_action;
          down_action["type"] = "pointerDown";
          down_action["button"] = 0;
            
          Json::Value up_action;
          up_action["type"] = "pointerUp";
          up_action["button"] = 0;

          Json::Value action_array(Json::arrayValue);
          action_array.append(move_action);
          action_array.append(down_action);
          action_array.append(up_action);
            
          // Check to make sure we're not within the double-click time for this element
          // since the last click.
          int double_click_time = ::GetDoubleClickTime();

          Json::Value parameters_value;
          parameters_value["pointerType"] = "mouse";

          Json::Value value;
          value["type"] = "pointer";
          value["id"] = "click action mouse";
          value["parameters"] = parameters_value;
          value["actions"] = action_array;

          Json::Value actions(Json::arrayValue);
          actions.append(value);

          IECommandExecutor& mutable_executor = const_cast<IECommandExecutor&>(executor);
          status_code = mutable_executor.input_manager()->PerformInputSequence(browser_wrapper, actions);
          browser_wrapper->set_wait_required(true);
          ::Sleep(double_click_time + 10);
          if (status_code != WD_SUCCESS) {
            if (status_code == EELEMENTCLICKPOINTNOTSCROLLED) {
              // We hard-code the error code here to be "Element not visible"
              // to maintain compatibility with previous behavior.
              response->SetErrorResponse(ERROR_ELEMENT_NOT_INTERACTABLE, "The point at which the driver is attempting to click on the element was not scrolled into the viewport.");
            } else {
              response->SetErrorResponse(status_code, "Cannot click on element");
            }
            return;
          }
        }
      } else {
        bool displayed;
        status_code = element_wrapper->IsDisplayed(true, &displayed);
        if (status_code != WD_SUCCESS) {
          response->SetErrorResponse(status_code, "Unable to determine element is displayed");
          return;
        } 

        if (!displayed) {
          response->SetErrorResponse(ERROR_ELEMENT_NOT_INTERACTABLE, "Element is not displayed");
          return;
        }
        std::string synthetic_click_error = "";
        status_code = this->ExecuteAtom(this->GetSyntheticClickAtom(),
                                        browser_wrapper,
                                        element_wrapper,
                                        &synthetic_click_error);
        if (status_code != WD_SUCCESS) {
          // This is a hack. We should change this when we can get proper error
          // codes back from the atoms. We'll assume the script failed because
          // the element isn't visible.
          response->SetErrorResponse(ERROR_ELEMENT_NOT_INTERACTABLE,
              "Received a JavaScript error attempting to click on the element using synthetic events. We are assuming this is because the element isn't displayed, but it may be due to other problems with executing JavaScript.");
          return;
        }
        browser_wrapper->set_wait_required(true);
      }
    } 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);
  }
}
Example #17
0
int main(int argc, char * argv[])
{
	signal(SIGABRT, &sighandler);
	signal(SIGTERM, &sighandler);
	signal(SIGINT, &sighandler);

	ULogger::setType(ULogger::kTypeConsole);
	ULogger::setLevel(ULogger::kError);

	ParametersMap customParameters = Parameters::parseArguments(argc, argv);

	if(argc < 3)
	{
		showUsage();
	}

	bool assemble2dMap = false;
	bool assemble3dMap = false;
	bool assemble2dOctoMap = false;
	bool assemble3dOctoMap = false;
	bool useDatabaseRate = false;
	ParametersMap configParameters;
	for(int i=1; i<argc-2; ++i)
	{
		if(strcmp(argv[i], "-r") == 0 || strcmp(argv[i], "--r") == 0)
		{
			useDatabaseRate = true;
			printf("Using database stamps as input rate.\n");
		}
		else if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--c") == 0)
		{
			++i;
			if (i < argc - 2 && UFile::exists(argv[i]) && UFile::getExtension(argv[i]).compare("ini") == 0)
			{
				Parameters::readINI(argv[i], configParameters);
				printf("Using %d parameters from config file \"%s\"\n", (int)configParameters.size(), argv[i]);
			}
			else if(i < argc - 2)
			{
				printf("Config file \"%s\" is not valid or doesn't exist!\n", argv[i]);
			}
			else
			{
				printf("Config file is not set!\n");
			}
		}
		else if(strcmp(argv[i], "-g2") == 0 || strcmp(argv[i], "--g2") == 0)
		{
			assemble2dMap = true;
			printf("2D occupancy grid will be assembled (-g2 option).\n");
		}
		else if(strcmp(argv[i], "-g3") == 0 || strcmp(argv[i], "--g3") == 0)
		{
			assemble3dMap = true;
			printf("3D cloud map will be assembled (-g3 option).\n");
		}
		else if(strcmp(argv[i], "-o2") == 0 || strcmp(argv[i], "--o2") == 0)
		{
#ifdef RTABMAP_OCTOMAP
			assemble2dOctoMap = true;
			printf("OctoMap will be assembled (-o2 option).\n");
#else
			printf("RTAB-Map is not built with OctoMap support, cannot set -o2 option!\n");
#endif
		}
		else if(strcmp(argv[i], "-o3") == 0 || strcmp(argv[i], "--o3") == 0)
		{
#ifdef RTABMAP_OCTOMAP
			assemble3dOctoMap = true;
			printf("OctoMap will be assembled (-o3 option).\n");
#else
			printf("RTAB-Map is not built with OctoMap support, cannot set -o3 option!\n");
#endif
		}
	}

	std::string inputDatabasePath = uReplaceChar(argv[argc-2], '~', UDirectory::homeDir());
	std::string outputDatabasePath = uReplaceChar(argv[argc-1], '~', UDirectory::homeDir());

	std::list<std::string> databases = uSplit(inputDatabasePath, ';');
	if (databases.empty())
	{
		printf("No input database \"%s\" detected!\n", inputDatabasePath.c_str());
		return -1;
	}
	for (std::list<std::string>::iterator iter = databases.begin(); iter != databases.end(); ++iter)
	{
		if (!UFile::exists(*iter))
		{
			printf("Input database \"%s\" doesn't exist!\n", iter->c_str());
			return -1;
		}

		if (UFile::getExtension(*iter).compare("db") != 0)
		{
			printf("File \"%s\" is not a database format (*.db)!\n", iter->c_str());
			return -1;
		}
	}

	if(UFile::getExtension(outputDatabasePath).compare("db") != 0)
	{
		printf("File \"%s\" is not a database format (*.db)!\n", outputDatabasePath.c_str());
		return -1;
	}

	if(UFile::exists(outputDatabasePath))
	{
		UFile::erase(outputDatabasePath);
	}

	// Get parameters of the first database
	DBDriver * dbDriver = DBDriver::create();
	if(!dbDriver->openConnection(databases.front(), false))
	{
		printf("Failed opening input database!\n");
		delete dbDriver;
		return -1;
	}

	ParametersMap parameters = dbDriver->getLastParameters();
	if(parameters.empty())
	{
		printf("WARNING: Failed getting parameters from database, reprocessing will be done with default parameters! Database version may be too old (%s).\n", dbDriver->getDatabaseVersion().c_str());
	}
	if(customParameters.size())
	{
		printf("Custom parameters:\n");
		for(ParametersMap::iterator iter=customParameters.begin(); iter!=customParameters.end(); ++iter)
		{
			printf("  %s\t= %s\n", iter->first.c_str(), iter->second.c_str());
		}
	}
	uInsert(parameters, configParameters);
	uInsert(parameters, customParameters);

	bool incrementalMemory = Parameters::defaultMemIncrementalMemory();
	Parameters::parse(parameters, Parameters::kMemIncrementalMemory(), incrementalMemory);

	int totalIds = 0;
	std::set<int> ids;
	dbDriver->getAllNodeIds(ids);
	if(ids.empty())
	{
		printf("Input database doesn't have any nodes saved in it.\n");
		dbDriver->closeConnection(false);
		delete dbDriver;
		return -1;
	}
	if(!(!incrementalMemory && databases.size() > 1))
	{
		totalIds = ids.size();
	}
	dbDriver->closeConnection(false);

	// Count remaining ids in the other databases
	for (std::list<std::string>::iterator iter = ++databases.begin(); iter != databases.end(); ++iter)
	{
		if (!dbDriver->openConnection(*iter, false))
		{
			printf("Failed opening input database!\n");
			delete dbDriver;
			return -1;
		}
		ids.clear();
		dbDriver->getAllNodeIds(ids);
		totalIds += ids.size();
		dbDriver->closeConnection(false);
	}
	delete dbDriver;
	dbDriver = 0;

	std::string workingDirectory = UDirectory::getDir(outputDatabasePath);
	printf("Set working directory to \"%s\".\n", workingDirectory.c_str());
	uInsert(parameters, ParametersPair(Parameters::kRtabmapWorkingDirectory(), workingDirectory));
	uInsert(parameters, ParametersPair(Parameters::kRtabmapPublishStats(), "true")); // to log status below

	if(!incrementalMemory && databases.size() > 1)
	{
		UFile::copy(databases.front(), outputDatabasePath);
		printf("Parameter \"%s\" is set to false, initializing RTAB-Map with \"%s\" for localization...\n", Parameters::kMemIncrementalMemory().c_str(), databases.front().c_str());
		databases.pop_front();
		inputDatabasePath = uJoin(databases, ";");
	}

	Rtabmap rtabmap;
	rtabmap.init(parameters, outputDatabasePath);

	bool rgbdEnabled = Parameters::defaultRGBDEnabled();
	Parameters::parse(parameters, Parameters::kRGBDEnabled(), rgbdEnabled);
	bool odometryIgnored = !rgbdEnabled;
	DBReader dbReader(inputDatabasePath, useDatabaseRate?-1:0, odometryIgnored);
	dbReader.init();

	OccupancyGrid grid(parameters);
	grid.setCloudAssembling(assemble3dMap);
#ifdef RTABMAP_OCTOMAP
	OctoMap octomap(parameters);
#endif

	printf("Reprocessing data of \"%s\"...\n", inputDatabasePath.c_str());
	std::map<std::string, float> globalMapStats;
	int processed = 0;
	CameraInfo info;
	SensorData data = dbReader.takeImage(&info);
	Transform lastLocalizationPose = info.odomPose;
	while(data.isValid() && g_loopForever)
	{
		UTimer iterationTime;
		std::string status;
		if(!odometryIgnored && info.odomPose.isNull())
		{
			printf("Skipping node %d as it doesn't have odometry pose set.\n", data.id());
		}
		else
		{
			if(!odometryIgnored && !info.odomCovariance.empty() && info.odomCovariance.at<double>(0,0)>=9999)
			{
				printf("High variance detected, triggering a new map...\n");
				if(!incrementalMemory && processed>0)
				{
					showLocalizationStats();
					lastLocalizationPose = info.odomPose;
				}
				if(incrementalMemory)
				{
					rtabmap.triggerNewMap();
				}
			}
			UTimer t;
			if(!rtabmap.process(data, info.odomPose, info.odomCovariance, info.odomVelocity, globalMapStats))
			{
				printf("Failed processing node %d.\n", data.id());
				globalMapStats.clear();
			}
			else if(assemble2dMap || assemble3dMap || assemble2dOctoMap || assemble3dOctoMap)
			{
				globalMapStats.clear();
				double timeRtabmap = t.ticks();
				double timeUpdateInit = 0.0;
				double timeUpdateGrid = 0.0;
#ifdef RTABMAP_OCTOMAP
				double timeUpdateOctoMap = 0.0;
#endif
				const rtabmap::Statistics & stats = rtabmap.getStatistics();
				if(stats.poses().size() && stats.getLastSignatureData().id())
				{
					int id = stats.poses().rbegin()->first;
					if(id == stats.getLastSignatureData().id() &&
					   stats.getLastSignatureData().sensorData().gridCellSize() > 0.0f)
					{
						bool updateGridMap = false;
						bool updateOctoMap = false;
						if((assemble2dMap || assemble3dMap) && grid.addedNodes().find(id) == grid.addedNodes().end())
						{
							updateGridMap = true;
						}
#ifdef RTABMAP_OCTOMAP
						if((assemble2dOctoMap || assemble3dOctoMap) && octomap.addedNodes().find(id) == octomap.addedNodes().end())
						{
							updateOctoMap = true;
						}
#endif
						if(updateGridMap || updateOctoMap)
						{
							cv::Mat ground, obstacles, empty;
							stats.getLastSignatureData().sensorData().uncompressDataConst(0, 0, 0, 0, &ground, &obstacles, &empty);

							timeUpdateInit = t.ticks();

							if(updateGridMap)
							{
								grid.addToCache(id, ground, obstacles, empty);
								grid.update(stats.poses());
								timeUpdateGrid = t.ticks() + timeUpdateInit;
							}
#ifdef RTABMAP_OCTOMAP
							if(updateOctoMap)
							{
								const cv::Point3f & viewpoint = stats.getLastSignatureData().sensorData().gridViewPoint();
								octomap.addToCache(id, ground, obstacles, empty, viewpoint);
								octomap.update(stats.poses());
								timeUpdateOctoMap = t.ticks() + timeUpdateInit;
							}
#endif
						}
					}
				}

				globalMapStats.insert(std::make_pair(std::string("GlobalGrid/GridUpdate/ms"), timeUpdateGrid*1000.0f));
#ifdef RTABMAP_OCTOMAP
				//Simulate publishing
				double timePub2dOctoMap = 0.0;
				double timePub3dOctoMap = 0.0;
				if(assemble2dOctoMap)
				{
					float xMin, yMin, size;
					octomap.createProjectionMap(xMin, yMin, size);
					timePub2dOctoMap = t.ticks();
				}
				if(assemble3dOctoMap)
				{
					octomap.createCloud();
					timePub3dOctoMap = t.ticks();
				}

				globalMapStats.insert(std::make_pair(std::string("GlobalGrid/OctoMapUpdate/ms"), timeUpdateOctoMap*1000.0f));
				globalMapStats.insert(std::make_pair(std::string("GlobalGrid/OctoMapProjection/ms"), timePub2dOctoMap*1000.0f));
				globalMapStats.insert(std::make_pair(std::string("GlobalGrid/OctomapToCloud/ms"), timePub3dOctoMap*1000.0f));
				globalMapStats.insert(std::make_pair(std::string("GlobalGrid/TotalWithRtabmap/ms"), (timeUpdateGrid+timeUpdateOctoMap+timePub2dOctoMap+timePub3dOctoMap+timeRtabmap)*1000.0f));
#else
				globalMapStats.insert(std::make_pair(std::string("GlobalGrid/TotalWithRtabmap/ms"), (timeUpdateGrid+timeRtabmap)*1000.0f));
#endif
			}
		}

		const rtabmap::Statistics & stats = rtabmap.getStatistics();
		int loopId = stats.loopClosureId() > 0? stats.loopClosureId(): stats.proximityDetectionId() > 0?stats.proximityDetectionId() :0;
		int landmarkId = (int)uValue(stats.data(), rtabmap::Statistics::kLoopLandmark_detected(), 0.0f);
		int refMapId = stats.refImageMapId();
		++totalFrames;
		if (loopId>0)
		{
			++loopCount;
			int loopMapId = stats.loopClosureId() > 0? stats.loopClosureMapId(): stats.proximityDetectionMapId();
			printf("Processed %d/%d nodes [%d]... %dms Loop on %d [%d]\n", ++processed, totalIds, refMapId, int(iterationTime.ticks() * 1000), loopId, loopMapId);
		}
		else if(landmarkId != 0)
		{
			printf("Processed %d/%d nodes [%d]... %dms Loop on landmark %d\n", ++processed, totalIds, refMapId, int(iterationTime.ticks() * 1000), landmarkId);
		}
		else
		{
			printf("Processed %d/%d nodes [%d]... %dms\n", ++processed, totalIds, refMapId, int(iterationTime.ticks() * 1000));
		}

		// Here we accumulate statistics about distance from last localization
		if(!incrementalMemory &&
		   !lastLocalizationPose.isNull() &&
		   !info.odomPose.isNull())
		{
			if(loopId>0 || landmarkId != 0)
			{
				previousLocalizationDistances.push_back(lastLocalizationPose.getDistance(info.odomPose));
				lastLocalizationPose = info.odomPose;
			}
		}
		if(!incrementalMemory)
		{
			float totalTime = uValue(stats.data(), rtabmap::Statistics::kTimingTotal(), 0.0f);
			localizationTime.push_back(totalTime);
			if(loopId>0)
			{
				localizationDistances.push_back(stats.loopClosureTransform().getNorm());
			}
		}

		Transform odomPose = info.odomPose;
		data = dbReader.takeImage(&info);

		if(!incrementalMemory &&
		   !odomPose.isNull() &&
		   !info.odomPose.isNull())
		{
			odomDistances.push_back(odomPose.getDistance(info.odomPose));
		}
	}

	if(!incrementalMemory)
	{
		showLocalizationStats();
	}
	else
	{
		printf("Total loop closures = %d\n", loopCount);
	}

	printf("Closing database \"%s\"...\n", outputDatabasePath.c_str());
	rtabmap.close(true);
	printf("Closing database \"%s\"... done!\n", outputDatabasePath.c_str());

	if(assemble2dMap)
	{
		std::string outputPath = outputDatabasePath.substr(0, outputDatabasePath.size()-3) + "_map.pgm";
		float xMin,yMin;
		cv::Mat map = grid.getMap(xMin, yMin);
		if(!map.empty())
		{
			cv::Mat map8U(map.rows, map.cols, CV_8U);
			//convert to gray scaled map
			for (int i = 0; i < map.rows; ++i)
			{
				for (int j = 0; j < map.cols; ++j)
				{
					char v = map.at<char>(i, j);
					unsigned char gray;
					if(v == 0)
					{
						gray = 178;
					}
					else if(v == 100)
					{
						gray = 0;
					}
					else // -1
					{
						gray = 89;
					}
					map8U.at<unsigned char>(i, j) = gray;
				}
			}
			if(cv::imwrite(outputPath, map8U))
			{
				printf("Saving occupancy grid \"%s\"... done!\n", outputPath.c_str());
			}
			else
			{
				printf("Saving occupancy grid \"%s\"... failed!\n", outputPath.c_str());
			}
		}
		else
		{
			printf("2D map is empty! Cannot save it!\n");
		}
	}
	if(assemble3dMap)
	{
		std::string outputPath = outputDatabasePath.substr(0, outputDatabasePath.size()-3) + "_obstacles.pcd";
		if(pcl::io::savePCDFileBinary(outputPath, *grid.getMapObstacles()) == 0)
		{
			printf("Saving 3d obstacles \"%s\"... done!\n", outputPath.c_str());
		}
		else
		{
			printf("Saving 3d obstacles \"%s\"... failed!\n", outputPath.c_str());
		}
		if(grid.getMapGround()->size())
		{
			outputPath = outputDatabasePath.substr(0, outputDatabasePath.size()-3) + "_ground.pcd";
			if(pcl::io::savePCDFileBinary(outputPath, *grid.getMapGround()) == 0)
			{
				printf("Saving 3d ground \"%s\"... done!\n", outputPath.c_str());
			}
			else
			{
				printf("Saving 3d ground \"%s\"... failed!\n", outputPath.c_str());
			}
		}
		if(grid.getMapEmptyCells()->size())
		{
			outputPath = outputDatabasePath.substr(0, outputDatabasePath.size()-3) + "_empty.pcd";
			if(pcl::io::savePCDFileBinary(outputPath, *grid.getMapEmptyCells()) == 0)
			{
				printf("Saving 3d empty cells \"%s\"... done!\n", outputPath.c_str());
			}
			else
			{
				printf("Saving 3d empty cells \"%s\"... failed!\n", outputPath.c_str());
			}
		}
	}
#ifdef RTABMAP_OCTOMAP
	if(assemble2dOctoMap)
	{
		std::string outputPath = outputDatabasePath.substr(0, outputDatabasePath.size()-3) + "_octomap.pgm";
		float xMin,yMin,cellSize;
		cv::Mat map = octomap.createProjectionMap(xMin, yMin, cellSize);
		if(!map.empty())
		{
			cv::Mat map8U(map.rows, map.cols, CV_8U);
			//convert to gray scaled map
			for (int i = 0; i < map.rows; ++i)
			{
				for (int j = 0; j < map.cols; ++j)
				{
					char v = map.at<char>(i, j);
					unsigned char gray;
					if(v == 0)
					{
						gray = 178;
					}
					else if(v == 100)
					{
						gray = 0;
					}
					else // -1
					{
						gray = 89;
					}
					map8U.at<unsigned char>(i, j) = gray;
				}
			}
			if(cv::imwrite(outputPath, map8U))
			{
				printf("Saving octomap 2D projection \"%s\"... done!\n", outputPath.c_str());
			}
			else
			{
				printf("Saving octomap 2D projection \"%s\"... failed!\n", outputPath.c_str());
			}
		}
		else
		{
			printf("OctoMap 2D projection map is empty! Cannot save it!\n");
		}
	}
	if(assemble3dOctoMap)
	{
		std::string outputPath = outputDatabasePath.substr(0, outputDatabasePath.size()-3) + "_octomap_occupied.pcd";
		std::vector<int> obstacles, emptySpace, ground;
		pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud = octomap.createCloud(0, &obstacles, &emptySpace, &ground);
		if(pcl::io::savePCDFile(outputPath, *cloud, obstacles, true) == 0)
		{
			printf("Saving obstacles cloud \"%s\"... done!\n", outputPath.c_str());
		}
		else
		{
			printf("Saving obstacles cloud \"%s\"... failed!\n", outputPath.c_str());
		}
		if(ground.size())
		{
			outputPath = outputDatabasePath.substr(0, outputDatabasePath.size()-3) + "_octomap_ground.pcd";
			if(pcl::io::savePCDFile(outputPath, *cloud, ground, true) == 0)
			{
				printf("Saving empty space cloud \"%s\"... done!\n", outputPath.c_str());
			}
			else
			{
				printf("Saving empty space cloud \"%s\"... failed!\n", outputPath.c_str());
			}
		}
		if(emptySpace.size())
		{
			outputPath = outputDatabasePath.substr(0, outputDatabasePath.size()-3) + "_octomap_empty.pcd";
			if(pcl::io::savePCDFile(outputPath, *cloud, emptySpace, true) == 0)
			{
				printf("Saving empty space cloud \"%s\"... done!\n", outputPath.c_str());
			}
			else
			{
				printf("Saving empty space cloud \"%s\"... failed!\n", outputPath.c_str());
			}
		}
	}
#endif

	return 0;
}
Example #18
0
int main(int argc, char * argv[])
{
	signal(SIGABRT, &sighandler);
	signal(SIGTERM, &sighandler);
	signal(SIGINT, &sighandler);

	/*for(int i=0; i<argc; i++)
	{
		printf("argv[%d] = %s\n", i, argv[i]);
	}*/
	const ParametersMap & defaultParameters = Parameters::getDefaultParameters();
	if(argc < 2)
	{
		showUsage();
	}
	else if(argc == 2 && strcmp(argv[1], "-v") == 0)
	{
		printf("%s\n", Rtabmap::getVersion().c_str());
		exit(0);
	}
	else if(argc == 2 && strcmp(argv[1], "-default_params") == 0)
	{
		for(ParametersMap::const_iterator iter = defaultParameters.begin(); iter!=defaultParameters.end(); ++iter)
		{
			printf("%s=%s\n", iter->first.c_str(), iter->second.c_str());
		}
		exit(0);
	}
	printf("\n");

	std::string path;
	float timeThreshold = 0.0;
	float rate = 0.0;
	int loopDataset = 0;
	int repeat = 0;
	bool createGT = false;
	int imageWidth = 0;
	int imageHeight = 0;
	int startAt = 1;
	ParametersMap pm;
	ULogger::Level logLevel = ULogger::kError;
	ULogger::Level exitLevel = ULogger::kFatal;

	for(int i=1; i<argc; ++i)
	{
		if(i == argc-1)
		{
			// The last must be the path
			path = argv[i];
			if(!UDirectory::exists(path.c_str()) && !UFile::exists(path.c_str()))
			{
				printf("Path not valid : %s\n", path.c_str());
				showUsage();
				exit(1);
			}
			break;
		}
		if(strcmp(argv[i], "-t") == 0)
		{
			++i;
			if(i < argc)
			{
				timeThreshold = std::atof(argv[i]);
				if(timeThreshold < 0)
				{
					showUsage();
				}
			}
			else
			{
				showUsage();
			}
			continue;
		}
		if(strcmp(argv[i], "-rate") == 0)
		{
			++i;
			if(i < argc)
			{
				rate = std::atof(argv[i]);
				if(rate < 0)
				{
					showUsage();
				}
			}
			else
			{
				showUsage();
			}
			continue;
		}
		if(strcmp(argv[i], "-rateHz") == 0)
		{
			++i;
			if(i < argc)
			{
				rate = std::atof(argv[i]);
				if(rate < 0)
				{
					showUsage();
				}
				else if(rate)
				{
					rate = 1/rate;
				}
			}
			else
			{
				showUsage();
			}
			continue;
		}
		if(strcmp(argv[i], "-repeat") == 0)
		{
			++i;
			if(i < argc)
			{
				repeat = std::atoi(argv[i]);
				if(repeat < 1)
				{
					showUsage();
				}
			}
			else
			{
				showUsage();
			}
			continue;
		}
		if(strcmp(argv[i], "-image_width") == 0)
		{
			++i;
			if(i < argc)
			{
				imageWidth = std::atoi(argv[i]);
				if(imageWidth < 0)
				{
					showUsage();
				}
			}
			else
			{
				showUsage();
			}
			continue;
		}
		if(strcmp(argv[i], "-image_height") == 0)
		{
			++i;
			if(i < argc)
			{
				imageHeight = std::atoi(argv[i]);
				if(imageHeight < 0)
				{
					showUsage();
				}
			}
			else
			{
				showUsage();
			}
			continue;
		}
		if(strcmp(argv[i], "-start_at") == 0)
		{
			++i;
			if(i < argc)
			{
				startAt = std::atoi(argv[i]);
				if(startAt < 0)
				{
					showUsage();
				}
			}
			else
			{
				showUsage();
			}
			continue;
		}
		if(strcmp(argv[i], "-createGT") == 0)
		{
			createGT = true;
			continue;
		}
		if(strcmp(argv[i], "-debug") == 0)
		{
			logLevel = ULogger::kDebug;
			continue;
		}
		if(strcmp(argv[i], "-info") == 0)
		{
			logLevel = ULogger::kInfo;
			continue;
		}
		if(strcmp(argv[i], "-warn") == 0)
		{
			logLevel = ULogger::kWarning;
			continue;
		}
		if(strcmp(argv[i], "-exit_warn") == 0)
		{
			exitLevel = ULogger::kWarning;
			continue;
		}
		if(strcmp(argv[i], "-exit_error") == 0)
		{
			exitLevel = ULogger::kError;
			continue;
		}

		// Check for RTAB-Map's parameters
		std::string key = argv[i];
		key = uSplit(key, '-').back();
		if(defaultParameters.find(key) != defaultParameters.end())
		{
			++i;
			if(i < argc)
			{
				std::string value = argv[i];
				if(value.empty())
				{
					showUsage();
				}
				else
				{
					value = uReplaceChar(value, ',', ' ');
				}
				std::pair<ParametersMap::iterator, bool> inserted = pm.insert(ParametersPair(key, value));
				if(inserted.second == false)
				{
					inserted.first->second = value;
				}
			}
			else
			{
				showUsage();
			}
			continue;
		}

		printf("Unrecognized option : %s\n", argv[i]);
		showUsage();
	}

	if(repeat && createGT)
	{
		printf("Cannot create a Ground truth if repeat is on.\n");
		showUsage();
	}
	else if((imageWidth && imageHeight == 0) ||
			(imageHeight && imageWidth == 0))
	{
		printf("If imageWidth is set, imageHeight must be too.\n");
		showUsage();
	}

	UTimer timer;
	timer.start();
	std::queue<double> iterationMeanTime;

	Camera * camera = 0;
	if(UDirectory::exists(path))
	{
		camera = new CameraImages(path, startAt, false, 1/rate, imageWidth, imageHeight);
	}
	else
	{
		camera = new CameraVideo(path, 1/rate, imageWidth, imageHeight);
	}

	if(!camera || !camera->init())
	{
		printf("Camera init failed, using path \"%s\"\n", path.c_str());
		exit(1);
	}

	std::map<int, int> groundTruth;

	ULogger::setType(ULogger::kTypeConsole);
	//ULogger::setType(ULogger::kTypeFile, rtabmap.getWorkingDir()+"/LogConsole.txt", false);
	//ULogger::setBuffered(true);
	ULogger::setLevel(logLevel);
	ULogger::setExitLevel(exitLevel);

	// Create tasks : memory is deleted
	Rtabmap rtabmap;
	// Disable statistics (we don't need them)
	pm.insert(ParametersPair(Parameters::kRtabmapPublishStats(), "false"));
	// use default working directory
	pm.insert(ParametersPair(Parameters::kRtabmapWorkingDirectory(), Parameters::defaultRtabmapWorkingDirectory()));
	pm.insert(ParametersPair(Parameters::kRGBDEnabled(), "false"));

	rtabmap.init(pm);
	rtabmap.setTimeThreshold(timeThreshold); // in ms

	printf("Avpd init time = %fs\n", timer.ticks());

	// Start thread's task
	int loopClosureId;
	int count = 0;
	int countLoopDetected=0;

	printf("\nParameters : \n");
	printf(" Data set : %s\n", path.c_str());
	printf(" Time threshold = %1.2f ms\n", timeThreshold);
	printf(" Image rate = %1.2f s (%1.2f Hz)\n", rate, 1/rate);
	printf(" Repeating data set = %s\n", repeat?"true":"false");
	printf(" Camera width=%d, height=%d (0 is default)\n", imageWidth, imageHeight);
	printf(" Camera starts at image %d (default 1)\n", startAt);
	if(createGT)
	{
		printf(" Creating the ground truth matrix.\n");
	}
	printf(" INFO: All other parameters are set to defaults\n");
	if(pm.size()>1)
	{
		printf("   Overwritten parameters :\n");
		for(ParametersMap::iterator iter = pm.begin(); iter!=pm.end(); ++iter)
		{
			printf("    %s=%s\n",iter->first.c_str(), iter->second.c_str());
		}
	}
	if(rtabmap.getWM().size() || rtabmap.getSTM().size())
	{
		printf("[Warning] RTAB-Map database is not empty (%s)\n", (rtabmap.getWorkingDir()+Parameters::getDefaultDatabaseName()).c_str());
	}
	printf("\nProcessing images...\n");

	UTimer iterationTimer;
	UTimer rtabmapTimer;
	int imagesProcessed = 0;
	std::list<std::vector<float> > teleopActions;
	while(loopDataset <= repeat && g_forever)
	{
		cv::Mat img = camera->takeImage();
		int i=0;
		double maxIterationTime = 0.0;
		int maxIterationTimeId = 0;
		while(!img.empty() && g_forever)
		{
			++imagesProcessed;
			iterationTimer.start();
			rtabmapTimer.start();
			rtabmap.process(img);
			double rtabmapTime = rtabmapTimer.elapsed();
			loopClosureId = rtabmap.getLoopClosureId();
			if(rtabmap.getLoopClosureId())
			{
				++countLoopDetected;
			}
			img = camera->takeImage();
			if(++count % 100 == 0)
			{
				printf(" count = %d, loop closures = %d, max time (at %d) = %fs\n",
						count, countLoopDetected, maxIterationTimeId, maxIterationTime);
				maxIterationTime = 0.0;
				maxIterationTimeId = 0;
				std::map<int, int> wm = rtabmap.getWeights();
				printf(" WM(%d)=[", (int)wm.size());
				for(std::map<int, int>::iterator iter=wm.begin(); iter!=wm.end();++iter)
				{
					if(iter != wm.begin())
					{
						printf(";");
					}
					printf("%d,%d", iter->first, iter->second);
				}
				printf("]\n");
			}

			// Update generated ground truth matrix
			if(createGT)
			{
				if(loopClosureId > 0)
				{
					groundTruth.insert(std::make_pair(i, loopClosureId-1));
				}
			}

			++i;

			double iterationTime = iterationTimer.ticks();

			if(rtabmapTime > maxIterationTime)
			{
				maxIterationTime = rtabmapTime;
				maxIterationTimeId = count;
			}

			ULogger::flush();

			if(rtabmap.getLoopClosureId())
			{
				printf(" iteration(%d) loop(%d) hyp(%.2f) time=%fs/%fs *\n",
						count, rtabmap.getLoopClosureId(), rtabmap.getLcHypValue(), rtabmapTime, iterationTime);
			}
			else if(rtabmap.getRetrievedId())
			{
				printf(" iteration(%d) high(%d) hyp(%.2f) time=%fs/%fs\n",
						count, rtabmap.getRetrievedId(), rtabmap.getLcHypValue(), rtabmapTime, iterationTime);
			}
			else
			{
				printf(" iteration(%d) time=%fs/%fs\n", count, rtabmapTime, iterationTime);
			}

			if(timeThreshold && rtabmapTime > timeThreshold*100.0f)
			{
				printf(" ERROR,  there is  problem, too much time taken... %fs", rtabmapTime);
				break; // there is  problem, don't continue
			}
		}
		++loopDataset;
		if(loopDataset <= repeat)
		{
			camera->init();
			printf(" Beginning loop %d...\n", loopDataset);
		}
	}
	printf("Processing images completed. Loop closures found = %d\n", countLoopDetected);
	printf(" Total time = %fs\n", timer.ticks());

	if(imagesProcessed && createGT)
	{
		cv::Mat groundTruthMat = cv::Mat::zeros(imagesProcessed, imagesProcessed, CV_8U);

		for(std::map<int, int>::iterator iter = groundTruth.begin(); iter!=groundTruth.end(); ++iter)
		{
			groundTruthMat.at<unsigned char>(iter->first, iter->second) = 255;
		}

		// Generate the ground truth file
		printf("Generate ground truth to file %s, size of %d\n", (rtabmap.getWorkingDir()+GENERATED_GT_NAME).c_str(), groundTruthMat.rows);
		IplImage img = groundTruthMat;
		cvSaveImage((rtabmap.getWorkingDir()+GENERATED_GT_NAME).c_str(), &img);
		printf(" Creating ground truth file = %fs\n", timer.ticks());
	}

	if(camera)
	{
		delete camera;
		camera = 0 ;
	}

	rtabmap.close();

	printf(" Cleanup time = %fs\n", timer.ticks());

	return 0;
}
void SetWindowRectCommandHandler::ExecuteInternal(
    const IECommandExecutor& executor,
    const ParametersMap& command_parameters,
    Response* response) {
  int width = -1;
  int height = -1;
  int x = -1;
  int y = -1;

  ParametersMap::const_iterator width_parameter_iterator = command_parameters.find("width");
  ParametersMap::const_iterator height_parameter_iterator = command_parameters.find("height");
  ParametersMap::const_iterator x_parameter_iterator = command_parameters.find("x");
  ParametersMap::const_iterator y_parameter_iterator = command_parameters.find("y");
  
  if (width_parameter_iterator != command_parameters.end()) {
    width = width_parameter_iterator->second.asInt();
  }
  
  if (height_parameter_iterator != command_parameters.end()) {
    height = height_parameter_iterator->second.asInt();
  }
  
  if (x_parameter_iterator != command_parameters.end()) {
    x = x_parameter_iterator->second.asInt();
  }
  
  if (y_parameter_iterator != command_parameters.end()) {
    y = y_parameter_iterator->second.asInt();
  } 
  
  int status_code = WD_SUCCESS;

  BrowserHandle browser_wrapper;
  status_code = executor.GetCurrentBrowser(&browser_wrapper);
  if (status_code != WD_SUCCESS) {
    response->SetErrorResponse(ERROR_NO_SUCH_WINDOW, "Error retrieving current window");
    return;
  }

  // If the window is maximized, the window needs to be restored.
  HWND window_handle = browser_wrapper->GetTopLevelWindowHandle();
  if (::IsZoomed(window_handle) || ::IsIconic(window_handle)) {
    ::ShowWindow(window_handle, SW_RESTORE);
  }

  if (x >= 0 && y >= 0) {
    BOOL set_window_pos_result = ::SetWindowPos(window_handle, NULL, x, y, 0, 0, SWP_NOSIZE);
    if (!set_window_pos_result) {
      response->SetErrorResponse(ERROR_UNKNOWN_ERROR,
                                "Unexpected error setting window size (SetWindowPos API failed)");
      return;
    }
  }

  if (width >= 0 && height >= 0) {
    BOOL set_window_size_result = ::SetWindowPos(window_handle, NULL, 0, 0, width, height, SWP_NOMOVE);
    if (!set_window_size_result) {
      response->SetErrorResponse(ERROR_UNKNOWN_ERROR,
                                 "Unexpected error setting window size (SetWindowPos API failed)");
      return;
    }
  }

  Json::Value returned_rect;
  returned_rect["x"] = x;
  returned_rect["y"] = y;
  returned_rect["width"] = width;
  returned_rect["height"] = height;
  response->SetSuccessResponse(returned_rect);
}
void FindChildElementsCommandHandler::ExecuteInternal(
    const IECommandExecutor& executor,
    const ParametersMap& command_parameters,
    Response* response) {
  ParametersMap::const_iterator id_parameter_iterator = command_parameters.find("id");
  ParametersMap::const_iterator using_parameter_iterator = command_parameters.find("using");
  ParametersMap::const_iterator value_parameter_iterator = command_parameters.find("value");
  if (id_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "Missing parameter in URL: id");
    return;
  }
  if (using_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "Missing parameter: using");
    return;
  }
  if (!using_parameter_iterator->second.isString()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "using parameter must be a string");
    return;
  }
  if (value_parameter_iterator == command_parameters.end()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "Missing parameter: value");
    return;
  }
  if (!value_parameter_iterator->second.isString()) {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "value parameter must be a string");
    return;
  }

  std::string mechanism = using_parameter_iterator->second.asString();
  std::string value = value_parameter_iterator->second.asString();
  std::string element_id = id_parameter_iterator->second.asString();

  if (mechanism != "css selector" &&
      mechanism != "tag name" &&
      mechanism != "link text" &&
      mechanism != "partial link text" &&
      mechanism != "xpath") {
    response->SetErrorResponse(ERROR_INVALID_ARGUMENT, "using parameter value '" + mechanism + "' is not a valid value");
    return;
  }

  BrowserHandle browser_wrapper;
  int status_code = executor.GetCurrentBrowser(&browser_wrapper);
  if (status_code != WD_SUCCESS) {
    response->SetErrorResponse(status_code, "Currently focused window has been closed.");
    return;
  }

  ElementHandle parent_element_wrapper;
  status_code = this->GetElement(executor,
                                 element_id,
                                 &parent_element_wrapper);

  if (status_code == WD_SUCCESS) {
    Json::Value found_elements(Json::arrayValue);

    int timeout = static_cast<int>(executor.implicit_wait_timeout());
    clock_t end = clock() + (timeout / 1000 * CLOCKS_PER_SEC);
    if (timeout > 0 && timeout < 1000) {
      end += 1 * CLOCKS_PER_SEC;
    }

    do {
      status_code = executor.LocateElements(parent_element_wrapper,
                                            mechanism,
                                            value,
                                            &found_elements);
      if (status_code == WD_SUCCESS) {
        if (found_elements.isArray() && found_elements.size() > 0) {
          response->SetSuccessResponse(found_elements);
          return;
        }
      } else if (status_code == ENOSUCHWINDOW) {
        response->SetErrorResponse(ERROR_NO_SUCH_WINDOW, 
                                   "Unable to find elements on closed window");
        return;
      } else {
        response->SetErrorResponse(status_code, found_elements.asString());
        return;
      }

      // Release the thread so that the browser doesn't starve.
      ::Sleep(FIND_ELEMENT_WAIT_TIME_IN_MILLISECONDS);
    } while (clock() < end);

    // This code is executed when no elements where found and no errors occurred.
    if (status_code == WD_SUCCESS) {
      response->SetSuccessResponse(found_elements);
    } else {
      response->SetErrorResponse(status_code, 
          "Finding elements with " + mechanism + " == " + value +
          "returned an unexpected error");
    }
  } else {
    if (status_code == EOBSOLETEELEMENT) {
      response->SetErrorResponse(ERROR_STALE_ELEMENT_REFERENCE,
                                 "Specified parent element is no longer attached to the DOM");
    } else {
      response->SetErrorResponse(ERROR_INVALID_ARGUMENT,
                                 "Element is no longer valid");
    }
  }
}