<commit_before>/*
* File:   Cell.cpp
* Author: Ozan YILDIZ
*
* Created on November 12, 2015, 4:06 PM
*/

#include <iostream>
#include <string>

#include "Cell.h"

Cell::Cell()
	: axisX(NULL), axisY(" "), who(NULL)
{

}

Cell::Cell(const Cell& copyCell)
{
	axisX = copyCell.axisX;
	axisY = copyCell.axisY;
	who = copyCell.who;
}

Cell::Cell(char newWho)
	: who(newWho)
{

}

Cell::Cell(int newAxisX, string newAxisY, char newWho)
	: axisX(newAxisX), axisY(newAxisY), who(newWho)
{

}

bool Cell::operator==(const Cell & temp)
{
	if (axisX == temp.axisX)
		if (axisY == temp.axisY)
			return true;

	return false;
}

<commit_msg>new Fundamental<commit_after>/*
* File:   Cell.cpp
* Author: Ozan YILDIZ
*
* Created on November 25, 2015, 4:06 PM
*/

#include <string>
#include <iostream>

#include "Cell.h"

Cell::Cell()
{
    who = '2';
}

Cell::Cell(const int newAxisX, const string newAxisY, const char newWho)
	: axisX(newAxisX), axisY(newAxisY), who(newWho)
{
}

Cell::Cell(const Cell& orig)
{
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   KWSys - Kitware System Library
  Module:    Glob.cxx

  Copyright (c) Kitware, Inc., Insight Consortium.  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Glob.hxx)

#include KWSYS_HEADER(Configure.hxx)

#include KWSYS_HEADER(RegularExpression.hxx)
#include KWSYS_HEADER(SystemTools.hxx)
#include KWSYS_HEADER(Directory.hxx)
#include KWSYS_HEADER(stl/string)
#include KWSYS_HEADER(stl/vector)

// Work-around CMake dependency scanning limitation.  This must
// duplicate the above list of headers.
#if 0
# include "Glob.hxx.in"
# include "Configure.hxx.in"
# include "RegularExpression.hxx.in"
# include "SystemTools.hxx.in"
# include "kwsys_stl.hxx.in"
# include "kwsys_stl_string.hxx.in"
#endif

#include <ctype.h>
#include <stdio.h>
#include <string.h>
namespace KWSYS_NAMESPACE
{
#if defined( _WIN32 ) || defined( APPLE ) || defined( __CYGWIN__ )
  // On Windows and apple, no difference between lower and upper case
  #define KWSYS_GLOB_CASE_INDEPENDENT
#endif

#if defined( _WIN32 ) || defined( __CYGWIN__ )
  // Handle network paths
  #define KWSYS_GLOB_SUPPORT_NETWORK_PATHS
#endif

//----------------------------------------------------------------------------
class GlobInternals
{
public:
  kwsys_stl::vector<kwsys_stl::string> Files;
  kwsys_stl::vector<kwsys::RegularExpression> Expressions;
  kwsys_stl::vector<kwsys_stl::string> TextExpressions;
};

//----------------------------------------------------------------------------
Glob::Glob()
{
  m_Internals = new GlobInternals;
  m_Recurse = false;
}

//----------------------------------------------------------------------------
Glob::~Glob()
{
  delete m_Internals;
}

//----------------------------------------------------------------------------
void Glob::Escape(int ch, char* buffer)
{
  if (! (
      'a' <= ch && ch <= 'z' ||
      'A' <= ch && ch <= 'Z' ||
      '0' <= ch && ch <= '9') )
    {
    sprintf(buffer, "\\%c", ch);
    }
  else
    {
#if defined( KWSYS_GLOB_CASE_INDEPENDENT )
    // On Windows and apple, no difference between lower and upper case
    sprintf(buffer, "%c", tolower(ch));
#else
    sprintf(buffer, "%c", ch);
#endif
    }
}

//----------------------------------------------------------------------------
kwsys_stl::vector<kwsys_stl::string>& Glob::GetFiles()
{
  return m_Internals->Files;
}

//----------------------------------------------------------------------------
kwsys_stl::string Glob::ConvertExpression(const kwsys_stl::string& expr)
{

  kwsys_stl::string::size_type i = 0;
  kwsys_stl::string::size_type n = expr.size();

  kwsys_stl::string res = "^";
  kwsys_stl::string stuff = "";

  while ( i < n )
    {
    int c = expr[i];
    i = i+1;
    if ( c == '*' )
      {
      res = res + ".*";
      }
    else if ( c == '?' )
      {
      res = res + ".";
      }
    else if ( c == '[' )
      {
      kwsys_stl::string::size_type j = i;
      if ( j < n && ( expr[j] == '!' || expr[j] == '^' ) )
        {
        j = j+1;
        }
      if ( j < n && expr[j] == ']' )
        {
        j = j+1;
        }
      while ( j < n && expr[j] != ']' )
        {
        j = j+1;
        }
      if ( j >= n )
        {
        res = res + "\\[";
        }
      else
        {
        stuff = "";
        kwsys_stl::string::size_type cc;
        for ( cc = i; cc < j; cc ++ )
          {
          if ( expr[cc] == '\\' )
            {
            stuff += "\\\\";
            }
          else
            {
            stuff += expr[cc];
            }
          }
        i = j+1;
        if ( stuff[0] == '!' || stuff[0] == '^' )
          {
          stuff = '^' + stuff.substr(1);
          }
        else if ( stuff[0] == '^' )
          {
          stuff = '\\' + stuff;
          }
        res = res + "[" + stuff + "]";
        }
      }
    else
      {
      char buffer[100];
      buffer[0] = 0;
      this->Escape(c, buffer);
      res = res + buffer;
      }
    }
  return res + "$";
}

//----------------------------------------------------------------------------
void Glob::RecurseDirectory(kwsys_stl::string::size_type start,
  const kwsys_stl::string& dir, bool dir_only)
{
  kwsys::Directory d;
  if ( !d.Load(dir.c_str()) )
    {
    return;
    }
  unsigned long cc;
  kwsys_stl::string fullname;
  kwsys_stl::string realname;
  kwsys_stl::string fname;
  for ( cc = 0; cc < d.GetNumberOfFiles(); cc ++ )
    {
    fname = d.GetFile(cc);
    if ( strcmp(fname.c_str(), ".") == 0 ||
      strcmp(fname.c_str(), "..") == 0  )
      {
      continue;
      }

    if ( start == 0 )
      {
      realname = dir + fname;
      }
    else
      {
      realname = dir + "/" + fname;
      }

#if defined( KWSYS_GLOB_CASE_INDEPENDENT )
    // On Windows and apple, no difference between lower and upper case
    fname = kwsys::SystemTools::LowerCase(fname);
#endif

    if ( start == 0 )
      {
      fullname = dir + fname;
      }
    else
      {
      fullname = dir + "/" + fname;
      }

    if ( !dir_only || !kwsys::SystemTools::FileIsDirectory(realname.c_str()) )
      {
      if ( m_Internals->Expressions[m_Internals->Expressions.size()-1].find(fname.c_str()) )
        {
        m_Internals->Files.push_back(realname);
        }
      }
    if ( kwsys::SystemTools::FileIsDirectory(realname.c_str()) )
      {
      this->RecurseDirectory(start+1, realname, dir_only);
      }
    }
}

//----------------------------------------------------------------------------
void Glob::ProcessDirectory(kwsys_stl::string::size_type start,
  const kwsys_stl::string& dir, bool dir_only)
{
  //kwsys_ios::cout << "ProcessDirectory: " << dir << kwsys_ios::endl;
  bool last = ( start == m_Internals->Expressions.size()-1 );
  if ( last && m_Recurse )
    {
    this->RecurseDirectory(start, dir, dir_only);
    return;
    }
  kwsys::Directory d;
  if ( !d.Load(dir.c_str()) )
    {
    return;
    }
  unsigned long cc;
  kwsys_stl::string fullname;
  kwsys_stl::string realname;
  kwsys_stl::string fname;
  for ( cc = 0; cc < d.GetNumberOfFiles(); cc ++ )
    {
    fname = d.GetFile(cc);
    if ( strcmp(fname.c_str(), ".") == 0 ||
      strcmp(fname.c_str(), "..") == 0  )
      {
      continue;
      }

    if ( start == 0 )
      {
      realname = dir + fname;
      }
    else
      {
      realname = dir + "/" + fname;
      }

#if defined( KWSYS_GLOB_CASE_INDEPENDENT )
    // On Windows and apple, no difference between lower and upper case
    fname = kwsys::SystemTools::LowerCase(fname);
#endif

    if ( start == 0 )
      {
      fullname = dir + fname;
      }
    else
      {
      fullname = dir + "/" + fname;
      }

    //kwsys_ios::cout << "Look at file: " << fname << kwsys_ios::endl;
    //kwsys_ios::cout << "Match: " << m_Internals->TextExpressions[start].c_str() << kwsys_ios::endl;
    //kwsys_ios::cout << "Full name: " << fullname << kwsys_ios::endl;

    if ( (!dir_only || !last) && !kwsys::SystemTools::FileIsDirectory(realname.c_str()) )
      {
      continue;
      }

    if ( m_Internals->Expressions[start].find(fname.c_str()) )
      {
      if ( last )
        {
        m_Internals->Files.push_back(realname);
        }
      else
        {
        this->ProcessDirectory(start+1, realname + "/", dir_only);
        }
      }
    }
}

//----------------------------------------------------------------------------
bool Glob::FindFiles(const kwsys_stl::string& inexpr)
{
  kwsys_stl::string cexpr;
  kwsys_stl::string::size_type cc;
  kwsys_stl::string expr = inexpr;

  m_Internals->Expressions.clear();
  m_Internals->Files.clear();

  if ( !kwsys::SystemTools::FileIsFullPath(expr.c_str()) )
    {
    expr = kwsys::SystemTools::GetCurrentWorkingDirectory();
    expr += "/" + inexpr;
    }
  kwsys_stl::string fexpr = expr;

  int skip = 0;
  int last_slash = 0;
  for ( cc = 0; cc < expr.size(); cc ++ )
    {
    if ( cc > 0 && expr[cc] == '/' && expr[cc-1] != '\\' )
      {
      last_slash = cc;
      }
    if ( cc > 0 &&
      (expr[cc] == '[' || expr[cc] == '?' || expr[cc] == '*') &&
      expr[cc-1] != '\\' )
      {
      break;
      }
    }
  if ( last_slash > 0 )
    {
    //kwsys_ios::cout << "I can skip: " << fexpr.substr(0, last_slash) << kwsys_ios::endl;
    skip = last_slash;
    }
  if ( skip == 0 )
    {
#if defined( KWSYS_GLOB_SUPPORT_NETWORK_PATHS )
    // Handle network paths
    if ( expr[0] == '/' && expr[1] == '/' )
      {
      int cnt = 0;
      for ( cc = 2; cc < expr.size(); cc ++ )
        {
        if ( expr[cc] == '/' )
          {
          cnt ++;
          if ( cnt == 2 )
            {
            break;
            }
          }
        }
      skip = cc + 1;
      }
    else
#endif
      // Handle drive letters on Windows
      if ( expr[1] == ':' && expr[0] != '/' )
        {
        skip = 2;
        }
    }

  if ( skip > 0 )
    {
    expr = expr.substr(skip);
    }

  cexpr = "";
  for ( cc = 0; cc < expr.size(); cc ++ )
    {
    int ch = expr[cc];
    if ( ch == '/' )
      {
      if ( cexpr.size() > 0 )
        {
        this->AddExpression(cexpr.c_str());
        }
      cexpr = "";
      }
    else
      {
      cexpr.append(1, (char)ch);
      }
    }
  if ( cexpr.size() > 0 )
    {
    this->AddExpression(cexpr.c_str());
    }

  // Handle network paths
  if ( skip > 0 )
    {
    this->ProcessDirectory(0, fexpr.substr(0, skip) + "/",
      true);
    }
  else
    {
    this->ProcessDirectory(0, "/", true);
    }
  return true;
}

void Glob::AddExpression(const char* expr)
{
  m_Internals->Expressions.push_back(
    kwsys::RegularExpression(
      this->ConvertExpression(expr).c_str()));
  m_Internals->TextExpressions.push_back(this->ConvertExpression(expr));
}

} // namespace KWSYS_NAMESPACE

