<commit_before>/******************************************************************************\
* File:          lexers.cpp
* Purpose:       Implementation of wxExLexers classes
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 2008-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/config.h>
#include <wx/tokenzr.h>
#include <wx/stc/stc.h>
#include <wx/textfile.h>
#include <wx/extension/lexers.h>
#include <wx/extension/util.h> // for wxExMatchesOneOf

wxExLexers::wxExLexers(const wxFileName& filename)
  : m_FileName(filename)
{
}

const wxString wxExLexers::BuildWildCards(const wxFileName& filename) const
{
  const wxString allfiles_wildcard =
    _("All Files") + wxString::Format(" (%s)|%s",
      wxFileSelectorDefaultWildcardStr,
      wxFileSelectorDefaultWildcardStr);

  wxString wildcards = allfiles_wildcard;

  // Build the wildcard string using all available lexers.
  for (
    std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
    it != m_Lexers.end();
    ++it)
  {
    if (!it->GetAssociations().empty())
    {
      const wxString wildcard =
        it->GetScintillaLexer() +
        " (" + it->GetAssociations() + ") |" +
        it->GetAssociations();

      if (wxExMatchesOneOf(filename, it->GetAssociations()))
      {
        wildcards = wildcard + "|" + wildcards;
      }
      else
      {
        wildcards = wildcards + "|" + wildcard;
      }
    }
  }

  return wildcards;
}

const wxExLexer wxExLexers::FindByFileName(const wxFileName& filename) const
{
  if (!filename.IsOk())
  {
    return wxExLexer();
  }

  for (
    std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
    it != m_Lexers.end();
    ++it)
  {
    if (wxExMatchesOneOf(filename, it->GetAssociations()))
    {
      return *it;
    }
  }

  return wxExLexer();
}

const wxExLexer wxExLexers::FindByName(
  const wxString& name,
  bool fail_if_not_found) const
{
  for (
    std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
    it != m_Lexers.end();
    ++it)
  {
    if (name == it->GetScintillaLexer())
    {
      return *it;
    }
  }

  if (!m_Lexers.empty() && fail_if_not_found)
  {
    wxFAIL;
  }

  return wxExLexer();
}

const wxExLexer wxExLexers::FindByText(const wxString& text) const
{
  // Add automatic lexers if text starts with some special tokens.
  const wxString text_lowercase = text.Lower();

  if (text_lowercase.StartsWith("#") ||
      // .po files that do not have comment headers, start with msgid, so set them
      text_lowercase.StartsWith("msgid"))
  {
    return FindByName("bash", false); // don't show error
  }
  else if (text_lowercase.StartsWith("<html>") ||
           text_lowercase.StartsWith("<?php"))
  {
    return FindByName("hypertext", false); // don't show error
  }
  else if (text_lowercase.StartsWith("<?xml"))
  {
    return FindByName("xml", false); // don't show error
  }
  // cpp files like #include <map> really do not have a .h extension (e.g. /usr/include/c++/3.3.5/map)
  // so add here.
  else if (text_lowercase.StartsWith("//"))
  {
    return FindByName("cpp", false); // don't show error
  }

  return wxExLexer();
}

const wxString wxExLexers::GetLexerAssociations() const
{
  wxString text;

  for (
    std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
    it != m_Lexers.end();
    ++it)
  {
    if (!it->GetAssociations().empty())
    {
      if (!text.empty())
      {
        text += ",";
      }

      text += it->GetAssociations();
    }
  }

  return text;
}

const wxString wxExLexers::ParseTagColourings(const wxXmlNode* node) const
{
  wxString text;

  wxXmlNode* child = node->GetChildren();

  while (child)
  {
    if (child->GetName() == "colouring")
    {
      text +=
        child->GetAttribute("no", "0") + "=" +
        child->GetNodeContent().Strip(wxString::both) + wxTextFile::GetEOL();
    }
    else if (child->GetName() == "comment")
    {
      // Ignore comments.
    }
    else
    {
      wxLogError("Undefined colourings tag: %s on: %d",
        child->GetName().c_str(), child->GetLineNumber());
    }

    child = child->GetNext();
  }

  return text;
}

void wxExLexers::ParseTagGlobal(const wxXmlNode* node)
{
  wxXmlNode* child = node->GetChildren();

  while (child)
  {
    if (child->GetName() == "comment")
    {
      // Ignore comments.
    }
    else if (child->GetName() == "hex")
    {
      m_StylesHex.push_back(
        child->GetAttribute("no", "0") + "=" +
        child->GetNodeContent().Strip(wxString::both));
    }
    else if (child->GetName() == "indicator")
    {
      m_Indicators.insert(std::make_pair(
        atoi(child->GetAttribute("no", "0").c_str()),
        atoi(child->GetNodeContent().Strip(wxString::both).c_str())));
    }
    else if (child->GetName() == "marker")
    {
      const wxExMarker marker(ParseTagMarker(
        child->GetAttribute("no", "0"),
        child->GetNodeContent().Strip(wxString::both)));

      if (marker.GetMarkerNumber() < wxSTC_STYLE_MAX &&
          marker.GetMarkerSymbol() < wxSTC_STYLE_MAX)
      {
        m_Markers.push_back(marker);
      }
      else
      {
        wxLogError("Illegal marker number: %d or symbol: %d on: %d",
          marker.GetMarkerNumber(),
          marker.GetMarkerSymbol(),
          child->GetLineNumber());
      }
    }
    else if (child->GetName() == "style")
    {
      m_Styles.push_back(
        child->GetAttribute("no", "0") + "=" +
        child->GetNodeContent().Strip(wxString::both));
    }
    else
    {
      wxLogError("Undefined global tag: %s on: %d",
        child->GetName().c_str(), child->GetLineNumber());
    }

    child = child->GetNext();
  }
}

const wxExLexer wxExLexers::ParseTagLexer(const wxXmlNode* node) const
{
  wxExLexer lexer;
  lexer.m_ScintillaLexer = node->GetAttribute("name", "");
  lexer.m_Associations = node->GetAttribute("extensions", "");

  wxXmlNode *child = node->GetChildren();

  while (child)
  {
    if (child->GetName() == "colourings")
    {
      lexer.m_Colourings = ParseTagColourings(child);
    }
    else if (child->GetName() == "keywords")
    {
      if (!lexer.SetKeywords(child->GetNodeContent().Strip(wxString::both)))
      {
        wxLogError("Keywords could not be set on: %d", child->GetLineNumber());
      }
    }
    else if (child->GetName() == "properties")
    {
      lexer.m_Properties = ParseTagProperties(child);
    }
    else if (child->GetName() == "comments")
    {
      lexer.m_CommentBegin = child->GetAttribute("begin1", "");
      lexer.m_CommentEnd = child->GetAttribute("end1", "");
      lexer.m_CommentBegin2 = child->GetAttribute("begin2", "");
      lexer.m_CommentEnd2 = child->GetAttribute("end2", "");
    }
    else if (child->GetName() == "comment")
    {
      // Ignore comments.
    }
    else
    {
      wxLogError("Undefined lexer tag: %s on: %d",
        child->GetName().c_str(), child->GetLineNumber());
    }

    child = child->GetNext();
  }

  return lexer;
}

const wxExMarker wxExLexers::ParseTagMarker(
  const wxString& number,
  const wxString& props) const
{
  wxStringTokenizer prop_fields(props, ",");

  const wxString symbol = prop_fields.GetNextToken();

  wxColour foreground;
  wxColour background;

  if (prop_fields.HasMoreTokens())
  {
    foreground = prop_fields.GetNextToken();

    if (prop_fields.HasMoreTokens())
    {
      background = prop_fields.GetNextToken();
    }
  }

  const int no = atoi(number.c_str());
  const int symbol_no = atoi(symbol.c_str());

  if (no <= wxSTC_MARKER_MAX && symbol_no <= wxSTC_MARKER_MAX)
  {
    return wxExMarker(no, symbol_no, foreground, background);
  }
  else
  {
    wxLogError("Illegal marker number: %d or symbol: %d", no, symbol_no);
    return wxExMarker(0, 0, foreground, background);
  }
}

const wxString wxExLexers::ParseTagProperties(const wxXmlNode* node) const
{
  wxString text;

  wxXmlNode *child = node->GetChildren();

  while (child)
  {
    if (child->GetName() == "property")
    {
      text +=
        child->GetAttribute("name", "0") + "=" +
        child->GetNodeContent().Strip(wxString::both) + wxTextFile::GetEOL();
    }
    else if (child->GetName() == "comment")
    {
      // Ignore comments.
    }
    else
    {
      wxLogError("Undefined properties tag: %s on %d",
        child->GetName().c_str(), child->GetLineNumber());
    }

    child = child->GetNext();
  }

  return text;
}

void wxExLexers::Read()
{
  // This test is to prevent showing an error if the lexers file does not exist,
  // as this is not required.
  if (!m_FileName.FileExists())
  {
    return;
  }

  wxXmlDocument doc;

  if (!doc.Load(m_FileName.GetFullPath()))
  {
    return;
  }

  // Initialize members.
  m_Indicators.clear();
  m_Lexers.clear();
  m_Markers.clear();
  m_Styles.clear();
  m_StylesHex.clear();

  wxXmlNode* child = doc.GetRoot()->GetChildren();

  while (child)
  {
    if (child->GetName() == "global")
    {
      ParseTagGlobal(child);
    }
    else if (child->GetName() == "lexer")
    {
      const wxExLexer& lexer = ParseTagLexer(child);

      if (!lexer.GetScintillaLexer().empty())
      {
        if (lexer.GetScintillaLexer() == "hypertext")
        {
          // As our lexers.xml files cannot use xml comments,
          // add them here.
          wxExLexer l(lexer);
          l.m_CommentBegin = "<!--";
          l.m_CommentEnd = "-->";
          m_Lexers.push_back(l);
        }
        else
        {
          m_Lexers.push_back(lexer);
        }
      }
    }

    child = child->GetNext();
  }

  // Initialize the config.
  if (!wxConfigBase::Get()->Exists(_("In files")))
  {
    wxConfigBase::Get()->Write(_("In files"), GetLexerAssociations());
  }

  if (!wxConfigBase::Get()->Exists(_("Add what")))
  {
    wxConfigBase::Get()->Read(_("Add what"), GetLexerAssociations());
  }
}

bool wxExLexers::ShowDialog(
  wxWindow* parent,
  wxExLexer& lexer,
  const wxString& caption) const
{
  wxArrayString aChoices;
  int choice = -1;
  int index = 0;

  for (
    std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
    it != m_Lexers.end();
    ++it)
  {
    aChoices.Add(it->GetScintillaLexer());

    if (lexer.GetScintillaLexer() == it->GetScintillaLexer())
    {
      choice = index;
    }

    index++;
  }

  // Add the <none> lexer (index is already incremented).
  const wxString no_lexer = _("<none>");

  aChoices.Add(no_lexer);

  // And set the choice if we do not have a lexer.
  if (lexer.GetScintillaLexer().empty())
  {
    choice = index;
  }

  wxSingleChoiceDialog dlg(parent, _("Input") + ":", caption, aChoices);

  if (choice != -1)
  {
    dlg.SetSelection(choice);
  }

  if (dlg.ShowModal() == wxID_CANCEL)
  {
    return false;
  }

  const wxString sel = dlg.GetStringSelection();

  if (sel == no_lexer)
  {
    lexer = wxExLexer();
  }
  else
  {
    lexer = FindByName(sel);
  }

  return true;
}
<commit_msg>fixed error Read into Write<commit_after>/******************************************************************************\
* File:          lexers.cpp
* Purpose:       Implementation of wxExLexers classes
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 2008-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/config.h>
#include <wx/tokenzr.h>
#include <wx/stc/stc.h>
#include <wx/textfile.h>
#include <wx/extension/lexers.h>
#include <wx/extension/util.h> // for wxExMatchesOneOf

wxExLexers::wxExLexers(const wxFileName& filename)
  : m_FileName(filename)
{
}

const wxString wxExLexers::BuildWildCards(const wxFileName& filename) const
{
  const wxString allfiles_wildcard =
    _("All Files") + wxString::Format(" (%s)|%s",
      wxFileSelectorDefaultWildcardStr,
      wxFileSelectorDefaultWildcardStr);

  wxString wildcards = allfiles_wildcard;

  // Build the wildcard string using all available lexers.
  for (
    std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
    it != m_Lexers.end();
    ++it)
  {
    if (!it->GetAssociations().empty())
    {
      const wxString wildcard =
        it->GetScintillaLexer() +
        " (" + it->GetAssociations() + ") |" +
        it->GetAssociations();

      if (wxExMatchesOneOf(filename, it->GetAssociations()))
      {
        wildcards = wildcard + "|" + wildcards;
      }
      else
      {
        wildcards = wildcards + "|" + wildcard;
      }
    }
  }

  return wildcards;
}

const wxExLexer wxExLexers::FindByFileName(const wxFileName& filename) const
{
  if (!filename.IsOk())
  {
    return wxExLexer();
  }

  for (
    std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
    it != m_Lexers.end();
    ++it)
  {
    if (wxExMatchesOneOf(filename, it->GetAssociations()))
    {
      return *it;
    }
  }

  return wxExLexer();
}

const wxExLexer wxExLexers::FindByName(
  const wxString& name,
  bool fail_if_not_found) const
{
  for (
    std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
    it != m_Lexers.end();
    ++it)
  {
    if (name == it->GetScintillaLexer())
    {
      return *it;
    }
  }

  if (!m_Lexers.empty() && fail_if_not_found)
  {
    wxFAIL;
  }

  return wxExLexer();
}

const wxExLexer wxExLexers::FindByText(const wxString& text) const
{
  // Add automatic lexers if text starts with some special tokens.
  const wxString text_lowercase = text.Lower();

  if (text_lowercase.StartsWith("#") ||
      // .po files that do not have comment headers, start with msgid, so set them
      text_lowercase.StartsWith("msgid"))
  {
    return FindByName("bash", false); // don't show error
  }
  else if (text_lowercase.StartsWith("<html>") ||
           text_lowercase.StartsWith("<?php"))
  {
    return FindByName("hypertext", false); // don't show error
  }
  else if (text_lowercase.StartsWith("<?xml"))
  {
    return FindByName("xml", false); // don't show error
  }
  // cpp files like #include <map> really do not have a .h extension (e.g. /usr/include/c++/3.3.5/map)
  // so add here.
  else if (text_lowercase.StartsWith("//"))
  {
    return FindByName("cpp", false); // don't show error
  }

  return wxExLexer();
}

const wxString wxExLexers::GetLexerAssociations() const
{
  wxString text;

  for (
    std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
    it != m_Lexers.end();
    ++it)
  {
    if (!it->GetAssociations().empty())
    {
      if (!text.empty())
      {
        text += ",";
      }

      text += it->GetAssociations();
    }
  }

  return text;
}

const wxString wxExLexers::ParseTagColourings(const wxXmlNode* node) const
{
  wxString text;

  wxXmlNode* child = node->GetChildren();

  while (child)
  {
    if (child->GetName() == "colouring")
    {
      text +=
        child->GetAttribute("no", "0") + "=" +
        child->GetNodeContent().Strip(wxString::both) + wxTextFile::GetEOL();
    }
    else if (child->GetName() == "comment")
    {
      // Ignore comments.
    }
    else
    {
      wxLogError("Undefined colourings tag: %s on: %d",
        child->GetName().c_str(), child->GetLineNumber());
    }

    child = child->GetNext();
  }

  return text;
}

void wxExLexers::ParseTagGlobal(const wxXmlNode* node)
{
  wxXmlNode* child = node->GetChildren();

  while (child)
  {
    if (child->GetName() == "comment")
    {
      // Ignore comments.
    }
    else if (child->GetName() == "hex")
    {
      m_StylesHex.push_back(
        child->GetAttribute("no", "0") + "=" +
        child->GetNodeContent().Strip(wxString::both));
    }
    else if (child->GetName() == "indicator")
    {
      m_Indicators.insert(std::make_pair(
        atoi(child->GetAttribute("no", "0").c_str()),
        atoi(child->GetNodeContent().Strip(wxString::both).c_str())));
    }
    else if (child->GetName() == "marker")
    {
      const wxExMarker marker(ParseTagMarker(
        child->GetAttribute("no", "0"),
        child->GetNodeContent().Strip(wxString::both)));

      if (marker.GetMarkerNumber() < wxSTC_STYLE_MAX &&
          marker.GetMarkerSymbol() < wxSTC_STYLE_MAX)
      {
        m_Markers.push_back(marker);
      }
      else
      {
        wxLogError("Illegal marker number: %d or symbol: %d on: %d",
          marker.GetMarkerNumber(),
          marker.GetMarkerSymbol(),
          child->GetLineNumber());
      }
    }
    else if (child->GetName() == "style")
    {
      m_Styles.push_back(
        child->GetAttribute("no", "0") + "=" +
        child->GetNodeContent().Strip(wxString::both));
    }
    else
    {
      wxLogError("Undefined global tag: %s on: %d",
        child->GetName().c_str(), child->GetLineNumber());
    }

    child = child->GetNext();
  }
}

const wxExLexer wxExLexers::ParseTagLexer(const wxXmlNode* node) const
{
  wxExLexer lexer;
  lexer.m_ScintillaLexer = node->GetAttribute("name", "");
  lexer.m_Associations = node->GetAttribute("extensions", "");

  wxXmlNode *child = node->GetChildren();

  while (child)
  {
    if (child->GetName() == "colourings")
    {
      lexer.m_Colourings = ParseTagColourings(child);
    }
    else if (child->GetName() == "keywords")
    {
      if (!lexer.SetKeywords(child->GetNodeContent().Strip(wxString::both)))
      {
        wxLogError("Keywords could not be set on: %d", child->GetLineNumber());
      }
    }
    else if (child->GetName() == "properties")
    {
      lexer.m_Properties = ParseTagProperties(child);
    }
    else if (child->GetName() == "comments")
    {
      lexer.m_CommentBegin = child->GetAttribute("begin1", "");
      lexer.m_CommentEnd = child->GetAttribute("end1", "");
      lexer.m_CommentBegin2 = child->GetAttribute("begin2", "");
      lexer.m_CommentEnd2 = child->GetAttribute("end2", "");
    }
    else if (child->GetName() == "comment")
    {
      // Ignore comments.
    }
    else
    {
      wxLogError("Undefined lexer tag: %s on: %d",
        child->GetName().c_str(), child->GetLineNumber());
    }

    child = child->GetNext();
  }

  return lexer;
}

const wxExMarker wxExLexers::ParseTagMarker(
  const wxString& number,
  const wxString& props) const
{
  wxStringTokenizer prop_fields(props, ",");

  const wxString symbol = prop_fields.GetNextToken();

  wxColour foreground;
  wxColour background;

  if (prop_fields.HasMoreTokens())
  {
    foreground = prop_fields.GetNextToken();

    if (prop_fields.HasMoreTokens())
    {
      background = prop_fields.GetNextToken();
    }
  }

  const int no = atoi(number.c_str());
  const int symbol_no = atoi(symbol.c_str());

  if (no <= wxSTC_MARKER_MAX && symbol_no <= wxSTC_MARKER_MAX)
  {
    return wxExMarker(no, symbol_no, foreground, background);
  }
  else
  {
    wxLogError("Illegal marker number: %d or symbol: %d", no, symbol_no);
    return wxExMarker(0, 0, foreground, background);
  }
}

const wxString wxExLexers::ParseTagProperties(const wxXmlNode* node) const
{
  wxString text;

  wxXmlNode *child = node->GetChildren();

  while (child)
  {
    if (child->GetName() == "property")
    {
      text +=
        child->GetAttribute("name", "0") + "=" +
        child->GetNodeContent().Strip(wxString::both) + wxTextFile::GetEOL();
    }
    else if (child->GetName() == "comment")
    {
      // Ignore comments.
    }
    else
    {
      wxLogError("Undefined properties tag: %s on %d",
        child->GetName().c_str(), child->GetLineNumber());
    }

    child = child->GetNext();
  }

  return text;
}

void wxExLexers::Read()
{
  // This test is to prevent showing an error if the lexers file does not exist,
  // as this is not required.
  if (!m_FileName.FileExists())
  {
    return;
  }

  wxXmlDocument doc;

  if (!doc.Load(m_FileName.GetFullPath()))
  {
    return;
  }

  // Initialize members.
  m_Indicators.clear();
  m_Lexers.clear();
  m_Markers.clear();
  m_Styles.clear();
  m_StylesHex.clear();

  wxXmlNode* child = doc.GetRoot()->GetChildren();

  while (child)
  {
    if (child->GetName() == "global")
    {
      ParseTagGlobal(child);
    }
    else if (child->GetName() == "lexer")
    {
      const wxExLexer& lexer = ParseTagLexer(child);

      if (!lexer.GetScintillaLexer().empty())
      {
        if (lexer.GetScintillaLexer() == "hypertext")
        {
          // As our lexers.xml files cannot use xml comments,
          // add them here.
          wxExLexer l(lexer);
          l.m_CommentBegin = "<!--";
          l.m_CommentEnd = "-->";
          m_Lexers.push_back(l);
        }
        else
        {
          m_Lexers.push_back(lexer);
        }
      }
    }

    child = child->GetNext();
  }

  // Initialize the config.
  if (!wxConfigBase::Get()->Exists(_("In files")))
  {
    wxConfigBase::Get()->Write(_("In files"), GetLexerAssociations());
  }

  if (!wxConfigBase::Get()->Exists(_("Add what")))
  {
    wxConfigBase::Get()->Write(_("Add what"), GetLexerAssociations());
  }
}

bool wxExLexers::ShowDialog(
  wxWindow* parent,
  wxExLexer& lexer,
  const wxString& caption) const
{
  wxArrayString aChoices;
  int choice = -1;
  int index = 0;

  for (
    std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
    it != m_Lexers.end();
    ++it)
  {
    aChoices.Add(it->GetScintillaLexer());

    if (lexer.GetScintillaLexer() == it->GetScintillaLexer())
    {
      choice = index;
    }

    index++;
  }

  // Add the <none> lexer (index is already incremented).
  const wxString no_lexer = _("<none>");

  aChoices.Add(no_lexer);

  // And set the choice if we do not have a lexer.
  if (lexer.GetScintillaLexer().empty())
  {
    choice = index;
  }

  wxSingleChoiceDialog dlg(parent, _("Input") + ":", caption, aChoices);

  if (choice != -1)
  {
    dlg.SetSelection(choice);
  }

  if (dlg.ShowModal() == wxID_CANCEL)
  {
    return false;
  }

  const wxString sel = dlg.GetStringSelection();

  if (sel == no_lexer)
  {
    lexer = wxExLexer();
  }
  else
  {
    lexer = FindByName(sel);
  }

  return true;
}
<|endoftext|>


<commit_before>/**
 * @{
 *  \copyright TU Dresden ZIH. All rights reserved.
 *  \authors Martin Flehmig, Marc Hartung, Marcus Walther
 *  \date Oct 2015
 */

