<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_TEST_OPERATORS_WEIGHTED_L2_HH
#define DUNE_GDT_TEST_OPERATORS_WEIGHTED_L2_HH

#include <dune/stuff/test/gtest/gtest.h>

#include <dune/gdt/operators/projections.hh>
#include <dune/gdt/operators/weighted-l2.hh>

#include "base.hh"

namespace Dune {
namespace GDT {
namespace Tests {

/**
 * \note The values in correct_for_constant_arguments(), etc., are valid for the d-dimendional unit cube.
 */
template <class SpaceType>
struct WeightedL2ProductBase
{
  typedef typename SpaceType::GridViewType GridViewType;
  typedef typename GridViewType::Grid GridType;
  typedef Dune::Stuff::Grid::Providers::Cube<GridType> GridProviderType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;
  typedef typename SpaceType::DomainFieldType DomainFieldType;
  static const size_t dimDomain = SpaceType::dimDomain;
  typedef typename SpaceType::RangeFieldType RangeFieldType;
  typedef Stuff::Functions::Expression<EntityType, DomainFieldType, dimDomain, RangeFieldType, 1>
      ExpressionFunctionType;

  WeightedL2ProductBase()
    : one_("x", "1.0", 1, "constant gradient", {{"1.0", "1.0", "1.0"}})
    , linear_("x", "x[0] - 1.0", 1)
    , quadratic_("x", "x[0]*x[0]", 2)
  {
  }

  virtual ~WeightedL2ProductBase() = default;

  virtual RangeFieldType compute(const ExpressionFunctionType& function) const = 0;

  void correct_for_constant_arguments() const
  {
    check(compute(one_), 1.0);
  }

  void correct_for_linear_arguments() const
  {
    check(compute(linear_), 1.0 / 3.0);
  }

  void correct_for_quadratic_arguments() const
  {
    check(compute(quadratic_), 1.0 / 5.0);
  }

  void check(const RangeFieldType& result, const RangeFieldType& expected, const RangeFieldType epsilon = 1e-14) const
  {
    const auto error = std::abs(expected - result);
    EXPECT_LE(error, epsilon) << "result:     " << result << "\n"
                              << "expected:   " << expected << "\n"
                              << "difference: " << std::scientific << error;
  } // ... check(...)

  const ExpressionFunctionType one_;
  const ExpressionFunctionType linear_;
  const ExpressionFunctionType quadratic_;
}; // struct WeightedL2ProductBase

template <class SpaceType>
struct WeightedL2LocalizableProductTest : public WeightedL2ProductBase<SpaceType>,
                                          public LocalizableProductBase<SpaceType>
{
  typedef WeightedL2ProductBase<SpaceType> EllipticBaseType;
  typedef LocalizableProductBase<SpaceType> LocalizableBaseType;
  typedef typename LocalizableBaseType::GridViewType GridViewType;
  typedef typename EllipticBaseType::ExpressionFunctionType ExpressionFunctionType;
  typedef typename LocalizableBaseType::ScalarFunctionType ScalarFunctionType;
  typedef typename LocalizableBaseType::TensorFunctionType TensorFunctionType;
  typedef typename LocalizableBaseType::RangeFieldType RangeFieldType;

  void constructible_by_ctor()
  {
    const auto& weight    = this->one_;
    const auto& grid_view = this->space_.grid_view();
    const auto& source    = this->scalar_function_;
    const auto& range     = this->scalar_function_;

    typedef WeightedL2LocalizableProduct<ExpressionFunctionType,
                                         GridViewType,
                                         ScalarFunctionType,
                                         ScalarFunctionType,
                                         double> CtorTestProductType;
    CtorTestProductType DUNE_UNUSED(wo_over_integrate)(weight, grid_view, range, source);
    CtorTestProductType DUNE_UNUSED(with_over_integrate)(1, weight, grid_view, range, source);
  } // ... constructible_by_ctor(...)

  void constructible_by_factory()
  {
    const auto& weight    = this->one_;
    const auto& grid_view = this->space_.grid_view();
    const auto& source    = this->scalar_function_;
    const auto& range     = this->scalar_function_;

    auto DUNE_UNUSED(wo_over_integrate) = make_weighted_l2_localizable_product(weight, grid_view, range, source);
    auto DUNE_UNUSED(with_over_integrate) = make_weighted_l2_localizable_product(weight, grid_view, range, source, 1);
  } // ... constructible_by_factory()

  virtual RangeFieldType compute(const ExpressionFunctionType& function) const override final
  {
    const auto& weight    = this->one_;
    const auto& grid_view = this->space_.grid_view();

    auto product      = make_weighted_l2_localizable_product(weight, grid_view, function, function);
    const auto result = product->apply2();

    auto product_tbb = make_weighted_l2_localizable_product(weight, grid_view, function, function);
    product_tbb->walk(true);
    const auto result_tbb = product_tbb->apply2();

    EXPECT_EQ(result_tbb, result);
    return result;
  } // ... compute(...)

  void is_localizable_product()
  {
    const auto& weight    = this->one_;
    const auto& grid_view = this->space_.grid_view();
    const auto& source    = this->scalar_function_;
    const auto& range     = this->scalar_function_;

    auto product = make_weighted_l2_localizable_product(weight, grid_view, range, source);
    this->localizable_product_test(*product);
  } // ... is_localizable_product(...)
}; // struct WeightedL2LocalizableProductTest

} // namespace Tests
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_TEST_OPERATORS_WEIGHTED_L2_HH
<commit_msg>[tests.operators.weighted-l2] use a weight that is not 1<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_TEST_OPERATORS_WEIGHTED_L2_HH
#define DUNE_GDT_TEST_OPERATORS_WEIGHTED_L2_HH

#include <dune/stuff/common/string.hh>
#include <dune/stuff/test/gtest/gtest.h>

#include <dune/gdt/operators/projections.hh>
#include <dune/gdt/operators/weighted-l2.hh>

#include "base.hh"

namespace Dune {
namespace GDT {
namespace Tests {

/**
 * \note The values in correct_for_constant_arguments(), etc., are valid for the d-dimendional unit cube.
 */
template <class SpaceType>
struct WeightedL2ProductBase
{
  typedef typename SpaceType::GridViewType GridViewType;
  typedef typename GridViewType::Grid GridType;
  typedef Dune::Stuff::Grid::Providers::Cube<GridType> GridProviderType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;
  typedef typename SpaceType::DomainFieldType DomainFieldType;
  static const size_t dimDomain = SpaceType::dimDomain;
  typedef typename SpaceType::RangeFieldType RangeFieldType;
  typedef Stuff::Functions::Expression<EntityType, DomainFieldType, dimDomain, RangeFieldType, 1>
      ExpressionFunctionType;

  static const int weight_value = 42;

  WeightedL2ProductBase() // linker error if int(...) is missing, at least with clang
      : weight_("x", DSC::toString(int(weight_value)), 0),
        constant_("x", "1.0", 0),
        linear_("x", "x[0] - 1.0", 1),
        quadratic_("x", "x[0]*x[0]", 2)
  {
  }

  virtual ~WeightedL2ProductBase() = default;

  virtual RangeFieldType compute(const ExpressionFunctionType& function) const = 0;

  void correct_for_constant_arguments() const
  {
    check(compute(constant_), weight_value * 1.0);
  }

  void correct_for_linear_arguments() const
  {
    check(compute(linear_), weight_value * (1.0 / 3.0));
  }

  void correct_for_quadratic_arguments() const
  {
    check(compute(quadratic_), weight_value * (1.0 / 5.0));
  }

  void check(const RangeFieldType& result, const RangeFieldType& expected,
             const RangeFieldType epsilon = 2.14e-14) const
  {
    const auto error = std::abs(expected - result);
    EXPECT_LE(error, epsilon) << "result:     " << result << "\n"
                              << "expected:   " << expected << "\n"
                              << "difference: " << std::scientific << error;
  } // ... check(...)