<commit_msg>ENH: add missing cmake include<commit_after>/*=========================================================================

  Program:   KWSys - Kitware System Library
  Module:    Glob.cxx

  Copyright (c) Kitware, Inc., Insight Consortium.  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Glob.hxx)

#include KWSYS_HEADER(Configure.hxx)

#include KWSYS_HEADER(RegularExpression.hxx)
#include KWSYS_HEADER(SystemTools.hxx)
#include KWSYS_HEADER(Directory.hxx)
#include KWSYS_HEADER(stl/string)
#include KWSYS_HEADER(stl/vector)

// Work-around CMake dependency scanning limitation.  This must
// duplicate the above list of headers.
#if 0
# include "Glob.hxx.in"
# include "Directory.hxx.in"
# include "Configure.hxx.in"
# include "RegularExpression.hxx.in"
# include "SystemTools.hxx.in"
# include "kwsys_stl.hxx.in"
# include "kwsys_stl_string.hxx.in"
#endif

#include <ctype.h>
#include <stdio.h>
#include <string.h>
namespace KWSYS_NAMESPACE
{
#if defined( _WIN32 ) || defined( APPLE ) || defined( __CYGWIN__ )
  // On Windows and apple, no difference between lower and upper case
  #define KWSYS_GLOB_CASE_INDEPENDENT
#endif

#if defined( _WIN32 ) || defined( __CYGWIN__ )
  // Handle network paths
  #define KWSYS_GLOB_SUPPORT_NETWORK_PATHS
#endif

//----------------------------------------------------------------------------
class GlobInternals
{
public:
  kwsys_stl::vector<kwsys_stl::string> Files;
  kwsys_stl::vector<kwsys::RegularExpression> Expressions;
  kwsys_stl::vector<kwsys_stl::string> TextExpressions;
};

//----------------------------------------------------------------------------
Glob::Glob()
{
  m_Internals = new GlobInternals;
  m_Recurse = false;
}

//----------------------------------------------------------------------------
Glob::~Glob()
{
  delete m_Internals;
}

//----------------------------------------------------------------------------
void Glob::Escape(int ch, char* buffer)
{
  if (! (
      'a' <= ch && ch <= 'z' ||
      'A' <= ch && ch <= 'Z' ||
      '0' <= ch && ch <= '9') )
    {
    sprintf(buffer, "\\%c", ch);
    }
  else
    {
#if defined( KWSYS_GLOB_CASE_INDEPENDENT )
    // On Windows and apple, no difference between lower and upper case
    sprintf(buffer, "%c", tolower(ch));
#else
    sprintf(buffer, "%c", ch);
#endif
    }
}

//----------------------------------------------------------------------------
kwsys_stl::vector<kwsys_stl::string>& Glob::GetFiles()
{
  return m_Internals->Files;
}

//----------------------------------------------------------------------------
kwsys_stl::string Glob::ConvertExpression(const kwsys_stl::string& expr)
{

  kwsys_stl::string::size_type i = 0;
  kwsys_stl::string::size_type n = expr.size();

  kwsys_stl::string res = "^";
  kwsys_stl::string stuff = "";

  while ( i < n )
    {
    int c = expr[i];
    i = i+1;
    if ( c == '*' )
      {
      res = res + ".*";
      }
    else if ( c == '?' )
      {
      res = res + ".";
      }
    else if ( c == '[' )
      {
      kwsys_stl::string::size_type j = i;
      if ( j < n && ( expr[j] == '!' || expr[j] == '^' ) )
        {
        j = j+1;
        }
      if ( j < n && expr[j] == ']' )
        {
        j = j+1;
        }
      while ( j < n && expr[j] != ']' )
        {
        j = j+1;
        }
      if ( j >= n )
        {
        res = res + "\\[";
        }
      else
        {
        stuff = "";
        kwsys_stl::string::size_type cc;
        for ( cc = i; cc < j; cc ++ )
          {
          if ( expr[cc] == '\\' )
            {
            stuff += "\\\\";
            }
          else
            {
            stuff += expr[cc];
            }
          }
        i = j+1;
        if ( stuff[0] == '!' || stuff[0] == '^' )
          {
          stuff = '^' + stuff.substr(1);
          }
        else if ( stuff[0] == '^' )
          {
          stuff = '\\' + stuff;
          }
        res = res + "[" + stuff + "]";
        }
      }
    else
      {
      char buffer[100];
      buffer[0] = 0;
      this->Escape(c, buffer);
      res = res + buffer;
      }
    }
  return res + "$";
}

//----------------------------------------------------------------------------
void Glob::RecurseDirectory(kwsys_stl::string::size_type start,
  const kwsys_stl::string& dir, bool dir_only)
{
  kwsys::Directory d;
  if ( !d.Load(dir.c_str()) )
    {
    return;
    }
  unsigned long cc;
  kwsys_stl::string fullname;
  kwsys_stl::string realname;
  kwsys_stl::string fname;
  for ( cc = 0; cc < d.GetNumberOfFiles(); cc ++ )
    {
    fname = d.GetFile(cc);
    if ( strcmp(fname.c_str(), ".") == 0 ||
      strcmp(fname.c_str(), "..") == 0  )
      {
      continue;
      }

    if ( start == 0 )
      {
      realname = dir + fname;
      }
    else
      {
      realname = dir + "/" + fname;
      }

#if defined( KWSYS_GLOB_CASE_INDEPENDENT )
    // On Windows and apple, no difference between lower and upper case
    fname = kwsys::SystemTools::LowerCase(fname);
#endif

    if ( start == 0 )
      {
      fullname = dir + fname;
      }
    else
      {
      fullname = dir + "/" + fname;
      }

    if ( !dir_only || !kwsys::SystemTools::FileIsDirectory(realname.c_str()) )
      {
      if ( m_Internals->Expressions[m_Internals->Expressions.size()-1].find(fname.c_str()) )
        {
        m_Internals->Files.push_back(realname);
        }
      }
    if ( kwsys::SystemTools::FileIsDirectory(realname.c_str()) )
      {
      this->RecurseDirectory(start+1, realname, dir_only);
      }
    }
}

//----------------------------------------------------------------------------
void Glob::ProcessDirectory(kwsys_stl::string::size_type start,
  const kwsys_stl::string& dir, bool dir_only)
{
  //kwsys_ios::cout << "ProcessDirectory: " << dir << kwsys_ios::endl;
  bool last = ( start == m_Internals->Expressions.size()-1 );
  if ( last && m_Recurse )
    {
    this->RecurseDirectory(start, dir, dir_only);
    return;
    }
  kwsys::Directory d;
  if ( !d.Load(dir.c_str()) )
    {
    return;
    }
  unsigned long cc;
  kwsys_stl::string fullname;
  kwsys_stl::string realname;
  kwsys_stl::string fname;
  for ( cc = 0; cc < d.GetNumberOfFiles(); cc ++ )
    {
    fname = d.GetFile(cc);
    if ( strcmp(fname.c_str(), ".") == 0 ||
      strcmp(fname.c_str(), "..") == 0  )
      {
      continue;
      }

    if ( start == 0 )
      {
      realname = dir + fname;
      }
    else
      {
      realname = dir + "/" + fname;
      }

#if defined( KWSYS_GLOB_CASE_INDEPENDENT )
    // On Windows and apple, no difference between lower and upper case
    fname = kwsys::SystemTools::LowerCase(fname);
#endif

    if ( start == 0 )
      {
      fullname = dir + fname;
      }
    else
      {
      fullname = dir + "/" + fname;
      }

    //kwsys_ios::cout << "Look at file: " << fname << kwsys_ios::endl;
    //kwsys_ios::cout << "Match: " << m_Internals->TextExpressions[start].c_str() << kwsys_ios::endl;
    //kwsys_ios::cout << "Full name: " << fullname << kwsys_ios::endl;

    if ( (!dir_only || !last) && !kwsys::SystemTools::FileIsDirectory(realname.c_str()) )
      {
      continue;
      }

    if ( m_Internals->Expressions[start].find(fname.c_str()) )
      {
      if ( last )
        {
        m_Internals->Files.push_back(realname);
        }
      else
        {
        this->ProcessDirectory(start+1, realname + "/", dir_only);
        }
      }
    }
}

//----------------------------------------------------------------------------
bool Glob::FindFiles(const kwsys_stl::string& inexpr)
{
  kwsys_stl::string cexpr;
  kwsys_stl::string::size_type cc;
  kwsys_stl::string expr = inexpr;

  m_Internals->Expressions.clear();
  m_Internals->Files.clear();

  if ( !kwsys::SystemTools::FileIsFullPath(expr.c_str()) )
    {
    expr = kwsys::SystemTools::GetCurrentWorkingDirectory();
    expr += "/" + inexpr;
    }
  kwsys_stl::string fexpr = expr;

  int skip = 0;
  int last_slash = 0;
  for ( cc = 0; cc < expr.size(); cc ++ )
    {
    if ( cc > 0 && expr[cc] == '/' && expr[cc-1] != '\\' )
      {
      last_slash = cc;
      }
    if ( cc > 0 &&
      (expr[cc] == '[' || expr[cc] == '?' || expr[cc] == '*') &&
      expr[cc-1] != '\\' )
      {
      break;
      }
    }
  if ( last_slash > 0 )
    {
    //kwsys_ios::cout << "I can skip: " << fexpr.substr(0, last_slash) << kwsys_ios::endl;
    skip = last_slash;
    }
  if ( skip == 0 )
    {
#if defined( KWSYS_GLOB_SUPPORT_NETWORK_PATHS )
    // Handle network paths
    if ( expr[0] == '/' && expr[1] == '/' )
      {
      int cnt = 0;
      for ( cc = 2; cc < expr.size(); cc ++ )
        {
        if ( expr[cc] == '/' )
          {
          cnt ++;
          if ( cnt == 2 )
            {
            break;
            }
          }
        }
      skip = cc + 1;
      }
    else
#endif
      // Handle drive letters on Windows
      if ( expr[1] == ':' && expr[0] != '/' )
        {
        skip = 2;
        }
    }

  if ( skip > 0 )
    {
    expr = expr.substr(skip);
    }

  cexpr = "";
  for ( cc = 0; cc < expr.size(); cc ++ )
    {
    int ch = expr[cc];
    if ( ch == '/' )
      {
      if ( cexpr.size() > 0 )
        {
        this->AddExpression(cexpr.c_str());
        }
      cexpr = "";
      }
    else
      {
      cexpr.append(1, (char)ch);
      }
    }
  if ( cexpr.size() > 0 )
    {
    this->AddExpression(cexpr.c_str());
    }

  // Handle network paths
  if ( skip > 0 )
    {
    this->ProcessDirectory(0, fexpr.substr(0, skip) + "/",
      true);
    }
  else
    {
    this->ProcessDirectory(0, "/", true);
    }
  return true;
}

void Glob::AddExpression(const char* expr)
{
  m_Internals->Expressions.push_back(
    kwsys::RegularExpression(
      this->ConvertExpression(expr).c_str()));
  m_Internals->TextExpressions.push_back(this->ConvertExpression(expr));
}

} // namespace KWSYS_NAMESPACE

<|endoftext|>


<commit_before>#include <stdint.h>
#include <vector>
#include <string>
#include "HPACK.h"
#include "hpack_table.h"

uint16_t
encode_int(uint8_t* &dst, uint32_t I, uint8_t N) {
    if (I < (1 << N)-1) {
        dst = new uint8_t[1];
        *dst = I;
        return 1;
    }

    I -= (1 << N)-1;
    uint16_t i;
    uint32_t tmpI = I;
    for (i = 1; tmpI >= 128; i++) {
        tmpI = tmpI >> 7;
    } // check length

    dst = new uint8_t[i+1];
    *dst =  (1 << N) - 1;
    uint8_t j = 1;
    for (; I >= 128; j++) {
        *(dst+j) = (I & 0x7f) | 0x80;
        I = I >> 7;
    }
    *(dst+j) = I;

    return i+1;
}

int64_t
hpack_encode(uint8_t* buf, std::vector<header> headers, bool from_sTable, bool from_dTable, bool is_huffman, Table* table, int dynamic_table_size) {
    uint16_t len;
    uint8_t* d_table_size;
    if (dynamic_table_size != -1) {
        len = encode_int(d_table_size, dynamic_table_size, 5);
        *d_table_size |= 0x20;
        //delete d_table_size;
    }
    for (header h : headers) {
        int index;
        bool match = table->find_header(index, h);
        if (from_sTable && match) {
            uint8_t index_len = 8;
            uint8_t mask = 0;
            uint8_t* content;
            if (from_dTable) {
                index_len = 7;
                mask = 0x80;
            } else {
                content = table->pack_string(h.second, is_huffman); // temporally
            }
            uint8_t* intRep;
            len = encode_int(intRep, index, index_len);
            *intRep |= mask;
            // append gub and intRep
        } else if (from_sTable && !match && index > 0) {
            uint8_t index_len = 4;
            uint8_t mask = 0;
            if (from_dTable) {
                index_len = 6;
                mask = 0x40;
                table->add_header(h);
            }
        }
    }
    return 0;
}

uint32_t
decode_int(uint8_t* buf, uint8_t N) {
    uint32_t I = *buf & ((1 << N) - 1);
    if (I == (1 << N) -1) {
        int M = 0;
        do {
            I += (*(++buf) & 0x7f) << M;
            M += 7;
        }
        while (*buf & 0x80);
    }
    return I;
}

std::vector< header >
hpack_decode(uint8_t* buf, Table* table) {
    std::vector< header > headers;
    while (*buf != '\0') {
        bool isIndexed = 0;
        bool isIncremental = 0;
        uint32_t index;
        if ((*buf & 0xe0) == 0x20) {
            // 7/3 Header table Size Update
            uint32_t dst = decode_int(buf, 5);
            table->set_dynamic_table_size(dst);
        }

        if ((*buf & 0x80) > 0)  {
            // 7.1 Indexwd Header Field
            if ((*buf & 0x7f) == 0) {
                // error
            }
            l = decode_int(index, ++buf, 7);
            isIndexed = true;
        } else {
            if ((*buf & 0xc0) == 0x40) {
                // 7.2.1 Literal Header Field with Incremental Indexing
                l = decode_int(index, ++buf, 6);
                isIncremental = true;
            } else if ((*buf & 0xf0) == 0xf0) {
                l = decode_int(index, ++buf, 4);
            } else {
                l = decode_int(index, ++buf, 4);
            }
        }
        index = decode_int(++buf, nLen);
        header h = table->parse_header(index, buf, isIndexed);
        //buf += l;
        if (isIncremental) {
            table->add_header(h);
        }
        headers.push_back(h);
    }
    return headers;
}
<commit_msg>improve code<commit_after>#include <stdint.h>
#include <vector>
#include <string>
#include "HPACK.h"
#include "hpack_table.h"

uint16_t
encode_int(uint8_t* &dst, uint32_t I, uint8_t N) {
    if (I < (1 << N)-1) {
        dst = new uint8_t[1];
        *dst = I;
        return 1;
    }

    I -= (1 << N)-1;
    uint16_t i;
    uint32_t tmpI = I;
    for (i = 1; tmpI >= 128; i++) {
        tmpI = tmpI >> 7;
    } // check length

    dst = new uint8_t[i+1];
    *dst =  (1 << N) - 1;
    uint8_t j = 1;
    for (; I >= 128; j++) {
        *(dst+j) = (I & 0x7f) | 0x80;
        I = I >> 7;
    }
    *(dst+j) = I;

    return i+1;
}

int64_t
hpack_encode(uint8_t* buf, std::vector<header> headers, bool from_sTable, bool from_dTable, bool is_huffman, Table* table, int dynamic_table_size) {
    uint16_t len;
    uint8_t* d_table_size;
    if (dynamic_table_size != -1) {
        len = encode_int(d_table_size, dynamic_table_size, 5);
        *d_table_size |= 0x20;
        //delete d_table_size;
    }
    for (header h : headers) {
        int index;
        bool match = table->find_header(index, h);
        if (from_sTable && match) {
            uint8_t index_len = 8;
            uint8_t mask = 0;
            uint8_t* content;
            if (from_dTable) {
                index_len = 7;
                mask = 0x80;
            } else {
                content = table->pack_string(h.second, is_huffman); // temporally
            }
            uint8_t* intRep;
            len = encode_int(intRep, index, index_len);
            *intRep |= mask;
            // append gub and intRep
        } else if (from_sTable && !match && index > 0) {
            uint8_t index_len = 4;
            uint8_t mask = 0;
            if (from_dTable) {
                index_len = 6;
                mask = 0x40;
                table->add_header(h);
            }
        }
    }
    return 0;
}

uint32_t
decode_int(uint8_t* buf, uint8_t N) {
    uint32_t I = *buf & ((1 << N) - 1);
    if (I == (1 << N) -1) {
        int M = 0;
        do {
            I += (*(++buf) & 0x7f) << M;
            M += 7;
        }
        while (*buf & 0x80);
    }
    return I;
}

std::vector< header >
hpack_decode(uint8_t* buf, Table* table) {
    std::vector< header > headers;
    while (*buf != '\0') {
        bool isIndexed = 0;
        uint32_t index;
        if ((*buf & 0xe0) == 0x20) {
            // 7/3 Header table Size Update
            uint32_t dst = decode_int(buf, 5);
            table->set_dynamic_table_size(dst);
        }

        uint8_t nLen = 0;
        if ((*buf & 0x80) > 0)  {
            // 7.1 Indexwd Header Field
            if ((*buf & 0x7f) == 0) {
                // error
            }
            nLen = 7;
            isIndexed = true;
        } else {
            if ((*buf & 0xc0) == 0x40) {
                // 7.2.1 Literal Header Field with Incremental Indexing
                nLen = 6;
            } else {
                // when buf[cursor]&0xf0 == 0xf0
                // 7.2.2 Literal Header Field without Indexing
                // else
                // 7.2.3 Literal Header Field never Indexed
                nLen = 4;
            }
        }
        index = decode_int(++buf, nLen);
        header h = table->parse_header(index, buf, isIndexed);
        if (nLen == 6) {
            table->add_header(h);
        }
        headers.push_back(h);
    }
    return headers;
}
<|endoftext|>


<commit_before>class Item {

};<commit_msg>item class<commit_after>class Item {

};<|endoftext|>


<commit_before>/*
#include <vector>
#include <ostream>

namespace Graph
{
	template <class Key, Value> class Node
	{//A single edge of a graph.
		private:
			Key key;
			Value value;
			Node left, right;
			int N;

		public:
			Node( Key newKey, Value newValue, int newN );//Constructor with values.
			int size() const;//Return the size.
			Value get( Key getKey );
			void put( Key newKey, Value newValue );
	};
}
*/
#include "Node.h"