#ifndef INCLUDE_STDAFX_HPP_
#define INCLUDE_STDAFX_HPP_

#include <cstring>
#include <cmath>

#include <string>
#include <sstream>
#include <fstream>
#include <iostream>

#include <list>
#include <deque>
#include <vector>
#include <map>
#include <set>
#include <unordered_map>
#include <tuple>
#include <memory>
#include <stdexcept>
#include <iomanip>
#include <limits>
#include <assert.h>
#include <type_traits>
#include <utility>

using std::list;
using std::deque;
using std::unordered_map;
using std::map;
using std::tuple;
using std::pair;
using std::vector;
using std::set;
using std::copy;
using std::shared_ptr;
using std::weak_ptr;
using std::ios;
using std::iostream;
using std::ostream;
using std::fstream;
using std::stringstream;
using std::cerr;
using std::cout;
using std::endl;
using std::exception;
using std::runtime_error;
using std::to_string;
using std::signbit;
using std::get;
using std::function;
using std::make_tuple;
using std::max;
using std::string;

#include "BasicTypedefs.hpp"
#include "util/Logger.hpp"
#include "util/StringHelper.hpp"

#endif /* INCLUDE_STDAFX_HPP_ */
/**
 * @}
 */
<commit_msg>Make make_shared usable without namespace<commit_after>/**
 * @{
 *  \copyright TU Dresden ZIH. All rights reserved.
 *  \authors Martin Flehmig, Marc Hartung, Marcus Walther
 *  \date Oct 2015
 */

