<commit_before>#include <stan/math/prim/scal/meta/require_generics.hpp>
#include <test/unit/math/require_util.hpp>
#include <gtest/gtest.h>
#include <type_traits>
#include <string>

// Basic tests for the underlying requires
TEST(requires_prim_scal, t_test) {
  using stan::require_t;
  using stan::test::unary_require_tester;
  EXPECT_TRUE((unary_require_tester<require_t, std::true_type>::value));
  EXPECT_FALSE((unary_require_tester<require_t, std::false_type>::value));
}

TEST(requires_prim_scal, not_test) {
  using stan::require_not_t;
  using stan::test::unary_require_tester;
  EXPECT_TRUE((unary_require_tester<require_not_t, std::false_type>::value));
  EXPECT_FALSE((unary_require_tester<require_not_t, std::true_type>::value));
}

TEST(requires_prim_scal, all_not_test) {
  using stan::require_all_not_t;
  using stan::test::require_variadic_checker;
  EXPECT_TRUE((require_variadic_checker<require_all_not_t, std::false_type,
                                        std::false_type>::value));
  EXPECT_FALSE((require_variadic_checker<require_all_not_t, std::true_type,
                                         std::true_type>::value));
  EXPECT_TRUE((require_variadic_checker<require_all_not_t, std::true_type,
                                        std::false_type>::value));
}

TEST(requires_prim_scal, any_not_test) {
  using stan::require_any_not_t;
  using stan::test::require_variadic_checker;
  EXPECT_TRUE((require_variadic_checker<require_any_not_t, std::false_type,
                                        std::false_type>::value));
  EXPECT_FALSE((require_variadic_checker<require_any_not_t, std::true_type,
                                         std::true_type>::value));
  EXPECT_FALSE((require_variadic_checker<require_any_not_t, std::true_type,
                                         std::false_type>::value));
}

TEST(requires_prim_scal, all_test) {
  using stan::require_all_t;
  using stan::test::require_variadic_checker;
  EXPECT_FALSE((require_variadic_checker<require_all_t, std::false_type,
                                         std::false_type>::value));
  EXPECT_TRUE((require_variadic_checker<require_all_t, std::true_type,
                                        std::true_type>::value));
  EXPECT_FALSE((require_variadic_checker<require_all_t, std::true_type,
                                         std::false_type>::value));
}

TEST(requires_prim_scal, any_test) {
  using stan::require_any_t;
  using stan::test::require_variadic_checker;
  EXPECT_FALSE((require_variadic_checker<require_any_t, std::false_type,
                                         std::false_type>::value));
  EXPECT_TRUE((require_variadic_checker<require_any_t, std::true_type,
                                        std::true_type>::value));
  EXPECT_TRUE((require_variadic_checker<require_any_t, std::true_type,
                                        std::false_type>::value));
}

// Test same
TEST(requires_prim_scal, same_test) {
  using stan::require_same_t;
  using stan::test::require_variadic_checker;
  EXPECT_FALSE(
      (require_variadic_checker<stan::require_same_t, double, int>::value));
  EXPECT_TRUE(
      (require_variadic_checker<stan::require_same_t, double, double>::value));
  EXPECT_TRUE(
      (require_variadic_checker<stan::require_same_t, int, int>::value));
}

TEST(requires_prim_scal, not_same_test) {
  using stan::require_not_same_t;
  using stan::test::require_variadic_checker;
  EXPECT_TRUE(
      (require_variadic_checker<require_not_same_t, double, int>::value));
  EXPECT_FALSE(
      (require_variadic_checker<require_not_same_t, double, double>::value));
  EXPECT_FALSE((require_variadic_checker<require_not_same_t, int, int>::value));
}

TEST(requires_prim_scal, all_same_test) {
  using stan::require_all_same_t;
  using stan::test::require_variadic_checker;
  EXPECT_FALSE((require_variadic_checker<require_all_same_t, double,
                                         std::string, double>::value));
  EXPECT_TRUE((require_variadic_checker<require_all_same_t, double, double,
                                        double>::value));
  EXPECT_TRUE(
      (require_variadic_checker<require_all_same_t, int, int, int>::value));
}

TEST(requires_prim_scal, all_not_same_test) {
  using stan::require_any_not_same_t;
  using stan::test::require_variadic_checker;
  EXPECT_TRUE((require_variadic_checker<require_any_not_same_t, double, int,
                                        double>::value));
  EXPECT_FALSE((require_variadic_checker<require_any_not_same_t, double, double,
                                         double>::value));
  EXPECT_FALSE(
      (require_variadic_checker<require_any_not_same_t, int, int, int>::value));
}

// Test convertible
TEST(requires_prim_scal, convertible_test) {
  using stan::require_convertible_t;
  using stan::test::require_variadic_checker;
  EXPECT_FALSE((require_variadic_checker<stan::require_convertible_t, double,
                                         char[1]>::value));
  EXPECT_TRUE((require_variadic_checker<stan::require_convertible_t, double,
                                        double>::value));
  EXPECT_TRUE(
      (require_variadic_checker<stan::require_convertible_t, int, int>::value));
}

TEST(requires_prim_scal, not_convertible_test) {
  using stan::require_not_convertible_t;
  using stan::test::require_variadic_checker;
  EXPECT_TRUE((require_variadic_checker<require_not_convertible_t, double,
                                        char[1]>::value));
  EXPECT_FALSE((require_variadic_checker<require_not_convertible_t, double,
                                         double>::value));
  EXPECT_FALSE(
      (require_variadic_checker<require_not_convertible_t, int, int>::value));
}

TEST(requires_prim_scal, all_convertible_test) {
  using stan::require_all_convertible_t;
  using stan::test::require_variadic_checker;
  EXPECT_FALSE((require_variadic_checker<require_all_convertible_t, double,
                                         std::string, double>::value));
  EXPECT_TRUE((require_variadic_checker<require_all_convertible_t, double, int,
                                        int>::value));
  EXPECT_TRUE((require_variadic_checker<require_all_convertible_t, int, int,
                                        int>::value));
}

TEST(requires_prim_scal, all_not_convertible_test) {
  using stan::require_any_not_convertible_t;
  using stan::test::require_variadic_checker;
  EXPECT_TRUE((require_variadic_checker<require_any_not_convertible_t, double,
                                        int, std::string>::value));
  EXPECT_FALSE((require_variadic_checker<require_any_not_convertible_t, double,
                                         double, double>::value));
  EXPECT_FALSE((require_variadic_checker<require_any_not_convertible_t, int,
                                         double, int>::value));
}

// Double or Int
TEST(requires_prim_scal, double_or_int_test) {
  using stan::test::require_scal_checker;
  require_scal_checker<stan::require_double_or_int_t, double, int>::unary();
  require_scal_checker<stan::require_not_double_or_int_t, double,
                       int>::not_unary();
  require_scal_checker<stan::require_all_double_or_int_t, double, int>::all();
  require_scal_checker<stan::require_all_not_double_or_int_t, double,
                       int>::all_not();
  require_scal_checker<stan::require_any_double_or_int_t, double, int>::any();
  require_scal_checker<stan::require_any_not_double_or_int_t, double,
                       int>::any_not();
}

// Double or Int
TEST(requires_prim_scal, double_or_int_test) {
  using stan::test::require_scal_checker;
  require_scal_checker<stan::require_string_convertible_t, string, const char*>::unary();
  require_scal_checker<stan::require_not_string_convertible_t, string, const char*>::not_unary();
  require_scal_checker<stan::require_all_string_convertible_t, string, const char*>::all();
  require_scal_checker<stan::require_all_not_string_convertible_t, string, const char*>::all_not();
  require_scal_checker<stan::require_any_string_convertible_t, string, const char*>::any();
  require_scal_checker<stan::require_any_not_string_convertible_t, string, const char*>::any_not();
}

TEST(requires_prim_scal, arithmetic_test) {
  using stan::test::require_scal_checker;
  require_scal_checker<stan::require_arithmetic_t, double, float, int>::unary();
  require_scal_checker<stan::require_not_arithmetic_t, double, float,
                       int>::not_unary();
  require_scal_checker<stan::require_all_arithmetic_t, double, float,
                       int>::all();
  require_scal_checker<stan::require_all_not_arithmetic_t, double, float,
                       int>::all_not();
  require_scal_checker<stan::require_any_arithmetic_t, double, float,
                       int>::any();
  require_scal_checker<stan::require_any_not_arithmetic_t, double, float,
                       int>::any_not();
}

TEST(requires_prim_scal, var_or_arithmetic_test) {
  using stan::test::require_scal_checker;
  require_scal_checker<stan::require_var_or_arithmetic_t, double, int>::unary();
  require_scal_checker<stan::require_not_var_or_arithmetic_t, double,
                       int>::not_unary();
  require_scal_checker<stan::require_all_var_or_arithmetic_t, double,
                       int>::all();
  require_scal_checker<stan::require_all_not_var_or_arithmetic_t, double,
                       int>::all_not();
  require_scal_checker<stan::require_any_var_or_arithmetic_t, double,
                       int>::any();
  require_scal_checker<stan::require_any_not_var_or_arithmetic_t, double,
                       int>::any_not();
}
<commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.0-3~16.04.1 (tags/RELEASE_500/final)<commit_after>#include <stan/math/prim/scal/meta/require_generics.hpp>
#include <test/unit/math/require_util.hpp>
#include <gtest/gtest.h>
#include <type_traits>
#include <string>

// Basic tests for the underlying requires
TEST(requires_prim_scal, t_test) {
  using stan::require_t;
  using stan::test::unary_require_tester;
  EXPECT_TRUE((unary_require_tester<require_t, std::true_type>::value));
  EXPECT_FALSE((unary_require_tester<require_t, std::false_type>::value));
}

TEST(requires_prim_scal, not_test) {
  using stan::require_not_t;
  using stan::test::unary_require_tester;
  EXPECT_TRUE((unary_require_tester<require_not_t, std::false_type>::value));
  EXPECT_FALSE((unary_require_tester<require_not_t, std::true_type>::value));
}

TEST(requires_prim_scal, all_not_test) {
  using stan::require_all_not_t;
  using stan::test::require_variadic_checker;
  EXPECT_TRUE((require_variadic_checker<require_all_not_t, std::false_type,
                                        std::false_type>::value));
  EXPECT_FALSE((require_variadic_checker<require_all_not_t, std::true_type,
                                         std::true_type>::value));
  EXPECT_TRUE((require_variadic_checker<require_all_not_t, std::true_type,
                                        std::false_type>::value));
}

TEST(requires_prim_scal, any_not_test) {
  using stan::require_any_not_t;
  using stan::test::require_variadic_checker;
  EXPECT_TRUE((require_variadic_checker<require_any_not_t, std::false_type,
                                        std::false_type>::value));
  EXPECT_FALSE((require_variadic_checker<require_any_not_t, std::true_type,
                                         std::true_type>::value));
  EXPECT_FALSE((require_variadic_checker<require_any_not_t, std::true_type,
                                         std::false_type>::value));
}

TEST(requires_prim_scal, all_test) {
  using stan::require_all_t;
  using stan::test::require_variadic_checker;
  EXPECT_FALSE((require_variadic_checker<require_all_t, std::false_type,
                                         std::false_type>::value));
  EXPECT_TRUE((require_variadic_checker<require_all_t, std::true_type,
                                        std::true_type>::value));
  EXPECT_FALSE((require_variadic_checker<require_all_t, std::true_type,
                                         std::false_type>::value));
}

TEST(requires_prim_scal, any_test) {
  using stan::require_any_t;
  using stan::test::require_variadic_checker;
  EXPECT_FALSE((require_variadic_checker<require_any_t, std::false_type,
                                         std::false_type>::value));
  EXPECT_TRUE((require_variadic_checker<require_any_t, std::true_type,
                                        std::true_type>::value));
  EXPECT_TRUE((require_variadic_checker<require_any_t, std::true_type,
                                        std::false_type>::value));
}