namespace Graph
{
	template<typename Key, typename Value> Node<Key, Value>::Node()
	{
	}

	template<typename Key, typename Value> Node<Key, Value>::Node( Key newKey, Value newValue, int newN )
	{//Constructor with values.
	}

	int Node::size() const
	{//Return the size.
	}

	template <typename Key, typename Value> Value Node::get( Key getKey )
	{//Return the value of the node with a given key.
	}

	template <typename Key, typename Value> void put( Key newKey, Value newValue )
	{
	}
}
<commit_msg>Commented out a constructor in the Node class.<commit_after>/*
#include <vector>
#include <ostream>

namespace Graph
{
	template <class Key, Value> class Node
	{//A single edge of a graph.
		private:
			Key key;
			Value value;
			Node left, right;
			int N;

		public:
			//Node( Key newKey, Value newValue, int newN );//Constructor with values.
			int size() const;//Return the size.
			Value get( Key getKey );
			void put( Key newKey, Value newValue );
	};
}
*/
#include "Node.h"

namespace Graph
{
	template<typename Key, typename Value> Node<Key, Value>::Node()
	{
	}

/*
	template<typename Key, typename Value> Node<Key, Value>::Node( Key newKey, Value newValue, int newN )
	{//Constructor with values.
	}
*/

	int Node::size() const
	{//Return the size.
	}

	template <typename Key, typename Value> Value Node::get( Key getKey )
	{//Return the value of the node with a given key.
	}

	template <typename Key, typename Value> void put( Key newKey, Value newValue )
	{
	}
}
<|endoftext|>


<commit_before>#include <nan.h>
#include "addon.h"
#include "dvbtee-parser.h"

void logLevel(const Nan::FunctionCallbackInfo<v8::Value>& info) {

  libdvbtee_set_debug_level((info[0]->IsNumber()) ? info[0]->Uint32Value() : 255,
                            (info[1]->IsNumber()) ? info[1]->Uint32Value() : 0);

  info.GetReturnValue().Set(info.Holder());
}

NAN_MODULE_INIT(InitAll) {

  Nan::Set(target, Nan::New<v8::String>("logLevel").ToLocalChecked(),
    Nan::GetFunction(Nan::New<v8::FunctionTemplate>(logLevel)).ToLocalChecked());

  dvbteeParser::Init(target);
}

NODE_MODULE(addon, InitAll)
<commit_msg>addon: NODE_MODULE(dvbtee, InitAll)<commit_after>#include <nan.h>
#include "addon.h"
#include "dvbtee-parser.h"

void logLevel(const Nan::FunctionCallbackInfo<v8::Value>& info) {

  libdvbtee_set_debug_level((info[0]->IsNumber()) ? info[0]->Uint32Value() : 255,
                            (info[1]->IsNumber()) ? info[1]->Uint32Value() : 0);

  info.GetReturnValue().Set(info.Holder());
}

NAN_MODULE_INIT(InitAll) {

  Nan::Set(target, Nan::New<v8::String>("logLevel").ToLocalChecked(),
    Nan::GetFunction(Nan::New<v8::FunctionTemplate>(logLevel)).ToLocalChecked());

  dvbteeParser::Init(target);
}

NODE_MODULE(dvbtee, InitAll)
<|endoftext|>


<commit_before>//#include "cmd_args.h"
#include <iostream>

//using namespace cmd_args;

// structure type that represents the
// information to be read
//struct arguments_t {
//	bool show_version;
//	bool show_usage;
//	int value_a;
//	int value_b;
//};

#include <memory>
#include <vector>

using namespace std;

namespace command_line {

	namespace details {

		// domain iterator range
		struct range_t {
			char
				** it,
				** end;

			// returns true if range is length is zero
			inline bool finished () const { return it == end; }

			// consume first item in range and return it's value
			inline const char * consume() {
				return *it++;
			}
		};

		// merge two ranges together
		// (TODO: this name and operator does not correctly represent method)
		inline range_t operator && (const range_t & v1, const range_t & v2) {
			if (distance(v1.it, v2.it) > 0)
				return{ v1.it, v2.it };
			else
				return{ v2.it, v1.it };
		}

		// value setter abstraction
		struct base_setter_t {
			using unique = unique_ptr < base_setter_t >;
			virtual void set(const range_t & r) = 0;
		};

		// setter specialization for single items
		template < class _dest_t, class _t >
		struct setter_t : public base_setter_t {
			_t _dest_t::*address;

			setter_t(_t _dest_t::*address_v) : address(address) {}

			virtual void set(const range_t & r) {}
		};

		// setter specialization for vectors
		template < class _dest_t, class _t, class ... _other_tv >
		struct setter_t < _dest_t, vector < _t, _other_tv...> > : public base_setter_t {
			vector < _t, _other_tv...> _dest_t::*address;
			setter_t(vector < _t, _other_tv...> _dest_t::*address_v) : address(address) {}

			virtual void set(const range_t & r) {}
		};

		// solution building/execution node
		struct solution_node {
			range_t range;
			base_setter_t::unique setter;

			int sequence_index;
		};

		struct solution_tree_state_t {
			size_t	tree_size;
			int		parent_node;
		};