#ifndef INCLUDE_STDAFX_HPP_
#define INCLUDE_STDAFX_HPP_

#include <cstring>
#include <cmath>

#include <string>
#include <sstream>
#include <fstream>
#include <iostream>

#include <list>
#include <deque>
#include <vector>
#include <map>
#include <set>
#include <unordered_map>
#include <tuple>
#include <memory>
#include <stdexcept>
#include <iomanip>
#include <limits>
#include <assert.h>
#include <type_traits>
#include <utility>

using std::list;
using std::deque;
using std::unordered_map;
using std::map;
using std::tuple;
using std::pair;
using std::vector;
using std::set;
using std::copy;
using std::shared_ptr;
using std::weak_ptr;
using std::ios;
using std::iostream;
using std::ostream;
using std::fstream;
using std::stringstream;
using std::cerr;
using std::cout;
using std::endl;
using std::exception;
using std::runtime_error;
using std::to_string;
using std::signbit;
using std::get;
using std::function;
using std::make_tuple;
using std::max;
using std::string;
using std::make_shared;

#include "BasicTypedefs.hpp"
#include "util/Logger.hpp"
#include "util/StringHelper.hpp"

#endif /* INCLUDE_STDAFX_HPP_ */
/**
 * @}
 */
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2014.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef STRUCT_H
#define STRUCT_H

#include <memory>
#include <string>
#include <vector>

namespace eddic {

class Type;

/*!
 * \class Member
 * \brief A member of a struct.
 */
struct Member {
    std::string name;
    std::shared_ptr<const Type> type;

    Member(const std::string& n, std::shared_ptr<const Type> t);

    /*!
     * Increment the reference counter of the member.
     */
    void add_reference();

    /*!
     * Return the reference counter of the member.
     * \return The reference counter of the member.
     */
    unsigned int get_references();

    private:
        unsigned int references = 0;
};

/*!
 * \class Struct
 * \brief A structure entry in the function table.
 */
struct Struct {
    std::string name;
    std::vector<Member> members;
    std::shared_ptr<const Type> parent_type;

    Struct(const std::string& n);

    /*!
     * Indicates if the specified member exists in this structure.
     * \param name The name of the member to search for.
     * \return true if the member exists, otherwise false.
     */
    bool member_exists(const std::string& name);

    /*!
     * Return the member with the specified name.
     * \param name The name of the member to search for.
     * \return A pointer to the member with the given name.
     */
    Member& operator[](const std::string& name);

    /*!
     * Increment the reference counter of the structure.
     */
    void add_reference();

    /*!
     * Return the reference counter of the member.
     * \return The reference counter of the member.
     */
    unsigned int get_references();

    private:
        unsigned int references = 0;
};

} //end of eddic

#endif
<commit_msg>Cleanup<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2014.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef STRUCT_H
#define STRUCT_H

#include <memory>
#include <string>
#include <vector>

namespace eddic {

class Type;

/*!
 * \class Member
 * \brief A member of a struct.
 */
struct Member {
    std::string name;
    std::shared_ptr<const Type> type;

    Member(const std::string& n, std::shared_ptr<const Type> t);

    Member(const Member& rhs) = default;
    Member& operator=(const Member& rhs) = default;

    Member(Member&& rhs) = default;
    Member& operator=(Member&& rhs) = default;

    /*!
     * Increment the reference counter of the member.
     */
    void add_reference();

    /*!
     * Return the reference counter of the member.
     * \return The reference counter of the member.
     */
    unsigned int get_references();

    private:
        unsigned int references = 0;
};

/*!
 * \class Struct
 * \brief A structure entry in the function table.
 */
struct Struct {
    std::string name;
    std::vector<Member> members;
    std::shared_ptr<const Type> parent_type;

    Struct(const std::string& n);

    Struct(const Struct& rhs) = default;
    Struct& operator=(const Struct& rhs) = default;

    Struct(Struct&& rhs) = default;
    Struct& operator=(Struct&& rhs) = default;

    /*!
     * Indicates if the specified member exists in this structure.
     * \param name The name of the member to search for.
     * \return true if the member exists, otherwise false.
     */
    bool member_exists(const std::string& name);

    /*!
     * Return the member with the specified name.
     * \param name The name of the member to search for.
     * \return A pointer to the member with the given name.
     */
    Member& operator[](const std::string& name);

    /*!
     * Increment the reference counter of the structure.
     */
    void add_reference();

    /*!
     * Return the reference counter of the member.
     * \return The reference counter of the member.
     */
    unsigned int get_references();

    private:
        unsigned int references = 0;
};

} //end of eddic

#endif
<|endoftext|>


<commit_before>/*
 * MPT C++ buffer implementation
 */

#include <cerrno>

#include <sys/uio.h>

#include "message.h"
#include "convert.h"

#include "../mptio/stream.h"

#include "array.h"

__MPT_NAMESPACE_BEGIN

// buffer instance
Buffer::Buffer(array const &a)
{
    _d = a;
    _state.done = _d.length();
}
Buffer::~Buffer()
{ }
// reference interface
void Buffer::unref()
{
    delete this;
}
// metatype interface
Buffer *Buffer::clone() const
{
    if (_enc) {
        if (_state.scratch || _state._ctx) {
            return 0;
        }
    }
    Buffer *b = new Buffer(_d);
    b->_state = _state;
    b->_enc = _enc;
    return b;
}
int Buffer::conv(int type, void *ptr) const
{
    int me;
    if ((me = IODevice::typeIdentifier()) < 0) {
        me = metatype::Type;
    }
    if (!type) {
        static const char types[] = { metatype::Type, iterator::Type, MPT_value_toVector('c'), 's', 0 };
        if (ptr) *((const char **) ptr) = types;
        return me;
    }
    if (type == metatype::Type) {
        if (ptr) *static_cast<const metatype **>(ptr) = this;
        return me;
    }
    if (type == iterator::Type) {
        if (ptr) *static_cast<const iterator **>(ptr) = this;
        return me;
    }
    if (type == MPT_value_toVector('c')) {
        struct iovec *vec;
        if ((vec = static_cast<struct iovec *>(ptr))) {
            Slice<uint8_t> d = data();
            vec->iov_base = d.base();
            vec->iov_len = d.length();
        }
        return me;
    }
    if (type == 's') {
        Slice<uint8_t> d = data();
        if (!memchr(d.begin(), 0, d.length())) {
            return BadValue;
        }
        if (ptr) *static_cast<const uint8_t **>(ptr) = d.begin();
        return me;
    }
    return BadType;
}
// iterator interface
int Buffer::get(int type, void *ptr)
{
    if (!type) {
        int me;
        if ((me = IODevice::typeIdentifier()) < 0) {
            me = array::Type;
        }
        mpt_slice_get(0, type, ptr);
        return me;
    }
    if (_state.scratch) {
        return MessageInProgress;
    }
    size_t off = _d.length() - _state.done;
    slice s(_d);
    s.shift(off);
    if ((type = mpt_slice_get(&s, type, ptr)) < 0) {
        return type;
    }
    int me = IODevice::typeIdentifier();
    return me < 0 ? metatype::Type : me;
}
int Buffer::advance()
{
    if (!_state.done) {
        return MissingData;
    }
    Slice<uint8_t> d = data();
    uint8_t *end;
    if (!(end = (uint8_t *) memchr(d.base(), 0, d.length()))) {
        return BadValue;
    }
    shift((end + 1) - d.base());
    return _state.done ? 's' : 0;
}
int Buffer::reset()
{
    _state.done = _d.length() - _state.scratch;
    return _state.done;
}

// I/O device interface
ssize_t Buffer::read(size_t nblk, void *dest, size_t esze)
{
    Slice<uint8_t> d = data();
    if (!esze) {
        if ((size_t) d.length() < nblk) return -2;
        if (dest) memcpy(dest, d.base(), nblk);
        return nblk;
    }
    size_t avail = d.length() / esze;

    if (nblk > avail) nblk = avail;

    if (!nblk) return 0;

    avail = nblk * esze;
    if (dest) memcpy(dest, d.base(), avail);

    shift(avail);

    return nblk;
}
ssize_t Buffer::write(size_t nblk, const void *from, size_t esze)
{
    if (!nblk) {
        return push(0, 0);
    }
    if ((SIZE_MAX / nblk) < esze) {
        errno = ERANGE;
        return -2;
    }
    if (!esze) {
        return 0;
    }
    size_t left = nblk;
    while (nblk) {
        bool wait = _state.scratch;
        if (!push(esze, from)) {
            break;
        }
        if (!wait && !_enc) push(0, 0);
        from = ((uint8_t *) from) + esze;
        --nblk;
    }
    return left - nblk;

}
int64_t Buffer::pos()
{
    size_t len = _state.done + _state.scratch;
    return _d.length() - len;
}
bool Buffer::seek(int64_t pos)
{
    if (pos >= 0) {
        if ((size_t) pos > _state.done) {
            return false;
        }
        _state.done -= pos;
        return true;
    }
    ssize_t off = _state.done + _state.scratch;

    pos = -pos;
    if (off < pos) {
        return false;
    }
    _state.done += pos;

    return true;
}
Slice<uint8_t> Buffer::peek(size_t)
{
    return encode_array::data();
}

__MPT_NAMESPACE_END
<commit_msg>fix: buffer metatype iterator end detection<commit_after>/*
 * MPT C++ buffer implementation
 */

#include <cerrno>

#include <sys/uio.h>

#include "message.h"
#include "convert.h"

#include "../mptio/stream.h"

#include "array.h"

__MPT_NAMESPACE_BEGIN