// Test same
TEST(requires_prim_scal, same_test) {
  using stan::require_same_t;
  using stan::test::require_variadic_checker;
  EXPECT_FALSE(
      (require_variadic_checker<stan::require_same_t, double, int>::value));
  EXPECT_TRUE(
      (require_variadic_checker<stan::require_same_t, double, double>::value));
  EXPECT_TRUE(
      (require_variadic_checker<stan::require_same_t, int, int>::value));
}

TEST(requires_prim_scal, not_same_test) {
  using stan::require_not_same_t;
  using stan::test::require_variadic_checker;
  EXPECT_TRUE(
      (require_variadic_checker<require_not_same_t, double, int>::value));
  EXPECT_FALSE(
      (require_variadic_checker<require_not_same_t, double, double>::value));
  EXPECT_FALSE((require_variadic_checker<require_not_same_t, int, int>::value));
}

TEST(requires_prim_scal, all_same_test) {
  using stan::require_all_same_t;
  using stan::test::require_variadic_checker;
  EXPECT_FALSE((require_variadic_checker<require_all_same_t, double,
                                         std::string, double>::value));
  EXPECT_TRUE((require_variadic_checker<require_all_same_t, double, double,
                                        double>::value));
  EXPECT_TRUE(
      (require_variadic_checker<require_all_same_t, int, int, int>::value));
}

TEST(requires_prim_scal, all_not_same_test) {
  using stan::require_any_not_same_t;
  using stan::test::require_variadic_checker;
  EXPECT_TRUE((require_variadic_checker<require_any_not_same_t, double, int,
                                        double>::value));
  EXPECT_FALSE((require_variadic_checker<require_any_not_same_t, double, double,
                                         double>::value));
  EXPECT_FALSE(
      (require_variadic_checker<require_any_not_same_t, int, int, int>::value));
}

// Test convertible
TEST(requires_prim_scal, convertible_test) {
  using stan::require_convertible_t;
  using stan::test::require_variadic_checker;
  EXPECT_FALSE((require_variadic_checker<stan::require_convertible_t, double,
                                         char[1]>::value));
  EXPECT_TRUE((require_variadic_checker<stan::require_convertible_t, double,
                                        double>::value));
  EXPECT_TRUE(
      (require_variadic_checker<stan::require_convertible_t, int, int>::value));
}

TEST(requires_prim_scal, not_convertible_test) {
  using stan::require_not_convertible_t;
  using stan::test::require_variadic_checker;
  EXPECT_TRUE((require_variadic_checker<require_not_convertible_t, double,
                                        char[1]>::value));
  EXPECT_FALSE((require_variadic_checker<require_not_convertible_t, double,
                                         double>::value));
  EXPECT_FALSE(
      (require_variadic_checker<require_not_convertible_t, int, int>::value));
}

TEST(requires_prim_scal, all_convertible_test) {
  using stan::require_all_convertible_t;
  using stan::test::require_variadic_checker;
  EXPECT_FALSE((require_variadic_checker<require_all_convertible_t, double,
                                         std::string, double>::value));
  EXPECT_TRUE((require_variadic_checker<require_all_convertible_t, double, int,
                                        int>::value));
  EXPECT_TRUE((require_variadic_checker<require_all_convertible_t, int, int,
                                        int>::value));
}

TEST(requires_prim_scal, all_not_convertible_test) {
  using stan::require_any_not_convertible_t;
  using stan::test::require_variadic_checker;
  EXPECT_TRUE((require_variadic_checker<require_any_not_convertible_t, double,
                                        int, std::string>::value));
  EXPECT_FALSE((require_variadic_checker<require_any_not_convertible_t, double,
                                         double, double>::value));
  EXPECT_FALSE((require_variadic_checker<require_any_not_convertible_t, int,
                                         double, int>::value));
}

// Double or Int
TEST(requires_prim_scal, double_or_int_test) {
  using stan::test::require_scal_checker;
  require_scal_checker<stan::require_double_or_int_t, double, int>::unary();
  require_scal_checker<stan::require_not_double_or_int_t, double,
                       int>::not_unary();
  require_scal_checker<stan::require_all_double_or_int_t, double, int>::all();
  require_scal_checker<stan::require_all_not_double_or_int_t, double,
                       int>::all_not();
  require_scal_checker<stan::require_any_double_or_int_t, double, int>::any();
  require_scal_checker<stan::require_any_not_double_or_int_t, double,
                       int>::any_not();
}

// Double or Int
TEST(requires_prim_scal, double_or_int_test) {
  using stan::test::require_scal_checker;
  require_scal_checker<stan::require_string_convertible_t, string,
                       const char*>::unary();
  require_scal_checker<stan::require_not_string_convertible_t, string,
                       const char*>::not_unary();
  require_scal_checker<stan::require_all_string_convertible_t, string,
                       const char*>::all();
  require_scal_checker<stan::require_all_not_string_convertible_t, string,
                       const char*>::all_not();
  require_scal_checker<stan::require_any_string_convertible_t, string,
                       const char*>::any();
  require_scal_checker<stan::require_any_not_string_convertible_t, string,
                       const char*>::any_not();
}

TEST(requires_prim_scal, arithmetic_test) {
  using stan::test::require_scal_checker;
  require_scal_checker<stan::require_arithmetic_t, double, float, int>::unary();
  require_scal_checker<stan::require_not_arithmetic_t, double, float,
                       int>::not_unary();
  require_scal_checker<stan::require_all_arithmetic_t, double, float,
                       int>::all();
  require_scal_checker<stan::require_all_not_arithmetic_t, double, float,
                       int>::all_not();
  require_scal_checker<stan::require_any_arithmetic_t, double, float,
                       int>::any();
  require_scal_checker<stan::require_any_not_arithmetic_t, double, float,
                       int>::any_not();
}

TEST(requires_prim_scal, var_or_arithmetic_test) {
  using stan::test::require_scal_checker;
  require_scal_checker<stan::require_var_or_arithmetic_t, double, int>::unary();
  require_scal_checker<stan::require_not_var_or_arithmetic_t, double,
                       int>::not_unary();
  require_scal_checker<stan::require_all_var_or_arithmetic_t, double,
                       int>::all();
  require_scal_checker<stan::require_all_not_var_or_arithmetic_t, double,
                       int>::all_not();
  require_scal_checker<stan::require_any_var_or_arithmetic_t, double,
                       int>::any();
  require_scal_checker<stan::require_any_not_var_or_arithmetic_t, double,
                       int>::any_not();
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2003-2009 Rony Shapiro <ronys@users.sourceforge.net>.
 * All rights reserved. Use of the code is allowed under the
 * Artistic License 2.0 terms, as specified in the LICENSE file
 * distributed with this code, or available from
 * http://www.opensource.org/licenses/artistic-license-2.0.php
 */

/** \file safecombinationprompt.cpp
*
*/
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
#pragma hdrstop
#endif

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

////@begin includes
////@end includes

#include "safecombinationprompt.h"
#include "os/file.h"

////@begin XPM images
#include "../graphics/cpane.xpm"
////@end XPM images

/*!
 * CSafeCombinationPrompt type definition
 */

IMPLEMENT_CLASS( CSafeCombinationPrompt, wxDialog )

/*!
 * CSafeCombinationPrompt event table definition
 */

BEGIN_EVENT_TABLE( CSafeCombinationPrompt, wxDialog )

////@begin CSafeCombinationPrompt event table entries
  EVT_BUTTON( wxID_OK, CSafeCombinationPrompt::OnOkClick )

  EVT_BUTTON( wxID_CANCEL, CSafeCombinationPrompt::OnCancelClick )

////@end CSafeCombinationPrompt event table entries

END_EVENT_TABLE()

/*!
 * CSafeCombinationPrompt constructors
 */

CSafeCombinationPrompt::CSafeCombinationPrompt(wxWindow* parent, PWScore &core,
                                               const wxString &fname, wxWindowID id,
                                               const wxString& caption,
                                               const wxPoint& pos,
                                               const wxSize& size, long style)
: m_core(core), m_filename(fname), m_tries(0)
{
  Init();
  Create(parent, id, caption, pos, size, style);
}

/*!
 * CSafeCombinationPrompt creator
 */

bool CSafeCombinationPrompt::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
////@begin CSafeCombinationPrompt creation
  SetExtraStyle(wxWS_EX_BLOCK_EVENTS);
  wxDialog::Create( parent, id, caption, pos, size, style );

  CreateControls();
  if (GetSizer())
  {
    GetSizer()->SetSizeHints(this);
  }
  Centre();
////@end CSafeCombinationPrompt creation
  return true;
}

/*!
 * CSafeCombinationPrompt destructor
 */

CSafeCombinationPrompt::~CSafeCombinationPrompt()
{
////@begin CSafeCombinationPrompt destruction
////@end CSafeCombinationPrompt destruction
}

/*!
 * Member initialisation
 */

void CSafeCombinationPrompt::Init()
{
////@begin CSafeCombinationPrompt member initialisation
////@end CSafeCombinationPrompt member initialisation
}

/*!
 * Control creation for CSafeCombinationPrompt
 */