		struct solution_tree_t {
		private:
			vector < solution_node > tree;
			int32_t parent_node;
		public:

			inline solution_node & operator [] (size_t i) {
				return tree[i];
			}

			inline size_t size() const {
				return tree.size();
			}

			inline solution_tree_t() : parent_node(-1) {}

			inline void add_node (const range_t & rng, base_setter_t * setter ) {
				tree.push_back(solution_node{
					rng,
					unique_ptr < base_setter_t >(setter),
					parent_node++
				});
			}

			inline solution_tree_state_t state () const {
				return{
					tree.size(),
					parent_node
				};
			}

			inline void restore(const solution_tree_state_t & state) {
				tree.resize(state.tree_size);
				parent_node = state.parent_node;
			}

			inline void backtrack(const solution_tree_state_t & state) {
				parent_node = state.parent_node;
			}

		};

		struct context_state {
			solution_tree_state_t	tree_state;
			range_t					range;
		};

		struct context {
			range_t			range;
			solution_tree_t	solution_tree;

			inline context_state state() const {
				return {
					solution_tree.state(),
					range
				};
			}

			inline void restore(const context_state & state) {
				solution_tree.restore(state.tree_state);
				range = state.range;
			}

			inline void backtrack(const context_state & state) {
				solution_tree.backtrack(state.tree_state);
				range = state.range;
			}
		};

		// setter_t
		template < class _exp_t, class _dest_t, class _t >
		struct setter_op {
			_exp_t exp;
			_t _dest_t::* address;

			inline bool eval(context & cxt) const {
				auto state = cxt.state();
				if (exp.eval(cxt)) {
					cxt.solution_tree.add_node(
						state.range && cxt.range,
						new setter_t < _dest_t, _t >(address)
					);

					return true;
				}
				return false;
			}

			inline setter_op(const _exp_t & e, _t _dest_t::*address_v) : exp(e), address(address_v) {}
		};

		template < class _derived_t >
		struct setter_container_t {
			template < class _dest_t, class _t >
			inline auto operator [] (_t _dest_t::*address) {
				return setter_op < _derived_t, _dest_t, _t >(*static_cast < _derived_t * > (this), address);
			}
		};

		// sequence
		template < class _lhe_t, class _rhe_t >
		struct seq_op {
			_lhe_t lhe;
			_rhe_t rhe;

			inline bool eval(context & cxt) const {
				return lhe.eval(cxt) && rhe.eval(cxt);
			}
		};

		template < class _lhe_t, class _rhe_t >
		auto operator >> (const _lhe_t & l, const _rhe_t & r) {
			return seq_op < _lhe_t, _rhe_t > { l, r };
		}

		// alternation
		template < class _lhe_t, class _rhe_t >
		struct alt_op {
			_lhe_t lhe;
			_rhe_t rhe;

			inline bool eval(context & cxt) const {
				auto
					state = cxt.state(),
					lhe_state = state;

				bool
					valid = lhe.eval(cxt),
					backtrack_lhe_state = valid;

				if (valid) {
					lhe_state = cxt.state();
					cxt.backtrack(state);
				} else {
					cxt.restore(state);
				}

				valid |= rhe.eval(cxt);

				if (!valid)
					cxt.restore(state);

				if (backtrack_lhe_state)
					cxt.backtrack(lhe_state);

				return valid;
			}
		};

		template < class _lhe_t, class _rhe_t >
		auto operator | (const _lhe_t & l, const _rhe_t & r) {
			return alt_op < _lhe_t, _rhe_t > { l, r };
		}

		// zero or one
		template < class _exp_t >
		struct z_one_op {
			_exp_t exp;

			inline bool eval(context & cxt) const {
				auto state = context_state();

				if (!exp.eval(cxt))
					cxt.restore(state);

				return true;
			}
		};

		template < class _exp_t >
		auto operator - (const _exp_t & e) {
			return z_one_op < _exp_t > { e };
		}

		// one or n
		template < class _exp_t >
		struct one_n_op {
			_exp_t exp;

			inline bool eval(context & cxt) const {
				bool one_valid = exp.eval(cxt);

				if (one_valid) {
					auto state = context_state();

					do {
						state = cxt.state();
					} while (exp.eval(cxt));

					cxt.restore(state);
				}

				return one_valid;
			}
		};

		template < class _exp_t >
		auto operator + (const _exp_t & e) {
			return one_n_op < _exp_t > { e };
		}

		// zero or n
		template < class _exp_t >
		struct z_n_op {
			_exp_t exp;

			inline bool eval(context & cxt) const {
				auto state = context_state();

				do {
					state = cxt.state();
				} while (exp.eval(cxt));

				// restore last correct state
				cxt.restore(state);

				return true;
			}
		};

		template < class _exp_t >
		auto operator * (const _exp_t & e) {
			return z_n_op < _exp_t > { e };
		}

		// scaners
		struct value_t : public setter_container_t < value_t > {
			const char * key;

			inline value_t ( const char * key_v ) : key (key_v) {}

			inline bool eval(context & cxt) const {
				if (cxt.range.finished ())
					return false;

				auto v = cxt.range.consume();
				return strcmp(v, key) == 0;
			}
		};

		struct any_t : public setter_container_t < any_t > {

			inline bool eval(context & cxt) const {
				if (cxt.range.finished())
					return false;

				cxt.range.consume();
				return true;
			}

		};

		// solution node inversion and execution
		inline bool execute(details::context & cxt, details::range_t & arg_range) {

			auto & tree = cxt.solution_tree;
			int solution_index = -1;

			for (
				int i = 0;
				i < static_cast < int > (tree.size());
				++i
			) {
				if (tree[i].range.end == arg_range.end) {
					solution_index = i;
					break;
				}
			}

			if (solution_index == -1)
				return false;

			// reorder instructions and execute
			{
				int n = solution_index;
				int i = tree[n].sequence_index;
				tree[n].sequence_index = -1;

				do {
					int t = tree[i].sequence_index;
					tree[i].sequence_index = n;
					n = i;
					i = t;
				} while (i != -1);

				while (i != -1) {
					auto & node = tree[i];
					node.setter->set(node.range);
					i = node.sequence_index;
				}
			}

			return true;
		}

	}

	inline details::value_t key(const char * k) {
		return{ k };
	}

	inline details::any_t any() { return{}; }

	template < class _exp_t >
	inline bool parse(const _exp_t & exp, int arg_c, char ** arg_v) {
		using namespace details;

		auto s_range = range_t {
			+arg_v + 1,	// ignore first item
			+arg_v + arg_c
		};

		context cxt = { s_range };

		// evaluate solutions
		exp.eval(cxt);

		// process and execute solutions
		return details::execute (cxt, s_range);
	}

}

struct demo {
	float	xxx;
	float	yyy;
	int		zzz;

	vector < string > files;

	bool show_version;
	bool show_help;
};

int main(int arg_c, char * arg_v[]) {

	using namespace command_line;

	char * args[] = { "garbage", "-x", "-x", "-z", "luciano", "da", "silva" };

	//auto expression = key("-t") > key("-v") | +key("-x") > key("-v");

	auto usage_options = *(
		key("-x") [&demo::xxx] |
		key("-y") [&demo::yyy] |
		key("-z") [&demo::zzz]
	);

	auto usage_default_values = +any()[&demo::files];

	auto expression =
		usage_options >> usage_default_values |
		usage_options
	;

	parse (expression, 7, args);

	//auto val = command_line::value(&demo::xxx, .0F);

	/*
	// define an instance of the command line parser
	parser < arguments_t > command_line;

	// set its available arguments and options
	command_line
		// option ( < member field address >, < list of command switches >, < description > )
		+ option(&arguments_t::show_version, { "-v", "--version" }, "shows the version of the application")
		+ option(&arguments_t::show_usage, { "-h, --help" }, "shows this usage page")
		// argument ( < member field address >, < list of command switches >, < description >, < is optional >, < default value > )
		+ argument(&arguments_t::value_a, { "-va", "--value_a" }, "multiplicand")
		+ argument(&arguments_t::value_b, { "-vb", "--value_b" }, "multiplier");

	arguments_t args;

	// command line parser returs a context with information about
	// the success of the parsing operation and related errors
	auto context = command_line.parse(arg_c, arg_v, args);

	// if the parsing failed
	if (context.has_failed()) {
		cout << "example failed with the following invalid arguments" << endl;
		// the user can print all errors to an ostream
		context.to_stream(cout);
		return -1;
	}

	if (args.show_version)
		cout << "example 1.0" << endl;

	// users can also print a list of options and arguments with their descriptions
	// to an ostream
	if (args.show_usage)
		command_line.usage_to_stream(cout);

	cout << "example value: " << (args.value_a * args.value_b) << endl;
	*/
	return 0;
}
<commit_msg>implementing usage<commit_after>//#include "cmd_args.h"
#include <iostream>
#include <functional>

//using namespace cmd_args;

// structure type that represents the
// information to be read
//struct arguments_t {
//	bool show_version;
//	bool show_usage;
//	int value_a;
//	int value_b;
//};

#include <memory>
#include <vector>

using namespace std;

namespace command_line {

	namespace details {

		// domain iterator range
		struct range_t {
			char
				** it,
				** end;

			// returns true if range is length is zero
			inline bool finished () const { return it == end; }

			// consume first item in range and return it's value
			inline const char * consume() {
				return *it++;
			}
		};

		// merge two ranges together
		// (TODO: this name and operator does not correctly represent method)
		inline range_t operator && (const range_t & v1, const range_t & v2) {
			if (distance(v1.it, v2.it) > 0)
				return{ v1.it, v2.it };
			else
				return{ v2.it, v1.it };
		}

		// action
		struct base_action_t {
			using unique = unique_ptr < base_action_t >;
			virtual void run(const range_t & range) const = 0;
		};

		// setter action specialization for single items
		template < class _dest_t, class _t >
		struct setter_t : public base_action_t {
			_t _dest_t::*address;

			setter_t(_t _dest_t::*address_v) : address(address) {}

			virtual void run(const range_t & r) const override {}
		};

		// setter specialization for vectors
		template < class _dest_t, class _t, class ... _other_tv >
		struct setter_t < _dest_t, vector < _t, _other_tv...> > : public base_action_t {
			vector < _t, _other_tv...> _dest_t::*address;
			setter_t(vector < _t, _other_tv...> _dest_t::*address_v) : address(address) {}

			virtual void run(const range_t & r) const override {}
		};

		// solution building/execution node
		struct solution_node {
			range_t range;
			base_action_t::unique action;

			int sequence_index;
		};

		struct solution_tree_state_t {
			size_t	tree_size;
			int		parent_node;
		};

		struct solution_tree_t {
		private:
			vector < solution_node > tree;
			int32_t parent_node;
		public:

			inline solution_node & operator [] (size_t i) {
				return tree[i];
			}

			inline size_t size() const {
				return tree.size();
			}

			inline solution_tree_t() : parent_node(-1) {}

			inline void add_node (const range_t & rng, base_action_t * setter ) {
				tree.push_back(solution_node{
					rng,
					unique_ptr < base_action_t >(setter),
					parent_node++
				});
			}

			inline solution_tree_state_t state () const {
				return{
					tree.size(),
					parent_node
				};
			}

			inline void restore(const solution_tree_state_t & state) {
				tree.resize(state.tree_size);
				parent_node = state.parent_node;
			}

			inline void backtrack(const solution_tree_state_t & state) {
				parent_node = state.parent_node;
			}

		};

		struct context_state {
			solution_tree_state_t	tree_state;
			range_t					range;
		};

		struct context {
			range_t			range;
			solution_tree_t	solution_tree;

			inline context_state state() const {
				return {
					solution_tree.state(),
					range
				};
			}

			inline void restore(const context_state & state) {
				solution_tree.restore(state.tree_state);
				range = state.range;
			}

			inline void backtrack(const context_state & state) {
				solution_tree.backtrack(state.tree_state);
				range = state.range;
			}
		};

		// setter_t
		template < class _exp_t, class _dest_t, class _t >
		struct setter_op {
			_exp_t exp;
			_t _dest_t::* address;