// buffer instance
Buffer::Buffer(array const &a)
{
    _d = a;
    _state.done = _d.length();
}
Buffer::~Buffer()
{ }
// reference interface
void Buffer::unref()
{
    delete this;
}
// metatype interface
Buffer *Buffer::clone() const
{
    if (_enc) {
        if (_state.scratch || _state._ctx) {
            return 0;
        }
    }
    Buffer *b = new Buffer(_d);
    b->_state = _state;
    b->_enc = _enc;
    return b;
}
int Buffer::conv(int type, void *ptr) const
{
    int me;
    if ((me = IODevice::typeIdentifier()) < 0) {
        me = metatype::Type;
    }
    if (!type) {
        static const char types[] = { metatype::Type, iterator::Type, MPT_value_toVector('c'), 's', 0 };
        if (ptr) *((const char **) ptr) = types;
        return me;
    }
    if (type == metatype::Type) {
        if (ptr) *static_cast<const metatype **>(ptr) = this;
        return me;
    }
    if (type == iterator::Type) {
        if (ptr) *static_cast<const iterator **>(ptr) = this;
        return me;
    }
    if (type == MPT_value_toVector('c')) {
        struct iovec *vec;
        if ((vec = static_cast<struct iovec *>(ptr))) {
            Slice<uint8_t> d = data();
            vec->iov_base = d.base();
            vec->iov_len = d.length();
        }
        return me;
    }
    if (type == 's') {
        Slice<uint8_t> d = data();
        if (!memchr(d.begin(), 0, d.length())) {
            return BadValue;
        }
        if (ptr) *static_cast<const uint8_t **>(ptr) = d.begin();
        return me;
    }
    return BadType;
}
// iterator interface
int Buffer::get(int type, void *ptr)
{
    if (!type) {
        int me;
        if ((me = IODevice::typeIdentifier()) < 0) {
            me = array::Type;
        }
        mpt_slice_get(0, type, ptr);
        return me;
    }
    if (_state.scratch) {
        return MessageInProgress;
    }
    size_t off = _d.length() - _state.done;
    slice s(_d);
    s.shift(off);
    if ((type = mpt_slice_get(&s, type, ptr)) <= 0) {
        return type;
    }
    int me = IODevice::typeIdentifier();
    return me < 0 ? metatype::Type : me;
}
int Buffer::advance()
{
    if (!_state.done) {
        return MissingData;
    }
    Slice<uint8_t> d = data();
    uint8_t *end;
    if (!(end = (uint8_t *) memchr(d.base(), 0, d.length()))) {
        return BadValue;
    }
    shift((end + 1) - d.base());
    return _state.done ? 's' : 0;
}
int Buffer::reset()
{
    _state.done = _d.length() - _state.scratch;
    return _state.done;
}

// I/O device interface
ssize_t Buffer::read(size_t nblk, void *dest, size_t esze)
{
    Slice<uint8_t> d = data();
    if (!esze) {
        if ((size_t) d.length() < nblk) return -2;
        if (dest) memcpy(dest, d.base(), nblk);
        return nblk;
    }
    size_t avail = d.length() / esze;

    if (nblk > avail) nblk = avail;

    if (!nblk) return 0;

    avail = nblk * esze;
    if (dest) memcpy(dest, d.base(), avail);

    shift(avail);

    return nblk;
}
ssize_t Buffer::write(size_t nblk, const void *from, size_t esze)
{
    if (!nblk) {
        return push(0, 0);
    }
    if ((SIZE_MAX / nblk) < esze) {
        errno = ERANGE;
        return -2;
    }
    if (!esze) {
        return 0;
    }
    size_t left = nblk;
    while (nblk) {
        bool wait = _state.scratch;
        if (!push(esze, from)) {
            break;
        }
        if (!wait && !_enc) push(0, 0);
        from = ((uint8_t *) from) + esze;
        --nblk;
    }
    return left - nblk;

}
int64_t Buffer::pos()
{
    size_t len = _state.done + _state.scratch;
    return _d.length() - len;
}
bool Buffer::seek(int64_t pos)
{
    if (pos >= 0) {
        if ((size_t) pos > _state.done) {
            return false;
        }
        _state.done -= pos;
        return true;
    }
    ssize_t off = _state.done + _state.scratch;

    pos = -pos;
    if (off < pos) {
        return false;
    }
    _state.done += pos;

    return true;
}
Slice<uint8_t> Buffer::peek(size_t)
{
    return encode_array::data();
}

__MPT_NAMESPACE_END
<|endoftext|>


<commit_before>/* This file is part of Mapnik (c++ mapping toolkit)
 * Copyright (C) 2005 Artem Pavlenko
 *
 * Mapnik is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

//$Id: plugin.hpp 39 2005-04-10 20:39:53Z pavlenko $

#ifndef PLUGIN_HPP
#define PLUGIN_HPP

#include <ltdl.h>
#include <string>

namespace mapnik
{
    class PluginInfo
    {
    private:
	std::string name_;
	lt_dlhandle module_;

    public:
	PluginInfo (const std::string& name,const lt_dlhandle module);
	~PluginInfo();
	const std::string& name() const;
	lt_dlhandle handle() const;
    private:
	PluginInfo(const PluginInfo&);
	PluginInfo& operator=(const PluginInfo&);
    };
}

#endif //PLUGIN_HPP
<commit_msg>use boost::noncopyable<commit_after>/* This file is part of Mapnik (c++ mapping toolkit)
 * Copyright (C) 2005 Artem Pavlenko
 *
 * Mapnik is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

//$Id: plugin.hpp 39 2005-04-10 20:39:53Z pavlenko $

#ifndef PLUGIN_HPP
#define PLUGIN_HPP

#include <ltdl.h>
#include <string>
#include <boost/utility.hpp>

namespace mapnik
{
    class PluginInfo : boost::noncopyable
    {
    private:
	std::string name_;
	lt_dlhandle module_;

    public:
	PluginInfo (const std::string& name,const lt_dlhandle module);
	~PluginInfo();
	const std::string& name() const;
	lt_dlhandle handle() const;
    };
}

#endif //PLUGIN_HPP
<|endoftext|>


<commit_before>/*!
 * MPT C++ stream implementation
 */

#include <inttypes.h>

#include <cstring>

#include <cstdio>
#include <cerrno>

#include <poll.h>

#include <sys/uio.h>

#include "queue.h"
#include "array.h"
#include "message.h"

#include "output.h"
#include "meta.h"

#include "stream.h"

__MPT_NAMESPACE_BEGIN

// streaminfo access
streaminfo::~streaminfo()
{
    _mpt_stream_setfile(this, -1, -1);
}
bool streaminfo::setFlags(int fl)
{
    if (fl & ~0xf0) return false;
    _fd |= fl;
    return true;
}

// stream data operations
stream::stream() : _mlen(0)
{ }
stream::~stream()
{
    mpt_stream_close(this);
}
int stream::flags() const
{
    return mpt_stream_flags(&this->_info) & 0xff;
}
int stream::errors() const {
    return MPT_stream_errors(mpt_stream_flags(&this->_info));
}
void stream::setError(int err)
{
    return mpt_stream_seterror(&this->_info, err);
}
bool stream::endline()
{
    int nl = (mpt_stream_flags(&this->_info) & 0xc000) >> 14;

    switch (nl) {
      case NewlineMac:  return mpt_stream_write(this, 1, "\r",   1);
      case NewlineUnix: return mpt_stream_write(this, 1, "\n",   1);
      case NewlineNet:  return mpt_stream_write(this, 1, "\r\n", 2);
      default: return false;
    }
}
void stream::setNewline(int nl, int what)
{
    return mpt_stream_setnewline(&this->_info, nl, what);
}
bool stream::open(const char *fn, const char *mode)
{
    if (!fn) { mpt_stream_close(this); return true; }
    return mpt_stream_open(this, fn, mode) < 0 ? false : true;
}

// stream class
Stream::Stream(const streaminfo *from) : _inputFile(-1)
{
    if (!from) return;
    _srm = new stream;
    _mpt_stream_setfile(&_srm->_info, _mpt_stream_fread(from), _mpt_stream_fwrite(from));
    int flags = mpt_stream_flags(from);
    mpt_stream_setmode(_srm, flags & 0xff);
    _srm->setNewline(MPT_stream_newline_read(flags),  _srm->Read);
    _srm->setNewline(MPT_stream_newline_write(flags), _srm->Write);
}
Stream::~Stream()
{ }

// metatype interface
void Stream::unref()
{
    if (_srm) delete _srm;
    delete this;
}
int Stream::assign(const value *val)
{
    if (val) {
        return setProperty(0, 0);
    } else {
        return mpt_object_pset(this, 0, val);
    }
}
int Stream::conv(int type, void *ptr)
{
    static const char fmt[] = { output::Type, input::Type, IODevice::Type, 0 };
    const void *addr = 0;
    switch (type) {
      case 0: addr = fmt; type = Type;
      case metatype::Type: addr = static_cast<metatype *>(this); break;
      case output::Type: addr = static_cast<output *>(this); break;
      case input::Type: addr = static_cast<input *>(this); break;
      case IODevice::Type: addr = static_cast<IODevice *>(this); break;
      default: return BadType;
    }
    if (ptr) *reinterpret_cast<const void **>(ptr) = addr;
    return type;
}
// object interface
int Stream::property(struct property *pr) const
{
    if (!pr) {
        return Type;
    }
    const char *name;
    intptr_t pos;

    if (!(name = pr->name)) {
        if (((pos = (intptr_t) pr->desc) < 0)) {
            errno = EINVAL;
            return BadValue;
        }
    }
    else {
        // get stream interface types
        if (!*name) {
            static const char fmt[] = { output::Type, input::Type, IODevice::Type, 0 };
            pr->name = "stream";
            pr->desc = "interfaces to stream data";
            pr->val.fmt = fmt;
            pr->val.ptr = 0;
            return _srm ? mpt_stream_flags(&_srm->_info) : 0;
        }
    }
    intptr_t id = 0;
    if (name ? !strcasecmp(name, "idlen") : (pos == id++)) {
        pr->name = "idlen";
        pr->desc = "message id length";
        pr->val.fmt = "y";
        pr->val.ptr = &_idlen;
        return id;
    }
    return BadArgument;
}
int Stream::setProperty(const char *pr, metatype *src)
{
    if (!pr) {
        return _srm ? mpt_stream_setter(_srm, src) : BadOperation;
    }
    if (strcasecmp(pr, "idlen")) {
        if (_inputFile >= 0) {
            return BadOperation;
        }
        int ret;
        uint8_t l;

        if (!src) {
            ret = l = 0;
        } else {
            if ((ret = src->conv('y', &l)) < 0) return ret;
            if (l > sizeof(uintptr_t)) {
                return BadValue;
            }
        }
        _idlen = l;
        return ret;
    }
    return BadArgument;
}
bool Stream::open(const char *dest, const char *type)
{
    if (_inputFile >= 0) return false;
    if (!_srm) _srm = new stream;
    return mpt_stream_open(_srm, dest, type) < 0 ? false : true;
}
bool Stream::open(void *base, size_t len, int mode)
{
    if (_inputFile >= 0) {
        return false;
    }
    if (len && !base) {
        return false;
    }
    struct iovec data = { base, len };
    int ret;
    if (!_srm) _srm = new stream;
    switch (mode) {
      case stream::Read:  ret = mpt_stream_memory(_srm, &data, 0); break;
      case stream::Write: ret = mpt_stream_memory(_srm, 0, &data); break;
    default: return false;
    }
    if (ret < 0) {
        return false;
    }
    return true;
}
// IODevice interface
ssize_t Stream::write(size_t len, const void *data, size_t part)
{
    if (!_srm) {
        return BadArgument;
    }
    return mpt_stream_write(_srm, len, data, part);
}
ssize_t Stream::read(size_t len, void *data, size_t part)
{
    if (!_srm) {
        return BadArgument;
    }
    return mpt_stream_read(_srm, len, data, part);
}
int64_t Stream::pos()
{
    if (!_srm) {
        return BadArgument;
    }
    return mpt_stream_seek(_srm, 0, SEEK_CUR);
}
bool Stream::seek(int64_t pos)
{
    if (!_srm) {
        return BadArgument;
    }
    return mpt_stream_seek(_srm, pos, SEEK_SET) >= 0 ? true : false;
}
// input interface
int Stream::next(int what)
{
    if (!_srm) {
        return BadArgument;
    }
    int ret = mpt_stream_poll(_srm, what, 0);
    if (ret < 0) {
        _inputFile = -1;
    }
    return ret;
}
class Stream::Dispatch
{
public:
    Dispatch(Stream &s, EventHandler c, void *a) : srm(s), cmd(c), arg(a)
    { }
    int dispatch(const struct message *msg)
    {
        static const char _func[] = "mpt::Stream::dispatch";
        struct event ev;
        uint8_t idlen;

        if (!msg || !(idlen = srm._idlen)) {
            return cmd(arg, &ev);
        }
        uint8_t id[__UINT8_MAX__];
        int ret;

        struct message tmp = *msg;
        if (tmp.read(idlen, id) < idlen) {
            error(_func, "%s", MPT_tr("message id incomplete"));
        }
        if (id[0] & 0x80) {
            command *ans;
            uint64_t rid;
            id[0] &= 0x7f;
            if ((ret = mpt_message_buf2id(id, idlen, &rid)) < 0 || ret > (int) sizeof(ans->id)) {
                error(_func, "%s", MPT_tr("bad reply id"));
                return BadValue;
            }
            if ((ans = srm._wait.get(rid))) {
                return ans->cmd(ans->arg, &tmp);
            }
            error(_func, "%s (id = %08" PRIx64 ")", MPT_tr("unknown reply id"), rid);
            return BadValue;
        }
        reply_data::context *rc = 0;
        for (uint8_t i = 0; i < idlen; ++i) {
            if (!id[i]) {
                continue;
            }
            if (!(rc = srm._ctx.pointer())) {
                warning(_func, "%s", MPT_tr("no reply context"));
                break;
            }
            if (!rc->setData(idlen, id)) {
                error(_func, "%s", MPT_tr("reply context unusable"));
                return BadOperation;
            }
            break;
        }
        ev.reply = rc;
        ret = cmd(arg, &ev);
        if (rc && rc->active()) {
            struct msgtype mt(MessageAnswer, ret);
            struct message msg(&mt, sizeof(mt));
            id[0] |= 0x80;
            mpt_stream_reply(srm._srm, &msg, idlen, id);
        }
        return ret;
    }
protected:
    Stream &srm;
    EventHandler cmd;
    void *arg;
};
static int streamDispatch(void *ptr, const struct message *msg)
{
    Stream::Dispatch *sd = reinterpret_cast<Stream::Dispatch *>(ptr);
    return sd->dispatch(msg);
}
int Stream::dispatch(EventHandler cmd, void *arg)
{
    if (!_srm) {
        return BadArgument;
    }
    if (_srm->_mlen < 0
        && (_srm->_mlen = mpt_queue_recv(&_srm->_rd)) < 0) {
        if (_mpt_stream_fread(&_srm->_info) < 0) {
            return BadArgument;
        }
        return 0;
    }
    class Dispatch sd(*this, cmd, arg);
    return mpt_stream_dispatch(_srm, streamDispatch, &sd);
}
int Stream::_file()
{
    if (_inputFile >= 0) {
        return _inputFile;
    }
    if (!_srm) {
        return BadArgument;
    }
    if ((_inputFile = _mpt_stream_fread(&_srm->_info)) >= 0) {
        return _inputFile;
    }
    return _inputFile = _mpt_stream_fwrite(&_srm->_info);
}