void CSafeCombinationPrompt::CreateControls()
{
////@begin CSafeCombinationPrompt content construction
  CSafeCombinationPrompt* itemDialog1 = this;

  wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL);
  itemDialog1->SetSizer(itemBoxSizer2);

  wxBoxSizer* itemBoxSizer3 = new wxBoxSizer(wxHORIZONTAL);
  itemBoxSizer2->Add(itemBoxSizer3, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);

  wxStaticBitmap* itemStaticBitmap4 = new wxStaticBitmap( itemDialog1, wxID_STATIC, itemDialog1->GetBitmapResource(wxT("../graphics/cpane.xpm")), wxDefaultPosition, itemDialog1->ConvertDialogToPixels(wxSize(49, 46)), 0 );
  itemBoxSizer3->Add(itemStaticBitmap4, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

  wxBoxSizer* itemBoxSizer5 = new wxBoxSizer(wxVERTICAL);
  itemBoxSizer3->Add(itemBoxSizer5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

  wxStaticText* itemStaticText6 = new wxStaticText( itemDialog1, wxID_STATIC, _("Please enter the safe combination for this password database."), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer5->Add(itemStaticText6, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);

  wxStaticText* itemStaticText7 = new wxStaticText( itemDialog1, wxID_STATIC, _("filename"), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer5->Add(itemStaticText7, 0, wxALIGN_LEFT|wxALL, 5);

  wxBoxSizer* itemBoxSizer8 = new wxBoxSizer(wxHORIZONTAL);
  itemBoxSizer5->Add(itemBoxSizer8, 0, wxGROW|wxALL, 5);

  wxStaticText* itemStaticText9 = new wxStaticText( itemDialog1, wxID_STATIC, _("Safe\ncombination:"), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer8->Add(itemStaticText9, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

  wxTextCtrl* itemTextCtrl10 = new wxTextCtrl( itemDialog1, ID_PASSWORD, wxEmptyString, wxDefaultPosition, wxSize(itemDialog1->ConvertDialogToPixels(wxSize(150, -1)).x, -1), wxTE_PASSWORD );
  itemBoxSizer8->Add(itemTextCtrl10, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

  wxStdDialogButtonSizer* itemStdDialogButtonSizer11 = new wxStdDialogButtonSizer;

  itemBoxSizer2->Add(itemStdDialogButtonSizer11, 0, wxGROW|wxALL, 5);
  wxButton* itemButton12 = new wxButton( itemDialog1, wxID_OK, _("&OK"), wxDefaultPosition, wxDefaultSize, 0 );
  itemButton12->SetDefault();
  itemStdDialogButtonSizer11->AddButton(itemButton12);

  wxButton* itemButton13 = new wxButton( itemDialog1, wxID_CANCEL, _("&Cancel"), wxDefaultPosition, wxDefaultSize, 0 );
  itemStdDialogButtonSizer11->AddButton(itemButton13);

  wxButton* itemButton14 = new wxButton( itemDialog1, wxID_HELP, _("&Help"), wxDefaultPosition, wxDefaultSize, 0 );
  itemStdDialogButtonSizer11->AddButton(itemButton14);

  itemStdDialogButtonSizer11->Realize();

  // Set validators
  itemStaticText7->SetValidator( wxGenericValidator(& m_filename) );
  itemTextCtrl10->SetValidator( wxGenericValidator(& m_password) );
////@end CSafeCombinationPrompt content construction
}

/*!
 * Should we show tooltips?
 */

bool CSafeCombinationPrompt::ShowToolTips()
{
  return true;
}

/*!
 * Get bitmap resources
 */

wxBitmap CSafeCombinationPrompt::GetBitmapResource( const wxString& name )
{
  // Bitmap retrieval
////@begin CSafeCombinationPrompt bitmap retrieval
  wxUnusedVar(name);
  if (name == _T("../graphics/cpane.xpm"))
  {
    wxBitmap bitmap(cpane_xpm);
    return bitmap;
  }
  return wxNullBitmap;
////@end CSafeCombinationPrompt bitmap retrieval
}

/*!
 * Get icon resources
 */

wxIcon CSafeCombinationPrompt::GetIconResource( const wxString& name )
{
  // Icon retrieval
////@begin CSafeCombinationPrompt icon retrieval
  wxUnusedVar(name);
  return wxNullIcon;
////@end CSafeCombinationPrompt icon retrieval
}

/*!
 * wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_OK
 */

void CSafeCombinationPrompt::OnOkClick( wxCommandEvent& event )
{
  if (Validate() && TransferDataFromWindow()) {
    if (m_password.empty()) {
      wxMessageDialog err(this, _("The combination cannot be blank."),
                          _("Error"), wxOK | wxICON_EXCLAMATION);
      err.ShowModal();
      return;
    }
    if (!pws_os::FileExists(m_filename.c_str())) {
      wxMessageDialog err(this, _("File or path not found."),
                          _("Error"), wxOK | wxICON_EXCLAMATION);
      err.ShowModal();
      return;
    }
    if (m_core.CheckPassword(m_filename.c_str(),
                             m_password.c_str()) != PWScore::SUCCESS) {
      wxString errmess;
      if (m_tries >= 2) {
        errmess = _("Three strikes - yer out!");
      } else {
        m_tries++;
        errmess = _("Incorrect passkey, not a PasswordSafe database, or a corrupt database. (Backup database has same name as original, ending with '~')");
      }
      wxMessageDialog err(this, errmess,
                          _("Error"), wxOK | wxICON_EXCLAMATION);
      err.ShowModal();
      wxTextCtrl *txt = (wxTextCtrl *)FindWindow(ID_PASSWORD);
      txt->SetSelection(-1,-1);
      txt->SetFocus();
      return;
    }
    // m_core.SetReadOnly(m_readOnly);
    m_core.SetCurFile(m_filename.c_str());
    EndModal(wxID_OK);
  }
}

/*!
 * wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CANCEL
 */

void CSafeCombinationPrompt::OnCancelClick( wxCommandEvent& event )
{
////@begin wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CANCEL in CSafeCombinationPrompt.
  // Before editing this code, remove the block markers.
  EndModal(wxID_CANCEL);
////@end wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CANCEL in CSafeCombinationPrompt.
}

<commit_msg>Set focus to password entry field by default<commit_after>/*
 * Copyright (c) 2003-2009 Rony Shapiro <ronys@users.sourceforge.net>.
 * All rights reserved. Use of the code is allowed under the
 * Artistic License 2.0 terms, as specified in the LICENSE file
 * distributed with this code, or available from
 * http://www.opensource.org/licenses/artistic-license-2.0.php
 */

/** \file safecombinationprompt.cpp
*
*/
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
#pragma hdrstop
#endif

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

////@begin includes
////@end includes

#include "safecombinationprompt.h"
#include "os/file.h"

////@begin XPM images
#include "../graphics/cpane.xpm"
////@end XPM images

/*!
 * CSafeCombinationPrompt type definition
 */

IMPLEMENT_CLASS( CSafeCombinationPrompt, wxDialog )

/*!
 * CSafeCombinationPrompt event table definition
 */

BEGIN_EVENT_TABLE( CSafeCombinationPrompt, wxDialog )

////@begin CSafeCombinationPrompt event table entries
  EVT_BUTTON( wxID_OK, CSafeCombinationPrompt::OnOkClick )

  EVT_BUTTON( wxID_CANCEL, CSafeCombinationPrompt::OnCancelClick )

////@end CSafeCombinationPrompt event table entries

END_EVENT_TABLE()

/*!
 * CSafeCombinationPrompt constructors
 */

CSafeCombinationPrompt::CSafeCombinationPrompt(wxWindow* parent, PWScore &core,
                                               const wxString &fname, wxWindowID id,
                                               const wxString& caption,
                                               const wxPoint& pos,
                                               const wxSize& size, long style)
: m_core(core), m_filename(fname), m_tries(0)
{
  Init();
  Create(parent, id, caption, pos, size, style);
}

/*!
 * CSafeCombinationPrompt creator
 */

bool CSafeCombinationPrompt::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
////@begin CSafeCombinationPrompt creation
  SetExtraStyle(wxWS_EX_BLOCK_EVENTS);
  wxDialog::Create( parent, id, caption, pos, size, style );

  CreateControls();
  if (GetSizer())
  {
    GetSizer()->SetSizeHints(this);
  }
  Centre();
////@end CSafeCombinationPrompt creation
  return true;
}

/*!
 * CSafeCombinationPrompt destructor
 */

CSafeCombinationPrompt::~CSafeCombinationPrompt()
{
////@begin CSafeCombinationPrompt destruction
////@end CSafeCombinationPrompt destruction
}

/*!
 * Member initialisation
 */

void CSafeCombinationPrompt::Init()
{
////@begin CSafeCombinationPrompt member initialisation
////@end CSafeCombinationPrompt member initialisation
}

/*!
 * Control creation for CSafeCombinationPrompt
 */

void CSafeCombinationPrompt::CreateControls()
{
////@begin CSafeCombinationPrompt content construction
  CSafeCombinationPrompt* itemDialog1 = this;

  wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL);
  itemDialog1->SetSizer(itemBoxSizer2);

  wxBoxSizer* itemBoxSizer3 = new wxBoxSizer(wxHORIZONTAL);
  itemBoxSizer2->Add(itemBoxSizer3, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);

  wxStaticBitmap* itemStaticBitmap4 = new wxStaticBitmap( itemDialog1, wxID_STATIC, itemDialog1->GetBitmapResource(wxT("../graphics/cpane.xpm")), wxDefaultPosition, itemDialog1->ConvertDialogToPixels(wxSize(49, 46)), 0 );
  itemBoxSizer3->Add(itemStaticBitmap4, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

  wxBoxSizer* itemBoxSizer5 = new wxBoxSizer(wxVERTICAL);
  itemBoxSizer3->Add(itemBoxSizer5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

  wxStaticText* itemStaticText6 = new wxStaticText( itemDialog1, wxID_STATIC, _("Please enter the safe combination for this password database."), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer5->Add(itemStaticText6, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);

  wxStaticText* itemStaticText7 = new wxStaticText( itemDialog1, wxID_STATIC, _("filename"), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer5->Add(itemStaticText7, 0, wxALIGN_LEFT|wxALL, 5);

  wxBoxSizer* itemBoxSizer8 = new wxBoxSizer(wxHORIZONTAL);
  itemBoxSizer5->Add(itemBoxSizer8, 0, wxGROW|wxALL, 5);

  wxStaticText* itemStaticText9 = new wxStaticText( itemDialog1, wxID_STATIC, _("Safe\ncombination:"), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer8->Add(itemStaticText9, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

  wxTextCtrl* itemTextCtrl10 = new wxTextCtrl( itemDialog1, ID_PASSWORD, wxEmptyString, wxDefaultPosition, wxSize(itemDialog1->ConvertDialogToPixels(wxSize(150, -1)).x, -1), wxTE_PASSWORD );
  itemBoxSizer8->Add(itemTextCtrl10, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

  wxStdDialogButtonSizer* itemStdDialogButtonSizer11 = new wxStdDialogButtonSizer;

  itemBoxSizer2->Add(itemStdDialogButtonSizer11, 0, wxGROW|wxALL, 5);
  wxButton* itemButton12 = new wxButton( itemDialog1, wxID_OK, _("&OK"), wxDefaultPosition, wxDefaultSize, 0 );
  itemButton12->SetDefault();
  itemStdDialogButtonSizer11->AddButton(itemButton12);

  wxButton* itemButton13 = new wxButton( itemDialog1, wxID_CANCEL, _("&Cancel"), wxDefaultPosition, wxDefaultSize, 0 );
  itemStdDialogButtonSizer11->AddButton(itemButton13);

  wxButton* itemButton14 = new wxButton( itemDialog1, wxID_HELP, _("&Help"), wxDefaultPosition, wxDefaultSize, 0 );
  itemStdDialogButtonSizer11->AddButton(itemButton14);

  itemStdDialogButtonSizer11->Realize();

  // Set validators
  itemStaticText7->SetValidator( wxGenericValidator(& m_filename) );
  itemTextCtrl10->SetValidator( wxGenericValidator(& m_password) );
////@end CSafeCombinationPrompt content construction

  wxWindow* passwdCtrl = FindWindow(ID_PASSWORD);
  if (passwdCtrl)
    passwdCtrl->SetFocus();
}

/*!
 * Should we show tooltips?
 */

bool CSafeCombinationPrompt::ShowToolTips()
{
  return true;
}

/*!
 * Get bitmap resources
 */

wxBitmap CSafeCombinationPrompt::GetBitmapResource( const wxString& name )
{
  // Bitmap retrieval
////@begin CSafeCombinationPrompt bitmap retrieval
  wxUnusedVar(name);
  if (name == _T("../graphics/cpane.xpm"))
  {
    wxBitmap bitmap(cpane_xpm);
    return bitmap;
  }
  return wxNullBitmap;
////@end CSafeCombinationPrompt bitmap retrieval
}

/*!
 * Get icon resources
 */

wxIcon CSafeCombinationPrompt::GetIconResource( const wxString& name )
{
  // Icon retrieval
////@begin CSafeCombinationPrompt icon retrieval
  wxUnusedVar(name);
  return wxNullIcon;
////@end CSafeCombinationPrompt icon retrieval
}

/*!
 * wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_OK
 */

void CSafeCombinationPrompt::OnOkClick( wxCommandEvent& event )
{
  if (Validate() && TransferDataFromWindow()) {
    if (m_password.empty()) {
      wxMessageDialog err(this, _("The combination cannot be blank."),
                          _("Error"), wxOK | wxICON_EXCLAMATION);
      err.ShowModal();
      return;
    }
    if (!pws_os::FileExists(m_filename.c_str())) {
      wxMessageDialog err(this, _("File or path not found."),
                          _("Error"), wxOK | wxICON_EXCLAMATION);
      err.ShowModal();
      return;
    }
    if (m_core.CheckPassword(m_filename.c_str(),
                             m_password.c_str()) != PWScore::SUCCESS) {
      wxString errmess;
      if (m_tries >= 2) {
        errmess = _("Three strikes - yer out!");
      } else {
        m_tries++;
        errmess = _("Incorrect passkey, not a PasswordSafe database, or a corrupt database. (Backup database has same name as original, ending with '~')");
      }
      wxMessageDialog err(this, errmess,
                          _("Error"), wxOK | wxICON_EXCLAMATION);
      err.ShowModal();
      wxTextCtrl *txt = (wxTextCtrl *)FindWindow(ID_PASSWORD);
      txt->SetSelection(-1,-1);
      txt->SetFocus();
      return;
    }
    // m_core.SetReadOnly(m_readOnly);
    m_core.SetCurFile(m_filename.c_str());
    EndModal(wxID_OK);
  }
}

/*!
 * wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CANCEL
 */

void CSafeCombinationPrompt::OnCancelClick( wxCommandEvent& event )
{
////@begin wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CANCEL in CSafeCombinationPrompt.
  // Before editing this code, remove the block markers.
  EndModal(wxID_CANCEL);
////@end wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CANCEL in CSafeCombinationPrompt.
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: resourceprovider.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 23:53:20 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _RESOURCEPROVIDER_HXX_
#define _RESOURCEPROVIDER_HXX_

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring>
#endif

//------------------------------------------------------------------------
// deklarations
//------------------------------------------------------------------------

class CResourceProvider_Impl;

class CResourceProvider
{
public:
    CResourceProvider( );
    ~CResourceProvider( );

    rtl::OUString getResString( sal_Int32 aId );

private:
    CResourceProvider_Impl* m_pImpl;
};

#endif
<commit_msg>INTEGRATION: CWS sb59 (1.2.100); FILE MERGED 2006/08/10 12:04:55 sb 1.2.100.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: resourceprovider.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 10:56:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _RESOURCEPROVIDER_HXX_
#define _RESOURCEPROVIDER_HXX_

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring>
#endif

//------------------------------------------------------------------------
// deklarations
//------------------------------------------------------------------------

class CResourceProvider_Impl;

class CResourceProvider
{
public:
    CResourceProvider( );
    ~CResourceProvider( );

    rtl::OUString getResString( sal_Int16 aId );

private:
    CResourceProvider_Impl* m_pImpl;
};

#endif
<|endoftext|>


<commit_before>//===-- SocketTest.cpp ------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "SocketTestUtilities.h"
#include "lldb/Utility/UriParser.h"
#include "gtest/gtest.h"

using namespace lldb_private;

class SocketTest : public testing::Test {
public:
  void SetUp() override {
    ASSERT_THAT_ERROR(Socket::Initialize(), llvm::Succeeded());
  }

  void TearDown() override { Socket::Terminate(); }
};

TEST_F(SocketTest, DecodeHostAndPort) {
  std::string host_str;
  std::string port_str;
  int32_t port;
  Status error;
  EXPECT_TRUE(Socket::DecodeHostAndPort("localhost:1138", host_str, port_str,
                                        port, &error));
  EXPECT_STREQ("localhost", host_str.c_str());
  EXPECT_STREQ("1138", port_str.c_str());
  EXPECT_EQ(1138, port);
  EXPECT_TRUE(error.Success());

  EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:65536", host_str, port_str,
                                         port, &error));
  EXPECT_TRUE(error.Fail());
  EXPECT_STREQ("invalid host:port specification: 'google.com:65536'",
               error.AsCString());

  EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:-1138", host_str, port_str,
                                         port, &error));
  EXPECT_TRUE(error.Fail());
  EXPECT_STREQ("invalid host:port specification: 'google.com:-1138'",
               error.AsCString());

  EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:65536", host_str, port_str,
                                         port, &error));
  EXPECT_TRUE(error.Fail());
  EXPECT_STREQ("invalid host:port specification: 'google.com:65536'",
               error.AsCString());

  EXPECT_TRUE(
      Socket::DecodeHostAndPort("12345", host_str, port_str, port, &error));
  EXPECT_STREQ("", host_str.c_str());
  EXPECT_STREQ("12345", port_str.c_str());
  EXPECT_EQ(12345, port);
  EXPECT_TRUE(error.Success());

  EXPECT_TRUE(
      Socket::DecodeHostAndPort("*:0", host_str, port_str, port, &error));
  EXPECT_STREQ("*", host_str.c_str());
  EXPECT_STREQ("0", port_str.c_str());
  EXPECT_EQ(0, port);
  EXPECT_TRUE(error.Success());

  EXPECT_TRUE(
      Socket::DecodeHostAndPort("*:65535", host_str, port_str, port, &error));
  EXPECT_STREQ("*", host_str.c_str());
  EXPECT_STREQ("65535", port_str.c_str());
  EXPECT_EQ(65535, port);
  EXPECT_TRUE(error.Success());

  EXPECT_TRUE(
      Socket::DecodeHostAndPort("[::1]:12345", host_str, port_str, port, &error));
  EXPECT_STREQ("::1", host_str.c_str());
  EXPECT_STREQ("12345", port_str.c_str());
  EXPECT_EQ(12345, port);
  EXPECT_TRUE(error.Success());

  EXPECT_TRUE(
      Socket::DecodeHostAndPort("[abcd:12fg:AF58::1]:12345", host_str, port_str, port, &error));
  EXPECT_STREQ("abcd:12fg:AF58::1", host_str.c_str());
  EXPECT_STREQ("12345", port_str.c_str());
  EXPECT_EQ(12345, port);
  EXPECT_TRUE(error.Success());
}

#ifndef LLDB_DISABLE_POSIX
TEST_F(SocketTest, DomainListenConnectAccept) {
  llvm::SmallString<64> Path;
  std::error_code EC = llvm::sys::fs::createUniqueDirectory("DomainListenConnectAccept", Path);
  ASSERT_FALSE(EC);
  llvm::sys::path::append(Path, "test");
  // If this fails, $TMPDIR is too long to hold a domain socket.
  EXPECT_LE(Path.size(), 107u);

  std::unique_ptr<DomainSocket> socket_a_up;
  std::unique_ptr<DomainSocket> socket_b_up;
  CreateDomainConnectedSockets(Path, &socket_a_up, &socket_b_up);
}
#endif

TEST_F(SocketTest, TCPListen0ConnectAccept) {
  std::unique_ptr<TCPSocket> socket_a_up;
  std::unique_ptr<TCPSocket> socket_b_up;
  CreateTCPConnectedSockets("127.0.0.1", &socket_a_up, &socket_b_up);
}

TEST_F(SocketTest, TCPGetAddress) {
  std::unique_ptr<TCPSocket> socket_a_up;
  std::unique_ptr<TCPSocket> socket_b_up;
  if (!IsAddressFamilySupported("127.0.0.1")) {
    GTEST_LOG_(WARNING) << "Skipping test due to missing IPv4 support.";
    return;
  }
  CreateTCPConnectedSockets("127.0.0.1", &socket_a_up, &socket_b_up);

  EXPECT_EQ(socket_a_up->GetLocalPortNumber(),
            socket_b_up->GetRemotePortNumber());
  EXPECT_EQ(socket_b_up->GetLocalPortNumber(),
            socket_a_up->GetRemotePortNumber());
  EXPECT_NE(socket_a_up->GetLocalPortNumber(),
            socket_b_up->GetLocalPortNumber());
  EXPECT_STREQ("127.0.0.1", socket_a_up->GetRemoteIPAddress().c_str());
  EXPECT_STREQ("127.0.0.1", socket_b_up->GetRemoteIPAddress().c_str());
}

TEST_F(SocketTest, UDPConnect) {
  Socket *socket;

  bool child_processes_inherit = false;
  auto error = UDPSocket::Connect("127.0.0.1:0", child_processes_inherit,
                                  socket);

  std::unique_ptr<Socket> socket_up(socket);

  EXPECT_TRUE(error.Success());
  EXPECT_TRUE(socket_up->IsValid());
}

TEST_F(SocketTest, TCPListen0GetPort) {
  Socket *server_socket;
  Predicate<uint16_t> port_predicate;
  port_predicate.SetValue(0, eBroadcastNever);
  Status err =
      Socket::TcpListen("10.10.12.3:0", false, server_socket, &port_predicate);
  std::unique_ptr<TCPSocket> socket_up((TCPSocket*)server_socket);
  EXPECT_TRUE(socket_up->IsValid());
  EXPECT_NE(socket_up->GetLocalPortNumber(), 0);
}

TEST_F(SocketTest, TCPGetConnectURI) {
  std::unique_ptr<TCPSocket> socket_a_up;
  std::unique_ptr<TCPSocket> socket_b_up;
  if (!IsAddressFamilySupported("127.0.0.1")) {
    GTEST_LOG_(WARNING) << "Skipping test due to missing IPv4 support.";
    return;
  }
  CreateTCPConnectedSockets("127.0.0.1", &socket_a_up, &socket_b_up);

  llvm::StringRef scheme;
  llvm::StringRef hostname;
  int port;
  llvm::StringRef path;
  std::string uri(socket_a_up->GetRemoteConnectionURI());
  EXPECT_TRUE(UriParser::Parse(uri, scheme, hostname, port, path));
  EXPECT_EQ(scheme, "connect");
  EXPECT_EQ(port, socket_a_up->GetRemotePortNumber());
}

TEST_F(SocketTest, UDPGetConnectURI) {
  if (!IsAddressFamilySupported("127.0.0.1")) {
    GTEST_LOG_(WARNING) << "Skipping test due to missing IPv4 support.";
    return;
  }
  Socket *socket;
  bool child_processes_inherit = false;
  auto error =
      UDPSocket::Connect("127.0.0.1:0", child_processes_inherit, socket);

  llvm::StringRef scheme;
  llvm::StringRef hostname;
  int port;
  llvm::StringRef path;
  std::string uri(socket->GetRemoteConnectionURI());
  EXPECT_TRUE(UriParser::Parse(uri, scheme, hostname, port, path));
  EXPECT_EQ(scheme, "udp");
}

#ifndef LLDB_DISABLE_POSIX
TEST_F(SocketTest, DomainGetConnectURI) {
  llvm::SmallString<64> domain_path;
  std::error_code EC =
      llvm::sys::fs::createUniqueDirectory("DomainListenConnectAccept", domain_path);
  ASSERT_FALSE(EC);
  llvm::sys::path::append(domain_path, "test");
  // If this fails, $TMPDIR is too long to hold a domain socket.
  EXPECT_LE(domain_path.size(), 107u);

  std::unique_ptr<DomainSocket> socket_a_up;
  std::unique_ptr<DomainSocket> socket_b_up;
  CreateDomainConnectedSockets(domain_path, &socket_a_up, &socket_b_up);

  llvm::StringRef scheme;
  llvm::StringRef hostname;
  int port;
  llvm::StringRef path;
  std::string uri(socket_a_up->GetRemoteConnectionURI());
  EXPECT_TRUE(UriParser::Parse(uri, scheme, hostname, port, path));
  EXPECT_EQ(scheme, "unix-connect");
  EXPECT_EQ(path, domain_path);
}
#endif
<commit_msg>[unittest] Skip the socket tests if we $TMPDIR is too long.<commit_after>//===-- SocketTest.cpp ------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "SocketTestUtilities.h"
#include "lldb/Utility/UriParser.h"
#include "gtest/gtest.h"

using namespace lldb_private;

class SocketTest : public testing::Test {
public:
  void SetUp() override {
    ASSERT_THAT_ERROR(Socket::Initialize(), llvm::Succeeded());
  }

  void TearDown() override { Socket::Terminate(); }
};

TEST_F(SocketTest, DecodeHostAndPort) {
  std::string host_str;
  std::string port_str;
  int32_t port;
  Status error;
  EXPECT_TRUE(Socket::DecodeHostAndPort("localhost:1138", host_str, port_str,
                                        port, &error));
  EXPECT_STREQ("localhost", host_str.c_str());
  EXPECT_STREQ("1138", port_str.c_str());
  EXPECT_EQ(1138, port);
  EXPECT_TRUE(error.Success());

  EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:65536", host_str, port_str,
                                         port, &error));
  EXPECT_TRUE(error.Fail());
  EXPECT_STREQ("invalid host:port specification: 'google.com:65536'",
               error.AsCString());

  EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:-1138", host_str, port_str,
                                         port, &error));
  EXPECT_TRUE(error.Fail());
  EXPECT_STREQ("invalid host:port specification: 'google.com:-1138'",
               error.AsCString());

  EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:65536", host_str, port_str,
                                         port, &error));
  EXPECT_TRUE(error.Fail());
  EXPECT_STREQ("invalid host:port specification: 'google.com:65536'",
               error.AsCString());

  EXPECT_TRUE(
      Socket::DecodeHostAndPort("12345", host_str, port_str, port, &error));
  EXPECT_STREQ("", host_str.c_str());
  EXPECT_STREQ("12345", port_str.c_str());
  EXPECT_EQ(12345, port);
  EXPECT_TRUE(error.Success());

  EXPECT_TRUE(
      Socket::DecodeHostAndPort("*:0", host_str, port_str, port, &error));
  EXPECT_STREQ("*", host_str.c_str());
  EXPECT_STREQ("0", port_str.c_str());
  EXPECT_EQ(0, port);
  EXPECT_TRUE(error.Success());

  EXPECT_TRUE(
      Socket::DecodeHostAndPort("*:65535", host_str, port_str, port, &error));
  EXPECT_STREQ("*", host_str.c_str());
  EXPECT_STREQ("65535", port_str.c_str());
  EXPECT_EQ(65535, port);
  EXPECT_TRUE(error.Success());

  EXPECT_TRUE(
      Socket::DecodeHostAndPort("[::1]:12345", host_str, port_str, port, &error));
  EXPECT_STREQ("::1", host_str.c_str());
  EXPECT_STREQ("12345", port_str.c_str());
  EXPECT_EQ(12345, port);
  EXPECT_TRUE(error.Success());

  EXPECT_TRUE(
      Socket::DecodeHostAndPort("[abcd:12fg:AF58::1]:12345", host_str, port_str, port, &error));
  EXPECT_STREQ("abcd:12fg:AF58::1", host_str.c_str());
  EXPECT_STREQ("12345", port_str.c_str());
  EXPECT_EQ(12345, port);
  EXPECT_TRUE(error.Success());
}