			inline bool eval(context & cxt) const {
				auto state = cxt.state();
				if (exp.eval(cxt)) {
					cxt.solution_tree.add_node(
						state.range && cxt.range,
						new setter_t < _dest_t, _t >(address)
					);

					return true;
				}
				return false;
			}

			inline setter_op(const _exp_t & e, _t _dest_t::*address_v) : exp(e), address(address_v) {}
		};

		template < class _derived_t >
		struct setter_container_t {
			template < class _dest_t, class _t >
			inline auto operator [] (_t _dest_t::*address) {
				return setter_op < _derived_t, _dest_t, _t >(*static_cast < _derived_t * > (this), address);
			}
		};

		// sequence
		template < class _lhe_t, class _rhe_t >
		struct seq_op {
			_lhe_t lhe;
			_rhe_t rhe;

			inline bool eval(context & cxt) const {
				return lhe.eval(cxt) && rhe.eval(cxt);
			}
		};

		template < class _lhe_t, class _rhe_t >
		auto operator >> (const _lhe_t & l, const _rhe_t & r) {
			return seq_op < _lhe_t, _rhe_t > { l, r };
		}

		// alternation
		template < class _lhe_t, class _rhe_t >
		struct alt_op {
			_lhe_t lhe;
			_rhe_t rhe;

			inline bool eval(context & cxt) const {
				auto
					state = cxt.state(),
					lhe_state = state;

				bool
					valid = lhe.eval(cxt),
					backtrack_lhe_state = valid;

				if (valid) {
					lhe_state = cxt.state();
					cxt.backtrack(state);
				} else {
					cxt.restore(state);
				}

				valid |= rhe.eval(cxt);

				if (!valid)
					cxt.restore(state);

				if (backtrack_lhe_state)
					cxt.backtrack(lhe_state);

				return valid;
			}
		};

		template < class _lhe_t, class _rhe_t >
		auto operator | (const _lhe_t & l, const _rhe_t & r) {
			return alt_op < _lhe_t, _rhe_t > { l, r };
		}

		// zero or one
		template < class _exp_t >
		struct z_one_op {
			_exp_t exp;

			inline bool eval(context & cxt) const {
				auto state = context_state();

				if (!exp.eval(cxt))
					cxt.restore(state);

				return true;
			}
		};

		template < class _exp_t >
		auto operator - (const _exp_t & e) {
			return z_one_op < _exp_t > { e };
		}

		// one or n
		template < class _exp_t >
		struct one_n_op {
			_exp_t exp;

			inline bool eval(context & cxt) const {
				bool one_valid = exp.eval(cxt);

				if (one_valid) {
					auto state = context_state();

					do {
						state = cxt.state();
					} while (exp.eval(cxt));

					cxt.restore(state);
				}

				return one_valid;
			}
		};

		template < class _exp_t >
		auto operator + (const _exp_t & e) {
			return one_n_op < _exp_t > { e };
		}

		// zero or n
		template < class _exp_t >
		struct z_n_op {
			_exp_t exp;

			inline bool eval(context & cxt) const {
				auto state = context_state();

				do {
					state = cxt.state();
				} while (exp.eval(cxt));

				// restore last correct state
				cxt.restore(state);

				return true;
			}
		};

		template < class _exp_t >
		auto operator * (const _exp_t & e) {
			return z_n_op < _exp_t > { e };
		}

		// scaners
		struct value_t : public setter_container_t < value_t > {
			const char * key;

			inline value_t ( const char * key_v ) : key (key_v) {}

			inline bool eval(context & cxt) const {
				if (cxt.range.finished ())
					return false;

				auto v = cxt.range.consume();
				return strcmp(v, key) == 0;
			}
		};

		struct any_t : public setter_container_t < any_t > {

			inline bool eval(context & cxt) const {
				if (cxt.range.finished())
					return false;

				cxt.range.consume();
				return true;
			}

		};

		// solution node inversion and execution
		inline bool execute(details::context & cxt, details::range_t & arg_range) {

			auto & tree = cxt.solution_tree;
			int solution_index = -1;

			for (
				int i = 0;
				i < static_cast < int > (tree.size());
				++i
			) {
				if (tree[i].range.end == arg_range.end) {
					solution_index = i;
					break;
				}
			}

			if (solution_index == -1)
				return false;

			// reorder instructions and execute
			{
				int n = solution_index;
				int i = tree[n].sequence_index;
				tree[n].sequence_index = -1;

				do {
					int t = tree[i].sequence_index;
					tree[i].sequence_index = n;
					n = i;
					i = t;
				} while (i != -1);

				while (i != -1) {
					auto & node = tree[i];
					node.action->run(node.range);
					i = node.sequence_index;
				}
			}

			return true;
		}

	}

	// scanner methods
	inline details::value_t key(const char * k) {
		return{ k };
	}

	inline details::any_t any() { return{}; }

	// create parameterless callback expression
	template < class _exp_t >
	inline auto usage(void(*callback)(), const _exp_t & exp) {
		return exp;
	}

	// create expression callback with parameter
	template < class _out_t, class _exp_t >
	inline auto usage(void (*callback)(_out_t &), const _exp_t & exp ) {
		return exp;
	}

	// parser
	template < class _exp_t >
	inline bool parse(const _exp_t & exp, int arg_c, char ** arg_v) {
		using namespace details;

		auto s_range = range_t {
			+arg_v + 1,	// ignore first item
			+arg_v + arg_c
		};

		context cxt = { s_range };

		// evaluate solutions
		exp.eval(cxt);

		// process and execute solutions
		return details::execute (cxt, s_range);
	}

}

struct demo {
	float	xxx;
	float	yyy;
	int		zzz;

	vector < string > files;

	bool show_version;
	bool show_help;
};

void main_usage(demo & d) {}

void show_version() {}

int main(int arg_c, char * arg_v[]) {

	using namespace command_line;

	char * args[] = { "garbage", "-x", "-x", "-z", "luciano", "da", "silva" };

	//auto expression = key("-t") > key("-v") | +key("-x") > key("-v");

	auto usage_options = *(
		key("-x") [&demo::xxx] |
		key("-y") [&demo::yyy] |
		key("-z") [&demo::zzz]
	);

	auto usage_default_values = +any()[&demo::files];

	auto expression =
		usage (&main_usage,		usage_options >> usage_default_values) | //.desc ("yada yada yada ayad acoiso e tal") |
		usage (&main_usage,		usage_options) | //.desc ("coiso e tal")
		usage (&show_version,	key("-v"))
	;

	parse (expression, 7, args);

	//auto val = command_line::value(&demo::xxx, .0F);

	/*
	// define an instance of the command line parser
	parser < arguments_t > command_line;

	// set its available arguments and options
	command_line
		// option ( < member field address >, < list of command switches >, < description > )
		+ option(&arguments_t::show_version, { "-v", "--version" }, "shows the version of the application")
		+ option(&arguments_t::show_usage, { "-h, --help" }, "shows this usage page")
		// argument ( < member field address >, < list of command switches >, < description >, < is optional >, < default value > )
		+ argument(&arguments_t::value_a, { "-va", "--value_a" }, "multiplicand")
		+ argument(&arguments_t::value_b, { "-vb", "--value_b" }, "multiplier");

	arguments_t args;

	// command line parser returs a context with information about
	// the success of the parsing operation and related errors
	auto context = command_line.parse(arg_c, arg_v, args);

	// if the parsing failed
	if (context.has_failed()) {
		cout << "example failed with the following invalid arguments" << endl;
		// the user can print all errors to an ostream
		context.to_stream(cout);
		return -1;
	}

	if (args.show_version)
		cout << "example 1.0" << endl;

	// users can also print a list of options and arguments with their descriptions
	// to an ostream
	if (args.show_usage)
		command_line.usage_to_stream(cout);

	cout << "example value: " << (args.value_a * args.value_b) << endl;
	*/
	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>

#include <boost/program_options.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/preprocessor/seq/for_each.hpp>

#include <amgcl/backend/builtin.hpp>
#include <amgcl/value_type/static_matrix.hpp>
#include <amgcl/make_solver.hpp>
#include <amgcl/amg.hpp>
#include <amgcl/solver/runtime.hpp>
#include <amgcl/coarsening/runtime.hpp>
#include <amgcl/relaxation/runtime.hpp>
#include <amgcl/relaxation/as_preconditioner.hpp>
#include <amgcl/preconditioner/cpr.hpp>
#include <amgcl/adapter/crs_tuple.hpp>
#include <amgcl/adapter/block_matrix.hpp>
#include <amgcl/io/mm.hpp>
#include <amgcl/io/binary.hpp>
#include <amgcl/profiler.hpp>

namespace amgcl { profiler<> prof; }
using amgcl::prof;
using amgcl::precondition;

//---------------------------------------------------------------------------
template <class Matrix>
void solve_cpr(const Matrix &K, const std::vector<double> &rhs, boost::property_tree::ptree &prm)
{
    auto t1 = prof.scoped_tic("CPR");

    typedef amgcl::backend::builtin<double> Backend;

    typedef
        amgcl::amg<Backend, amgcl::runtime::coarsening::wrapper, amgcl::runtime::relaxation::wrapper>
        PPrecond;

    typedef
        amgcl::relaxation::as_preconditioner<Backend, amgcl::runtime::relaxation::wrapper>
        SPrecond;

    amgcl::make_solver<
        amgcl::preconditioner::cpr<PPrecond, SPrecond>,
        amgcl::runtime::solver::wrapper<Backend>
        > solve(K, prm);

    std::cout << solve.precond() << std::endl;

    auto t2 = prof.scoped_tic("solve");
    std::vector<double> x(rhs.size(), 0.0);

    size_t iters;
    double error;

    std::tie(iters, error) = solve(rhs, x);

    std::cout << "Iterations: " << iters << std::endl
              << "Error:      " << error << std::endl;
}

//---------------------------------------------------------------------------
template <int B, class Matrix>
void solve_block_cpr(const Matrix &K, const std::vector<double> &rhs, boost::property_tree::ptree &prm)
{
    auto t1 = prof.scoped_tic("CPR");

    typedef amgcl::static_matrix<double, B, B> val_type;
    typedef amgcl::static_matrix<double, B, 1> rhs_type;
    typedef amgcl::backend::builtin<val_type>  SBackend;
    typedef amgcl::backend::builtin<double>    PBackend;

    typedef
        amgcl::amg<
            PBackend,
            amgcl::runtime::coarsening::wrapper,
            amgcl::runtime::relaxation::wrapper>
        PPrecond;

    typedef
        amgcl::relaxation::as_preconditioner<
            SBackend,
            amgcl::runtime::relaxation::wrapper
            >
        SPrecond;

    amgcl::make_solver<
        amgcl::preconditioner::cpr<PPrecond, SPrecond>,
        amgcl::runtime::solver::wrapper<SBackend>
        > solve(amgcl::adapter::block_matrix<val_type>(K), prm);

    std::cout << solve.precond() << std::endl;

    auto t2 = prof.scoped_tic("solve");
    std::vector<rhs_type> x(rhs.size(), amgcl::math::zero<rhs_type>());

    auto rhs_ptr = reinterpret_cast<const rhs_type*>(rhs.data());
    size_t n = amgcl::backend::rows(K) / B;

    size_t iters;
    double error;

    std::tie(iters, error) = solve(amgcl::make_iterator_range(rhs_ptr, rhs_ptr + n), x);

    std::cout << "Iterations: " << iters << std::endl
              << "Error:      " << error << std::endl;
}

//---------------------------------------------------------------------------
int main(int argc, char *argv[]) {
    using std::string;
    using std::vector;
    using amgcl::prof;
    using amgcl::precondition;

    namespace po = boost::program_options;
    namespace io = amgcl::io;

    po::options_description desc("Options");

    desc.add_options()
        ("help,h", "show help")
        (
         "binary,B",
         po::bool_switch()->default_value(false),
         "When specified, treat input files as binary instead of as MatrixMarket. "
         "It is assumed the files were converted to binary format with mm2bin utility. "
        )
        (
         "matrix,A",
         po::value<string>()->required(),
         "The system matrix in MatrixMarket format"
        )
        (
         "rhs,f",
         po::value<string>(),
         "The right-hand side in MatrixMarket format"
        )
        (
         "runtime-block-size,b",
         po::value<int>(),
         "The block size of the system matrix set at runtime"
        )
        (
         "static-block-size,c",
         po::value<int>()->default_value(1),
         "The block size of the system matrix set at compiletime"
        )
        (
         "params,P",
         po::value<string>(),
         "parameter file in json format"
        )
        (
         "prm,p",
         po::value< vector<string> >()->multitoken(),
         "Parameters specified as name=value pairs. "
         "May be provided multiple times. Examples:\n"
         "  -p solver.tol=1e-3\n"
         "  -p precond.coarse_enough=300"
        )
        ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);

    if (vm.count("help")) {
        std::cout << desc << std::endl;
        return 0;
    }

    po::notify(vm);

    boost::property_tree::ptree prm;
    if (vm.count("params")) read_json(vm["params"].as<string>(), prm);

    if (vm.count("prm")) {
        for(const string &v : vm["prm"].as<vector<string> >()) {
            amgcl::put(prm, v);
        }
    }

    int cb = vm["static-block-size"].as<int>();

    if (vm.count("runtime-block-size"))
        prm.put("precond.block_size", vm["runtime-block-size"].as<int>());
    else
        prm.put("precond.block_size", cb);

    size_t rows;
    vector<ptrdiff_t> ptr, col;
    vector<double> val, rhs;
    std::vector<char> pm;

    {
        auto t = prof.scoped_tic("reading");

        string Afile  = vm["matrix"].as<string>();
        bool   binary = vm["binary"].as<bool>();

        if (binary) {
            io::read_crs(Afile, rows, ptr, col, val);
        } else {
            size_t cols;
            std::tie(rows, cols) = io::mm_reader(Afile)(ptr, col, val);
            precondition(rows == cols, "Non-square system matrix");
        }

        if (vm.count("rhs")) {
            string bfile = vm["rhs"].as<string>();

            size_t n, m;

            if (binary) {
                io::read_dense(bfile, n, m, rhs);
            } else {
                std::tie(n, m) = io::mm_reader(bfile)(rhs);
            }

            precondition(n == rows && m == 1, "The RHS vector has wrong size");
        } else {
            rhs.resize(rows, 1.0);
        }
    }

#define CALL_BLOCK_SOLVER(z, data, B)                                          \
    case B:                                                                    \
        solve_block_cpr<B>(std::tie(rows, ptr, col, val), rhs, prm);           \
        break;

    switch(cb) {
        case 1:
            solve_cpr(std::tie(rows, ptr, col, val), rhs, prm);
            break;

        BOOST_PP_SEQ_FOR_EACH(CALL_BLOCK_SOLVER, ~, AMGCL_BLOCK_SIZES)

        default:
            precondition(false, "Unsupported block size");
            break;
    }

    std::cout << prof << std::endl;
}
<commit_msg>Profile setup operations in examples/cpr under "setup"<commit_after>#include <iostream>
#include <string>