  const ExpressionFunctionType weight_;
  const ExpressionFunctionType constant_;
  const ExpressionFunctionType linear_;
  const ExpressionFunctionType quadratic_;
}; // struct WeightedL2ProductBase

template <class SpaceType>
struct WeightedL2LocalizableProductTest : public WeightedL2ProductBase<SpaceType>,
                                          public LocalizableProductBase<SpaceType>
{
  typedef WeightedL2ProductBase<SpaceType> EllipticBaseType;
  typedef LocalizableProductBase<SpaceType> LocalizableBaseType;
  typedef typename LocalizableBaseType::GridViewType GridViewType;
  typedef typename EllipticBaseType::ExpressionFunctionType ExpressionFunctionType;
  typedef typename LocalizableBaseType::ScalarFunctionType ScalarFunctionType;
  typedef typename LocalizableBaseType::TensorFunctionType TensorFunctionType;
  typedef typename LocalizableBaseType::RangeFieldType RangeFieldType;

  void constructible_by_ctor()
  {
    const auto& weight    = this->weight_;
    const auto& grid_view = this->space_.grid_view();
    const auto& source    = this->scalar_function_;
    const auto& range     = this->scalar_function_;

    typedef WeightedL2LocalizableProduct<ExpressionFunctionType,
                                         GridViewType,
                                         ScalarFunctionType,
                                         ScalarFunctionType,
                                         double> CtorTestProductType;
    CtorTestProductType DUNE_UNUSED(wo_over_integrate)(weight, grid_view, range, source);
    CtorTestProductType DUNE_UNUSED(with_over_integrate)(1, weight, grid_view, range, source);
  } // ... constructible_by_ctor(...)

  void constructible_by_factory()
  {
    const auto& weight    = this->weight_;
    const auto& grid_view = this->space_.grid_view();
    const auto& source    = this->scalar_function_;
    const auto& range     = this->scalar_function_;

    auto DUNE_UNUSED(wo_over_integrate) = make_weighted_l2_localizable_product(weight, grid_view, range, source);
    auto DUNE_UNUSED(with_over_integrate) = make_weighted_l2_localizable_product(weight, grid_view, range, source, 1);
  } // ... constructible_by_factory()

  virtual RangeFieldType compute(const ExpressionFunctionType& function) const override final
  {
    const auto& weight    = this->weight_;
    const auto& grid_view = this->space_.grid_view();

    auto product      = make_weighted_l2_localizable_product(weight, grid_view, function, function);
    const auto result = product->apply2();

    auto product_tbb = make_weighted_l2_localizable_product(weight, grid_view, function, function);
    product_tbb->walk(true);
    const auto result_tbb = product_tbb->apply2();

    EXPECT_EQ(result_tbb, result);
    return result;
  } // ... compute(...)

  void is_localizable_product()
  {
    const auto& weight    = this->weight_;
    const auto& grid_view = this->space_.grid_view();
    const auto& source    = this->scalar_function_;
    const auto& range     = this->scalar_function_;

    auto product = make_weighted_l2_localizable_product(weight, grid_view, range, source);
    this->localizable_product_test(*product);
  } // ... is_localizable_product(...)
}; // struct WeightedL2LocalizableProductTest

} // namespace Tests
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_TEST_OPERATORS_WEIGHTED_L2_HH
<|endoftext|>


<commit_before><commit_msg>Added file lost in merge.<commit_after><|endoftext|>


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

// This file is here so other GLES2 related files can have a common set of
// includes where appropriate.

#include <windows.h>
#include <windowsx.h>
#include <shellapi.h>
#include <stdlib.h>
#include <stdio.h>
#include "base/ref_counted.h"
#include "base/shared_memory.h"
#include "base/scoped_ptr.h"
#include "gpu/command_buffer/service/gpu_processor.h"
#include "gpu/command_buffer/service/command_buffer_service.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "gpu/command_buffer/client/gles2_lib.h"
#include "gpu/command_buffer/client/gles2_demo_c.h"
#include "gpu/command_buffer/client/gles2_demo_cc.h"

using base::SharedMemory;
using command_buffer::GPUProcessor;
using command_buffer::CommandBufferService;
using command_buffer::gles2::GLES2CmdHelper;
using command_buffer::gles2::GLES2Implementation;

class GLES2Demo {
 public:
  GLES2Demo();

  bool GLES2Demo::Setup(void* hwnd, int32 size);

 private:
  DISALLOW_COPY_AND_ASSIGN(GLES2Demo);
};

GLES2Demo::GLES2Demo() {
}

bool GLES2Demo::Setup(void* hwnd, int32 size) {
  scoped_ptr<SharedMemory> ring_buffer(new SharedMemory);
  if (!ring_buffer->Create(std::wstring(), false, false, size)) {
    return NULL;
  }

  if (!ring_buffer->Map(size)) {
    return NULL;
  }

  scoped_ptr<CommandBufferService> command_buffer(new CommandBufferService);
  if (!command_buffer->Initialize(ring_buffer.release())) {
    return NULL;
  }

  scoped_refptr<GPUProcessor> gpu_processor(
      new GPUProcessor(command_buffer.get()));
  if (!gpu_processor->Initialize(reinterpret_cast<HWND>(hwnd))) {
    return NULL;
  }

  command_buffer->SetPutOffsetChangeCallback(
      NewCallback(gpu_processor.get(), &GPUProcessor::ProcessCommands));

  GLES2CmdHelper* helper = new GLES2CmdHelper(command_buffer.get());
  if (!helper->Initialize()) {
    // TODO(gman): cleanup.
    return false;
  }

  size_t transfer_buffer_size = 512 * 1024;
  int32 transfer_buffer_id =
      command_buffer->CreateTransferBuffer(transfer_buffer_size);
  ::base::SharedMemory* shared_memory =
      command_buffer->GetTransferBuffer(transfer_buffer_id);
  if (!shared_memory->Map(transfer_buffer_size)) {
    return false;
  }
  void* transfer_buffer = shared_memory->memory();
  if (!transfer_buffer) {
    return false;
  }

  gles2::g_gl_impl = new GLES2Implementation(helper,
                                             transfer_buffer_size,
                                             transfer_buffer,
                                             transfer_buffer_id);

  return command_buffer.release() != NULL;
}

#if defined(OS_WIN)
LRESULT CALLBACK WindowProc(
    HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param) {
  switch (msg) {
    case WM_CLOSE:
      DestroyWindow(hwnd);
      break;
    case WM_DESTROY:
      PostQuitMessage(0);
      break;
    case WM_PAINT: {
      GLFromCPPTestFunction();
      GLFromCTestFunction();
      // TODO(gman): Not sure how SwapBuffer should be exposed.
      gles2::GetGLContext()->SwapBuffers();
      break;
    }
    default:
      return ::DefWindowProc(hwnd, msg, w_param, l_param);
  }
  return 0;
}

HINSTANCE GetInstance(void) {
  HWND hwnd = GetConsoleWindow();
  return reinterpret_cast<HINSTANCE>(GetWindowLong(hwnd, GWL_HINSTANCE));
}

void ProcessMessages(void* in_hwnd) {
  HWND hwnd = reinterpret_cast<HWND>(in_hwnd);
  MSG msg;

  bool done = false;
  while (!done) {
    while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
      if (msg.message == WM_QUIT) {
        done = true;
      }
      // dispatch the message
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
    if (!done) {
      InvalidateRect(hwnd, NULL, TRUE);
    }
  }
}

#endif

void* SetupWindow() {
#if defined(OS_WIN)
  HINSTANCE instance = GetInstance();
  WNDCLASSEX wc = {0};
  wc.lpszClassName = L"MY_WINDOWS_CLASS";
  wc.cbSize = sizeof(WNDCLASSEX);
  wc.style = CS_HREDRAW | CS_VREDRAW;
  wc.lpfnWndProc = ::WindowProc;
  wc.cbClsExtra = 0;
  wc.cbWndExtra = 0;
  wc.hInstance = instance;
  wc.hIcon = ::LoadIcon(instance, IDI_APPLICATION);
  wc.hIconSm = NULL;
  wc.hCursor = ::LoadCursor(instance, IDC_ARROW);
  wc.hbrBackground = static_cast<HBRUSH>(::GetStockObject(BLACK_BRUSH));
  wc.lpszMenuName = NULL;

  if (!::RegisterClassEx(&wc))
    return false;

  // Leaving this window onscreen leads to a redraw error which makes it
  // a hassle to debug tests in an IDE, so we place the window somewhere that
  // won't happen.
  HWND hwnd = ::CreateWindowExW(
      NULL,
      wc.lpszClassName,
      L"",
      WS_OVERLAPPEDWINDOW,
      10,
      0,
      512,
      512,
      0,
      0,
      instance,
      0);

  if (hwnd == NULL) {
    return false;
  }

  ::ShowWindow(hwnd, SW_SHOWNORMAL);

  return hwnd;
#else
#error Need code.
#endif
}

int main(int argc, const char** argv) {
  const int32 kCommandBufferSize = 1024 * 1024;
  GLES2Demo* demo = new GLES2Demo();

  void* hwnd = SetupWindow();
  if (!hwnd) {
    ::fprintf(stdout, "Could not setup window.\n");
    return EXIT_FAILURE;
  }

  demo->Setup(hwnd, kCommandBufferSize);

  ProcessMessages(hwnd);

  return EXIT_SUCCESS;
}

<commit_msg>Update initialization of gles2_demo.cc to match requirements of using Chrome base.<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file implements a standalone executable demo of using GLES2 over
// command buffers. This code is temporary as the setup that happens
// here is in a state of flux. Eventually there will be several versions of
// setup, one for trusted code, one for pepper, one for NaCl, and maybe others.

#include <windows.h>
#include <windowsx.h>
#include <shellapi.h>
#include <stdlib.h>
#include <stdio.h>
#include "base/at_exit.h"
#include "base/message_loop.h"
#include "base/ref_counted.h"
#include "base/shared_memory.h"
#include "base/scoped_ptr.h"
#include "gpu/command_buffer/service/gpu_processor.h"
#include "gpu/command_buffer/service/command_buffer_service.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "gpu/command_buffer/client/gles2_lib.h"
#include "gpu/command_buffer/client/gles2_demo_c.h"
#include "gpu/command_buffer/client/gles2_demo_cc.h"

using base::SharedMemory;
using command_buffer::GPUProcessor;
using command_buffer::CommandBufferService;
using command_buffer::gles2::GLES2CmdHelper;
using command_buffer::gles2::GLES2Implementation;

class GLES2Demo {
 public:
  GLES2Demo();

  bool GLES2Demo::Setup(void* hwnd, int32 size);