#ifndef LLDB_DISABLE_POSIX
TEST_F(SocketTest, DomainListenConnectAccept) {
  llvm::SmallString<64> Path;
  std::error_code EC = llvm::sys::fs::createUniqueDirectory("DomainListenConnectAccept", Path);
  ASSERT_FALSE(EC);
  llvm::sys::path::append(Path, "test");

  // Skip the test if the $TMPDIR is too long to hold a domain socket.
  if (Path.size() > 107u)
    return;

  std::unique_ptr<DomainSocket> socket_a_up;
  std::unique_ptr<DomainSocket> socket_b_up;
  CreateDomainConnectedSockets(Path, &socket_a_up, &socket_b_up);
}
#endif

TEST_F(SocketTest, TCPListen0ConnectAccept) {
  std::unique_ptr<TCPSocket> socket_a_up;
  std::unique_ptr<TCPSocket> socket_b_up;
  CreateTCPConnectedSockets("127.0.0.1", &socket_a_up, &socket_b_up);
}

TEST_F(SocketTest, TCPGetAddress) {
  std::unique_ptr<TCPSocket> socket_a_up;
  std::unique_ptr<TCPSocket> socket_b_up;
  if (!IsAddressFamilySupported("127.0.0.1")) {
    GTEST_LOG_(WARNING) << "Skipping test due to missing IPv4 support.";
    return;
  }
  CreateTCPConnectedSockets("127.0.0.1", &socket_a_up, &socket_b_up);

  EXPECT_EQ(socket_a_up->GetLocalPortNumber(),
            socket_b_up->GetRemotePortNumber());
  EXPECT_EQ(socket_b_up->GetLocalPortNumber(),
            socket_a_up->GetRemotePortNumber());
  EXPECT_NE(socket_a_up->GetLocalPortNumber(),
            socket_b_up->GetLocalPortNumber());
  EXPECT_STREQ("127.0.0.1", socket_a_up->GetRemoteIPAddress().c_str());
  EXPECT_STREQ("127.0.0.1", socket_b_up->GetRemoteIPAddress().c_str());
}