ssize_t Stream::push(size_t len, const void *src)
{
    if (!_srm) {
        return BadArgument;
    }
    ssize_t curr;
    if (_idlen && !(_srm->flags() & MessageInProgress)) {
        uint8_t id[__UINT8_MAX__];
        mpt_message_id2buf(_cid, id, _idlen);
        if (mpt_stream_push(_srm, _idlen, id) < _idlen) {
            push(1, 0);
        }
    }
    if ((curr = mpt_stream_push(_srm, len, src)) < 0) {
        return curr;
    }
    if (!len) {
        _cid = 0;
    }
    else if (!src && _cid) {
        command *c;
        if ((c = _wait.get(_cid))) {
            c->cmd(c->arg, 0);
        }
    }
    return curr;
}
int Stream::sync(int timeout)
{
    if (!_srm || !_idlen) {
        return BadArgument;
    }
    return mpt_stream_sync(_srm, _idlen, &_wait, timeout);
}

int Stream::await(int (*rctl)(void *, const struct message *), void *rpar)
{
    if (!_idlen) {
        return BadArgument;
    }
    struct command *cmd;

    if (mpt_stream_flags(&_srm->_info) & _srm->MesgActive) {
        return MessageInProgress;
    }
    if (!rctl) {
        return 0;
    }
    if (!(cmd = _wait.next(_idlen))) {
        return BadOperation;
    }
    _cid = cmd->id;
    cmd->cmd = (int (*)(void *, void *)) rctl;
    cmd->arg = rpar;
    return 1;
}

int Stream::getchar()
{
    if (!_srm || _srm->_rd.encoded()) {
        return BadArgument;
    }
    if (_srm->_rd.len) {
        uint8_t *base = (uint8_t *) _srm->_rd.base;
        if (_srm->_rd.off >= _srm->_rd.max) {
            _srm->_rd.off = 0;
        }
        --_srm->_rd.len;
        return base[_srm->_rd.off++];
    }
    return IODevice::getchar();
}

__MPT_NAMESPACE_END

<commit_msg>fix: uninitialized members mpt::Stream constructor<commit_after>/*!
 * MPT C++ stream implementation
 */

#include <inttypes.h>

#include <cstring>

#include <cstdio>
#include <cerrno>

#include <poll.h>

#include <sys/uio.h>

#include "queue.h"
#include "array.h"
#include "message.h"

#include "output.h"
#include "meta.h"

#include "stream.h"

__MPT_NAMESPACE_BEGIN

// streaminfo access
streaminfo::~streaminfo()
{
    _mpt_stream_setfile(this, -1, -1);
}
bool streaminfo::setFlags(int fl)
{
    if (fl & ~0xf0) return false;
    _fd |= fl;
    return true;
}

// stream data operations
stream::stream() : _mlen(0)
{ }
stream::~stream()
{
    mpt_stream_close(this);
}
int stream::flags() const
{
    return mpt_stream_flags(&this->_info) & 0xff;
}
int stream::errors() const {
    return MPT_stream_errors(mpt_stream_flags(&this->_info));
}
void stream::setError(int err)
{
    return mpt_stream_seterror(&this->_info, err);
}
bool stream::endline()
{
    int nl = (mpt_stream_flags(&this->_info) & 0xc000) >> 14;

    switch (nl) {
      case NewlineMac:  return mpt_stream_write(this, 1, "\r",   1);
      case NewlineUnix: return mpt_stream_write(this, 1, "\n",   1);
      case NewlineNet:  return mpt_stream_write(this, 1, "\r\n", 2);
      default: return false;
    }
}
void stream::setNewline(int nl, int what)
{
    return mpt_stream_setnewline(&this->_info, nl, what);
}
bool stream::open(const char *fn, const char *mode)
{
    if (!fn) { mpt_stream_close(this); return true; }
    return mpt_stream_open(this, fn, mode) < 0 ? false : true;
}

// stream class
Stream::Stream(const streaminfo *from) : _srm(0), _cid(0), _inputFile(-1), _idlen(0)
{
    if (!from) return;
    _srm = new stream;
    _mpt_stream_setfile(&_srm->_info, _mpt_stream_fread(from), _mpt_stream_fwrite(from));
    int flags = mpt_stream_flags(from);
    mpt_stream_setmode(_srm, flags & 0xff);
    _srm->setNewline(MPT_stream_newline_read(flags),  _srm->Read);
    _srm->setNewline(MPT_stream_newline_write(flags), _srm->Write);
}
Stream::~Stream()
{ }

// metatype interface
void Stream::unref()
{
    if (_srm) delete _srm;
    delete this;
}
int Stream::assign(const value *val)
{
    if (val) {
        return setProperty(0, 0);
    } else {
        return mpt_object_pset(this, 0, val);
    }
}
int Stream::conv(int type, void *ptr)
{
    static const char fmt[] = { output::Type, input::Type, IODevice::Type, 0 };
    const void *addr = 0;
    switch (type) {
      case 0: addr = fmt; type = Type;
      case metatype::Type: addr = static_cast<metatype *>(this); break;
      case output::Type: addr = static_cast<output *>(this); break;
      case input::Type: addr = static_cast<input *>(this); break;
      case IODevice::Type: addr = static_cast<IODevice *>(this); break;
      default: return BadType;
    }
    if (ptr) *reinterpret_cast<const void **>(ptr) = addr;
    return type;
}
// object interface
int Stream::property(struct property *pr) const
{
    if (!pr) {
        return Type;
    }
    const char *name;
    intptr_t pos;

    if (!(name = pr->name)) {
        if (((pos = (intptr_t) pr->desc) < 0)) {
            errno = EINVAL;
            return BadValue;
        }
    }
    else {
        // get stream interface types
        if (!*name) {
            static const char fmt[] = { output::Type, input::Type, IODevice::Type, 0 };
            pr->name = "stream";
            pr->desc = "interfaces to stream data";
            pr->val.fmt = fmt;
            pr->val.ptr = 0;
            return _srm ? mpt_stream_flags(&_srm->_info) : 0;
        }
    }
    intptr_t id = 0;
    if (name ? !strcasecmp(name, "idlen") : (pos == id++)) {
        pr->name = "idlen";
        pr->desc = "message id length";
        pr->val.fmt = "y";
        pr->val.ptr = &_idlen;
        return id;
    }
    return BadArgument;
}
int Stream::setProperty(const char *pr, metatype *src)
{
    if (!pr) {
        return _srm ? mpt_stream_setter(_srm, src) : BadOperation;
    }
    if (strcasecmp(pr, "idlen")) {
        if (_inputFile >= 0) {
            return BadOperation;
        }
        int ret;
        uint8_t l;

        if (!src) {
            ret = l = 0;
        } else {
            if ((ret = src->conv('y', &l)) < 0) return ret;
            if (l > sizeof(uintptr_t)) {
                return BadValue;
            }
        }
        _idlen = l;
        return ret;
    }
    return BadArgument;
}
bool Stream::open(const char *dest, const char *type)
{
    if (_inputFile >= 0) return false;
    if (!_srm) _srm = new stream;
    return mpt_stream_open(_srm, dest, type) < 0 ? false : true;
}
bool Stream::open(void *base, size_t len, int mode)
{
    if (_inputFile >= 0) {
        return false;
    }
    if (len && !base) {
        return false;
    }
    struct iovec data = { base, len };
    int ret;
    if (!_srm) _srm = new stream;
    switch (mode) {
      case stream::Read:  ret = mpt_stream_memory(_srm, &data, 0); break;
      case stream::Write: ret = mpt_stream_memory(_srm, 0, &data); break;
    default: return false;
    }
    if (ret < 0) {
        return false;
    }
    return true;
}
// IODevice interface
ssize_t Stream::write(size_t len, const void *data, size_t part)
{
    if (!_srm) {
        return BadArgument;
    }
    return mpt_stream_write(_srm, len, data, part);
}
ssize_t Stream::read(size_t len, void *data, size_t part)
{
    if (!_srm) {
        return BadArgument;
    }
    return mpt_stream_read(_srm, len, data, part);
}
int64_t Stream::pos()
{
    if (!_srm) {
        return BadArgument;
    }
    return mpt_stream_seek(_srm, 0, SEEK_CUR);
}
bool Stream::seek(int64_t pos)
{
    if (!_srm) {
        return BadArgument;
    }
    return mpt_stream_seek(_srm, pos, SEEK_SET) >= 0 ? true : false;
}
// input interface
int Stream::next(int what)
{
    if (!_srm) {
        return BadArgument;
    }
    int ret = mpt_stream_poll(_srm, what, 0);
    if (ret < 0) {
        _inputFile = -1;
    }
    return ret;
}
class Stream::Dispatch
{
public:
    Dispatch(Stream &s, EventHandler c, void *a) : srm(s), cmd(c), arg(a)
    { }
    int dispatch(const struct message *msg)
    {
        static const char _func[] = "mpt::Stream::dispatch";
        struct event ev;
        uint8_t idlen;

        if (!msg || !(idlen = srm._idlen)) {
            return cmd(arg, &ev);
        }
        uint8_t id[__UINT8_MAX__];
        int ret;

        struct message tmp = *msg;
        if (tmp.read(idlen, id) < idlen) {
            error(_func, "%s", MPT_tr("message id incomplete"));
        }
        if (id[0] & 0x80) {
            command *ans;
            uint64_t rid;
            id[0] &= 0x7f;
            if ((ret = mpt_message_buf2id(id, idlen, &rid)) < 0 || ret > (int) sizeof(ans->id)) {
                error(_func, "%s", MPT_tr("bad reply id"));
                return BadValue;
            }
            if ((ans = srm._wait.get(rid))) {
                return ans->cmd(ans->arg, &tmp);
            }
            error(_func, "%s (id = %08" PRIx64 ")", MPT_tr("unknown reply id"), rid);
            return BadValue;
        }
        reply_data::context *rc = 0;
        for (uint8_t i = 0; i < idlen; ++i) {
            if (!id[i]) {
                continue;
            }
            if (!(rc = srm._ctx.pointer())) {
                warning(_func, "%s", MPT_tr("no reply context"));
                break;
            }
            if (!rc->setData(idlen, id)) {
                error(_func, "%s", MPT_tr("reply context unusable"));
                return BadOperation;
            }
            break;
        }
        ev.reply = rc;
        ret = cmd(arg, &ev);
        if (rc && rc->active()) {
            struct msgtype mt(MessageAnswer, ret);
            struct message msg(&mt, sizeof(mt));
            id[0] |= 0x80;
            mpt_stream_reply(srm._srm, &msg, idlen, id);
        }
        return ret;
    }
protected:
    Stream &srm;
    EventHandler cmd;
    void *arg;
};
static int streamDispatch(void *ptr, const struct message *msg)
{
    Stream::Dispatch *sd = reinterpret_cast<Stream::Dispatch *>(ptr);
    return sd->dispatch(msg);
}
int Stream::dispatch(EventHandler cmd, void *arg)
{
    if (!_srm) {
        return BadArgument;
    }
    if (_srm->_mlen < 0
        && (_srm->_mlen = mpt_queue_recv(&_srm->_rd)) < 0) {
        if (_mpt_stream_fread(&_srm->_info) < 0) {
            return BadArgument;
        }
        return 0;
    }
    class Dispatch sd(*this, cmd, arg);
    return mpt_stream_dispatch(_srm, streamDispatch, &sd);
}
int Stream::_file()
{
    if (_inputFile >= 0) {
        return _inputFile;
    }
    if (!_srm) {
        return BadArgument;
    }
    if ((_inputFile = _mpt_stream_fread(&_srm->_info)) >= 0) {
        return _inputFile;
    }
    return _inputFile = _mpt_stream_fwrite(&_srm->_info);
}