#include <boost/program_options.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/preprocessor/seq/for_each.hpp>

#include <amgcl/backend/builtin.hpp>
#include <amgcl/value_type/static_matrix.hpp>
#include <amgcl/make_solver.hpp>
#include <amgcl/amg.hpp>
#include <amgcl/solver/runtime.hpp>
#include <amgcl/coarsening/runtime.hpp>
#include <amgcl/relaxation/runtime.hpp>
#include <amgcl/relaxation/as_preconditioner.hpp>
#include <amgcl/preconditioner/cpr.hpp>
#include <amgcl/adapter/crs_tuple.hpp>
#include <amgcl/adapter/block_matrix.hpp>
#include <amgcl/io/mm.hpp>
#include <amgcl/io/binary.hpp>
#include <amgcl/profiler.hpp>

namespace amgcl { profiler<> prof; }
using amgcl::prof;
using amgcl::precondition;

//---------------------------------------------------------------------------
template <class Matrix>
void solve_cpr(const Matrix &K, const std::vector<double> &rhs, boost::property_tree::ptree &prm)
{
    auto t1 = prof.scoped_tic("CPR");

    typedef amgcl::backend::builtin<double> Backend;

    typedef
        amgcl::amg<Backend, amgcl::runtime::coarsening::wrapper, amgcl::runtime::relaxation::wrapper>
        PPrecond;

    typedef
        amgcl::relaxation::as_preconditioner<Backend, amgcl::runtime::relaxation::wrapper>
        SPrecond;

    prof.tic("setup");
    amgcl::make_solver<
        amgcl::preconditioner::cpr<PPrecond, SPrecond>,
        amgcl::runtime::solver::wrapper<Backend>
        > solve(K, prm);
    prof.toc("setup");

    std::cout << solve.precond() << std::endl;

    std::vector<double> x(rhs.size(), 0.0);

    size_t iters;
    double error;

    prof.tic("setup");
    std::tie(iters, error) = solve(rhs, x);
    prof.toc("setup");

    std::cout << "Iterations: " << iters << std::endl
              << "Error:      " << error << std::endl;
}

//---------------------------------------------------------------------------
template <int B, class Matrix>
void solve_block_cpr(const Matrix &K, const std::vector<double> &rhs, boost::property_tree::ptree &prm)
{
    auto t1 = prof.scoped_tic("CPR");

    typedef amgcl::static_matrix<double, B, B> val_type;
    typedef amgcl::static_matrix<double, B, 1> rhs_type;
    typedef amgcl::backend::builtin<val_type>  SBackend;
    typedef amgcl::backend::builtin<double>    PBackend;

    typedef
        amgcl::amg<
            PBackend,
            amgcl::runtime::coarsening::wrapper,
            amgcl::runtime::relaxation::wrapper>
        PPrecond;

    typedef
        amgcl::relaxation::as_preconditioner<
            SBackend,
            amgcl::runtime::relaxation::wrapper
            >
        SPrecond;

    prof.tic("setup");
    amgcl::make_solver<
        amgcl::preconditioner::cpr<PPrecond, SPrecond>,
        amgcl::runtime::solver::wrapper<SBackend>
        > solve(amgcl::adapter::block_matrix<val_type>(K), prm);
    prof.toc("setup");

    std::cout << solve.precond() << std::endl;

    std::vector<rhs_type> x(rhs.size(), amgcl::math::zero<rhs_type>());

    auto rhs_ptr = reinterpret_cast<const rhs_type*>(rhs.data());
    size_t n = amgcl::backend::rows(K) / B;

    size_t iters;
    double error;

    prof.tic("solve");
    std::tie(iters, error) = solve(amgcl::make_iterator_range(rhs_ptr, rhs_ptr + n), x);
    prof.toc("solve");

    std::cout << "Iterations: " << iters << std::endl
              << "Error:      " << error << std::endl;
}

//---------------------------------------------------------------------------
int main(int argc, char *argv[]) {
    using std::string;
    using std::vector;
    using amgcl::prof;
    using amgcl::precondition;

    namespace po = boost::program_options;
    namespace io = amgcl::io;

    po::options_description desc("Options");

    desc.add_options()
        ("help,h", "show help")
        (
         "binary,B",
         po::bool_switch()->default_value(false),
         "When specified, treat input files as binary instead of as MatrixMarket. "
         "It is assumed the files were converted to binary format with mm2bin utility. "
        )
        (
         "matrix,A",
         po::value<string>()->required(),
         "The system matrix in MatrixMarket format"
        )
        (
         "rhs,f",
         po::value<string>(),
         "The right-hand side in MatrixMarket format"
        )
        (
         "runtime-block-size,b",
         po::value<int>(),
         "The block size of the system matrix set at runtime"
        )
        (
         "static-block-size,c",
         po::value<int>()->default_value(1),
         "The block size of the system matrix set at compiletime"
        )
        (
         "params,P",
         po::value<string>(),
         "parameter file in json format"
        )
        (
         "prm,p",
         po::value< vector<string> >()->multitoken(),
         "Parameters specified as name=value pairs. "
         "May be provided multiple times. Examples:\n"
         "  -p solver.tol=1e-3\n"
         "  -p precond.coarse_enough=300"
        )
        ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);

    if (vm.count("help")) {
        std::cout << desc << std::endl;
        return 0;
    }

    po::notify(vm);

    boost::property_tree::ptree prm;
    if (vm.count("params")) read_json(vm["params"].as<string>(), prm);

    if (vm.count("prm")) {
        for(const string &v : vm["prm"].as<vector<string> >()) {
            amgcl::put(prm, v);
        }
    }

    int cb = vm["static-block-size"].as<int>();

    if (vm.count("runtime-block-size"))
        prm.put("precond.block_size", vm["runtime-block-size"].as<int>());
    else
        prm.put("precond.block_size", cb);

    size_t rows;
    vector<ptrdiff_t> ptr, col;
    vector<double> val, rhs;
    std::vector<char> pm;

    {
        auto t = prof.scoped_tic("reading");

        string Afile  = vm["matrix"].as<string>();
        bool   binary = vm["binary"].as<bool>();

        if (binary) {
            io::read_crs(Afile, rows, ptr, col, val);
        } else {
            size_t cols;
            std::tie(rows, cols) = io::mm_reader(Afile)(ptr, col, val);
            precondition(rows == cols, "Non-square system matrix");
        }

        if (vm.count("rhs")) {
            string bfile = vm["rhs"].as<string>();

            size_t n, m;

            if (binary) {
                io::read_dense(bfile, n, m, rhs);
            } else {
                std::tie(n, m) = io::mm_reader(bfile)(rhs);
            }

            precondition(n == rows && m == 1, "The RHS vector has wrong size");
        } else {
            rhs.resize(rows, 1.0);
        }
    }

#define CALL_BLOCK_SOLVER(z, data, B)                                          \
    case B:                                                                    \
        solve_block_cpr<B>(std::tie(rows, ptr, col, val), rhs, prm);           \
        break;

    switch(cb) {
        case 1:
            solve_cpr(std::tie(rows, ptr, col, val), rhs, prm);
            break;

        BOOST_PP_SEQ_FOR_EACH(CALL_BLOCK_SOLVER, ~, AMGCL_BLOCK_SIZES)

        default:
            precondition(false, "Unsupported block size");
            break;
    }

    std::cout << prof << std::endl;
}
<|endoftext|>


<commit_before><commit_msg>Edited a comment.<commit_after><|endoftext|>


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

#include "chrome/browser/views/app_launcher.h"

#include <string>
#include <vector>

#include "app/resource_bundle.h"
#include "base/command_line.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/task.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/dom_view.h"
#include "chrome/browser/views/info_bubble.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/location_bar/location_bar_view.h"
#include "chrome/common/url_constants.h"
#include "views/widget/root_view.h"

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/status/status_area_view.h"
#endif

namespace {

// Padding between the navigation bar and the render view contents.
const int kNavigationBarBottomPadding = 3;

// NavigationBar constants.
const int kNavigationBarBorderThickness = 1;

const SkColor kBorderColor = SkColorSetRGB(205, 201, 201);

// Command line switch for specifying url of the page.
// TODO: nuke when we convert to the real app page. Also nuke code in
// AddNewContents
const wchar_t kURLSwitch[] = L"main-menu-url";

// Returns the URL of the menu.
static GURL GetMenuURL() {
  std::wstring url_string =
      CommandLine::ForCurrentProcess()->GetSwitchValue(kURLSwitch);
  if (!url_string.empty())
    return GURL(WideToUTF8(url_string));
  return GURL(chrome::kChromeUIAppLauncherURL);
}

// Returns the location bar view of |browser|.
static views::View* GetBrowserLocationBar(Browser* browser) {
  BrowserView* browser_view = static_cast<BrowserView*>(browser->window());
  views::RootView* root_view = views::Widget::GetWidgetFromNativeWindow(
      browser_view->GetNativeHandle())->GetRootView();
  return root_view->GetViewByID(VIEW_ID_LOCATION_BAR);
}

}  // namespace

// InfoBubbleContentsView
//
// The view that contains the navigation bar and DOMUI.
// It is displayed in an info-bubble.