TEST_F(SocketTest, UDPConnect) {
  Socket *socket;

  bool child_processes_inherit = false;
  auto error = UDPSocket::Connect("127.0.0.1:0", child_processes_inherit,
                                  socket);

  std::unique_ptr<Socket> socket_up(socket);

  EXPECT_TRUE(error.Success());
  EXPECT_TRUE(socket_up->IsValid());
}

TEST_F(SocketTest, TCPListen0GetPort) {
  Socket *server_socket;
  Predicate<uint16_t> port_predicate;
  port_predicate.SetValue(0, eBroadcastNever);
  Status err =
      Socket::TcpListen("10.10.12.3:0", false, server_socket, &port_predicate);
  std::unique_ptr<TCPSocket> socket_up((TCPSocket*)server_socket);
  EXPECT_TRUE(socket_up->IsValid());
  EXPECT_NE(socket_up->GetLocalPortNumber(), 0);
}

TEST_F(SocketTest, TCPGetConnectURI) {
  std::unique_ptr<TCPSocket> socket_a_up;
  std::unique_ptr<TCPSocket> socket_b_up;
  if (!IsAddressFamilySupported("127.0.0.1")) {
    GTEST_LOG_(WARNING) << "Skipping test due to missing IPv4 support.";
    return;
  }
  CreateTCPConnectedSockets("127.0.0.1", &socket_a_up, &socket_b_up);

  llvm::StringRef scheme;
  llvm::StringRef hostname;
  int port;
  llvm::StringRef path;
  std::string uri(socket_a_up->GetRemoteConnectionURI());
  EXPECT_TRUE(UriParser::Parse(uri, scheme, hostname, port, path));
  EXPECT_EQ(scheme, "connect");
  EXPECT_EQ(port, socket_a_up->GetRemotePortNumber());
}

TEST_F(SocketTest, UDPGetConnectURI) {
  if (!IsAddressFamilySupported("127.0.0.1")) {
    GTEST_LOG_(WARNING) << "Skipping test due to missing IPv4 support.";
    return;
  }
  Socket *socket;
  bool child_processes_inherit = false;
  auto error =
      UDPSocket::Connect("127.0.0.1:0", child_processes_inherit, socket);

  llvm::StringRef scheme;
  llvm::StringRef hostname;
  int port;
  llvm::StringRef path;
  std::string uri(socket->GetRemoteConnectionURI());
  EXPECT_TRUE(UriParser::Parse(uri, scheme, hostname, port, path));
  EXPECT_EQ(scheme, "udp");
}

#ifndef LLDB_DISABLE_POSIX
TEST_F(SocketTest, DomainGetConnectURI) {
  llvm::SmallString<64> domain_path;
  std::error_code EC =
      llvm::sys::fs::createUniqueDirectory("DomainListenConnectAccept", domain_path);
  ASSERT_FALSE(EC);
  llvm::sys::path::append(domain_path, "test");

  // Skip the test if the $TMPDIR is too long to hold a domain socket.
  if (domain_path.size() > 107u)
    return;

  std::unique_ptr<DomainSocket> socket_a_up;
  std::unique_ptr<DomainSocket> socket_b_up;
  CreateDomainConnectedSockets(domain_path, &socket_a_up, &socket_b_up);

  llvm::StringRef scheme;
  llvm::StringRef hostname;
  int port;
  llvm::StringRef path;
  std::string uri(socket_a_up->GetRemoteConnectionURI());
  EXPECT_TRUE(UriParser::Parse(uri, scheme, hostname, port, path));
  EXPECT_EQ(scheme, "unix-connect");
  EXPECT_EQ(path, domain_path);
}
#endif
<|endoftext|>


<commit_before>#include "TestBlockLandApplication.h"
#include <Ogre.h>
#include <OIS/OIS.h>

TestBlockLandApplication::TestBlockLandApplication() {
	m_Blocks = new block_t[WORLD_SIZE * WORLD_SIZE * WORLD_SIZE];
	memset(m_Blocks, 0, sizeof(block_t) * WORLD_SIZE * WORLD_SIZE * WORLD_SIZE);
	initWorldBlocksSphere();
	m_ChunkID = 1;
}

TestBlockLandApplication::~TestBlockLandApplication() {
	delete[] m_Blocks;
}

void TestBlockLandApplication::createChunk(const int StartX, const int StartY, const int StartZ) {
	Ogre::ManualObject* MeshChunk = new Ogre::ManualObject("MeshManChunk" + Ogre::StringConverter::toString(m_ChunkID));
	MeshChunk->begin("BoxColor");

	int iVertex = 0;
	block_t Block;
	block_t Block1;

	for (int z = StartZ; z < CHUNK_SIZE + StartZ; ++z) {
		for (int y = StartY; y < CHUNK_SIZE + StartY; ++y) {
			for (int x = StartX; x < CHUNK_SIZE + StartX; ++x) {
				Block = GetBlock(x, y, z);
				if (Block == 0)
					continue;

				//x-1
				Block1 = 0;
				if (x > StartX)
					Block1 = GetBlock(x - 1, y, z);

				if (Block1 == 0) {
					MeshChunk->position(x, y, z + 1);
					MeshChunk->normal(-1, 0, 0);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x, y + 1, z + 1);
					MeshChunk->normal(-1, 0, 0);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x, y + 1, z);
					MeshChunk->normal(-1, 0, 0);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y, z);
					MeshChunk->normal(-1, 0, 0);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//x+1
				Block1 = 0;
				if (x < StartX + CHUNK_SIZE - 1)
					Block1 = GetBlock(x + 1, y, z);

				if (Block1 == 0) {
					MeshChunk->position(x + 1, y, z);
					MeshChunk->normal(1, 0, 0);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y + 1, z);
					MeshChunk->normal(1, 0, 0);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y + 1, z + 1);
					MeshChunk->normal(1, 0, 0);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x + 1, y, z + 1);
					MeshChunk->normal(1, 0, 0);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//y-1
				Block1 = 0;
				if (y > StartY)
					Block1 = GetBlock(x, y - 1, z);

				if (Block1 == 0) {
					MeshChunk->position(x, y, z);
					MeshChunk->normal(0, -1, 0);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y, z);
					MeshChunk->normal(0, -1, 0);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y, z + 1);
					MeshChunk->normal(0, -1, 0);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y, z + 1);
					MeshChunk->normal(0, -1, 0);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//y+1
				Block1 = 0;
				if (y < StartY + CHUNK_SIZE - 1)
					Block1 = GetBlock(x, y + 1, z);

				if (Block1 == 0) {
					MeshChunk->position(x, y + 1, z + 1);
					MeshChunk->normal(0, 1, 0);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y + 1, z + 1);
					MeshChunk->normal(0, 1, 0);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y + 1, z);
					MeshChunk->normal(0, 1, 0);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y + 1, z);
					MeshChunk->normal(0, 1, 0);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//z-1
				Block1 = 0;
				if (z > StartZ)
					Block1 = GetBlock(x, y, z - 1);

				if (Block1 == 0) {
					MeshChunk->position(x, y + 1, z);
					MeshChunk->normal(0, 0, -1);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y + 1, z);
					MeshChunk->normal(0, 0, -1);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y, z);
					MeshChunk->normal(0, 0, -1);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y, z);
					MeshChunk->normal(0, 0, -1);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//z+1
				Block1 = 0;
				if (z < StartZ + CHUNK_SIZE - 1)
					Block1 = GetBlock(x, y, z + 1);

				if (Block1 == 0) {
					MeshChunk->position(x, y, z + 1);
					MeshChunk->normal(0, 0, 1);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y, z + 1);
					MeshChunk->normal(0, 0, 1);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y + 1, z + 1);
					MeshChunk->normal(0, 0, 1);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y + 1, z + 1);
					MeshChunk->normal(0, 0, 1);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}
			}
		}
	}

	MeshChunk->end();
	mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(MeshChunk);

	++m_ChunkID;
}

void TestBlockLandApplication::createSolidTexture(const Ogre::String& pName) {
	Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create("BoxColor", "General", true);
	Ogre::Technique* tech = mat->getTechnique(0);
	Ogre::Pass* pass = tech->getPass(0);
	Ogre::TextureUnitState* tex = pass->createTextureUnitState();
	tex->setColourOperationEx(Ogre::LBX_MODULATE, Ogre::LBS_MANUAL, Ogre::LBS_CURRENT, Ogre::ColourValue(0, 0.5, 0));
}

void TestBlockLandApplication::createTexture(const Ogre::String& pName, const Ogre::String& pImageFilename) {
	Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create("BoxColor", "General", true);
	Ogre::Technique* tech = mat->getTechnique(0);
	Ogre::Pass* pass = tech->getPass(0);
	Ogre::TextureUnitState* tex = pass->createTextureUnitState();

	tex->setTextureName(pImageFilename);
	tex->setNumMipmaps(4);
	tex->setTextureAnisotropy(1);
	tex->setTextureFiltering(Ogre::FO_POINT, Ogre::FO_POINT, Ogre::FO_POINT);
}