ssize_t Stream::push(size_t len, const void *src)
{
    if (!_srm) {
        return BadArgument;
    }
    ssize_t curr;
    if (_idlen && !(_srm->flags() & MessageInProgress)) {
        uint8_t id[__UINT8_MAX__];
        mpt_message_id2buf(_cid, id, _idlen);
        if (mpt_stream_push(_srm, _idlen, id) < _idlen) {
            push(1, 0);
        }
    }
    if ((curr = mpt_stream_push(_srm, len, src)) < 0) {
        return curr;
    }
    if (!len) {
        _cid = 0;
    }
    else if (!src && _cid) {
        command *c;
        if ((c = _wait.get(_cid))) {
            c->cmd(c->arg, 0);
        }
    }
    return curr;
}
int Stream::sync(int timeout)
{
    if (!_srm || !_idlen) {
        return BadArgument;
    }
    return mpt_stream_sync(_srm, _idlen, &_wait, timeout);
}

int Stream::await(int (*rctl)(void *, const struct message *), void *rpar)
{
    if (!_idlen) {
        return BadArgument;
    }
    struct command *cmd;

    if (mpt_stream_flags(&_srm->_info) & _srm->MesgActive) {
        return MessageInProgress;
    }
    if (!rctl) {
        return 0;
    }
    if (!(cmd = _wait.next(_idlen))) {
        return BadOperation;
    }
    _cid = cmd->id;
    cmd->cmd = (int (*)(void *, void *)) rctl;
    cmd->arg = rpar;
    return 1;
}

int Stream::getchar()
{
    if (!_srm || _srm->_rd.encoded()) {
        return BadArgument;
    }
    if (_srm->_rd.len) {
        uint8_t *base = (uint8_t *) _srm->_rd.base;
        if (_srm->_rd.off >= _srm->_rd.max) {
            _srm->_rd.off = 0;
        }
        --_srm->_rd.len;
        return base[_srm->_rd.off++];
    }
    return IODevice::getchar();
}

__MPT_NAMESPACE_END

<|endoftext|>


<commit_before>//******************************************************************
//
// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// 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.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

//******************************************************************
// File name:
//     OCPlatform_impl.cpp
//
// Description: Implementation of the OCPlatform functionality.  It contains
// a singleton interface that is used only by the OCPlatform namespace and is the
// central entrance to the stack.
//
//
//
//*********************************************************************

#include "OCPlatform_impl.h"

#include <random>
#include <utility>
#include <functional>

#include "ocstack.h"

#include "OCPlatform.h"
#include "OCApi.h"
#include "OCException.h"
#include "OCUtilities.h"

#include "oc_logger.hpp"

namespace OC
{

    PlatformConfig& OCPlatform_impl::globalConfig()
    {
        static PlatformConfig s_config;
        return s_config;
    }

    void OCPlatform_impl::Configure(const PlatformConfig& config)
    {
        globalConfig() = config;
    }

    OCPlatform_impl& OCPlatform_impl::Instance()
    {
        static OCPlatform_impl platform(globalConfig());
        return platform;
    }

    void OCPlatform_impl::init(const PlatformConfig& config)
    {
        switch(config.mode)
        {
            case ModeType::Server:
                m_server = m_WrapperInstance->CreateServerWrapper(m_csdkLock, config);
                break;

            case ModeType::Client:
                m_client = m_WrapperInstance->CreateClientWrapper(m_csdkLock, config);
                break;

            case ModeType::Both:
                m_server = m_WrapperInstance->CreateServerWrapper(m_csdkLock, config);
                m_client = m_WrapperInstance->CreateClientWrapper(m_csdkLock, config);
                break;
         }
    }

    OCPlatform_impl::OCPlatform_impl(const PlatformConfig& config)
     : m_cfg             { config },
       m_WrapperInstance { make_unique<WrapperFactory>() },
       m_csdkLock        { std::make_shared<std::recursive_mutex>() }
    {
        init(m_cfg);
    }

    OCPlatform_impl::~OCPlatform_impl(void)
    {
    }

    OCStackResult OCPlatform_impl::setDefaultDeviceEntityHandler(EntityHandler entityHandler)
    {
        return checked_guard(m_server, &IServerWrapper::setDefaultDeviceEntityHandler,
                             entityHandler);
    }

    OCStackResult OCPlatform_impl::notifyAllObservers(OCResourceHandle resourceHandle,
                                                QualityOfService QoS)
    {
        return result_guard(OCNotifyAllObservers(resourceHandle,
                    static_cast<OCQualityOfService>(QoS)));
    }

    OCStackResult OCPlatform_impl::notifyAllObservers(OCResourceHandle resourceHandle)
    {
        return notifyAllObservers(resourceHandle, m_cfg.QoS);
    }

    OCStackResult OCPlatform_impl::notifyListOfObservers(OCResourceHandle resourceHandle,
                                       ObservationIds& observationIds,
                                       const std::shared_ptr<OCResourceResponse> pResponse)
    {
        return notifyListOfObservers(resourceHandle, observationIds, pResponse, m_cfg.QoS);
    }

    OCStackResult OCPlatform_impl::notifyListOfObservers(OCResourceHandle resourceHandle,
                                       ObservationIds& observationIds,
                                       const std::shared_ptr<OCResourceResponse> pResponse,
                                       QualityOfService QoS)
    {
        if(!pResponse)
        {
         return result_guard(OC_STACK_ERROR);
        }

        std::string payload(pResponse->getResourceRepresentation().getJSONRepresentation());

        return result_guard(
                   OCNotifyListOfObservers(resourceHandle,
                            &observationIds[0], observationIds.size(),
                            payload.c_str(),
                            static_cast<OCQualityOfService>(QoS)));
    }

    OCResource::Ptr OCPlatform_impl::constructResourceObject(const std::string& host,
                                                const std::string& uri,
                                                OCConnectivityType connectivityType,
                                                bool isObservable,
                                                const std::vector<std::string>& resourceTypes,
                                                const std::vector<std::string>& interfaces)
    {
        if(!m_client)
        {
            return std::shared_ptr<OCResource>();
        }

        return std::shared_ptr<OCResource>(new OCResource(m_client,
                                            host,
                                            uri, "", connectivityType,
                                            isObservable,
                                            resourceTypes,
                                            interfaces));
    }

    OCStackResult OCPlatform_impl::findResource(const std::string& host,
                                            const std::string& resourceName,
                                            OCConnectivityType connectivityType,
                                            FindCallback resourceHandler)
    {
        return findResource(host, resourceName, connectivityType, resourceHandler, m_cfg.QoS);
    }

    OCStackResult OCPlatform_impl::findResource(const std::string& host,
                                            const std::string& resourceName,
                                            OCConnectivityType connectivityType,
                                            FindCallback resourceHandler,
                                            QualityOfService QoS)
    {
        return checked_guard(m_client, &IClientWrapper::ListenForResource,
                             host, resourceName, connectivityType, resourceHandler, QoS);
    }

    OCStackResult OCPlatform_impl::getDeviceInfo(const std::string& host,
                                            const std::string& deviceURI,
                                            OCConnectivityType connectivityType,
                                            FindDeviceCallback deviceInfoHandler)
    {
        return result_guard(getDeviceInfo(host, deviceURI, connectivityType,
               deviceInfoHandler, m_cfg.QoS));
    }

    OCStackResult OCPlatform_impl::getDeviceInfo(const std::string& host,
                                            const std::string& deviceURI,
                                            OCConnectivityType connectivityType,
                                            FindDeviceCallback deviceInfoHandler,
                                            QualityOfService QoS)
    {
        return checked_guard(m_client, &IClientWrapper::ListenForDevice,
                             host, deviceURI, connectivityType, deviceInfoHandler, QoS);
    }

    OCStackResult OCPlatform_impl::getPlatformInfo(const std::string& host,
                                            const std::string& platformURI,
                                            OCConnectivityType connectivityType,
                                            FindPlatformCallback platformInfoHandler)
    {
        return result_guard(getPlatformInfo(host, platformURI, connectivityType,
               platformInfoHandler, m_cfg.QoS));
    }