class InfoBubbleContentsView : public views::View,
                               public LocationBarView::Delegate,
                               public CommandUpdater::CommandUpdaterDelegate {
 public:
  explicit InfoBubbleContentsView(AppLauncher* app_launcher);
  ~InfoBubbleContentsView();

  // Computes and sets the preferred size for the InfoBubbleContentsView based
  // on the preferred size of the DOMUI contents specified.
  void ComputePreferredSize(const gfx::Size& dom_view_preferred_size);

  // Sets the initial focus.
  // Should be called when the bubble that contains us is shown.
  void BubbleShown();

  // views::View override:
  virtual gfx::Size GetPreferredSize();
  virtual void Layout();
  virtual void ViewHierarchyChanged(bool is_add,
                                    views::View* parent,
                                    views::View* child);

  // LocationBarView::Delegate implementation:
  virtual TabContents* GetTabContents();
  virtual void OnInputInProgress(bool in_progress) {}

  // CommandUpdater::CommandUpdaterDelegate implementation:
  virtual void ExecuteCommand(int id);

 private:
  // The application launcher displaying this info bubble.
  AppLauncher* app_launcher_;

  // The location bar.
  LocationBarView* location_bar_;

  // The view containing the renderer view.
  DOMView* dom_view_;

  // The preferred size for this view (at which it fits its contents).
  gfx::Size preferred_size_;

  // CommandUpdater the location bar sends commands to.
  CommandUpdater command_updater_;

  // The width of the browser's location bar.
  int browser_location_bar_width_;

  DISALLOW_COPY_AND_ASSIGN(InfoBubbleContentsView);
};

InfoBubbleContentsView::InfoBubbleContentsView(AppLauncher* app_launcher)
    : app_launcher_(app_launcher),
      location_bar_(NULL),
      dom_view_(NULL),
      ALLOW_THIS_IN_INITIALIZER_LIST(command_updater_(this)) {
  // Allow the location bar to open URLs.
  command_updater_.UpdateCommandEnabled(IDC_OPEN_CURRENT_URL, true);
  DCHECK(app_launcher);

  browser_location_bar_width_ =
      GetBrowserLocationBar(app_launcher->browser())->width();
}

InfoBubbleContentsView::~InfoBubbleContentsView() {
}

void InfoBubbleContentsView::ComputePreferredSize(
    const gfx::Size& dom_view_preferred_size) {
  preferred_size_ = dom_view_preferred_size;

  // Add the padding and location bar height.
  preferred_size_.Enlarge(
      0, location_bar_->height() + kNavigationBarBottomPadding);

  // Make sure the width is at least the browser location bar width.
  if (preferred_size_.width() < browser_location_bar_width_)
    preferred_size_.set_width(browser_location_bar_width_);
}

void InfoBubbleContentsView::BubbleShown() {
  location_bar_->RequestFocus();
}

void InfoBubbleContentsView::ViewHierarchyChanged(
    bool is_add, views::View* parent, views::View* child) {
  if (!is_add || child != this)
    return;

  DCHECK(!dom_view_);
  dom_view_ = new DOMView();
  AddChildView(dom_view_);
  // We pass NULL for site instance so the renderer uses its own process.
  dom_view_->Init(app_launcher_->browser()->profile(), NULL);
  // We make the AppLauncher the TabContents delegate so we get notifications
  // from the page to open links.
  dom_view_->tab_contents()->set_delegate(app_launcher_);
  GURL url = GetMenuURL();
  std::string ref = url.ref();
  if (!app_launcher_->hash_params().empty()) {
    if (!ref.empty())
      ref += "&";
    ref += app_launcher_->hash_params();

    url_canon::Replacements<char> replacements;
    replacements.SetRef(ref.c_str(), url_parse::Component(0, ref.size()));
    url = url.ReplaceComponents(replacements);
  }
  dom_view_->LoadURL(url);

  Browser* browser = app_launcher_->browser();
  location_bar_ =  new LocationBarView(browser->profile(),
                                       &command_updater_,
                                       browser->toolbar_model(),
                                       this,
                                       LocationBarView::APP_LAUNCHER);

  location_bar_->set_border(
      views::Border::CreateSolidBorder(kNavigationBarBorderThickness,
                                       kBorderColor));
  AddChildView(location_bar_);
  location_bar_->Init();
  // Size the location to its preferred size so ComputePreferredSize() computes
  // the right size.
  location_bar_->SizeToPreferredSize();
  ComputePreferredSize(gfx::Size(browser_location_bar_width_, 0));
  Layout();
}

TabContents* InfoBubbleContentsView::GetTabContents() {
  return app_launcher_->browser()->GetSelectedTabContents();
}

gfx::Size InfoBubbleContentsView::GetPreferredSize() {
  return preferred_size_;
}

void InfoBubbleContentsView::Layout() {
  if (bounds().IsEmpty() || GetChildViewCount() == 0)
    return;

  gfx::Rect bounds = GetLocalBounds(false);
  location_bar_->SetBounds(bounds.x(), bounds.y(), bounds.width(),
                           location_bar_->GetPreferredSize().height());
  int render_y = location_bar_->bounds().bottom() + kNavigationBarBottomPadding;
  dom_view_->SetBounds(0, render_y,
                       width(),
                       std::max(0, bounds.height() - render_y + bounds.y()));
}

void InfoBubbleContentsView::ExecuteCommand(int id) {
  // The user navigated by typing or selecting an entry in the location bar.
  DCHECK_EQ(IDC_OPEN_CURRENT_URL, id);
  GURL url(WideToUTF8(location_bar_->GetInputString()));
  app_launcher_->AddTabWithURL(url, location_bar_->GetPageTransition());
  app_launcher_->Hide();
}

////////////////////////////////////////////////////////////////////////////////
// AppLauncher

AppLauncher::AppLauncher(Browser* browser)
    : browser_(browser),
      info_bubble_(NULL) {
  DCHECK(browser);
  info_bubble_content_ = new InfoBubbleContentsView(this);
}

AppLauncher::~AppLauncher() {
}

// static
AppLauncher* AppLauncher::Show(Browser* browser,
                               const gfx::Rect& bounds,
                               const gfx::Point& bubble_anchor,
                               const std::string& hash_params) {
  AppLauncher* app_launcher = new AppLauncher(browser);
  BrowserView* browser_view = static_cast<BrowserView*>(browser->window());
  app_launcher->hash_params_ = hash_params;
  app_launcher->info_bubble_ =
      PinnedContentsInfoBubble::Show(browser_view->GetWidget(),
          bounds, BubbleBorder::TOP_LEFT, bubble_anchor,
          app_launcher->info_bubble_content_, app_launcher);
  app_launcher->info_bubble_content_->BubbleShown();
  return app_launcher;
}

// static
AppLauncher* AppLauncher::ShowForNewTab(Browser* browser,
                                        const std::string& hash_params) {
  BrowserView* browser_view = static_cast<BrowserView*>(browser->window());
  TabStrip* tabstrip = browser_view->tabstrip()->AsTabStrip();
  if (!tabstrip)
    return NULL;
  gfx::Rect bounds = tabstrip->GetNewTabButtonBounds();
  gfx::Point origin = bounds.origin();
  views::RootView::ConvertPointToScreen(tabstrip, &origin);
  bounds.set_origin(origin);

  // Figure out where the location bar is, so we can pin the bubble to
  // make our url bar appear exactly over it.
  views::View* location_bar = GetBrowserLocationBar(browser);
  gfx::Point location_bar_origin = location_bar->bounds().origin();
  views::RootView::ConvertPointToScreen(location_bar->GetParent(),
                                        &location_bar_origin);

  return Show(browser, bounds, location_bar_origin, hash_params);
}

void AppLauncher::Hide() {
  info_bubble_->Close();
}

void AppLauncher::OpenURLFromTab(TabContents* source,
                                 const GURL& url, const GURL& referrer,
                                 WindowOpenDisposition disposition,
                                 PageTransition::Type transition) {
  // TODO(jcivelli): we should call Browser::OpenApplicationTab(), we would need
  //                 to access the app for this URL.
  // The user clicked an item in the app launcher contents.
  AddTabWithURL(url, PageTransition::AUTO_BOOKMARK);
  Hide();
}

void AppLauncher::AddNewContents(TabContents* source,
                                 TabContents* new_contents,
                                 WindowOpenDisposition disposition,
                                 const gfx::Rect& initial_pos,
                                 bool user_gesture) {
#if defined(OS_CHROMEOS)
  // ChromeOS uses the kURLSwitch to specify a page that opens popups. We need
  // to do this so the popups are opened when the user clicks on the page.
  // TODO: nuke when convert to the real app page.
  new_contents->set_delegate(NULL);
  browser_->GetSelectedTabContents()->AddNewContents(
      new_contents, disposition, initial_pos, user_gesture);
  Hide();
#endif
}

void AppLauncher::UpdatePreferredSize(const gfx::Size& pref_size) {
  if (pref_size.width() == 0 || pref_size.height() == 0)
    return;

  gfx::Size size(pref_size);
  info_bubble_content_->ComputePreferredSize(size);
  info_bubble_->SizeToContents();
}

void AppLauncher::InfoBubbleClosing(InfoBubble* info_bubble,
                                    bool closed_by_escape) {
  // Delay deleting to be safe (we, and our tabcontents may be on the stack).
  // Remove ourself as a delegate as on GTK the Widget destruction is
  // asynchronous and will happen after the AppLauncher has been deleted (and it
  // might notify us after we have been deleted).
  info_bubble_content_->GetTabContents()->set_delegate(NULL);
  MessageLoop::current()->PostTask(FROM_HERE,
                                   new DeleteTask<AppLauncher>(this));
}

void AppLauncher::AddTabWithURL(const GURL& url,
                                PageTransition::Type transition) {
#if defined(OS_CHROMEOS)
  switch (chromeos::StatusAreaView::GetOpenTabsMode()) {
    case chromeos::StatusAreaView::OPEN_TABS_ON_LEFT: {
      // Add the new tab at the first non-pinned location.
      int index = browser_->tabstrip_model()->IndexOfFirstNonMiniTab();
      browser_->AddTabWithURL(url, GURL(), transition, index,
                              Browser::ADD_SELECTED | Browser::ADD_FORCE_INDEX,
                              NULL, std::string());
      break;
    }
    case chromeos::StatusAreaView::OPEN_TABS_CLOBBER: {
      browser_->GetSelectedTabContents()->controller().LoadURL(
          url, GURL(), transition);
      break;
    }
    case chromeos::StatusAreaView::OPEN_TABS_ON_RIGHT: {
      browser_->AddTabWithURL(url, GURL(), transition, -1,
                              Browser::ADD_SELECTED | Browser::ADD_FORCE_INDEX,
                              NULL, std::string());
      break;
    }
  }
#else
  browser_->AddTabWithURL(url, GURL(), transition, -1,
                          Browser::ADD_SELECTED | Browser::ADD_FORCE_INDEX,
                          NULL, std::string());
#endif
}
<commit_msg>The wrong TabContents' delegate was being NULLed when the app launcher was closed (the browser's current tab instead of the app launcher's one). This was causing a crasher with the context menu and possibly way more bad things.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/views/app_launcher.h"

#include <string>
#include <vector>

#include "app/resource_bundle.h"
#include "base/command_line.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/task.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/dom_view.h"
#include "chrome/browser/views/info_bubble.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/location_bar/location_bar_view.h"
#include "chrome/common/url_constants.h"
#include "views/widget/root_view.h"

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/status/status_area_view.h"
#endif

namespace {

// Padding between the navigation bar and the render view contents.
const int kNavigationBarBottomPadding = 3;

// NavigationBar constants.
const int kNavigationBarBorderThickness = 1;

const SkColor kBorderColor = SkColorSetRGB(205, 201, 201);

// Command line switch for specifying url of the page.
// TODO: nuke when we convert to the real app page. Also nuke code in
// AddNewContents
const wchar_t kURLSwitch[] = L"main-menu-url";

// Returns the URL of the menu.
static GURL GetMenuURL() {
  std::wstring url_string =
      CommandLine::ForCurrentProcess()->GetSwitchValue(kURLSwitch);
  if (!url_string.empty())
    return GURL(WideToUTF8(url_string));
  return GURL(chrome::kChromeUIAppLauncherURL);
}

// Returns the location bar view of |browser|.
static views::View* GetBrowserLocationBar(Browser* browser) {
  BrowserView* browser_view = static_cast<BrowserView*>(browser->window());
  views::RootView* root_view = views::Widget::GetWidgetFromNativeWindow(
      browser_view->GetNativeHandle())->GetRootView();
  return root_view->GetViewByID(VIEW_ID_LOCATION_BAR);
}

}  // namespace