void TestBlockLandApplication::createWorldChunks() {
	Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create("BoxColor", "General", true);
	Ogre::Technique* tech = mat->getTechnique(0);
	Ogre::Pass* pass = tech->getPass(0);
	Ogre::TextureUnitState* tex = pass->createTextureUnitState();
	tex->setColourOperationEx(Ogre::LBX_MODULATE, Ogre::LBS_MANUAL, Ogre::LBS_CURRENT, Ogre::ColourValue(0, 0.5, 0));

	for (int z = 0; z < WORLD_SIZE; z += CHUNK_SIZE) {
		for (int y = 0; y < WORLD_SIZE; y += CHUNK_SIZE) {
			for (int x = 0; x < WORLD_SIZE; x += CHUNK_SIZE) {
				createChunk(x, y, z);
			}
		}
	}
}

void TestBlockLandApplication::createScene() {
	mSceneMgr->setSkyDome(true, "Examples/CloudySky", 2, 8, 100);
	mSceneMgr->setFog(Ogre::FOG_LINEAR, Ogre::ColourValue(0.8, 0.8, 1), 0.05, 0.0, 200);

	mCamera->setFarClipDistance(256);
	mCamera->setNearClipDistance(0.01);

	mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));
	Ogre::Light* l = mSceneMgr->createLight("MainLight");
	l->setPosition(20, 80, 50);

	createWorldChunks();
}

void TestBlockLandApplication::initWorldBlocksSphere() {
	Ogre::Image heightMap;
	heightMap.load("heightmap.png", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	const Ogre::PixelBox& pb = heightMap.getPixelBox();
	heightMap.scale(pb, Ogre::PixelBox(WORLD_SIZE, WORLD_SIZE, pb.getDepth(), Ogre::PF_BYTE_RGB));

	for (int z = 0; z < WORLD_SIZE; ++z) {
		for (int x = 0; x < WORLD_SIZE; ++x) {
			const Ogre::ColourValue& color = heightMap.getColourAt(x, z, 0);
			const int Height = static_cast<int>((((color.r + color.g + color.b) / 1.5f) - 1.0f) * WORLD_SIZE / 4.0f + WORLD_SIZE / 2.0f);
			for (int y = 0; y < Height; ++y) {
				GetBlock(x, y, z) = 1;
			}
		}
	}
}

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#endif

#ifdef __cplusplus
extern "C" {
#endif

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT)
#else
int main(int argc, char *argv[])
#endif
		{
	// Create application object
	TestBlockLandApplication app;

	try {
		app.go();
	} catch (Ogre::Exception& e) {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
		MessageBox(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
		std::cerr << "An exception has occurred: " << e.getFullDescription().c_str() << std::endl;
#endif
	}

	return 0;
}

#ifdef __cplusplus
}
#endif
<commit_msg>* fixed missing header include<commit_after>#include "TestBlockLandApplication.h"
#include <Ogre.h>
#include <OIS/OIS.h>
#include <iostream>

TestBlockLandApplication::TestBlockLandApplication() {
	m_Blocks = new block_t[WORLD_SIZE * WORLD_SIZE * WORLD_SIZE];
	memset(m_Blocks, 0, sizeof(block_t) * WORLD_SIZE * WORLD_SIZE * WORLD_SIZE);
	initWorldBlocksSphere();
	m_ChunkID = 1;
}

TestBlockLandApplication::~TestBlockLandApplication() {
	delete[] m_Blocks;
}

void TestBlockLandApplication::createChunk(const int StartX, const int StartY, const int StartZ) {
	Ogre::ManualObject* MeshChunk = new Ogre::ManualObject("MeshManChunk" + Ogre::StringConverter::toString(m_ChunkID));
	MeshChunk->begin("BoxColor");

	int iVertex = 0;
	block_t Block;
	block_t Block1;

	for (int z = StartZ; z < CHUNK_SIZE + StartZ; ++z) {
		for (int y = StartY; y < CHUNK_SIZE + StartY; ++y) {
			for (int x = StartX; x < CHUNK_SIZE + StartX; ++x) {
				Block = GetBlock(x, y, z);
				if (Block == 0)
					continue;

				//x-1
				Block1 = 0;
				if (x > StartX)
					Block1 = GetBlock(x - 1, y, z);

				if (Block1 == 0) {
					MeshChunk->position(x, y, z + 1);
					MeshChunk->normal(-1, 0, 0);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x, y + 1, z + 1);
					MeshChunk->normal(-1, 0, 0);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x, y + 1, z);
					MeshChunk->normal(-1, 0, 0);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y, z);
					MeshChunk->normal(-1, 0, 0);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//x+1
				Block1 = 0;
				if (x < StartX + CHUNK_SIZE - 1)
					Block1 = GetBlock(x + 1, y, z);

				if (Block1 == 0) {
					MeshChunk->position(x + 1, y, z);
					MeshChunk->normal(1, 0, 0);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y + 1, z);
					MeshChunk->normal(1, 0, 0);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y + 1, z + 1);
					MeshChunk->normal(1, 0, 0);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x + 1, y, z + 1);
					MeshChunk->normal(1, 0, 0);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//y-1
				Block1 = 0;
				if (y > StartY)
					Block1 = GetBlock(x, y - 1, z);

				if (Block1 == 0) {
					MeshChunk->position(x, y, z);
					MeshChunk->normal(0, -1, 0);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y, z);
					MeshChunk->normal(0, -1, 0);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y, z + 1);
					MeshChunk->normal(0, -1, 0);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y, z + 1);
					MeshChunk->normal(0, -1, 0);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//y+1
				Block1 = 0;
				if (y < StartY + CHUNK_SIZE - 1)
					Block1 = GetBlock(x, y + 1, z);

				if (Block1 == 0) {
					MeshChunk->position(x, y + 1, z + 1);
					MeshChunk->normal(0, 1, 0);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y + 1, z + 1);
					MeshChunk->normal(0, 1, 0);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y + 1, z);
					MeshChunk->normal(0, 1, 0);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y + 1, z);
					MeshChunk->normal(0, 1, 0);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//z-1
				Block1 = 0;
				if (z > StartZ)
					Block1 = GetBlock(x, y, z - 1);

				if (Block1 == 0) {
					MeshChunk->position(x, y + 1, z);
					MeshChunk->normal(0, 0, -1);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y + 1, z);
					MeshChunk->normal(0, 0, -1);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y, z);
					MeshChunk->normal(0, 0, -1);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y, z);
					MeshChunk->normal(0, 0, -1);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}

				//z+1
				Block1 = 0;
				if (z < StartZ + CHUNK_SIZE - 1)
					Block1 = GetBlock(x, y, z + 1);

				if (Block1 == 0) {
					MeshChunk->position(x, y, z + 1);
					MeshChunk->normal(0, 0, 1);
					MeshChunk->textureCoord(0, 1);
					MeshChunk->position(x + 1, y, z + 1);
					MeshChunk->normal(0, 0, 1);
					MeshChunk->textureCoord(1, 1);
					MeshChunk->position(x + 1, y + 1, z + 1);
					MeshChunk->normal(0, 0, 1);
					MeshChunk->textureCoord(1, 0);
					MeshChunk->position(x, y + 1, z + 1);
					MeshChunk->normal(0, 0, 1);
					MeshChunk->textureCoord(0, 0);

					MeshChunk->triangle(iVertex, iVertex + 1, iVertex + 2);
					MeshChunk->triangle(iVertex + 2, iVertex + 3, iVertex);

					iVertex += 4;
				}
			}
		}
	}

	MeshChunk->end();
	mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(MeshChunk);

	++m_ChunkID;
}

void TestBlockLandApplication::createSolidTexture(const Ogre::String& pName) {
	Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create("BoxColor", "General", true);
	Ogre::Technique* tech = mat->getTechnique(0);
	Ogre::Pass* pass = tech->getPass(0);
	Ogre::TextureUnitState* tex = pass->createTextureUnitState();
	tex->setColourOperationEx(Ogre::LBX_MODULATE, Ogre::LBS_MANUAL, Ogre::LBS_CURRENT, Ogre::ColourValue(0, 0.5, 0));
}

void TestBlockLandApplication::createTexture(const Ogre::String& pName, const Ogre::String& pImageFilename) {
	Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create("BoxColor", "General", true);
	Ogre::Technique* tech = mat->getTechnique(0);
	Ogre::Pass* pass = tech->getPass(0);
	Ogre::TextureUnitState* tex = pass->createTextureUnitState();

	tex->setTextureName(pImageFilename);
	tex->setNumMipmaps(4);
	tex->setTextureAnisotropy(1);
	tex->setTextureFiltering(Ogre::FO_POINT, Ogre::FO_POINT, Ogre::FO_POINT);
}

void TestBlockLandApplication::createWorldChunks() {
	Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create("BoxColor", "General", true);
	Ogre::Technique* tech = mat->getTechnique(0);
	Ogre::Pass* pass = tech->getPass(0);
	Ogre::TextureUnitState* tex = pass->createTextureUnitState();
	tex->setColourOperationEx(Ogre::LBX_MODULATE, Ogre::LBS_MANUAL, Ogre::LBS_CURRENT, Ogre::ColourValue(0, 0.5, 0));

	for (int z = 0; z < WORLD_SIZE; z += CHUNK_SIZE) {
		for (int y = 0; y < WORLD_SIZE; y += CHUNK_SIZE) {
			for (int x = 0; x < WORLD_SIZE; x += CHUNK_SIZE) {
				createChunk(x, y, z);
			}
		}
	}
}

void TestBlockLandApplication::createScene() {
	mSceneMgr->setSkyDome(true, "Examples/CloudySky", 2, 8, 100);
	mSceneMgr->setFog(Ogre::FOG_LINEAR, Ogre::ColourValue(0.8, 0.8, 1), 0.05, 0.0, 200);

	mCamera->setFarClipDistance(256);
	mCamera->setNearClipDistance(0.01);

	mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));
	Ogre::Light* l = mSceneMgr->createLight("MainLight");
	l->setPosition(20, 80, 50);

	createWorldChunks();
}