    OCStackResult OCPlatform_impl::getPlatformInfo(const std::string& host,
                                            const std::string& platformURI,
                                            OCConnectivityType connectivityType,
                                            FindPlatformCallback platformInfoHandler,
                                            QualityOfService QoS)
    {
        return checked_guard(m_client, &IClientWrapper::ListenForDevice,
                             host, platformURI, connectivityType, platformInfoHandler, QoS);
    }

    OCStackResult OCPlatform_impl::registerResource(OCResourceHandle& resourceHandle,
                                            std::string& resourceURI,
                                            const std::string& resourceTypeName,
                                            const std::string& resourceInterface,
                                            EntityHandler entityHandler,
                                            uint8_t resourceProperty)
    {
        return checked_guard(m_server, &IServerWrapper::registerResource,
                             std::ref(resourceHandle), resourceURI, resourceTypeName,
                             resourceInterface, entityHandler, resourceProperty);
    }

    OCStackResult OCPlatform_impl::registerDeviceInfo(const OCDeviceInfo deviceInfo)
    {
        return checked_guard(m_server, &IServerWrapper::registerDeviceInfo, deviceInfo);
    }

    OCStackResult OCPlatform_impl::registerPlatformInfo(const OCPlatformInfo platformInfo)
    {
        return checked_guard(m_server, &IServerWrapper::registerPlatformInfo, platformInfo);
    }

    OCStackResult OCPlatform_impl::registerResource(OCResourceHandle& resourceHandle,
                                            const std::shared_ptr< OCResource > resource)
    {
        uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
        std::vector<std::string> resourceTypes = resource->getResourceTypes();

        return checked_guard(m_server, &IServerWrapper::registerResource,
                std::ref(resourceHandle), resource->uri(),
                resourceTypes[0]/*"core.remote"*/, DEFAULT_INTERFACE,
                (EntityHandler) nullptr, resourceProperty);
    }

    OCStackResult OCPlatform_impl::unregisterResource(const OCResourceHandle& resourceHandle) const
    {
        return checked_guard(m_server, &IServerWrapper::unregisterResource,
                             resourceHandle);
    }

    OCStackResult OCPlatform_impl::unbindResource(OCResourceHandle collectionHandle,
                                            OCResourceHandle resourceHandle)
    {
        return result_guard(OCUnBindResource(std::ref(collectionHandle), std::ref(resourceHandle)));
    }

    OCStackResult OCPlatform_impl::unbindResources(const OCResourceHandle collectionHandle,
                                            const std::vector<OCResourceHandle>& resourceHandles)
    {
        for(const auto& h : resourceHandles)
        {
           OCStackResult r;

           if(OC_STACK_OK != (r = result_guard(OCUnBindResource(collectionHandle, h))))
           {
               return r;
           }
        }

        return OC_STACK_OK;
    }

    OCStackResult OCPlatform_impl::bindResource(const OCResourceHandle collectionHandle,
                                            const OCResourceHandle resourceHandle)
    {
        return result_guard(OCBindResource(collectionHandle, resourceHandle));
    }

    OCStackResult OCPlatform_impl::bindResources(const OCResourceHandle collectionHandle,
                                            const std::vector<OCResourceHandle>& resourceHandles)
    {
        for(const auto& h : resourceHandles)
        {
           OCStackResult r;

           if(OC_STACK_OK != (r = result_guard(OCBindResource(collectionHandle, h))))
           {
               return r;
           }
        }

        return OC_STACK_OK;
    }

    OCStackResult OCPlatform_impl::bindTypeToResource(const OCResourceHandle& resourceHandle,
                                             const std::string& resourceTypeName) const
    {
        return checked_guard(m_server, &IServerWrapper::bindTypeToResource,
                             resourceHandle, resourceTypeName);
    }

    OCStackResult OCPlatform_impl::bindInterfaceToResource(const OCResourceHandle& resourceHandle,
                                             const std::string& resourceInterfaceName) const
    {
        return checked_guard(m_server, &IServerWrapper::bindInterfaceToResource,
                             resourceHandle, resourceInterfaceName);
    }

    OCStackResult OCPlatform_impl::startPresence(const unsigned int announceDurationSeconds)
    {
        return checked_guard(m_server, &IServerWrapper::startPresence,
                             announceDurationSeconds);
    }

    OCStackResult OCPlatform_impl::stopPresence()
    {
        return checked_guard(m_server, &IServerWrapper::stopPresence);
    }

    OCStackResult OCPlatform_impl::subscribePresence(OCPresenceHandle& presenceHandle,
                                            const std::string& host,
                                            OCConnectivityType connectivityType,
                                            SubscribeCallback presenceHandler)
    {
        return subscribePresence(presenceHandle, host, "", connectivityType, presenceHandler);
    }

    OCStackResult OCPlatform_impl::subscribePresence(OCPresenceHandle& presenceHandle,
                                            const std::string& host,
                                            const std::string& resourceType,
                                            OCConnectivityType connectivityType,
                                            SubscribeCallback presenceHandler)
    {
        return checked_guard(m_client, &IClientWrapper::SubscribePresence,
                             &presenceHandle, host, resourceType, connectivityType,
                             presenceHandler);
    }

    OCStackResult OCPlatform_impl::unsubscribePresence(OCPresenceHandle presenceHandle)
    {
        return checked_guard(m_client, &IClientWrapper::UnsubscribePresence,
                             std::ref(presenceHandle));
    }

    OCStackResult OCPlatform_impl::sendResponse(const std::shared_ptr<OCResourceResponse> pResponse)
    {
        return checked_guard(m_server, &IServerWrapper::sendResponse,
                             pResponse);
    }
} //namespace OC

<commit_msg>Fix issue the previous CreateResourceWithHost change<commit_after>//******************************************************************
//
// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// 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.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

//******************************************************************
// File name:
//     OCPlatform_impl.cpp
//
// Description: Implementation of the OCPlatform functionality.  It contains
// a singleton interface that is used only by the OCPlatform namespace and is the
// central entrance to the stack.
//
//
//
//*********************************************************************

#include "OCPlatform_impl.h"

#include <random>
#include <utility>
#include <functional>

#include "ocstack.h"

#include "OCPlatform.h"
#include "OCApi.h"
#include "OCException.h"
#include "OCUtilities.h"

#include "oc_logger.hpp"

namespace OC
{

    PlatformConfig& OCPlatform_impl::globalConfig()
    {
        static PlatformConfig s_config;
        return s_config;
    }

    void OCPlatform_impl::Configure(const PlatformConfig& config)
    {
        globalConfig() = config;
    }

    OCPlatform_impl& OCPlatform_impl::Instance()
    {
        static OCPlatform_impl platform(globalConfig());
        return platform;
    }

    void OCPlatform_impl::init(const PlatformConfig& config)
    {
        switch(config.mode)
        {
            case ModeType::Server:
                m_server = m_WrapperInstance->CreateServerWrapper(m_csdkLock, config);
                break;

            case ModeType::Client:
                m_client = m_WrapperInstance->CreateClientWrapper(m_csdkLock, config);
                break;

            case ModeType::Both:
                m_server = m_WrapperInstance->CreateServerWrapper(m_csdkLock, config);
                m_client = m_WrapperInstance->CreateClientWrapper(m_csdkLock, config);
                break;
         }
    }

    OCPlatform_impl::OCPlatform_impl(const PlatformConfig& config)
     : m_cfg             { config },
       m_WrapperInstance { make_unique<WrapperFactory>() },
       m_csdkLock        { std::make_shared<std::recursive_mutex>() }
    {
        init(m_cfg);
    }

    OCPlatform_impl::~OCPlatform_impl(void)
    {
    }

    OCStackResult OCPlatform_impl::setDefaultDeviceEntityHandler(EntityHandler entityHandler)
    {
        return checked_guard(m_server, &IServerWrapper::setDefaultDeviceEntityHandler,
                             entityHandler);
    }

    OCStackResult OCPlatform_impl::notifyAllObservers(OCResourceHandle resourceHandle,
                                                QualityOfService QoS)
    {
        return result_guard(OCNotifyAllObservers(resourceHandle,
                    static_cast<OCQualityOfService>(QoS)));
    }

    OCStackResult OCPlatform_impl::notifyAllObservers(OCResourceHandle resourceHandle)
    {
        return notifyAllObservers(resourceHandle, m_cfg.QoS);
    }

    OCStackResult OCPlatform_impl::notifyListOfObservers(OCResourceHandle resourceHandle,
                                       ObservationIds& observationIds,
                                       const std::shared_ptr<OCResourceResponse> pResponse)
    {
        return notifyListOfObservers(resourceHandle, observationIds, pResponse, m_cfg.QoS);
    }

    OCStackResult OCPlatform_impl::notifyListOfObservers(OCResourceHandle resourceHandle,
                                       ObservationIds& observationIds,
                                       const std::shared_ptr<OCResourceResponse> pResponse,
                                       QualityOfService QoS)
    {
        if(!pResponse)
        {
         return result_guard(OC_STACK_ERROR);
        }

        std::string payload(pResponse->getResourceRepresentation().getJSONRepresentation());

        return result_guard(
                   OCNotifyListOfObservers(resourceHandle,
                            &observationIds[0], observationIds.size(),
                            payload.c_str(),
                            static_cast<OCQualityOfService>(QoS)));
    }

    OCResource::Ptr OCPlatform_impl::constructResourceObject(const std::string& host,
                                                const std::string& uri,
                                                OCConnectivityType connectivityType,
                                                bool isObservable,
                                                const std::vector<std::string>& resourceTypes,
                                                const std::vector<std::string>& interfaces)
    {
        if(!m_client)
        {
            return std::shared_ptr<OCResource>();
        }

        return std::shared_ptr<OCResource>(new OCResource(m_client,
                                            host,
                                            uri, "", connectivityType,
                                            isObservable,
                                            resourceTypes,
                                            interfaces));
    }

    OCStackResult OCPlatform_impl::findResource(const std::string& host,
                                            const std::string& resourceName,
                                            OCConnectivityType connectivityType,
                                            FindCallback resourceHandler)
    {
        return findResource(host, resourceName, connectivityType, resourceHandler, m_cfg.QoS);
    }

    OCStackResult OCPlatform_impl::findResource(const std::string& host,
                                            const std::string& resourceName,
                                            OCConnectivityType connectivityType,
                                            FindCallback resourceHandler,
                                            QualityOfService QoS)
    {
        return checked_guard(m_client, &IClientWrapper::ListenForResource,
                             host, resourceName, connectivityType, resourceHandler, QoS);
    }

    OCStackResult OCPlatform_impl::getDeviceInfo(const std::string& host,
                                            const std::string& deviceURI,
                                            OCConnectivityType connectivityType,
                                            FindDeviceCallback deviceInfoHandler)
    {
        return result_guard(getDeviceInfo(host, deviceURI, connectivityType,
               deviceInfoHandler, m_cfg.QoS));
    }

    OCStackResult OCPlatform_impl::getDeviceInfo(const std::string& host,
                                            const std::string& deviceURI,
                                            OCConnectivityType connectivityType,
                                            FindDeviceCallback deviceInfoHandler,
                                            QualityOfService QoS)
    {
        return checked_guard(m_client, &IClientWrapper::ListenForDevice,
                             host, deviceURI, connectivityType, deviceInfoHandler, QoS);
    }

    OCStackResult OCPlatform_impl::getPlatformInfo(const std::string& host,
                                            const std::string& platformURI,
                                            OCConnectivityType connectivityType,
                                            FindPlatformCallback platformInfoHandler)
    {
        return result_guard(getPlatformInfo(host, platformURI, connectivityType,
               platformInfoHandler, m_cfg.QoS));
    }