// InfoBubbleContentsView
//
// The view that contains the navigation bar and DOMUI.
// It is displayed in an info-bubble.

class InfoBubbleContentsView : public views::View,
                               public LocationBarView::Delegate,
                               public CommandUpdater::CommandUpdaterDelegate {
 public:
  explicit InfoBubbleContentsView(AppLauncher* app_launcher);
  ~InfoBubbleContentsView();

  // Computes and sets the preferred size for the InfoBubbleContentsView based
  // on the preferred size of the DOMUI contents specified.
  void ComputePreferredSize(const gfx::Size& dom_view_preferred_size);

  // Sets the initial focus.
  // Should be called when the bubble that contains us is shown.
  void BubbleShown();

  // Returns the TabContents displaying the contents for this bubble.
  TabContents* GetBubbleTabContents();

  // views::View override:
  virtual gfx::Size GetPreferredSize();
  virtual void Layout();
  virtual void ViewHierarchyChanged(bool is_add,
                                    views::View* parent,
                                    views::View* child);

  // LocationBarView::Delegate implementation:

  // WARNING: this is not the TabContents of the bubble!  Use
  // GetBubbleTabContents() to get the bubble's TabContents.
  virtual TabContents* GetTabContents();
  virtual void OnInputInProgress(bool in_progress) {}

  // CommandUpdater::CommandUpdaterDelegate implementation:
  virtual void ExecuteCommand(int id);

 private:
  // The application launcher displaying this info bubble.
  AppLauncher* app_launcher_;

  // The location bar.
  LocationBarView* location_bar_;

  // The view containing the renderer view.
  DOMView* dom_view_;

  // The preferred size for this view (at which it fits its contents).
  gfx::Size preferred_size_;

  // CommandUpdater the location bar sends commands to.
  CommandUpdater command_updater_;

  // The width of the browser's location bar.
  int browser_location_bar_width_;

  DISALLOW_COPY_AND_ASSIGN(InfoBubbleContentsView);
};

InfoBubbleContentsView::InfoBubbleContentsView(AppLauncher* app_launcher)
    : app_launcher_(app_launcher),
      location_bar_(NULL),
      dom_view_(NULL),
      ALLOW_THIS_IN_INITIALIZER_LIST(command_updater_(this)) {
  // Allow the location bar to open URLs.
  command_updater_.UpdateCommandEnabled(IDC_OPEN_CURRENT_URL, true);
  DCHECK(app_launcher);

  browser_location_bar_width_ =
      GetBrowserLocationBar(app_launcher->browser())->width();
}

InfoBubbleContentsView::~InfoBubbleContentsView() {
}

void InfoBubbleContentsView::ComputePreferredSize(
    const gfx::Size& dom_view_preferred_size) {
  preferred_size_ = dom_view_preferred_size;

  // Add the padding and location bar height.
  preferred_size_.Enlarge(
      0, location_bar_->height() + kNavigationBarBottomPadding);

  // Make sure the width is at least the browser location bar width.
  if (preferred_size_.width() < browser_location_bar_width_)
    preferred_size_.set_width(browser_location_bar_width_);
}

void InfoBubbleContentsView::BubbleShown() {
  location_bar_->RequestFocus();
}

TabContents* InfoBubbleContentsView::GetBubbleTabContents() {
  return dom_view_->tab_contents();
}

void InfoBubbleContentsView::ViewHierarchyChanged(
    bool is_add, views::View* parent, views::View* child) {
  if (!is_add || child != this)
    return;

  DCHECK(!dom_view_);
  dom_view_ = new DOMView();
  AddChildView(dom_view_);
  // We pass NULL for site instance so the renderer uses its own process.
  dom_view_->Init(app_launcher_->browser()->profile(), NULL);
  // We make the AppLauncher the TabContents delegate so we get notifications
  // from the page to open links.
  dom_view_->tab_contents()->set_delegate(app_launcher_);
  GURL url = GetMenuURL();
  std::string ref = url.ref();
  if (!app_launcher_->hash_params().empty()) {
    if (!ref.empty())
      ref += "&";
    ref += app_launcher_->hash_params();

    url_canon::Replacements<char> replacements;
    replacements.SetRef(ref.c_str(), url_parse::Component(0, ref.size()));
    url = url.ReplaceComponents(replacements);
  }
  dom_view_->LoadURL(url);

  Browser* browser = app_launcher_->browser();
  location_bar_ =  new LocationBarView(browser->profile(),
                                       &command_updater_,
                                       browser->toolbar_model(),
                                       this,
                                       LocationBarView::APP_LAUNCHER);

  location_bar_->set_border(
      views::Border::CreateSolidBorder(kNavigationBarBorderThickness,
                                       kBorderColor));
  AddChildView(location_bar_);
  location_bar_->Init();
  // Size the location to its preferred size so ComputePreferredSize() computes
  // the right size.
  location_bar_->SizeToPreferredSize();
  ComputePreferredSize(gfx::Size(browser_location_bar_width_, 0));
  Layout();
}

TabContents* InfoBubbleContentsView::GetTabContents() {
  return app_launcher_->browser()->GetSelectedTabContents();
}

gfx::Size InfoBubbleContentsView::GetPreferredSize() {
  return preferred_size_;
}

void InfoBubbleContentsView::Layout() {
  if (bounds().IsEmpty() || GetChildViewCount() == 0)
    return;

  gfx::Rect bounds = GetLocalBounds(false);
  location_bar_->SetBounds(bounds.x(), bounds.y(), bounds.width(),
                           location_bar_->GetPreferredSize().height());
  int render_y = location_bar_->bounds().bottom() + kNavigationBarBottomPadding;
  dom_view_->SetBounds(0, render_y,
                       width(),
                       std::max(0, bounds.height() - render_y + bounds.y()));
}

void InfoBubbleContentsView::ExecuteCommand(int id) {
  // The user navigated by typing or selecting an entry in the location bar.
  DCHECK_EQ(IDC_OPEN_CURRENT_URL, id);
  GURL url(WideToUTF8(location_bar_->GetInputString()));
  app_launcher_->AddTabWithURL(url, location_bar_->GetPageTransition());
  app_launcher_->Hide();
}

////////////////////////////////////////////////////////////////////////////////
// AppLauncher

AppLauncher::AppLauncher(Browser* browser)
    : browser_(browser),
      info_bubble_(NULL) {
  DCHECK(browser);
  info_bubble_content_ = new InfoBubbleContentsView(this);
}

AppLauncher::~AppLauncher() {
}

// static
AppLauncher* AppLauncher::Show(Browser* browser,
                               const gfx::Rect& bounds,
                               const gfx::Point& bubble_anchor,
                               const std::string& hash_params) {
  AppLauncher* app_launcher = new AppLauncher(browser);
  BrowserView* browser_view = static_cast<BrowserView*>(browser->window());
  app_launcher->hash_params_ = hash_params;
  app_launcher->info_bubble_ =
      PinnedContentsInfoBubble::Show(browser_view->GetWidget(),
          bounds, BubbleBorder::TOP_LEFT, bubble_anchor,
          app_launcher->info_bubble_content_, app_launcher);
  app_launcher->info_bubble_content_->BubbleShown();
  return app_launcher;
}

// static
AppLauncher* AppLauncher::ShowForNewTab(Browser* browser,
                                        const std::string& hash_params) {
  BrowserView* browser_view = static_cast<BrowserView*>(browser->window());
  TabStrip* tabstrip = browser_view->tabstrip()->AsTabStrip();
  if (!tabstrip)
    return NULL;
  gfx::Rect bounds = tabstrip->GetNewTabButtonBounds();
  gfx::Point origin = bounds.origin();
  views::RootView::ConvertPointToScreen(tabstrip, &origin);
  bounds.set_origin(origin);

  // Figure out where the location bar is, so we can pin the bubble to
  // make our url bar appear exactly over it.
  views::View* location_bar = GetBrowserLocationBar(browser);
  gfx::Point location_bar_origin = location_bar->bounds().origin();
  views::RootView::ConvertPointToScreen(location_bar->GetParent(),
                                        &location_bar_origin);

  return Show(browser, bounds, location_bar_origin, hash_params);
}

void AppLauncher::Hide() {
  info_bubble_->Close();
}

void AppLauncher::OpenURLFromTab(TabContents* source,
                                 const GURL& url, const GURL& referrer,
                                 WindowOpenDisposition disposition,
                                 PageTransition::Type transition) {
  // TODO(jcivelli): we should call Browser::OpenApplicationTab(), we would need
  //                 to access the app for this URL.
  // The user clicked an item in the app launcher contents.
  AddTabWithURL(url, PageTransition::AUTO_BOOKMARK);
  Hide();
}

void AppLauncher::AddNewContents(TabContents* source,
                                 TabContents* new_contents,
                                 WindowOpenDisposition disposition,
                                 const gfx::Rect& initial_pos,
                                 bool user_gesture) {
#if defined(OS_CHROMEOS)
  // ChromeOS uses the kURLSwitch to specify a page that opens popups. We need
  // to do this so the popups are opened when the user clicks on the page.
  // TODO: nuke when convert to the real app page.
  new_contents->set_delegate(NULL);
  browser_->GetSelectedTabContents()->AddNewContents(
      new_contents, disposition, initial_pos, user_gesture);
  Hide();
#endif
}

void AppLauncher::UpdatePreferredSize(const gfx::Size& pref_size) {
  if (pref_size.width() == 0 || pref_size.height() == 0)
    return;

  gfx::Size size(pref_size);
  info_bubble_content_->ComputePreferredSize(size);
  info_bubble_->SizeToContents();
}

void AppLauncher::InfoBubbleClosing(InfoBubble* info_bubble,
                                    bool closed_by_escape) {
  // Delay deleting to be safe (we, and our tabcontents may be on the stack).
  // Remove ourself as a delegate as on GTK the Widget destruction is
  // asynchronous and will happen after the AppLauncher has been deleted (and it
  // might notify us after we have been deleted).
  info_bubble_content_->GetBubbleTabContents()->set_delegate(NULL);
  MessageLoop::current()->PostTask(FROM_HERE,
                                   new DeleteTask<AppLauncher>(this));
}

void AppLauncher::AddTabWithURL(const GURL& url,
                                PageTransition::Type transition) {
#if defined(OS_CHROMEOS)
  switch (chromeos::StatusAreaView::GetOpenTabsMode()) {
    case chromeos::StatusAreaView::OPEN_TABS_ON_LEFT: {
      // Add the new tab at the first non-pinned location.
      int index = browser_->tabstrip_model()->IndexOfFirstNonMiniTab();
      browser_->AddTabWithURL(url, GURL(), transition, index,
                              Browser::ADD_SELECTED | Browser::ADD_FORCE_INDEX,
                              NULL, std::string());
      break;
    }
    case chromeos::StatusAreaView::OPEN_TABS_CLOBBER: {
      browser_->GetSelectedTabContents()->controller().LoadURL(
          url, GURL(), transition);
      break;
    }
    case chromeos::StatusAreaView::OPEN_TABS_ON_RIGHT: {
      browser_->AddTabWithURL(url, GURL(), transition, -1,
                              Browser::ADD_SELECTED | Browser::ADD_FORCE_INDEX,
                              NULL, std::string());
      break;
    }
  }
#else
  browser_->AddTabWithURL(url, GURL(), transition, -1,
                          Browser::ADD_SELECTED | Browser::ADD_FORCE_INDEX,
                          NULL, std::string());
#endif
}
<|endoftext|>


<commit_before><commit_msg>Try to cleanup temporary directories created during install operations.<commit_after><|endoftext|>