void TestBlockLandApplication::initWorldBlocksSphere() {
	Ogre::Image heightMap;
	heightMap.load("heightmap.png", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	const Ogre::PixelBox& pb = heightMap.getPixelBox();
	heightMap.scale(pb, Ogre::PixelBox(WORLD_SIZE, WORLD_SIZE, pb.getDepth(), Ogre::PF_BYTE_RGB));

	for (int z = 0; z < WORLD_SIZE; ++z) {
		for (int x = 0; x < WORLD_SIZE; ++x) {
			const Ogre::ColourValue& color = heightMap.getColourAt(x, z, 0);
			const int Height = static_cast<int>((((color.r + color.g + color.b) / 1.5f) - 1.0f) * WORLD_SIZE / 4.0f + WORLD_SIZE / 2.0f);
			for (int y = 0; y < Height; ++y) {
				GetBlock(x, y, z) = 1;
			}
		}
	}
}

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#endif

#ifdef __cplusplus
extern "C" {
#endif

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT)
#else
int main(int argc, char *argv[])
#endif
		{
	// Create application object
	TestBlockLandApplication app;

	try {
		app.go();
	} catch (Ogre::Exception& e) {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
		MessageBox(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
		std::cerr << "An exception has occurred: " << e.getFullDescription().c_str() << std::endl;
#endif
	}

	return 0;
}

#ifdef __cplusplus
}
#endif
<|endoftext|>


<commit_before>/*
 * Note: LoRaWAN per sub-band duty-cycle limitation is enforced (1% in g1,
 *  0.1% in g2).
 *
 * Change DEVADDR to a unique address!
 * See http://thethingsnetwork.org/wiki/AddressSpace
 *
 * Do not forget to define the radio type correctly in config.h.
 */
#include <lmic.h>
#include <hal/hal.h>
#include <SPI.h>
#include "Lora.h"

#if defined(DISABLE_INVERT_IQ_ON_RX)
#error This example requires DISABLE_INVERT_IQ_ON_RX to be NOT set. Update \
       config.h in the lmic library to set it.
#endif

// LoRaWAN NwkSKey, network session key
// This is the default Semtech key, which is used by the prototype TTN
// network initially.
// 2B7E151628AED2A6ABF7158809CF4F3C
//static const PROGMEM u1_t NWKSKEY[16] = { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C };

// LoRaWAN AppSKey, application session key
// This is the default Semtech key, which is used by the prototype TTN
// network initially.
//static const u1_t PROGMEM APPSKEY[16] = { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C };
//static const u4_t DEVADDR = 0x03FF0001 ; // <-- Change this address for every node!
//static const u4_t DEVADDR = 0x02D1EFEF ; // Manny's

//static const PROGMEM u1_t NWKSKEY[16] = { 0x80, 0x42, 0x43, 0x64, 0x2C, 0x1E, 0x3B, 0x04, 0x36, 0x6D, 0x36, 0xC3, 0x90, 0x9F, 0xCA, 0xA2 };
//static const u1_t PROGMEM APPSKEY[16] = { 0x43, 0x0D, 0x53, 0xB2, 0x72, 0xA6, 0x47, 0xAF, 0x5D, 0xFF, 0x6A, 0x16, 0x7A, 0xB7, 0x9A, 0x20 };
const u1_t NWKSKEY[16] = { 0x80, 0x42, 0x43, 0x64, 0x2C, 0x1E, 0x3B, 0x04, 0x36, 0x6D, 0x36, 0xC3, 0x90, 0x9F, 0xCA, 0xA2 };
const u1_t APPSKEY[16] = { 0x43, 0x0D, 0x53, 0xB2, 0x72, 0xA6, 0x47, 0xAF, 0x5D, 0xFF, 0x6A, 0x16, 0x7A, 0xB7, 0x9A, 0x20 };

// LoRaWAN end-device address (DevAddr)
// See http://thethingsnetwork.org/wiki/AddressSpace
const u4_t DEVADDR = 0xDEADAAAA ; // <-- Change this address for every node!

// These callbacks are only used in over-the-air activation, so they are
// left empty here (we cannot leave them out completely unless
// DISABLE_JOIN is set in config.h, otherwise the linker will complain).
void os_getArtEui (u1_t* buf) { }
void os_getDevEui (u1_t* buf) { }
void os_getDevKey (u1_t* buf) { }

// Pin mapping
const lmic_pinmap lmic_pins = {
    .nss = 18, // 6,
    .rxtx = LMIC_UNUSED_PIN,
    .rst = 19, // 5,
    .dio = {16, 5, 6}, // Moved dio0 from 17 because of overlapping ExtInt4 (pin6)
};

static osjob_t timeoutjob;
static void txtimeout_func(osjob_t *job) {
  digitalWrite(LED_BUILTIN, LOW); // off
  Serial.println(F("Transmit Timeout"));
  //txActive = false;
  LMIC_clrTxData ();
}

bool loraSendBytes(uint8_t *data, uint16_t len) {
  ostime_t t = os_getTime();
  //os_setTimedCallback(&txjob, t + ms2osticks(100), tx_func);
  // Check if there is not a current TX/RX job running
    if (LMIC.opmode & OP_TXRXPEND) {
        Serial.println(F("OP_TXRXPEND, not sending"));
        return false; // Did not enqueue
    } else {
        // Prepare upstream data transmission at the next possible time.
        Serial.println(F("Packet queued"));
        digitalWrite(LED_BUILTIN, HIGH); // off
        LMIC_setTxData2(1, data, len, 0);
    }
  // Timeout TX after 20 seconds
  os_setTimedCallback(&timeoutjob, t + ms2osticks(20000), txtimeout_func);
  return true;
}

void onEvent (ev_t ev) {
    Serial.print(os_getTime());
    Serial.print(": ");
    switch(ev) {
        case EV_SCAN_TIMEOUT:
            Serial.println(F("EV_SCAN_TIMEOUT"));
            break;
        case EV_BEACON_FOUND:
            Serial.println(F("EV_BEACON_FOUND"));
            break;
        case EV_BEACON_MISSED:
            Serial.println(F("EV_BEACON_MISSED"));
            break;
        case EV_BEACON_TRACKED:
            Serial.println(F("EV_BEACON_TRACKED"));
            break;
        case EV_JOINING:
            Serial.println(F("EV_JOINING"));
            break;
        case EV_JOINED:
            Serial.println(F("EV_JOINED"));
            break;
        case EV_RFU1:
            Serial.println(F("EV_RFU1"));
            break;
        case EV_JOIN_FAILED:
            Serial.println(F("EV_JOIN_FAILED"));
            break;
        case EV_REJOIN_FAILED:
            Serial.println(F("EV_REJOIN_FAILED"));
            break;
            break;
        case EV_TXCOMPLETE:
            os_clearCallback(&timeoutjob);
            Serial.println(F("EV_TXCOMPLETE (includes waiting for RX windows)"));
            digitalWrite(LED_BUILTIN, LOW); // off

            if(LMIC.dataLen) {
                // data received in rx slot after tx
                Serial.print(F("Data Received: "));
                Serial.write(LMIC.frame+LMIC.dataBeg, LMIC.dataLen);
                Serial.println();
            }
            break;
        case EV_LOST_TSYNC:
            Serial.println(F("EV_LOST_TSYNC"));
            break;
        case EV_RESET:
            Serial.println(F("EV_RESET"));
            break;
        case EV_RXCOMPLETE:
            // data received in ping slot
            Serial.println(F("EV_RXCOMPLETE"));
            break;
        case EV_LINK_DEAD:
            Serial.println(F("EV_LINK_DEAD"));
            break;
        case EV_LINK_ALIVE:
            Serial.println(F("EV_LINK_ALIVE"));
            break;
         default:
            Serial.println(F("Unknown event"));
            break;
    }
}

void setupLora() {
    #ifdef VCC_ENABLE
    // For Pinoccio Scout boards
    pinMode(VCC_ENABLE, OUTPUT);
    digitalWrite(VCC_ENABLE, HIGH);
    delay(1000);
    #endif

    // LMIC init
    os_init();
    // Reset the MAC state. Session and pending data transfers will be discarded.
    LMIC_reset();

    // Set static session parameters. Instead of dynamically establishing a session
    // by joining the network, precomputed session parameters are provided.
    #ifdef PROGMEM
    // On AVR, these values are stored in flash and only copied to RAM
    // once. Copy them to a temporary buffer here, LMIC_setSession will
    // copy them into a buffer of its own again.
    uint8_t appskey[sizeof(APPSKEY)];
    uint8_t nwkskey[sizeof(NWKSKEY)];
    memcpy_P(appskey, APPSKEY, sizeof(APPSKEY));
    memcpy_P(nwkskey, NWKSKEY, sizeof(NWKSKEY));
    LMIC_setSession (0x1, DEVADDR, nwkskey, appskey);
    #else
    // If not running an AVR with PROGMEM, just use the arrays directly
    LMIC_setSession (0x1, DEVADDR, NWKSKEY, APPSKEY);
    #endif

    #if defined(CFG_eu868)
    // Set up the channels used by the Things Network, which corresponds
    // to the defaults of most gateways. Without this, only three base
    // channels from the LoRaWAN specification are used, which certainly
    // works, so it is good for debugging, but can overload those
    // frequencies, so be sure to configure the full frequency range of
    // your network here (unless your network autoconfigures them).
    // Setting up channels should happen after LMIC_setSession, as that
    // configures the minimal channel set.
    LMIC_setupChannel(0, 868100000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI);      // g-band
    LMIC_setupChannel(1, 868300000, DR_RANGE_MAP(DR_SF12, DR_SF7B), BAND_CENTI);      // g-band
    LMIC_setupChannel(2, 868500000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI);      // g-band
    LMIC_setupChannel(3, 867100000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI);      // g-band
    LMIC_setupChannel(4, 867300000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI);      // g-band
    LMIC_setupChannel(5, 867500000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI);      // g-band
    LMIC_setupChannel(6, 867700000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI);      // g-band
    LMIC_setupChannel(7, 867900000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI);      // g-band
    LMIC_setupChannel(8, 868800000, DR_RANGE_MAP(DR_FSK,  DR_FSK),  BAND_MILLI);      // g2-band
    // TTN defines an additional channel at 869.525Mhz using SF9 for class B
    // devices' ping slots. LMIC does not have an easy way to define set this
    // frequency and support for class B is spotty and untested, so this
    // frequency is not configured here.
    #endif

    // Disable all but 2nd group of 8 channels
    for (int i=0; i<8; ++i) {
      LMIC_disableChannel(i);
    }
    for (int i=16; i<72; ++i) {
      LMIC_disableChannel(i);
    }

    // Disable link check validation
    LMIC_setLinkCheckMode(0);

    // Set data rate and transmit power (note: txpow seems to be ignored by the library)
    LMIC_setDrTxpow(DR_SF10,20);
}

void loopLora() {
    os_runloop_once();
}

void loraSetSF(uint sf) {
  dr_t dr;
  switch (sf) {
    case 7: dr = DR_SF7; break;
    case 8: dr = DR_SF8; break;
    case 9: dr = DR_SF9; break;
    case 10: dr = DR_SF10; break;
    default:
      dr = DR_SF10;
      Serial.print(F("Invalid SF value")); Serial.println(sf, DEC);
      break;
  }
  LMIC_setDrTxpow(dr,20);
}

<commit_msg>Use LMIC_selectSubBand API<commit_after>/*
 * Note: LoRaWAN per sub-band duty-cycle limitation is enforced (1% in g1,
 *  0.1% in g2).
 *
 * Change DEVADDR to a unique address!
 * See http://thethingsnetwork.org/wiki/AddressSpace
 *
 * Do not forget to define the radio type correctly in config.h.
 */
#include <lmic.h>
#include <hal/hal.h>
#include <SPI.h>
#include "Lora.h"

#if defined(DISABLE_INVERT_IQ_ON_RX)
#error This example requires DISABLE_INVERT_IQ_ON_RX to be NOT set. Update \
       config.h in the lmic library to set it.
#endif

// LoRaWAN NwkSKey, network session key
// This is the default Semtech key, which is used by the prototype TTN
// network initially.
// 2B7E151628AED2A6ABF7158809CF4F3C
//static const PROGMEM u1_t NWKSKEY[16] = { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C };

// LoRaWAN AppSKey, application session key
// This is the default Semtech key, which is used by the prototype TTN
// network initially.
//static const u1_t PROGMEM APPSKEY[16] = { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C };
//static const u4_t DEVADDR = 0x03FF0001 ; // <-- Change this address for every node!
//static const u4_t DEVADDR = 0x02D1EFEF ; // Manny's

//static const PROGMEM u1_t NWKSKEY[16] = { 0x80, 0x42, 0x43, 0x64, 0x2C, 0x1E, 0x3B, 0x04, 0x36, 0x6D, 0x36, 0xC3, 0x90, 0x9F, 0xCA, 0xA2 };
//static const u1_t PROGMEM APPSKEY[16] = { 0x43, 0x0D, 0x53, 0xB2, 0x72, 0xA6, 0x47, 0xAF, 0x5D, 0xFF, 0x6A, 0x16, 0x7A, 0xB7, 0x9A, 0x20 };
const u1_t NWKSKEY[16] = { 0x80, 0x42, 0x43, 0x64, 0x2C, 0x1E, 0x3B, 0x04, 0x36, 0x6D, 0x36, 0xC3, 0x90, 0x9F, 0xCA, 0xA2 };
const u1_t APPSKEY[16] = { 0x43, 0x0D, 0x53, 0xB2, 0x72, 0xA6, 0x47, 0xAF, 0x5D, 0xFF, 0x6A, 0x16, 0x7A, 0xB7, 0x9A, 0x20 };

// LoRaWAN end-device address (DevAddr)
// See http://thethingsnetwork.org/wiki/AddressSpace
const u4_t DEVADDR = 0xDEADAAAA ; // <-- Change this address for every node!

// These callbacks are only used in over-the-air activation, so they are
// left empty here (we cannot leave them out completely unless
// DISABLE_JOIN is set in config.h, otherwise the linker will complain).
void os_getArtEui (u1_t* buf) { }
void os_getDevEui (u1_t* buf) { }
void os_getDevKey (u1_t* buf) { }

// Pin mapping
const lmic_pinmap lmic_pins = {
    .nss = 18, // 6,
    .rxtx = LMIC_UNUSED_PIN,
    .rst = 19, // 5,
    .dio = {16, 5, 6}, // Moved dio0 from 17 because of overlapping ExtInt4 (pin6)
};

static osjob_t timeoutjob;
static void txtimeout_func(osjob_t *job) {
  digitalWrite(LED_BUILTIN, LOW); // off
  Serial.println(F("Transmit Timeout"));
  //txActive = false;
  LMIC_clrTxData ();
}

bool loraSendBytes(uint8_t *data, uint16_t len) {
  ostime_t t = os_getTime();
  //os_setTimedCallback(&txjob, t + ms2osticks(100), tx_func);
  // Check if there is not a current TX/RX job running
    if (LMIC.opmode & OP_TXRXPEND) {
        Serial.println(F("OP_TXRXPEND, not sending"));
        return false; // Did not enqueue
    } else {
        // Prepare upstream data transmission at the next possible time.
        Serial.println(F("Packet queued"));
        digitalWrite(LED_BUILTIN, HIGH); // off
        LMIC_setTxData2(1, data, len, 0);
    }
  // Timeout TX after 20 seconds
  os_setTimedCallback(&timeoutjob, t + ms2osticks(20000), txtimeout_func);
  return true;
}

void onEvent (ev_t ev) {
    Serial.print(os_getTime());
    Serial.print(": ");
    switch(ev) {
        case EV_SCAN_TIMEOUT:
            Serial.println(F("EV_SCAN_TIMEOUT"));
            break;
        case EV_BEACON_FOUND:
            Serial.println(F("EV_BEACON_FOUND"));
            break;
        case EV_BEACON_MISSED:
            Serial.println(F("EV_BEACON_MISSED"));
            break;
        case EV_BEACON_TRACKED:
            Serial.println(F("EV_BEACON_TRACKED"));
            break;
        case EV_JOINING:
            Serial.println(F("EV_JOINING"));
            break;
        case EV_JOINED:
            Serial.println(F("EV_JOINED"));
            break;
        case EV_RFU1:
            Serial.println(F("EV_RFU1"));
            break;
        case EV_JOIN_FAILED:
            Serial.println(F("EV_JOIN_FAILED"));
            break;
        case EV_REJOIN_FAILED:
            Serial.println(F("EV_REJOIN_FAILED"));
            break;
            break;
        case EV_TXCOMPLETE:
            os_clearCallback(&timeoutjob);
            Serial.println(F("EV_TXCOMPLETE (includes waiting for RX windows)"));
            digitalWrite(LED_BUILTIN, LOW); // off

            if(LMIC.dataLen) {
                // data received in rx slot after tx
                Serial.print(F("Data Received: "));
                Serial.write(LMIC.frame+LMIC.dataBeg, LMIC.dataLen);
                Serial.println();
            }
            break;
        case EV_LOST_TSYNC:
            Serial.println(F("EV_LOST_TSYNC"));
            break;
        case EV_RESET:
            Serial.println(F("EV_RESET"));
            break;
        case EV_RXCOMPLETE:
            // data received in ping slot
            Serial.println(F("EV_RXCOMPLETE"));
            break;
        case EV_LINK_DEAD:
            Serial.println(F("EV_LINK_DEAD"));
            break;
        case EV_LINK_ALIVE:
            Serial.println(F("EV_LINK_ALIVE"));
            break;
         default:
            Serial.println(F("Unknown event"));
            break;
    }
}

void setupLora() {
    #ifdef VCC_ENABLE
    // For Pinoccio Scout boards
    pinMode(VCC_ENABLE, OUTPUT);
    digitalWrite(VCC_ENABLE, HIGH);
    delay(1000);
    #endif

    // LMIC init
    os_init();
    // Reset the MAC state. Session and pending data transfers will be discarded.
    LMIC_reset();

    // Set static session parameters. Instead of dynamically establishing a session
    // by joining the network, precomputed session parameters are provided.
    #ifdef PROGMEM
    // On AVR, these values are stored in flash and only copied to RAM
    // once. Copy them to a temporary buffer here, LMIC_setSession will
    // copy them into a buffer of its own again.
    uint8_t appskey[sizeof(APPSKEY)];
    uint8_t nwkskey[sizeof(NWKSKEY)];
    memcpy_P(appskey, APPSKEY, sizeof(APPSKEY));
    memcpy_P(nwkskey, NWKSKEY, sizeof(NWKSKEY));
    LMIC_setSession (0x1, DEVADDR, nwkskey, appskey);
    #else
    // If not running an AVR with PROGMEM, just use the arrays directly
    LMIC_setSession (0x1, DEVADDR, NWKSKEY, APPSKEY);
    #endif

    #if defined(CFG_eu868)
    // Set up the channels used by the Things Network, which corresponds
    // to the defaults of most gateways. Without this, only three base
    // channels from the LoRaWAN specification are used, which certainly
    // works, so it is good for debugging, but can overload those
    // frequencies, so be sure to configure the full frequency range of
    // your network here (unless your network autoconfigures them).
    // Setting up channels should happen after LMIC_setSession, as that
    // configures the minimal channel set.
    LMIC_setupChannel(0, 868100000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI);      // g-band
    LMIC_setupChannel(1, 868300000, DR_RANGE_MAP(DR_SF12, DR_SF7B), BAND_CENTI);      // g-band
    LMIC_setupChannel(2, 868500000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI);      // g-band
    LMIC_setupChannel(3, 867100000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI);      // g-band
    LMIC_setupChannel(4, 867300000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI);      // g-band
    LMIC_setupChannel(5, 867500000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI);      // g-band
    LMIC_setupChannel(6, 867700000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI);      // g-band
    LMIC_setupChannel(7, 867900000, DR_RANGE_MAP(DR_SF12, DR_SF7),  BAND_CENTI);      // g-band
    LMIC_setupChannel(8, 868800000, DR_RANGE_MAP(DR_FSK,  DR_FSK),  BAND_MILLI);      // g2-band
    // TTN defines an additional channel at 869.525Mhz using SF9 for class B
    // devices' ping slots. LMIC does not have an easy way to define set this
    // frequency and support for class B is spotty and untested, so this
    // frequency is not configured here.
    #endif

    Serial.println(F("setupLora: 4"));
    LMIC_selectSubBand(1);

    // Disable link check validation
    LMIC_setLinkCheckMode(0);

    // Set data rate and transmit power (note: txpow seems to be ignored by the library)
    LMIC_setDrTxpow(DR_SF10,20);
}

void loopLora() {
    os_runloop_once();
}

void loraSetSF(uint sf) {
  dr_t dr;
  switch (sf) {
    case 7: dr = DR_SF7; break;
    case 8: dr = DR_SF8; break;
    case 9: dr = DR_SF9; break;
    case 10: dr = DR_SF10; break;
    default:
      dr = DR_SF10;
      Serial.print(F("Invalid SF value")); Serial.println(sf, DEC);
      break;
  }
  LMIC_setDrTxpow(dr,20);
}

<|endoftext|>


<commit_before>#include <boost/cast.hpp>

#include "watcherdAPIMessageHandler.h"
#include <libwatcher/messageStatus.h>

using namespace std;
using namespace watcher;
using namespace watcher::event;
using namespace boost;

namespace watcher {
    INIT_LOGGER(WatcherdAPIMessageHandler, "MessageHandler.WatcherdAPIMessageHandler");
}

WatcherdAPIMessageHandler::WatcherdAPIMessageHandler()
{
    TRACE_ENTER();
    TRACE_EXIT();
}

WatcherdAPIMessageHandler::~WatcherdAPIMessageHandler()
{
    TRACE_ENTER();
    TRACE_EXIT();
}

bool WatcherdAPIMessageHandler::handleMessageArrive(ConnectionPtr conn, const MessagePtr &message)
{
    TRACE_ENTER();

    // Log message arrival
    bool rv = MessageHandler::handleMessageArrive(conn, message);

    TRACE_EXIT_RET_BOOL(rv);
    return true;
}

// virtual
bool WatcherdAPIMessageHandler::handleMessagesArrive(ConnectionPtr conn, const std::vector<event::MessagePtr> &messages)
{
    TRACE_ENTER();

    bool rv = false;
    for(vector<MessagePtr>::const_iterator i=messages.begin(); i!=messages.end(); ++i)
        rv |= handleMessageArrive(conn, *i);

    TRACE_EXIT_RET_BOOL(rv);
    return rv;
}

bool WatcherdAPIMessageHandler::handleMessageSent(const MessagePtr &message)
{
    TRACE_ENTER();

    // Log the message.
    bool rv = MessageHandler::handleMessageSent(message);

    TRACE_EXIT_RET_BOOL(rv);
    return rv;
}

// virtual
bool WatcherdAPIMessageHandler::handleMessagesSent(const std::vector<event::MessagePtr> &messages)
{
    TRACE_ENTER();

    bool rv = false;
    for(vector<MessagePtr>::const_iterator i=messages.begin(); i!=messages.end(); ++i)
        rv |= handleMessageSent(*i);

    TRACE_EXIT_RET_BOOL(rv);
    return rv;
}
<commit_msg>return false from watcherdAPIMessageHandler::handleMessage() so GUI clients don't disconnect themselves.<commit_after>#include <boost/cast.hpp>

#include "watcherdAPIMessageHandler.h"
#include <libwatcher/messageStatus.h>

using namespace std;
using namespace watcher;
using namespace watcher::event;
using namespace boost;

namespace watcher {
    INIT_LOGGER(WatcherdAPIMessageHandler, "MessageHandler.WatcherdAPIMessageHandler");
}

WatcherdAPIMessageHandler::WatcherdAPIMessageHandler()
{
    TRACE_ENTER();
    TRACE_EXIT();
}

WatcherdAPIMessageHandler::~WatcherdAPIMessageHandler()
{
    TRACE_ENTER();
    TRACE_EXIT();
}

bool WatcherdAPIMessageHandler::handleMessageArrive(ConnectionPtr conn, const MessagePtr &message)
{
    TRACE_ENTER();

    // Log message arrival
    bool rv = MessageHandler::handleMessageArrive(conn, message);

    TRACE_EXIT_RET_BOOL(false);
    return false;
}

// virtual
bool WatcherdAPIMessageHandler::handleMessagesArrive(ConnectionPtr conn, const std::vector<event::MessagePtr> &messages)
{
    TRACE_ENTER();

    bool rv = false;
    for(vector<MessagePtr>::const_iterator i=messages.begin(); i!=messages.end(); ++i)
        rv |= handleMessageArrive(conn, *i);

    TRACE_EXIT_RET_BOOL(rv);
    return rv;
}

bool WatcherdAPIMessageHandler::handleMessageSent(const MessagePtr &message)
{
    TRACE_ENTER();

    // Log the message.
    bool rv = MessageHandler::handleMessageSent(message);

    TRACE_EXIT_RET_BOOL(rv);
    return rv;
}

// virtual
bool WatcherdAPIMessageHandler::handleMessagesSent(const std::vector<event::MessagePtr> &messages)
{
    TRACE_ENTER();

    bool rv = false;
    for(vector<MessagePtr>::const_iterator i=messages.begin(); i!=messages.end(); ++i)
        rv |= handleMessageSent(*i);

    TRACE_EXIT_RET_BOOL(rv);
    return rv;
}
<|endoftext|>


<commit_before>// For developing/testing, uncomment this directive if you want to see some
// helpful feedback messages while the script is running
#define FEEDBACK_MODE<commit_msg>Comment out FEEDBACK_MODE directive<commit_after>// For developing/testing, uncomment this directive if you want to see some
// helpful feedback messages while the script is running
// #define FEEDBACK_MODE<|endoftext|>