    OCStackResult OCPlatform_impl::getPlatformInfo(const std::string& host,
                                            const std::string& platformURI,
                                            OCConnectivityType connectivityType,
                                            FindPlatformCallback platformInfoHandler,
                                            QualityOfService QoS)
    {
        return checked_guard(m_client, &IClientWrapper::ListenForDevice,
                             host, platformURI, connectivityType, platformInfoHandler, QoS);
    }

    OCStackResult OCPlatform_impl::registerResource(OCResourceHandle& resourceHandle,
                                            std::string& resourceURI,
                                            const std::string& resourceTypeName,
                                            const std::string& resourceInterface,
                                            EntityHandler entityHandler,
                                            uint8_t resourceProperty)
    {
        return checked_guard(m_server, &IServerWrapper::registerResource,
                             std::ref(resourceHandle), resourceURI, resourceTypeName,
                             resourceInterface, entityHandler, resourceProperty);
    }

    OCStackResult OCPlatform_impl::registerDeviceInfo(const OCDeviceInfo deviceInfo)
    {
        return checked_guard(m_server, &IServerWrapper::registerDeviceInfo, deviceInfo);
    }

    OCStackResult OCPlatform_impl::registerPlatformInfo(const OCPlatformInfo platformInfo)
    {
        return checked_guard(m_server, &IServerWrapper::registerPlatformInfo, platformInfo);
    }

    OCStackResult OCPlatform_impl::registerResource(OCResourceHandle& resourceHandle,
                                            const std::shared_ptr< OCResource > resource)
    {
        uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
        std::vector<std::string> resourceTypes = resource->getResourceTypes();

        return checked_guard(m_server, &IServerWrapper::registerResource,
                std::ref(resourceHandle), resource->host() + resource->uri(),
                resourceTypes[0]/*"core.remote"*/, DEFAULT_INTERFACE,
                (EntityHandler) nullptr, resourceProperty);
    }

    OCStackResult OCPlatform_impl::unregisterResource(const OCResourceHandle& resourceHandle) const
    {
        return checked_guard(m_server, &IServerWrapper::unregisterResource,
                             resourceHandle);
    }

    OCStackResult OCPlatform_impl::unbindResource(OCResourceHandle collectionHandle,
                                            OCResourceHandle resourceHandle)
    {
        return result_guard(OCUnBindResource(std::ref(collectionHandle), std::ref(resourceHandle)));
    }

    OCStackResult OCPlatform_impl::unbindResources(const OCResourceHandle collectionHandle,
                                            const std::vector<OCResourceHandle>& resourceHandles)
    {
        for(const auto& h : resourceHandles)
        {
           OCStackResult r;

           if(OC_STACK_OK != (r = result_guard(OCUnBindResource(collectionHandle, h))))
           {
               return r;
           }
        }

        return OC_STACK_OK;
    }

    OCStackResult OCPlatform_impl::bindResource(const OCResourceHandle collectionHandle,
                                            const OCResourceHandle resourceHandle)
    {
        return result_guard(OCBindResource(collectionHandle, resourceHandle));
    }

    OCStackResult OCPlatform_impl::bindResources(const OCResourceHandle collectionHandle,
                                            const std::vector<OCResourceHandle>& resourceHandles)
    {
        for(const auto& h : resourceHandles)
        {
           OCStackResult r;

           if(OC_STACK_OK != (r = result_guard(OCBindResource(collectionHandle, h))))
           {
               return r;
           }
        }

        return OC_STACK_OK;
    }

    OCStackResult OCPlatform_impl::bindTypeToResource(const OCResourceHandle& resourceHandle,
                                             const std::string& resourceTypeName) const
    {
        return checked_guard(m_server, &IServerWrapper::bindTypeToResource,
                             resourceHandle, resourceTypeName);
    }

    OCStackResult OCPlatform_impl::bindInterfaceToResource(const OCResourceHandle& resourceHandle,
                                             const std::string& resourceInterfaceName) const
    {
        return checked_guard(m_server, &IServerWrapper::bindInterfaceToResource,
                             resourceHandle, resourceInterfaceName);
    }

    OCStackResult OCPlatform_impl::startPresence(const unsigned int announceDurationSeconds)
    {
        return checked_guard(m_server, &IServerWrapper::startPresence,
                             announceDurationSeconds);
    }

    OCStackResult OCPlatform_impl::stopPresence()
    {
        return checked_guard(m_server, &IServerWrapper::stopPresence);
    }

    OCStackResult OCPlatform_impl::subscribePresence(OCPresenceHandle& presenceHandle,
                                            const std::string& host,
                                            OCConnectivityType connectivityType,
                                            SubscribeCallback presenceHandler)
    {
        return subscribePresence(presenceHandle, host, "", connectivityType, presenceHandler);
    }

    OCStackResult OCPlatform_impl::subscribePresence(OCPresenceHandle& presenceHandle,
                                            const std::string& host,
                                            const std::string& resourceType,
                                            OCConnectivityType connectivityType,
                                            SubscribeCallback presenceHandler)
    {
        return checked_guard(m_client, &IClientWrapper::SubscribePresence,
                             &presenceHandle, host, resourceType, connectivityType,
                             presenceHandler);
    }

    OCStackResult OCPlatform_impl::unsubscribePresence(OCPresenceHandle presenceHandle)
    {
        return checked_guard(m_client, &IClientWrapper::UnsubscribePresence,
                             std::ref(presenceHandle));
    }

    OCStackResult OCPlatform_impl::sendResponse(const std::shared_ptr<OCResourceResponse> pResponse)
    {
        return checked_guard(m_server, &IServerWrapper::sendResponse,
                             pResponse);
    }
} //namespace OC

<|endoftext|>


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

#include <QtDeclarative/qdeclarativeextensionplugin.h>
#include <QtDeclarative/qdeclarative.h>

#include "qdeclarativebatteryinfo_p.h"
#include "qdeclarativedeviceinfo_p.h"
#include <qdeviceprofile.h>
#include <qdisplayinfo.h>
#include <qinputdeviceinfo.h>
#include "qdeclarativenetworkinfo_p.h"
#include <qscreensaver.h>
#include "qdeclarativestorageinfo_p.h"

QT_BEGIN_NAMESPACE

class QSystemInfoDeclarativeModule : public QDeclarativeExtensionPlugin
{
    Q_OBJECT

public:
    virtual void registerTypes(const char *uri)
    {
        Q_ASSERT(QLatin1String(uri) == QLatin1String("QtSystemInfo"));

        int major = 5;
        int minor = 0;
        qmlRegisterType<QDeclarativeBatteryInfo>(uri, major, minor, "BatteryInfo");
        qmlRegisterType<QDeclarativeDeviceInfo>(uri, major, minor, "DeviceInfo");
        qmlRegisterType<QDeviceProfile>(uri, major, minor, "DeviceProfile");
        qmlRegisterType<QDisplayInfo>(uri, major, minor, "DisplayInfo");
        qmlRegisterType<QInputDeviceInfo>(uri, major, minor, "InputDeviceInfo");
        qmlRegisterType<QDeclarativeNetworkInfo>(uri, major, minor, "NetworkInfo");
        qmlRegisterType<QScreenSaver>(uri, major, minor, "ScreenSaver");
        qmlRegisterType<QDeclarativeStorageInfo>(uri, major, minor, "StorageInfo");
    }
};

QT_END_NAMESPACE

#include "qsysteminfo.moc"

Q_EXPORT_PLUGIN2(qsysteminfodeclarativemodule, QT_PREPEND_NAMESPACE(QSystemInfoDeclarativeModule))

/*!
    \qmlclass ScreenSaver QScreenSaver
    \inmodule QtSystemInfo
    \ingroup qml-systeminfo
    \brief The ScreenSaver element provides information of the screen saver.
*/

/*!
    \qmlproperty bool ScreenSaver::screenSaverEnabled

    This property holds whether or not the screen saver is enabled.

    On certain platforms, if screen saver is disabled, deep system sleep won't be automatically triggered,
    and the display won't be automatically turned off, etc.
 */
<commit_msg>Add the doc for QML DeviceProfile element.<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtSystems module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtDeclarative/qdeclarativeextensionplugin.h>
#include <QtDeclarative/qdeclarative.h>

#include "qdeclarativebatteryinfo_p.h"
#include "qdeclarativedeviceinfo_p.h"
#include <qdeviceprofile.h>
#include <qdisplayinfo.h>
#include <qinputdeviceinfo.h>
#include "qdeclarativenetworkinfo_p.h"
#include <qscreensaver.h>
#include "qdeclarativestorageinfo_p.h"

QT_BEGIN_NAMESPACE

class QSystemInfoDeclarativeModule : public QDeclarativeExtensionPlugin
{
    Q_OBJECT

public:
    virtual void registerTypes(const char *uri)
    {
        Q_ASSERT(QLatin1String(uri) == QLatin1String("QtSystemInfo"));

        int major = 5;
        int minor = 0;
        qmlRegisterType<QDeclarativeBatteryInfo>(uri, major, minor, "BatteryInfo");
        qmlRegisterType<QDeclarativeDeviceInfo>(uri, major, minor, "DeviceInfo");
        qmlRegisterType<QDeviceProfile>(uri, major, minor, "DeviceProfile");
        qmlRegisterType<QDisplayInfo>(uri, major, minor, "DisplayInfo");
        qmlRegisterType<QInputDeviceInfo>(uri, major, minor, "InputDeviceInfo");
        qmlRegisterType<QDeclarativeNetworkInfo>(uri, major, minor, "NetworkInfo");
        qmlRegisterType<QScreenSaver>(uri, major, minor, "ScreenSaver");
        qmlRegisterType<QDeclarativeStorageInfo>(uri, major, minor, "StorageInfo");
    }
};

QT_END_NAMESPACE

#include "qsysteminfo.moc"

Q_EXPORT_PLUGIN2(qsysteminfodeclarativemodule, QT_PREPEND_NAMESPACE(QSystemInfoDeclarativeModule))

/*!
    \qmlclass ScreenSaver QScreenSaver
    \inmodule QtSystemInfo
    \ingroup qml-systeminfo
    \brief The ScreenSaver element provides information of the screen saver.
*/

/*!
    \qmlproperty bool ScreenSaver::screenSaverEnabled

    This property holds whether or not the screen saver is enabled.

    On certain platforms, if screen saver is disabled, deep system sleep won't be automatically triggered,
    and the display won't be automatically turned off, etc.
 */

/*!
    \qmlclass DeviceProfile QDeviceProfile
    \inmodule QtSystemInfo
    \ingroup qml-systeminfo
    \brief The DeviceProfile element provides information for the profile of the device.
*/

/*!
    \qmlmethod bool DeviceProfile::isVibrationActivated()

    Returns true if the vibration is currently activated, or false otherwise.
 */

/*!
    \qmlmethod int DeviceProfile::messageRingtoneVolume()

    Returns the current message ringtone volume, from 0 to 100. If this information is unknown, or
    error occurs, -1 is returned.
 */

/*!
    \qmlmethod int DeviceProfile::voiceRingtoneVolume()

    Returns the current voice ringtone volume, from 0 to 100. If this information is unknown, or error
    occurs, -1 is returned.
 */

/*!
    \qmlproperty enum DeviceProfile::profileType()

    Returns the type of the current profile, possible types are:
    \list
    \o UnknownProfile    Profile unknown or on error.
    \o SilentProfile     Neither sound nor vibration is on.
    \o NormalProfile     Normal sound is on.
    \o VibrationProfile  Only vibration is on, and sound is off.
    \o BeepProfile       Only beep is on.
    \endlist
 */
<|endoftext|>