 private:
  DISALLOW_COPY_AND_ASSIGN(GLES2Demo);
};

GLES2Demo::GLES2Demo() {
}

bool GLES2Demo::Setup(void* hwnd, int32 size) {
  scoped_ptr<SharedMemory> ring_buffer(new SharedMemory);
  if (!ring_buffer->Create(std::wstring(), false, false, size)) {
    return NULL;
  }

  if (!ring_buffer->Map(size)) {
    return NULL;
  }

  scoped_ptr<CommandBufferService> command_buffer(new CommandBufferService);
  if (!command_buffer->Initialize(ring_buffer.release())) {
    return NULL;
  }

  scoped_refptr<GPUProcessor> gpu_processor(
      new GPUProcessor(command_buffer.get()));
  if (!gpu_processor->Initialize(reinterpret_cast<HWND>(hwnd))) {
    return NULL;
  }

  command_buffer->SetPutOffsetChangeCallback(
      NewCallback(gpu_processor.get(), &GPUProcessor::ProcessCommands));

  GLES2CmdHelper* helper = new GLES2CmdHelper(command_buffer.get());
  if (!helper->Initialize()) {
    // TODO(gman): cleanup.
    return false;
  }

  size_t transfer_buffer_size = 512 * 1024;
  int32 transfer_buffer_id =
      command_buffer->CreateTransferBuffer(transfer_buffer_size);
  ::base::SharedMemory* shared_memory =
      command_buffer->GetTransferBuffer(transfer_buffer_id);
  if (!shared_memory->Map(transfer_buffer_size)) {
    return false;
  }
  void* transfer_buffer = shared_memory->memory();
  if (!transfer_buffer) {
    return false;
  }

  gles2::g_gl_impl = new GLES2Implementation(helper,
                                             transfer_buffer_size,
                                             transfer_buffer,
                                             transfer_buffer_id);

  return command_buffer.release() != NULL;
}

#if defined(OS_WIN)
LRESULT CALLBACK WindowProc(
    HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param) {
  switch (msg) {
    case WM_CLOSE:
      DestroyWindow(hwnd);
      break;
    case WM_DESTROY:
      PostQuitMessage(0);
      break;
    case WM_PAINT: {
      GLFromCPPTestFunction();
      GLFromCTestFunction();
      // TODO(gman): Not sure how SwapBuffer should be exposed.
      gles2::GetGLContext()->SwapBuffers();
      break;
    }
    default:
      return ::DefWindowProc(hwnd, msg, w_param, l_param);
  }
  return 0;
}

HINSTANCE GetInstance(void) {
  HWND hwnd = GetConsoleWindow();
  return reinterpret_cast<HINSTANCE>(GetWindowLong(hwnd, GWL_HINSTANCE));
}

void ProcessMessages(void* in_hwnd) {
  HWND hwnd = reinterpret_cast<HWND>(in_hwnd);
  MSG msg;

  bool done = false;
  while (!done) {
    while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
      if (msg.message == WM_QUIT) {
        done = true;
      }
      // dispatch the message
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
    if (!done) {
      InvalidateRect(hwnd, NULL, TRUE);
    }
  }
}

#endif

void* SetupWindow() {
#if defined(OS_WIN)
  HINSTANCE instance = GetInstance();
  WNDCLASSEX wc = {0};
  wc.lpszClassName = L"MY_WINDOWS_CLASS";
  wc.cbSize = sizeof(WNDCLASSEX);
  wc.style = CS_HREDRAW | CS_VREDRAW;
  wc.lpfnWndProc = ::WindowProc;
  wc.cbClsExtra = 0;
  wc.cbWndExtra = 0;
  wc.hInstance = instance;
  wc.hIcon = ::LoadIcon(instance, IDI_APPLICATION);
  wc.hIconSm = NULL;
  wc.hCursor = ::LoadCursor(instance, IDC_ARROW);
  wc.hbrBackground = static_cast<HBRUSH>(::GetStockObject(BLACK_BRUSH));
  wc.lpszMenuName = NULL;

  if (!::RegisterClassEx(&wc))
    return false;

  // Leaving this window onscreen leads to a redraw error which makes it
  // a hassle to debug tests in an IDE, so we place the window somewhere that
  // won't happen.
  HWND hwnd = ::CreateWindowExW(
      NULL,
      wc.lpszClassName,
      L"",
      WS_OVERLAPPEDWINDOW,
      10,
      0,
      512,
      512,
      0,
      0,
      instance,
      0);

  if (hwnd == NULL) {
    return false;
  }

  ::ShowWindow(hwnd, SW_SHOWNORMAL);

  return hwnd;
#else
#error Need code.
#endif
}

int main(int argc, const char** argv) {
  const int32 kCommandBufferSize = 1024 * 1024;

  base::AtExitManager at_exit_manager;
  MessageLoopForUI message_loop;

  GLES2Demo* demo = new GLES2Demo();

  void* hwnd = SetupWindow();
  if (!hwnd) {
    ::fprintf(stdout, "Could not setup window.\n");
    return EXIT_FAILURE;
  }

  demo->Setup(hwnd, kCommandBufferSize);

  ProcessMessages(hwnd);

  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/*
 * Copyright 2008, 2009 Google Inc.
 * Copyright 2007 Nintendo Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "cplusplus.h"

class Cxx : public CPlusPlus
{
public:
    Cxx(FILE* file, const char* stringTypeName = "char*", bool useExceptions = true) :
        CPlusPlus(file, stringTypeName, useExceptions)
    {
    }

    virtual void at(const StructType* node)
    {
        if (node->getJavadoc().size())
        {
            write("%s\n%s", node->getJavadoc().c_str(), indentString.c_str());
        }
        write("struct %s", node->getName().c_str());
        if (!node->isLeaf())
        {
            write("\n%s{\n", indentString.c_str());
            indent();
            printChildren(node);
            unindent();
            write("%s}", indentString.c_str());
        }
    }

    virtual void at(const ExceptDcl* node)
    {
        if (node->getJavadoc().size())
        {
            write("%s\n%s", node->getJavadoc().c_str(), indentString.c_str());
        }
        write("struct %s", node->getName().c_str());
        write("\n%s{\n", indentString.c_str());
        indent();
        printChildren(node);
        unindent();
        write("%s}", indentString.c_str());
    }

    virtual void at(const Interface* node)
    {
        if (node->getJavadoc().size())
        {
            write("%s\n", node->getJavadoc().c_str());
            writetab();
        }
        write("class %s", node->getName().c_str());
        if (node->getExtends())
        {
            write(" : ");
            prefix = "public ";
            node->getExtends()->accept(this);
            prefix = "";
        }
        if (!node->isLeaf())
        {
            writeln("");
            writeln("{");
            writeln("public:");
            indent();

            // printChildren(node);
            int count = 0;
            for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
            {
                if ((*i)->isSequence(node) || (*i)->isNative(node))
                {
                    continue;
                }

                optionalStage = 0;
                do
                {
                    if (0 < count)
                    {
                        write(";\n");
                    }
                    optionalCount = 0;
                    ++count;
                    writetab();
                    (*i)->accept(this);
                    ++optionalStage;
                } while (optionalStage <= optionalCount);
            }
            if (0 < count)
            {
                write(";\n");
            }

            writeln("static const char* iid()");
            writeln("{");
            indent();
                writeln("static const char* const name = \"%s\";",
                        node->getQualifiedName().c_str());
                writeln("return name;");
            unindent();
            writeln("}");

            if (Interface* constructor = node->getConstructor())
            {
                // Process constructors.
                constructorMode = true;
                for (NodeList::iterator i = constructor->begin();
                     i != constructor->end();
                     ++i)
                {
                    writetab();
                    (*i)->accept(this);
                }
                constructorMode = false;
                writeln("static Constructor* getConstructor()");
                writeln("{");
                indent();
                    writeln("return constructor;");
                unindent();
                writeln("}");
                writeln("static void setConstructor(Constructor* ctor)");
                writeln("{");
                indent();
                    writeln("constructor = ctor;");
                unindent();
                writeln("}");
                unindent();
                writeln("private:");
                indent();
                writeln("static Constructor* constructor;");
            }

            unindent();
            writetab();
            write("}");
        }

        if (node->getConstructor())
        {
            write(";\n\n");
            writetab();
            write("%s::Constructor* %s::constructor __attribute__((weak))",
                  node->getName().c_str(), node->getName().c_str());
        }
    }

    virtual void at(const NativeType* node)
    {
        if (node->getName() == "void_pointer")
        {
            write("void*");
        }
        else
        {
            write("%s", node->getName().c_str());
        }
    }

    virtual void at(const BinaryExpr* node)
    {
        node->getLeft()->accept(this);
        write(" %s ", node->getName().c_str());
        node->getRight()->accept(this);
    }

    virtual void at(const UnaryExpr* node)
    {
        write("%s", node->getName().c_str());
        NodeList::iterator elem = node->begin();
        (*elem)->accept(this);
    }

    virtual void at(const GroupingExpression* node)
    {
        write("(");
        NodeList::iterator elem = node->begin();
        (*elem)->accept(this);
        write(")");
    }

    virtual void at(const Literal* node)
    {
        if (node->getName() == "TRUE")
        {
            write("true");
        }
        else if (node->getName() == "FALSE")
        {
            write("false");
        }
        else
        {
            write("%s", node->getName().c_str());
        }
    }

    virtual void at(const Member* node)
    {
        if (node->isTypedef())
        {
            write("typedef ");
        }
        if (node->isInterface(node->getParent()))
        {
            node->getSpec()->accept(this);
            write(" %s", node->getName().c_str());
        }
        else
        {
            node->getSpec()->accept(this);
            write(" %s", node->getName().c_str());
        }
    }

    virtual void at(const ArrayDcl* node)
    {
        assert(!node->isLeaf());

        at(static_cast<const Member*>(node));
        for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
        {
            write("[");
            (*i)->accept(this);
            write("]");
        }
    }

    virtual void at(const ConstDcl* node)
    {
        if (node->getJavadoc().size())
        {
            write("%s\n", node->getJavadoc().c_str());
            writetab();
        }
        write("static const ");
        at(static_cast<const Member*>(node));
        write(" = ");
        node->getExp()->accept(this);
    }

    virtual void at(const Attribute* node)
    {
        if (node->getJavadoc().size())
        {
            write("%s\n", node->getJavadoc().c_str());
            writetab();
        }

        // getter
        CPlusPlus::getter(node);
        write(" = 0");

        if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable())
        {
            // setter
            write(";\n");
            writetab();
            CPlusPlus::setter(node);
            write(" = 0");
        }
    }

    virtual void at(const OpDcl* node)
    {
        if (node->getJavadoc().size())
        {
            write("%s\n", node->getJavadoc().c_str());
            writetab();
        }

        CPlusPlus::at(node);

        if (!constructorMode)
        {
            write(" = 0");
        }
        else
        {
            writeln("");
            writeln("{");
            indent();
                writeln("if (constructor)");
                indent();
                    writetab();
                    write("constructor->createInstance(");
                    for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
                    {
                        if (i != node->begin())
                        {
                            write(", ");
                        }
                        write("%s", (*i)->getName().c_str());
                    }
                    write(");");
                    writeln("");
                unindent();
            unindent();
            writeln("}");
        }
    }
};

class Import : public Visitor
{
    FILE* file;
    bool printed;

public:
    Import(FILE* file) :
        file(file),
        printed(false)
    {
    }

    virtual void at(const Node* node)
    {
        if (1 < node->getRank())
        {
            return;
        }
        visitChildren(node);
    }

    virtual void at(const Include* node)
    {
        if (1 < node->getRank())
        {
            return;
        }
        if (node->isSystem())
        {
            fprintf(file, "#include <%s>\n", getOutputFilename(node->getName().c_str(), "h").c_str());
        }
        else
        {
            fprintf(file, "#include \"%s\"\n", getOutputFilename(node->getName().c_str(), "h").c_str());
        }
        printed = true;
    }

    bool hasPrinted() const
    {
        return printed;
    }
};

class Predeclaration : public Visitor
{
    FILE* file;

public:
    Predeclaration(FILE* file) :
        file(file)
    {
    }

    virtual void at(const Node* node)
    {
        if (1 < node->getRank())
        {
            return;
        }
        visitChildren(node);
    }

    virtual void at(const Module* node)
    {
        if (!node->hasPredeclarations())
        {
            return;
        }
        if (0 < node->getName().size())
        {
            fprintf(file, "namespace %s\n", node->getName().c_str());
            fprintf(file, "{\n");
                visitChildren(node);
            fprintf(file, "}\n\n");
        }
        else
        {
            visitChildren(node);
        }
    }

    virtual void at(const Interface* node)
    {
        if (1 < node->getRank() || !node->isLeaf())
        {
            return;
        }
        fprintf(file, "    class %s;\n", node->getName().c_str());
    }
};

void printCxx(const std::string& filename, const char* stringTypeName, bool useExceptions)
{
    printf("# %s\n", filename.c_str());

    FILE* file = fopen(filename.c_str(), "w");
    if (!file)
    {
        return;
    }

    std::string included = getIncludedName(filename);
    fprintf(file, "// Generated by esidl %s.\n\n", VERSION);
    fprintf(file, "#ifndef %s\n", included.c_str());
    fprintf(file, "#define %s\n\n", included.c_str());

    Import import(file);
    getSpecification()->accept(&import);
    if (import.hasPrinted())
    {
        fprintf(file, "\n");
    }

    if (!Node::getFlatNamespace())
    {
        Predeclaration predeclaration(file);
        getSpecification()->accept(&predeclaration);
    }

    Cxx cxx(file, stringTypeName, useExceptions);
    getSpecification()->accept(&cxx);

    fprintf(file, "#endif  // %s\n", included.c_str());

    fclose(file);
}
<commit_msg>(at(const Interface)) : Expand mixin methods and attributes in the implemented-on interface.<commit_after>/*
 * Copyright 2008, 2009 Google Inc.
 * Copyright 2007 Nintendo Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "cplusplus.h"

class Cxx : public CPlusPlus
{
    void visitInterfaceElement(const Interface* interface, Node* element)
    {
        if (element->isSequence(interface) || element->isNative(interface))
        {
            return;
        }
        optionalStage = 0;
        do
        {
            optionalCount = 0;
            writetab();
            element->accept(this);
            write(";\n");
            ++optionalStage;
        } while (optionalStage <= optionalCount);
    }

public:
    Cxx(FILE* file, const char* stringTypeName = "char*", bool useExceptions = true) :
        CPlusPlus(file, stringTypeName, useExceptions)
    {
    }

    virtual void at(const StructType* node)
    {
        if (node->getJavadoc().size())
        {
            write("%s\n%s", node->getJavadoc().c_str(), indentString.c_str());
        }
        write("struct %s", node->getName().c_str());
        if (!node->isLeaf())
        {
            write("\n%s{\n", indentString.c_str());
            indent();
            printChildren(node);
            unindent();
            write("%s}", indentString.c_str());
        }
    }

    virtual void at(const ExceptDcl* node)
    {
        if (node->getJavadoc().size())
        {
            write("%s\n%s", node->getJavadoc().c_str(), indentString.c_str());
        }
        write("struct %s", node->getName().c_str());
        write("\n%s{\n", indentString.c_str());
        indent();
        printChildren(node);
        unindent();
        write("%s}", indentString.c_str());
    }

    virtual void at(const Interface* node)
    {
        if (node->getJavadoc().size())
        {
            write("%s\n", node->getJavadoc().c_str());
            writetab();
        }
        write("class %s", node->getName().c_str());
        if (node->getExtends())
        {
            write(" : ");
            prefix = "public ";
            node->getExtends()->accept(this);
            prefix = "";
        }
        if (!node->isLeaf())
        {
            writeln("");
            writeln("{");
            writeln("public:");
            indent();

            for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
            {
                visitInterfaceElement(node, *i);
            }

            // Expand mixins
            for (std::list<const Interface*>::const_iterator i = node->getMixins()->begin();
                 i != node->getMixins()->end();
                 ++i)
            {
                writeln("// %s", (*i)->getName().c_str());
                for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j)
                {
                    visitInterfaceElement(*i, *j);
                }
            }

            writeln("static const char* iid()");
            writeln("{");
            indent();
                writeln("static const char* const name = \"%s\";",
                        node->getQualifiedName().c_str());
                writeln("return name;");
            unindent();
            writeln("}");

            if (Interface* constructor = node->getConstructor())
            {
                // Process constructors.
                constructorMode = true;
                for (NodeList::iterator i = constructor->begin();
                     i != constructor->end();
                     ++i)
                {
                    writetab();
                    (*i)->accept(this);
                }
                constructorMode = false;
                writeln("static Constructor* getConstructor()");
                writeln("{");
                indent();
                    writeln("return constructor;");
                unindent();
                writeln("}");
                writeln("static void setConstructor(Constructor* ctor)");
                writeln("{");
                indent();
                    writeln("constructor = ctor;");
                unindent();
                writeln("}");
                unindent();
                writeln("private:");
                indent();
                writeln("static Constructor* constructor;");
            }

            unindent();
            writetab();
            write("}");
        }

        if (node->getConstructor())
        {
            write(";\n\n");
            writetab();
            write("%s::Constructor* %s::constructor __attribute__((weak))",
                  node->getName().c_str(), node->getName().c_str());
        }
    }

    virtual void at(const NativeType* node)
    {
        if (node->getName() == "void_pointer")
        {
            write("void*");
        }
        else
        {
            write("%s", node->getName().c_str());
        }
    }

    virtual void at(const BinaryExpr* node)
    {
        node->getLeft()->accept(this);
        write(" %s ", node->getName().c_str());
        node->getRight()->accept(this);
    }

    virtual void at(const UnaryExpr* node)
    {
        write("%s", node->getName().c_str());
        NodeList::iterator elem = node->begin();
        (*elem)->accept(this);
    }

    virtual void at(const GroupingExpression* node)
    {
        write("(");
        NodeList::iterator elem = node->begin();
        (*elem)->accept(this);
        write(")");
    }

    virtual void at(const Literal* node)
    {
        if (node->getName() == "TRUE")
        {
            write("true");
        }
        else if (node->getName() == "FALSE")
        {
            write("false");
        }
        else
        {
            write("%s", node->getName().c_str());
        }
    }

    virtual void at(const Member* node)
    {
        if (node->isTypedef())
        {
            write("typedef ");
        }
        if (node->isInterface(node->getParent()))
        {
            node->getSpec()->accept(this);
            write(" %s", node->getName().c_str());
        }
        else
        {
            node->getSpec()->accept(this);
            write(" %s", node->getName().c_str());
        }
    }

    virtual void at(const ArrayDcl* node)
    {
        assert(!node->isLeaf());

        at(static_cast<const Member*>(node));
        for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
        {
            write("[");
            (*i)->accept(this);
            write("]");
        }
    }

    virtual void at(const ConstDcl* node)
    {
        if (node->getJavadoc().size())
        {
            write("%s\n", node->getJavadoc().c_str());
            writetab();
        }
        write("static const ");
        at(static_cast<const Member*>(node));
        write(" = ");
        node->getExp()->accept(this);
    }

    virtual void at(const Attribute* node)
    {
        if (node->getJavadoc().size())
        {
            write("%s\n", node->getJavadoc().c_str());
            writetab();
        }

        // getter
        CPlusPlus::getter(node);
        write(" = 0");

        if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable())
        {
            // setter
            write(";\n");
            writetab();
            CPlusPlus::setter(node);
            write(" = 0");
        }
    }

    virtual void at(const OpDcl* node)
    {
        if (node->getJavadoc().size())
        {
            write("%s\n", node->getJavadoc().c_str());
            writetab();
        }

        CPlusPlus::at(node);

        if (!constructorMode)
        {
            write(" = 0");
        }
        else
        {
            writeln("");
            writeln("{");
            indent();
                writeln("if (constructor)");
                indent();
                    writetab();
                    write("constructor->createInstance(");
                    for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
                    {
                        if (i != node->begin())
                        {
                            write(", ");
                        }
                        write("%s", (*i)->getName().c_str());
                    }
                    write(");");
                    writeln("");
                unindent();
            unindent();
            writeln("}");
        }
    }
};

class Import : public Visitor
{
    FILE* file;
    bool printed;

public:
    Import(FILE* file) :
        file(file),
        printed(false)
    {
    }

    virtual void at(const Node* node)
    {
        if (1 < node->getRank())
        {
            return;
        }
        visitChildren(node);
    }

    virtual void at(const Include* node)
    {
        if (1 < node->getRank())
        {
            return;
        }
        if (node->isSystem())
        {
            fprintf(file, "#include <%s>\n", getOutputFilename(node->getName().c_str(), "h").c_str());
        }
        else
        {
            fprintf(file, "#include \"%s\"\n", getOutputFilename(node->getName().c_str(), "h").c_str());
        }
        printed = true;
    }

    bool hasPrinted() const
    {
        return printed;
    }
};

class Predeclaration : public Visitor
{
    FILE* file;

public:
    Predeclaration(FILE* file) :
        file(file)
    {
    }

    virtual void at(const Node* node)
    {
        if (1 < node->getRank())
        {
            return;
        }
        visitChildren(node);
    }

    virtual void at(const Module* node)
    {
        if (!node->hasPredeclarations())
        {
            return;
        }
        if (0 < node->getName().size())
        {
            fprintf(file, "namespace %s\n", node->getName().c_str());
            fprintf(file, "{\n");
                visitChildren(node);
            fprintf(file, "}\n\n");
        }
        else
        {
            visitChildren(node);
        }
    }

    virtual void at(const Interface* node)
    {
        if (1 < node->getRank() || !node->isLeaf())
        {
            return;
        }
        fprintf(file, "    class %s;\n", node->getName().c_str());
    }
};

void printCxx(const std::string& filename, const char* stringTypeName, bool useExceptions)
{
    printf("# %s\n", filename.c_str());

    FILE* file = fopen(filename.c_str(), "w");
    if (!file)
    {
        return;
    }

    std::string included = getIncludedName(filename);
    fprintf(file, "// Generated by esidl %s.\n\n", VERSION);
    fprintf(file, "#ifndef %s\n", included.c_str());
    fprintf(file, "#define %s\n\n", included.c_str());

    Import import(file);
    getSpecification()->accept(&import);
    if (import.hasPrinted())
    {
        fprintf(file, "\n");
    }

    if (!Node::getFlatNamespace())
    {
        Predeclaration predeclaration(file);
        getSpecification()->accept(&predeclaration);
    }

    Cxx cxx(file, stringTypeName, useExceptions);
    getSpecification()->accept(&cxx);

    fprintf(file, "#endif  // %s\n", included.c_str());

    fclose(file);
}
<|endoftext|>


<commit_before><commit_msg>WaE: declaration of 'nInd' shadows a previous local<commit_after><|endoftext|>


<commit_before>#include "Platform.hpp"
#include "Neuron.hpp"
#include "Synapse.hpp"
#include "Branch.hpp"
#include "ActivityStats.hpp"
#include "genome.pb.h"
#include "Brain.hpp"
#include "SimpleProteinEnvironment.hpp"
#include "ProteinDensity.hpp"
#include "SpatialSearch.hpp"
#include <time.h>

namespace Elysia {

/**
 *	Description:	Deletes the protein density from memory and removes this neuron from the nearest-neighbor search
**/
Neuron::~Neuron() {
	//TODO Send a detach signal to all synapses presently attached
    for (std::ptrdiff_t i=(std::ptrdiff_t)mConnectedSynapses.size()-1;i>=0;--i) {
        mConnectedSynapses[i]->detach();
    }
    assert(mConnectedSynapses.size()==0);
    delete mProteinDensity;
    mBrain->getSpatialSearch()->removeNeighbor(this);
	for(std::vector<Branch*>::iterator i=mChildBranches.begin(),ie=mChildBranches.end();
         i!=ie;
         ++i){
		delete *i;
	}
}

/**
 *	@param Brain* brain - inherits a parent brain structure from somewhere
 *	@param float BaseBranchiness -
 *	@param float TipBranchiness -
 *	@param float TreeDepth -
 *	@param const Vector3f &location - neuron's location in space
 *	@param const Elysia::Genome::Gene &gene - parent gene info
 *
 *	Description:	Instantiates a new neuron object at some phyiscal location, setting the development counter at zero.
 *					The branch density is synched based upon some random parameters and some base parameters, as well as a defined tree depth
 *					This neuron is added to the nearest neighbor spatial search
**/
Neuron::Neuron(Brain* brain, float BaseBranchiness, float TipBranchiness, float TreeDepth, const Vector3f &location, const Elysia::Genome::Gene&gene):  mNeuronLocation(location){
    mProteinDensity = new ProteinDensity(brain->getProteinEnvironment(),gene);
    mBrain=brain;
    mDevelopmentCounter = 0;
    mWhere=brain->activeNeuronListSentinel();
    mRandomDepthDeterminer=rand()/(float)RAND_MAX;
    mRandomBranchDeterminer=rand()/(float)RAND_MAX;
    //mWhere=mBrain->activateNeuron(this); //JUST FOR TESTING REMOVE ME LATER
    this->syncBranchDensity(mRandomBranchDeterminer, mRandomDepthDeterminer, BaseBranchiness, TipBranchiness, TreeDepth, 0);
    mBrain->getSpatialSearch()->addNeighbor(this);
	mBaseBranchiness = BaseBranchiness;
    mTipBranchiness = TipBranchiness;
    mTreeDepth = TreeDepth;
	/* These are not yet used
    mBaseThreshold;
    mTipThreshold;
	*/
}

/**
 *	Description:	Fires neuron into all synapses connected to it
**/
void Neuron::fire() {
	printf("fire");
    for (std::vector<Synapse*>::iterator i=mConnectedSynapses.begin(),ie=mConnectedSynapses.end();
         i!=ie;
         ++i) {
        this->fireNeuron(*i);
    }
}

/**
 *	@param Brain& - unused, here for inheritance
 *	@param float signal - signal to add to activity
 *
 *	Description:	If last activity is not current sim time in the brain, reset activity to zero
 *					and make last activity time current brain time.
 *					Then, if the activity is under some treshold, the signal parameter is added to activity,
 *					after which the neuron is activated if the new activity level is above some threshold
**/
void Neuron::activateComponent(Brain&, float signal){
	if(mLastActivity != mBrain->mCurTime){
		mLastActivity = mBrain->mCurTime;
		mActivity = 0;
	}
	if(mActivity <= mThreshold){
	    mActivity += signal;
		if(mActivity > mThreshold){
			mBrain -> activateNeuron(this);     //Add to Neuron List
		}
	}
}

/**
 *	@param Synapse *synapse - pointer to some synapse you want to remove
 *
 *	Description:	Looks for the provided synapse in the connected synapses vector and removes it, if found.
 *					Prints an error message if not found
**/
void Neuron::removeSynapse(Synapse*synapse){
  std::vector<Synapse* >::iterator where=std::find(mConnectedSynapses.begin(),mConnectedSynapses.end(),synapse);
  if (where!=mConnectedSynapses.end()) {
    mConnectedSynapses.erase(where);
  }else {
    std::cerr<< "Could not find synapse\n";
  }
}

/**
 *	@param Synapse *target - pointer to a synapse to fire
 *
 *	Description:	Fires some synapse
**/
void Neuron::fireNeuron(Synapse*target){
	target->fireSynapse();
}

/**
 *	@param Synapse *target - pointer to a synapse to add
 *
 *	Description:	Puts the new synapse at the end of the connected synapses vector
**/
void Neuron::attachSynapse(Synapse*target){
	mConnectedSynapses.push_back(target);
}

/**
 *	@param float signal - signal to add to development signal
 *
 *	Description:	Adds some value to the development signal level
**/
void Neuron::passDevelopmentSignal(float signal){
	mDevelopmentSignal += signal;
}
/**
 *	@returns *mProteinDensity
**/
ProteinDensity& Neuron::getProteinDensityStructure(){
    return *mProteinDensity;
}

/**
 *	@param const ActivityStats& stats - activity statistics for something
 *
 *	Description:	Develops all synapses attached as child branches of this neuron
**/
void Neuron::developSynapse(const ActivityStats& stats){
for (std::vector<Branch*>::iterator i=mChildBranches.begin(),ie=mChildBranches.end();
         i!=ie;
         ++i)
	(*i)->developSynapse(stats);
}

/**
 *	@param FILE *dendriteTree - output file for the visualized dendrite tree
 *	@param size_t parent - unused, please remove
 *
 *	Description:	Outputs a visualization of the dendrite tree to a file
**/
void Neuron::visualizeTree(FILE *dendriteTree, size_t parent){

    size_t self;

    self = (size_t)this;
    //fprintf(dendriteTree,"Graph Tree {\n");
    for (std::vector<Branch*>::iterator i=mChildBranches.begin(),ie=mChildBranches.end();
         i!=ie;
         ++i)
         (*i) -> visualizeTree(dendriteTree, self);
   //fprintf(dendriteTree,"}");

   }

/**
 *	Description:	Executes one "tick" of the brain simulation for this neuron.
 *					If activity is over some threshold, fires the neuron.
 *					If development stage is not set and development counter is not at zero,
 *					the development counter is decremented.  If it is at zero, then we developSynapse(getActivityStats())
 *					and reset development counter to 30.
 *					mActivity always cleared at the end of this
**/
void Neuron::tick(){
	if(mActivity > mThreshold){
		fire();
	}
	if(mDevelopmentStage == 0){
		if(mDevelopmentCounter == 0){
			ActivityStats& stats = getActivityStats();
			developSynapse(stats);
			mDevelopmentCounter	= 30;					//number of timesteps before next development re-evaluation
		}
		else{ mDevelopmentCounter--;}
	}
	mActivity = 0;
}
}
<commit_msg>fixing conflict<commit_after>#include "Platform.hpp"
#include "Neuron.hpp"
#include "Synapse.hpp"
#include "Branch.hpp"
#include "ActivityStats.hpp"
#include "genome.pb.h"
#include "Brain.hpp"
#include "SimpleProteinEnvironment.hpp"
#include "ProteinDensity.hpp"
#include "SpatialSearch.hpp"
#include <time.h>

namespace Elysia {

/**
 *	Description:	Deletes the protein density from memory and removes this neuron from the nearest-neighbor search
**/
Neuron::~Neuron() {
    for (std::ptrdiff_t i=(std::ptrdiff_t)mConnectedSynapses.size()-1;i>=0;--i) {
        mConnectedSynapses[i]->detach();
    }
    assert(mConnectedSynapses.size()==0);
    delete mProteinDensity;
    mBrain->getSpatialSearch()->removeNeighbor(this);
	for(std::vector<Branch*>::iterator i=mChildBranches.begin(),ie=mChildBranches.end();
         i!=ie;
         ++i){
		delete *i;
	}
}

/**
 *	@param Brain* brain - inherits a parent brain structure from somewhere
 *	@param float BaseBranchiness -
 *	@param float TipBranchiness -
 *	@param float TreeDepth -
 *	@param const Vector3f &location - neuron's location in space
 *	@param const Elysia::Genome::Gene &gene - parent gene info
 *
 *	Description:	Instantiates a new neuron object at some phyiscal location, setting the development counter at zero.
 *					The branch density is synched based upon some random parameters and some base parameters, as well as a defined tree depth
 *					This neuron is added to the nearest neighbor spatial search
**/
Neuron::Neuron(Brain* brain, float BaseBranchiness, float TipBranchiness, float TreeDepth, const Vector3f &location, const Elysia::Genome::Gene&gene):  mNeuronLocation(location){
    mProteinDensity = new ProteinDensity(brain->getProteinEnvironment(),gene);
    mBrain=brain;
    mDevelopmentCounter = 0;
    mWhere=brain->activeNeuronListSentinel();
    mRandomDepthDeterminer=rand()/(float)RAND_MAX;
    mRandomBranchDeterminer=rand()/(float)RAND_MAX;
    //mWhere=mBrain->activateNeuron(this); //JUST FOR TESTING REMOVE ME LATER
    this->syncBranchDensity(mRandomBranchDeterminer, mRandomDepthDeterminer, BaseBranchiness, TipBranchiness, TreeDepth, 0);
    mBrain->getSpatialSearch()->addNeighbor(this);
	mBaseBranchiness = BaseBranchiness;
    mTipBranchiness = TipBranchiness;
    mTreeDepth = TreeDepth;
	/* These are not yet used
    mBaseThreshold;
    mTipThreshold;
	*/
}

/**
 *	Description:	Fires neuron into all synapses connected to it
**/
void Neuron::fire() {
	printf("fire");
    for (std::vector<Synapse*>::iterator i=mConnectedSynapses.begin(),ie=mConnectedSynapses.end();
         i!=ie;
         ++i) {
        this->fireNeuron(*i);
    }
}

/**
 *	@param Brain& - unused, here for inheritance
 *	@param float signal - signal to add to activity
 *
 *	Description:	If last activity is not current sim time in the brain, reset activity to zero
 *					and make last activity time current brain time.
 *					Then, if the activity is under some treshold, the signal parameter is added to activity,
 *					after which the neuron is activated if the new activity level is above some threshold
**/
void Neuron::activateComponent(Brain&, float signal){
	if(mLastActivity != mBrain->mCurTime){
		mLastActivity = mBrain->mCurTime;
		mActivity = 0;
	}
	if(mActivity <= mThreshold){
	    mActivity += signal;
		if(mActivity > mThreshold){
			mBrain -> activateNeuron(this);     //Add to Neuron List
		}
	}
}

/**
 *	@param Synapse *synapse - pointer to some synapse you want to remove
 *
 *	Description:	Looks for the provided synapse in the connected synapses vector and removes it, if found.
 *					Prints an error message if not found
**/
void Neuron::removeSynapse(Synapse*synapse){
  std::vector<Synapse* >::iterator where=std::find(mConnectedSynapses.begin(),mConnectedSynapses.end(),synapse);
  if (where!=mConnectedSynapses.end()) {
    mConnectedSynapses.erase(where);
  }else {
    std::cerr<< "Could not find synapse\n";
  }
}

/**
 *	@param Synapse *target - pointer to a synapse to fire
 *
 *	Description:	Fires some synapse
**/
void Neuron::fireNeuron(Synapse*target){
	target->fireSynapse();
}

/**
 *	@param Synapse *target - pointer to a synapse to add
 *
 *	Description:	Puts the new synapse at the end of the connected synapses vector
**/
void Neuron::attachSynapse(Synapse*target){
	mConnectedSynapses.push_back(target);
}

/**
 *	@param float signal - signal to add to development signal
 *
 *	Description:	Adds some value to the development signal level
**/
void Neuron::passDevelopmentSignal(float signal){
	mDevelopmentSignal += signal;
}
/**
 *	@returns *mProteinDensity
**/
ProteinDensity& Neuron::getProteinDensityStructure(){
    return *mProteinDensity;
}

/**
 *	@param const ActivityStats& stats - activity statistics for something
 *
 *	Description:	Develops all synapses attached as child branches of this neuron
**/
void Neuron::developSynapse(const ActivityStats& stats){
for (std::vector<Branch*>::iterator i=mChildBranches.begin(),ie=mChildBranches.end();
         i!=ie;
         ++i)
	(*i)->developSynapse(stats);
}

/**
 *	@param FILE *dendriteTree - output file for the visualized dendrite tree
 *	@param size_t parent - unused, please remove
 *
 *	Description:	Outputs a visualization of the dendrite tree to a file
**/
void Neuron::visualizeTree(FILE *dendriteTree, size_t parent){

    size_t self;

    self = (size_t)this;
    //fprintf(dendriteTree,"Graph Tree {\n");
    for (std::vector<Branch*>::iterator i=mChildBranches.begin(),ie=mChildBranches.end();
         i!=ie;
         ++i)
         (*i) -> visualizeTree(dendriteTree, self);
   //fprintf(dendriteTree,"}");

   }

/**
 *	Description:	Executes one "tick" of the brain simulation for this neuron.
 *					If activity is over some threshold, fires the neuron.
 *					If development stage is not set and development counter is not at zero,
 *					the development counter is decremented.  If it is at zero, then we developSynapse(getActivityStats())
 *					and reset development counter to 30.
 *					mActivity always cleared at the end of this
**/
void Neuron::tick(){
	if(mActivity > mThreshold){
		fire();
	}
	if(mDevelopmentStage == 0){
		if(mDevelopmentCounter == 0){
			ActivityStats& stats = getActivityStats();
			developSynapse(stats);
			mDevelopmentCounter	= 30;					//number of timesteps before next development re-evaluation
		}
		else{ mDevelopmentCounter--;}
	}
	mActivity = 0;
}
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2003-2011 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 about.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
#include <wx/url.h>

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

#include "about.h"
#include "version.h"
#include "passwordsafeframe.h"
#include "core/CheckVersion.h"
////@begin XPM images
#include "./graphics/cpane.xpm"
////@end XPM images

/*!
 * CAbout type definition
 */

IMPLEMENT_CLASS( CAbout, wxDialog )

/*!
 * CAbout event table definition
 */

BEGIN_EVENT_TABLE( CAbout, wxDialog )

////@begin CAbout event table entries
  EVT_HYPERLINK( ID_HYPERLINKCTRL1, CAbout::OnHyperlinkctrl1HyperlinkClicked )

  EVT_BUTTON( wxID_CLOSE, CAbout::OnCloseClick )

////@end CAbout event table entries

END_EVENT_TABLE()

/*!
 * CAbout constructors
 */

CAbout::CAbout()
{
  Init();
}

CAbout::CAbout( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
  Init();
  Create(parent, id, caption, pos, size, style);
}

/*!
 * CAbout creator
 */

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

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

/*!
 * CAbout destructor
 */

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

/*!
 * Member initialisation
 */

void CAbout::Init()
{
////@begin CAbout member initialisation
  m_newVerStatus = NULL;
////@end CAbout member initialisation
}

/*!
 * Control creation for CAbout
 */

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

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

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

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

  wxStaticText* itemStaticText5 = new wxStaticText( itemDialog1, wxID_VERSIONSTR, _("Password Safe vx.yy (abcd)"), wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT );
  itemBoxSizer4->Add(itemStaticText5, 0, wxALIGN_LEFT|wxALL, 5);

  wxBoxSizer* itemBoxSizer6 = new wxBoxSizer(wxHORIZONTAL);
  itemBoxSizer4->Add(itemBoxSizer6, 0, wxALIGN_LEFT|wxALL, 0);

  wxStaticText* itemStaticText7 = new wxStaticText( itemDialog1, wxID_STATIC, _("Latest version? Click"), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer6->Add(itemStaticText7, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

  wxHyperlinkCtrl* itemHyperlinkCtrl8 = new wxHyperlinkCtrl( itemDialog1, ID_HYPERLINKCTRL1, _("here"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE );
  itemBoxSizer6->Add(itemHyperlinkCtrl8, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

  wxStaticText* itemStaticText9 = new wxStaticText( itemDialog1, wxID_STATIC, _("to check."), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer6->Add(itemStaticText9, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

  wxBoxSizer* itemBoxSizer10 = new wxBoxSizer(wxHORIZONTAL);
  itemBoxSizer4->Add(itemBoxSizer10, 0, wxALIGN_LEFT|wxALL, 0);

  wxStaticText* itemStaticText11 = new wxStaticText( itemDialog1, wxID_STATIC, _("Please visit the "), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer10->Add(itemStaticText11, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

  wxHyperlinkCtrl* itemHyperlinkCtrl12 = new wxHyperlinkCtrl( itemDialog1, ID_HYPERLINKCTRL, _("PasswordSafe website"), _T("http://pwsafe.org/"), wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE );
  itemBoxSizer10->Add(itemHyperlinkCtrl12, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

  wxStaticText* itemStaticText13 = new wxStaticText( itemDialog1, wxID_STATIC, _("See LICENSE for open souce details."), wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT );
  itemBoxSizer4->Add(itemStaticText13, 0, wxALIGN_LEFT|wxALL, 5);

  wxStaticText* itemStaticText14 = new wxStaticText( itemDialog1, wxID_STATIC, _("Copyright (c) 2003-2010 by Rony Shapiro"), wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT );
  itemBoxSizer4->Add(itemStaticText14, 0, wxALIGN_LEFT|wxALL, 5);

  m_newVerStatus = new wxTextCtrl( itemDialog1, ID_TEXTCTRL, wxEmptyString, wxDefaultPosition, wxSize(itemDialog1->ConvertDialogToPixels(wxSize(120, -1)).x, -1), wxTE_READONLY|wxNO_BORDER );
  m_newVerStatus->SetBackgroundColour(wxColour(230, 231, 232));
  itemBoxSizer4->Add(m_newVerStatus, 0, wxALIGN_LEFT|wxALL, 5);

  wxButton* itemButton16 = new wxButton( itemDialog1, wxID_CLOSE, _("&Close"), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer4->Add(itemButton16, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);

////@end CAbout content construction
  const wxString vstring = pwsafeAppName + _T(" ") + pwsafeVersionString;
  itemStaticText5->SetLabel(vstring);
}

/*!
 * Should we show tooltips?
 */

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

/*!
 * Get bitmap resources
 */

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

/*!
 * Get icon resources
 */

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

/*!
 * wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CLOSE
 */

void CAbout::OnCloseClick( wxCommandEvent& /* evt */ )
{
////@begin wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CLOSE in CAbout.
  // Before editing this code, remove the block markers.
  EndModal(wxID_CLOSE);
////@end wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CLOSE in CAbout.
}

/*
 * The latest version information is in
 * http://pwsafe.org/latest.xml
 *
 * And is of the form:
 * <VersionInfo>
 *  <Product name=PasswordSafe variant=PC major=3 minor=10 build=2 rev=1710 />
 *  <Product name=PasswordSafe variant=PPc major=1 minor=9 build=2
 *    rev=100 />
 *  <Product name=PasswordSafe variant=U3 major=3 minor=10 build=2
 *    rev=1710 />
 *  <Product name=SWTPasswordSafe variant=Java major=0 minor=6
 *    build=0 rev=1230 />
 * </VersionInfo>
 *
 * Note: The "rev" is the svn commit number. Not using it (for now),
 *       as I think it's too volatile.
 */

/*!
 * wxEVT_COMMAND_HYPERLINK event handler for ID_HYPERLINKCTRL1
 */

void CAbout::OnHyperlinkctrl1HyperlinkClicked( wxHyperlinkEvent& /* evt */ )
{
  // Get the latest.xml file from our site, compare to version,
  // and notify the user
  // First, make sure database is closed: Sensitive data with an
  // open socket makes me uneasy...
  PasswordSafeFrame *pFrm = static_cast<PasswordSafeFrame *>(GetParent());

  if (pFrm->GetNumEntries() != 0) {
    const wxString cs_txt(_("For security, the database must be closed before connecting to the Internet.\r\nPress OK to close database and continue (Changes will be saved)"));
    const wxString cs_title(_("Confirm Close Dialog"));
    wxMessageDialog dlg(this, cs_txt, cs_title,
                        (wxICON_QUESTION | wxOK | wxCANCEL));
    int rc = dlg.ShowModal();
    if (rc == wxCANCEL)
      return; // no hard feelings
    // Close database, prompt for save if changed
    wxCommandEvent closeEvent(wxEVT_COMMAND_MENU_SELECTED, wxID_CLOSE);
    pFrm->ProcessEvent(closeEvent);
    // User could have cancelled save, need to check if really closed:
    if (pFrm->GetNumEntries() != 0)
      return;
  }
  pFrm->Update(); // show user that we closed database
  ASSERT(pFrm->GetNumEntries() == 0);
  // safe to open external connection
  m_newVerStatus->Clear();
  *m_newVerStatus << _("Trying to contact server...");
  m_newVerStatus->Show();
  stringT latext_xml;
  wxURL url(_("http://pwsafe.org/latest.xml"));
  wxInputStream *in_stream = url.GetInputStream();
  unsigned char buff[BUFSIZ+1];
  StringX chunk;
  stringT latest_xml;
  CUTF8Conv conv;
  CheckVersion::CheckStatus status = CheckVersion::UP2DATE;
  do {
    in_stream->Read(buff, BUFSIZ);
    size_t nRead = in_stream->LastRead();
    if (nRead != 0) {
      buff[nRead] = '\0';
      // change to widechar representation
      if (!conv.FromUTF8(buff, nRead, chunk)) {
        delete in_stream;
        status = CheckVersion::CANT_READ;
        break;
      } else {
        latest_xml += chunk.c_str();
      }
    }
  } while (!in_stream->Eof());
  delete in_stream;
  if (url.GetError() != wxURL_NOERR)
    status = CheckVersion::CANT_CONNECT;

  stringT latest;
  if (status == CheckVersion::UP2DATE) {
    CheckVersion cv(MAJORVERSION, MINORVERSION, 0);
    status = cv.CheckLatestVersion(latest_xml, latest);
  }
  m_newVerStatus->Clear();
  switch (status) {
    case CheckVersion::CANT_CONNECT:
      *m_newVerStatus << _("Couldn't contact server.");
      break;
    case CheckVersion::UP2DATE:
      *m_newVerStatus << _("This is the latest release!");
      break;
    case CheckVersion::NEWER_AVAILABLE:
    {
      wxString newer(_("Current version: "));
      newer += pwsafeVersionString;
      newer += _("\r\nLatest version:\t"); newer += latest.c_str();
      newer += _("\r\n\r\nPlease visit the PasswordSafe website to download the latest version.");
      const wxString cs_title(_("Newer Version Found!"));
      *m_newVerStatus << cs_title;
      wxMessageDialog dlg(this, newer, cs_title, wxOK);
      dlg.ShowModal();
      break;
    }
    case CheckVersion::CANT_READ:
      *m_newVerStatus << _("Could not read server version data.");
      break;
    default:
      break;
  }
  m_newVerStatus->Show();
}

<commit_msg>Missed a 2011 :-)<commit_after>/*
 * Copyright (c) 2003-2011 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 about.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
#include <wx/url.h>

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

#include "about.h"
#include "version.h"
#include "passwordsafeframe.h"
#include "core/CheckVersion.h"
////@begin XPM images
#include "./graphics/cpane.xpm"
////@end XPM images

/*!
 * CAbout type definition
 */

IMPLEMENT_CLASS( CAbout, wxDialog )

/*!
 * CAbout event table definition
 */

BEGIN_EVENT_TABLE( CAbout, wxDialog )

////@begin CAbout event table entries
  EVT_HYPERLINK( ID_HYPERLINKCTRL1, CAbout::OnHyperlinkctrl1HyperlinkClicked )

  EVT_BUTTON( wxID_CLOSE, CAbout::OnCloseClick )

////@end CAbout event table entries

END_EVENT_TABLE()

/*!
 * CAbout constructors
 */

CAbout::CAbout()
{
  Init();
}

CAbout::CAbout( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
  Init();
  Create(parent, id, caption, pos, size, style);
}

/*!
 * CAbout creator
 */

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

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

/*!
 * CAbout destructor
 */

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

/*!
 * Member initialisation
 */

void CAbout::Init()
{
////@begin CAbout member initialisation
  m_newVerStatus = NULL;
////@end CAbout member initialisation
}

/*!
 * Control creation for CAbout
 */

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

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

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

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

  wxStaticText* itemStaticText5 = new wxStaticText( itemDialog1, wxID_VERSIONSTR, _("Password Safe vx.yy (abcd)"), wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT );
  itemBoxSizer4->Add(itemStaticText5, 0, wxALIGN_LEFT|wxALL, 5);

  wxBoxSizer* itemBoxSizer6 = new wxBoxSizer(wxHORIZONTAL);
  itemBoxSizer4->Add(itemBoxSizer6, 0, wxALIGN_LEFT|wxALL, 0);

  wxStaticText* itemStaticText7 = new wxStaticText( itemDialog1, wxID_STATIC, _("Latest version? Click"), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer6->Add(itemStaticText7, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

  wxHyperlinkCtrl* itemHyperlinkCtrl8 = new wxHyperlinkCtrl( itemDialog1, ID_HYPERLINKCTRL1, _("here"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE );
  itemBoxSizer6->Add(itemHyperlinkCtrl8, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

  wxStaticText* itemStaticText9 = new wxStaticText( itemDialog1, wxID_STATIC, _("to check."), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer6->Add(itemStaticText9, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

  wxBoxSizer* itemBoxSizer10 = new wxBoxSizer(wxHORIZONTAL);
  itemBoxSizer4->Add(itemBoxSizer10, 0, wxALIGN_LEFT|wxALL, 0);

  wxStaticText* itemStaticText11 = new wxStaticText( itemDialog1, wxID_STATIC, _("Please visit the "), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer10->Add(itemStaticText11, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

  wxHyperlinkCtrl* itemHyperlinkCtrl12 = new wxHyperlinkCtrl( itemDialog1, ID_HYPERLINKCTRL, _("PasswordSafe website"), _T("http://pwsafe.org/"), wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE );
  itemBoxSizer10->Add(itemHyperlinkCtrl12, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

  wxStaticText* itemStaticText13 = new wxStaticText( itemDialog1, wxID_STATIC, _("See LICENSE for open souce details."), wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT );
  itemBoxSizer4->Add(itemStaticText13, 0, wxALIGN_LEFT|wxALL, 5);

  wxStaticText* itemStaticText14 = new wxStaticText( itemDialog1, wxID_STATIC, _("Copyright (c) 2003-2011 by Rony Shapiro"), wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT );
  itemBoxSizer4->Add(itemStaticText14, 0, wxALIGN_LEFT|wxALL, 5);

  m_newVerStatus = new wxTextCtrl( itemDialog1, ID_TEXTCTRL, wxEmptyString, wxDefaultPosition, wxSize(itemDialog1->ConvertDialogToPixels(wxSize(120, -1)).x, -1), wxTE_READONLY|wxNO_BORDER );
  m_newVerStatus->SetBackgroundColour(wxColour(230, 231, 232));
  itemBoxSizer4->Add(m_newVerStatus, 0, wxALIGN_LEFT|wxALL, 5);

  wxButton* itemButton16 = new wxButton( itemDialog1, wxID_CLOSE, _("&Close"), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer4->Add(itemButton16, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);

////@end CAbout content construction
  const wxString vstring = pwsafeAppName + _T(" ") + pwsafeVersionString;
  itemStaticText5->SetLabel(vstring);
}

/*!
 * Should we show tooltips?
 */

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

/*!
 * Get bitmap resources
 */

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

/*!
 * Get icon resources
 */

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

/*!
 * wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CLOSE
 */

void CAbout::OnCloseClick( wxCommandEvent& /* evt */ )
{
////@begin wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CLOSE in CAbout.
  // Before editing this code, remove the block markers.
  EndModal(wxID_CLOSE);
////@end wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CLOSE in CAbout.
}

/*
 * The latest version information is in
 * http://pwsafe.org/latest.xml
 *
 * And is of the form:
 * <VersionInfo>
 *  <Product name=PasswordSafe variant=PC major=3 minor=10 build=2 rev=1710 />
 *  <Product name=PasswordSafe variant=PPc major=1 minor=9 build=2
 *    rev=100 />
 *  <Product name=PasswordSafe variant=U3 major=3 minor=10 build=2
 *    rev=1710 />
 *  <Product name=SWTPasswordSafe variant=Java major=0 minor=6
 *    build=0 rev=1230 />
 * </VersionInfo>
 *
 * Note: The "rev" is the svn commit number. Not using it (for now),
 *       as I think it's too volatile.
 */

/*!
 * wxEVT_COMMAND_HYPERLINK event handler for ID_HYPERLINKCTRL1
 */

void CAbout::OnHyperlinkctrl1HyperlinkClicked( wxHyperlinkEvent& /* evt */ )
{
  // Get the latest.xml file from our site, compare to version,
  // and notify the user
  // First, make sure database is closed: Sensitive data with an
  // open socket makes me uneasy...
  PasswordSafeFrame *pFrm = static_cast<PasswordSafeFrame *>(GetParent());

  if (pFrm->GetNumEntries() != 0) {
    const wxString cs_txt(_("For security, the database must be closed before connecting to the Internet.\r\nPress OK to close database and continue (Changes will be saved)"));
    const wxString cs_title(_("Confirm Close Dialog"));
    wxMessageDialog dlg(this, cs_txt, cs_title,
                        (wxICON_QUESTION | wxOK | wxCANCEL));
    int rc = dlg.ShowModal();
    if (rc == wxCANCEL)
      return; // no hard feelings
    // Close database, prompt for save if changed
    wxCommandEvent closeEvent(wxEVT_COMMAND_MENU_SELECTED, wxID_CLOSE);
    pFrm->ProcessEvent(closeEvent);
    // User could have cancelled save, need to check if really closed:
    if (pFrm->GetNumEntries() != 0)
      return;
  }
  pFrm->Update(); // show user that we closed database
  ASSERT(pFrm->GetNumEntries() == 0);
  // safe to open external connection
  m_newVerStatus->Clear();
  *m_newVerStatus << _("Trying to contact server...");
  m_newVerStatus->Show();
  stringT latext_xml;
  wxURL url(_("http://pwsafe.org/latest.xml"));
  wxInputStream *in_stream = url.GetInputStream();
  unsigned char buff[BUFSIZ+1];
  StringX chunk;
  stringT latest_xml;
  CUTF8Conv conv;
  CheckVersion::CheckStatus status = CheckVersion::UP2DATE;
  do {
    in_stream->Read(buff, BUFSIZ);
    size_t nRead = in_stream->LastRead();
    if (nRead != 0) {
      buff[nRead] = '\0';
      // change to widechar representation
      if (!conv.FromUTF8(buff, nRead, chunk)) {
        delete in_stream;
        status = CheckVersion::CANT_READ;
        break;
      } else {
        latest_xml += chunk.c_str();
      }
    }
  } while (!in_stream->Eof());
  delete in_stream;
  if (url.GetError() != wxURL_NOERR)
    status = CheckVersion::CANT_CONNECT;

  stringT latest;
  if (status == CheckVersion::UP2DATE) {
    CheckVersion cv(MAJORVERSION, MINORVERSION, 0);
    status = cv.CheckLatestVersion(latest_xml, latest);
  }
  m_newVerStatus->Clear();
  switch (status) {
    case CheckVersion::CANT_CONNECT:
      *m_newVerStatus << _("Couldn't contact server.");
      break;
    case CheckVersion::UP2DATE:
      *m_newVerStatus << _("This is the latest release!");
      break;
    case CheckVersion::NEWER_AVAILABLE:
    {
      wxString newer(_("Current version: "));
      newer += pwsafeVersionString;
      newer += _("\r\nLatest version:\t"); newer += latest.c_str();
      newer += _("\r\n\r\nPlease visit the PasswordSafe website to download the latest version.");
      const wxString cs_title(_("Newer Version Found!"));
      *m_newVerStatus << cs_title;
      wxMessageDialog dlg(this, newer, cs_title, wxOK);
      dlg.ShowModal();
      break;
    }
    case CheckVersion::CANT_READ:
      *m_newVerStatus << _("Could not read server version data.");
      break;
    default:
      break;
  }
  m_newVerStatus->Show();
}

<|endoftext|>