<commit_before>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2014 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include <poly/ui/win32/win32_window.h>

#include <dwmapi.h>
#include <tpcshrd.h>
#include <windowsx.h>

#include <poly/logging.h>

namespace poly {
namespace ui {
namespace win32 {

Win32Window::Win32Window(const std::wstring& title)
    : Window(title), main_menu_(nullptr), closing_(false) {}

Win32Window::~Win32Window() {}

bool Win32Window::Initialize() {
  Create();
  return true;
}

bool Win32Window::Create() {
  HINSTANCE hInstance = GetModuleHandle(nullptr);

  WNDCLASSEX wcex;
  wcex.cbSize = sizeof(WNDCLASSEX);
  wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
  wcex.lpfnWndProc = Win32Control::WndProcThunk;
  wcex.cbClsExtra = 0;
  wcex.cbWndExtra = 0;
  wcex.hInstance = hInstance;
  wcex.hIcon = nullptr;    // LoadIcon(hInstance, (LPCTSTR)IDI_TUTORIAL1);
  wcex.hIconSm = nullptr;  // LoadIcon(hInstance, (LPCTSTR)IDI_TUTORIAL1);
  wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
  wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
  wcex.lpszMenuName = nullptr;
  wcex.lpszClassName = L"XeniaWindowClass";
  if (!RegisterClassEx(&wcex)) {
    PLOGE("RegisterClassEx failed");
    return false;
  }

  // Setup initial size.
  DWORD window_style = WS_OVERLAPPEDWINDOW;
  DWORD window_ex_style = WS_EX_APPWINDOW | WS_EX_CONTROLPARENT;
  RECT rc = {0, 0, width_, height_};
  AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);

  // Create window.
  hwnd_ = CreateWindowEx(window_ex_style, L"XeniaWindowClass", L"Xenia",
                         window_style, CW_USEDEFAULT, CW_USEDEFAULT,
                         rc.right - rc.left, rc.bottom - rc.top, nullptr,
                         nullptr, hInstance, this);
  if (!hwnd_) {
    PLOGE("CreateWindow failed");
    return false;
  }

  main_menu_ = CreateMenu();
  AppendMenu(main_menu_, MF_STRING, 0, L"TODO");
  SetMenu(hwnd_, main_menu_);

  // Disable flicks.
  ATOM atom = GlobalAddAtom(L"MicrosoftTabletPenServiceProperty");
  const DWORD_PTR dwHwndTabletProperty =
      TABLET_DISABLE_PRESSANDHOLD |    // disables press and hold (right-click)
                                       // gesture
      TABLET_DISABLE_PENTAPFEEDBACK |  // disables UI feedback on pen up (waves)
      TABLET_DISABLE_PENBARRELFEEDBACK |  // disables UI feedback on pen button
                                          // down (circle)
      TABLET_DISABLE_FLICKS |  // disables pen flicks (back, forward, drag down,
                               // drag up)
      TABLET_DISABLE_TOUCHSWITCH | TABLET_DISABLE_SMOOTHSCROLLING |
      TABLET_DISABLE_TOUCHUIFORCEON | TABLET_ENABLE_MULTITOUCHDATA;
  SetProp(hwnd_, L"MicrosoftTabletPenServiceProperty",
          reinterpret_cast<HANDLE>(dwHwndTabletProperty));
  GlobalDeleteAtom(atom);

  // Enable DWM elevation.
  EnableMMCSS();

  ShowWindow(hwnd_, SW_SHOWNORMAL);
  UpdateWindow(hwnd_);

  return 0;
}

void Win32Window::EnableMMCSS() {
  HMODULE hLibrary = LoadLibrary(L"DWMAPI.DLL");
  if (!hLibrary) {
    return;
  }

  typedef HRESULT(__stdcall * PDwmEnableMMCSS)(BOOL);
  PDwmEnableMMCSS pDwmEnableMMCSS =
      (PDwmEnableMMCSS)GetProcAddress(hLibrary, "DwmEnableMMCSS");
  if (pDwmEnableMMCSS) {
    pDwmEnableMMCSS(TRUE);
  }

  typedef HRESULT(__stdcall * PDwmSetPresentParameters)(
      HWND, DWM_PRESENT_PARAMETERS*);
  PDwmSetPresentParameters pDwmSetPresentParameters =
      (PDwmSetPresentParameters)GetProcAddress(hLibrary,
                                               "DwmSetPresentParameters");
  if (pDwmSetPresentParameters) {
    DWM_PRESENT_PARAMETERS pp;
    memset(&pp, 0, sizeof(DWM_PRESENT_PARAMETERS));
    pp.cbSize = sizeof(DWM_PRESENT_PARAMETERS);
    pp.fQueue = FALSE;
    pp.cBuffer = 2;
    pp.fUseSourceRate = FALSE;
    pp.cRefreshesPerFrame = 1;
    pp.eSampling = DWM_SOURCE_FRAME_SAMPLING_POINT;
    pDwmSetPresentParameters(hwnd_, &pp);
  }

  FreeLibrary(hLibrary);
}

bool Win32Window::set_title(const std::wstring& title) {
  if (!Window::set_title(title)) {
    return false;
  }
  SetWindowText(hwnd_, title.c_str());
  return true;
}

void Win32Window::Resize(int32_t width, int32_t height) {
  RECT rc = {0, 0, width, height};
  bool has_menu = main_menu_ ? true : false;
  AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, has_menu);
  Window::Resize(rc.right - rc.left, rc.bottom - rc.top);
}

void Win32Window::Resize(int32_t left, int32_t top, int32_t right,
                         int32_t bottom) {
  RECT rc = {left, top, right, bottom};
  bool has_menu = main_menu_ ? true : false;
  AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, has_menu);
  Window::Resize(rc.left, rc.top, rc.right, rc.bottom);
}

void Win32Window::ResizeToFill(int32_t pad_left, int32_t pad_top,
                               int32_t pad_right, int32_t pad_bottom) {
  // TODO(benvanik): fullscreen.
}

void Win32Window::OnClose() {
  if (!closing_ && hwnd_) {
    closing_ = true;
    CloseWindow(hwnd_);
  }
}

LRESULT Win32Window::WndProc(HWND hWnd, UINT message, WPARAM wParam,
                             LPARAM lParam) {
  switch (message) {
    case WM_ACTIVATEAPP:
      if (wParam) {
        // Made active.
        OnShow();
      } else {
        // Made inactive.
        OnHide();
      }
      break;
    case WM_CLOSE:
      closing_ = true;
      Close();
      break;

    case WM_TABLET_QUERYSYSTEMGESTURESTATUS:
      return TABLET_DISABLE_PRESSANDHOLD |    // disables press and hold
                                              // (right-click) gesture
             TABLET_DISABLE_PENTAPFEEDBACK |  // disables UI feedback on pen up
                                              // (waves)
             TABLET_DISABLE_PENBARRELFEEDBACK |  // disables UI feedback on pen
                                                 // button down (circle)
             TABLET_DISABLE_FLICKS |  // disables pen flicks (back, forward,
                                      // drag down, drag up)
             TABLET_DISABLE_TOUCHSWITCH | TABLET_DISABLE_SMOOTHSCROLLING |
             TABLET_DISABLE_TOUCHUIFORCEON | TABLET_ENABLE_MULTITOUCHDATA;

    case WM_COMMAND:
      switch (LOWORD(wParam)) {
        // TODO(benvanik): dispatch to menu.
      }
      break;
  }

  return Win32Control::WndProc(hWnd, message, wParam, lParam);
}

}  // namespace win32
}  // namespace ui
}  // namespace poly
<commit_msg>Move the window in a bit.<commit_after>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2014 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include <poly/ui/win32/win32_window.h>

#include <dwmapi.h>
#include <tpcshrd.h>
#include <windowsx.h>

#include <poly/logging.h>

namespace poly {
namespace ui {
namespace win32 {

Win32Window::Win32Window(const std::wstring& title)
    : Window(title), main_menu_(nullptr), closing_(false) {}

Win32Window::~Win32Window() {}

bool Win32Window::Initialize() {
  Create();
  return true;
}

bool Win32Window::Create() {
  HINSTANCE hInstance = GetModuleHandle(nullptr);

  WNDCLASSEX wcex;
  wcex.cbSize = sizeof(WNDCLASSEX);
  wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
  wcex.lpfnWndProc = Win32Control::WndProcThunk;
  wcex.cbClsExtra = 0;
  wcex.cbWndExtra = 0;
  wcex.hInstance = hInstance;
  wcex.hIcon = nullptr;    // LoadIcon(hInstance, (LPCTSTR)IDI_TUTORIAL1);
  wcex.hIconSm = nullptr;  // LoadIcon(hInstance, (LPCTSTR)IDI_TUTORIAL1);
  wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
  wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
  wcex.lpszMenuName = nullptr;
  wcex.lpszClassName = L"XeniaWindowClass";
  if (!RegisterClassEx(&wcex)) {
    PLOGE("RegisterClassEx failed");
    return false;
  }

  // Setup initial size.
  DWORD window_style = WS_OVERLAPPEDWINDOW;
  DWORD window_ex_style = WS_EX_APPWINDOW | WS_EX_CONTROLPARENT;
  RECT rc = {0, 0, width_, height_};
  AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);

  // Create window.
  hwnd_ = CreateWindowEx(window_ex_style, L"XeniaWindowClass", L"Xenia",
                         window_style, rc.left, rc.top,
                         rc.right - rc.left, rc.bottom - rc.top, nullptr,
                         nullptr, hInstance, this);
  if (!hwnd_) {
    PLOGE("CreateWindow failed");
    return false;
  }

  main_menu_ = CreateMenu();
  AppendMenu(main_menu_, MF_STRING, 0, L"TODO");
  SetMenu(hwnd_, main_menu_);

  // Disable flicks.
  ATOM atom = GlobalAddAtom(L"MicrosoftTabletPenServiceProperty");
  const DWORD_PTR dwHwndTabletProperty =
      TABLET_DISABLE_PRESSANDHOLD |    // disables press and hold (right-click)
                                       // gesture
      TABLET_DISABLE_PENTAPFEEDBACK |  // disables UI feedback on pen up (waves)
      TABLET_DISABLE_PENBARRELFEEDBACK |  // disables UI feedback on pen button
                                          // down (circle)
      TABLET_DISABLE_FLICKS |  // disables pen flicks (back, forward, drag down,
                               // drag up)
      TABLET_DISABLE_TOUCHSWITCH | TABLET_DISABLE_SMOOTHSCROLLING |
      TABLET_DISABLE_TOUCHUIFORCEON | TABLET_ENABLE_MULTITOUCHDATA;
  SetProp(hwnd_, L"MicrosoftTabletPenServiceProperty",
          reinterpret_cast<HANDLE>(dwHwndTabletProperty));
  GlobalDeleteAtom(atom);

  // Enable DWM elevation.
  EnableMMCSS();

  ShowWindow(hwnd_, SW_SHOWNORMAL);
  UpdateWindow(hwnd_);

  return 0;
}

void Win32Window::EnableMMCSS() {
  HMODULE hLibrary = LoadLibrary(L"DWMAPI.DLL");
  if (!hLibrary) {
    return;
  }

  typedef HRESULT(__stdcall * PDwmEnableMMCSS)(BOOL);
  PDwmEnableMMCSS pDwmEnableMMCSS =
      (PDwmEnableMMCSS)GetProcAddress(hLibrary, "DwmEnableMMCSS");
  if (pDwmEnableMMCSS) {
    pDwmEnableMMCSS(TRUE);
  }

  typedef HRESULT(__stdcall * PDwmSetPresentParameters)(
      HWND, DWM_PRESENT_PARAMETERS*);
  PDwmSetPresentParameters pDwmSetPresentParameters =
      (PDwmSetPresentParameters)GetProcAddress(hLibrary,
                                               "DwmSetPresentParameters");
  if (pDwmSetPresentParameters) {
    DWM_PRESENT_PARAMETERS pp;
    memset(&pp, 0, sizeof(DWM_PRESENT_PARAMETERS));
    pp.cbSize = sizeof(DWM_PRESENT_PARAMETERS);
    pp.fQueue = FALSE;
    pp.cBuffer = 2;
    pp.fUseSourceRate = FALSE;
    pp.cRefreshesPerFrame = 1;
    pp.eSampling = DWM_SOURCE_FRAME_SAMPLING_POINT;
    pDwmSetPresentParameters(hwnd_, &pp);
  }

  FreeLibrary(hLibrary);
}

bool Win32Window::set_title(const std::wstring& title) {
  if (!Window::set_title(title)) {
    return false;
  }
  SetWindowText(hwnd_, title.c_str());
  return true;
}

void Win32Window::Resize(int32_t width, int32_t height) {
  RECT rc = {0, 0, width, height};
  bool has_menu = main_menu_ ? true : false;
  AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, has_menu);
  if (true) {
    rc.right += 100 - rc.left;
    rc.left = 100;
    rc.bottom += 100 - rc.top;
    rc.top = 100;
  }
  Window::Resize(rc.left, rc.top, rc.right, rc.bottom);
}

void Win32Window::Resize(int32_t left, int32_t top, int32_t right,
                         int32_t bottom) {
  RECT rc = {left, top, right, bottom};
  bool has_menu = main_menu_ ? true : false;
  AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, has_menu);
  Window::Resize(rc.left, rc.top, rc.right, rc.bottom);
}

void Win32Window::ResizeToFill(int32_t pad_left, int32_t pad_top,
                               int32_t pad_right, int32_t pad_bottom) {
  // TODO(benvanik): fullscreen.
}

void Win32Window::OnClose() {
  if (!closing_ && hwnd_) {
    closing_ = true;
    CloseWindow(hwnd_);
  }
}

LRESULT Win32Window::WndProc(HWND hWnd, UINT message, WPARAM wParam,
                             LPARAM lParam) {
  switch (message) {
    case WM_ACTIVATEAPP:
      if (wParam) {
        // Made active.
        OnShow();
      } else {
        // Made inactive.
        OnHide();
      }
      break;
    case WM_CLOSE:
      closing_ = true;
      Close();
      break;

    case WM_TABLET_QUERYSYSTEMGESTURESTATUS:
      return TABLET_DISABLE_PRESSANDHOLD |    // disables press and hold
                                              // (right-click) gesture
             TABLET_DISABLE_PENTAPFEEDBACK |  // disables UI feedback on pen up
                                              // (waves)
             TABLET_DISABLE_PENBARRELFEEDBACK |  // disables UI feedback on pen
                                                 // button down (circle)
             TABLET_DISABLE_FLICKS |  // disables pen flicks (back, forward,
                                      // drag down, drag up)
             TABLET_DISABLE_TOUCHSWITCH | TABLET_DISABLE_SMOOTHSCROLLING |
             TABLET_DISABLE_TOUCHUIFORCEON | TABLET_ENABLE_MULTITOUCHDATA;

    case WM_COMMAND:
      switch (LOWORD(wParam)) {
        // TODO(benvanik): dispatch to menu.
      }
      break;
  }

  return Win32Control::WndProc(hWnd, message, wParam, lParam);
}

}  // namespace win32
}  // namespace ui
}  // namespace poly
<|endoftext|>


<commit_before>#include "pomerol/FieldOperatorPart.h"

using std::stringstream;

namespace Pomerol{

FieldOperatorPart::FieldOperatorPart(
        const IndexClassification &IndexInfo, const StatesClassification &S, const HamiltonianPart &HFrom,  const HamiltonianPart &HTo, ParticleIndex PIndex) :
        ComputableObject(), IndexInfo(IndexInfo), S(S), HFrom(HFrom), HTo(HTo), PIndex(PIndex),
        MatrixElementTolerance(1e-8)
{}

void FieldOperatorPart::compute()
{
    if ( Status >= Computed ) return;
    BlockNumber to = HTo.getBlockNumber();
    BlockNumber from = HFrom.getBlockNumber();

    const std::vector<FockState>& toStates = S.getFockStates(to);
    const std::vector<FockState>& fromStates = S.getFockStates(from);

    MatrixType RightMat(fromStates.size(), fromStates.size());
    MatrixType LeftMat(toStates.size(), fromStates.size());
    RightMat.setZero();
    LeftMat.setZero();

    /* Rotation is done in the following way:
     * C_{nm} = \sum_{lk} U^{+}_{nl} C_{lk} U_{km} = \sum_{lk} U^{*}_{ln}O_{lk}U_{km},
     * where the actual sum starts from k state. Big letters denote global states, smaller - InnerQuantumStates.
     * We use the fact each column of O_{lk} has only one nonzero elements.
     * */
    for (std::vector<FockState>::const_iterator CurrentState = fromStates.begin();
                                                CurrentState < fromStates.end(); CurrentState++) {
	    FockState K=*CurrentState;
        std::map<FockState, MelemType> result1 = O->actRight(K);
        if (result1.size()) {
            FockState L=result1.begin()->first;
            #ifdef POMEROL_COMPLEX_MATRIX_ELEMENTS
            int sign = int(std::real(result1.begin()->second));
            #else
            int sign = result1.begin()->second;
            #endif
	        if ( L!=ERROR_FOCK_STATE && std::abs(sign)>std::numeric_limits<RealType>::epsilon() ) {
		        InnerQuantumState l=S.getInnerState(L), k=S.getInnerState(K);

                for (InnerQuantumState n=0; n<toStates.size(); n++) {
#ifdef POMEROL_COMPLEX_MATRIX_ELEMENTS
                    LeftMat(n,k) = std::conj(HTo.getMatrixElement(l,n));
#else
                    LeftMat(n,k) = HTo.getMatrixElement(l,n);
#endif
                }

                for (InnerQuantumState m=0; m<fromStates.size(); m++) {
                    RightMat(k,m) = RealType(sign) * HFrom.getMatrixElement(k,m);
                }
	        }
        }
    }

    elementsRowMajor = (LeftMat * RightMat).sparseView(MatrixElementTolerance);
    #ifndef POMEROL_COMPLEX_MATRIX_ELEMENTS
    elementsRowMajor.prune(MatrixElementTolerance);
    #endif
    elementsColMajor = elementsRowMajor;
    Status = Computed;
}

const ColMajorMatrixType& FieldOperatorPart::getColMajorValue(void) const
{
    return elementsColMajor;
}

const RowMajorMatrixType& FieldOperatorPart::getRowMajorValue(void) const
{
    return elementsRowMajor;
}

void FieldOperatorPart::print_to_screen() const  //print to screen C and CX
{
    BlockNumber to   = HTo.getBlockNumber();
    BlockNumber from = HFrom.getBlockNumber();
    INFO(S.getQuantumNumbers(from) << "->" << S.getQuantumNumbers(to));
    for (size_t P=0; P<elementsColMajor.outerSize(); ++P)
	for (ColMajorMatrixType::InnerIterator it(elementsColMajor,P); it; ++it) {
	    FockState N = S.getFockState(to, it.row());
	    FockState M = S.getFockState(from, it.col());
	    INFO(N <<" " << M << " : " << it.value());
        }
}

BlockNumber FieldOperatorPart::getLeftIndex(void) const
{
    return HTo.getBlockNumber();
}

BlockNumber FieldOperatorPart::getRightIndex(void) const
{
    return HFrom.getBlockNumber();
}

// Specialized methods

AnnihilationOperatorPart::AnnihilationOperatorPart(const IndexClassification &IndexInfo, const StatesClassification &S,
                                                  const HamiltonianPart &HFrom, const HamiltonianPart &HTo, ParticleIndex PIndex) :
    FieldOperatorPart(IndexInfo,S,HFrom,HTo,PIndex)
{
    O = new Pomerol::OperatorPresets::C(PIndex);
}

CreationOperatorPart::CreationOperatorPart(const IndexClassification &IndexInfo, const StatesClassification &S,
                                                  const HamiltonianPart &HFrom, const HamiltonianPart &HTo, ParticleIndex PIndex) :
    FieldOperatorPart(IndexInfo,S,HFrom,HTo,PIndex)
{
    O = new Pomerol::OperatorPresets::Cdag(PIndex);
}

const CreationOperatorPart& AnnihilationOperatorPart::transpose() const
{
    CreationOperatorPart *CX = new CreationOperatorPart(IndexInfo, S, HTo, HFrom, PIndex); // swapped h_to and h_from
    CX->elementsRowMajor = elementsRowMajor.transpose();
    CX->elementsColMajor = elementsColMajor.transpose();
    return *CX;
}

const AnnihilationOperatorPart& CreationOperatorPart::transpose() const
{
    AnnihilationOperatorPart *C = new AnnihilationOperatorPart(IndexInfo, S, HTo, HFrom, PIndex); // swapped h_to and h_from
    C->elementsRowMajor = elementsRowMajor.transpose();
    C->elementsColMajor = elementsColMajor.transpose();
    return *C;
}

QuadraticOperatorPart::QuadraticOperatorPart(const IndexClassification &IndexInfo, const StatesClassification &S,
                                             const HamiltonianPart &HFrom, const HamiltonianPart &HTo,
                                             ParticleIndex PIndex1, ParticleIndex PIndex2) :
        FieldOperatorPart(IndexInfo,S,HFrom,HTo,9999), Index1(PIndex1), Index2(PIndex2)
        // Index=9999 dummy
{
    O = new Pomerol::OperatorPresets::N_offdiag(PIndex1, PIndex2);
}

} // end of namespace Pomerol
<commit_msg>Workaround for Eigen issue 1224<commit_after>#include "pomerol/FieldOperatorPart.h"

using std::stringstream;

namespace Pomerol{

FieldOperatorPart::FieldOperatorPart(
        const IndexClassification &IndexInfo, const StatesClassification &S, const HamiltonianPart &HFrom,  const HamiltonianPart &HTo, ParticleIndex PIndex) :
        ComputableObject(), IndexInfo(IndexInfo), S(S), HFrom(HFrom), HTo(HTo), PIndex(PIndex),
        MatrixElementTolerance(1e-8)
{}

void FieldOperatorPart::compute()
{
    if ( Status >= Computed ) return;
    BlockNumber to = HTo.getBlockNumber();
    BlockNumber from = HFrom.getBlockNumber();

    const std::vector<FockState>& toStates = S.getFockStates(to);
    const std::vector<FockState>& fromStates = S.getFockStates(from);

    MatrixType RightMat(fromStates.size(), fromStates.size());
    MatrixType LeftMat(toStates.size(), fromStates.size());
    RightMat.setZero();
    LeftMat.setZero();

    /* Rotation is done in the following way:
     * C_{nm} = \sum_{lk} U^{+}_{nl} C_{lk} U_{km} = \sum_{lk} U^{*}_{ln}O_{lk}U_{km},
     * where the actual sum starts from k state. Big letters denote global states, smaller - InnerQuantumStates.
     * We use the fact each column of O_{lk} has only one nonzero elements.
     * */
    for (std::vector<FockState>::const_iterator CurrentState = fromStates.begin();
                                                CurrentState < fromStates.end(); CurrentState++) {
	    FockState K=*CurrentState;
        std::map<FockState, MelemType> result1 = O->actRight(K);
        if (result1.size()) {
            FockState L=result1.begin()->first;
            #ifdef POMEROL_COMPLEX_MATRIX_ELEMENTS
            int sign = int(std::real(result1.begin()->second));
            #else
            int sign = result1.begin()->second;
            #endif
	        if ( L!=ERROR_FOCK_STATE && std::abs(sign)>std::numeric_limits<RealType>::epsilon() ) {
		        InnerQuantumState l=S.getInnerState(L), k=S.getInnerState(K);

                for (InnerQuantumState n=0; n<toStates.size(); n++) {
#ifdef POMEROL_COMPLEX_MATRIX_ELEMENTS
                    LeftMat(n,k) = std::conj(HTo.getMatrixElement(l,n));
#else
                    LeftMat(n,k) = HTo.getMatrixElement(l,n);
#endif
                }

                for (InnerQuantumState m=0; m<fromStates.size(); m++) {
                    RightMat(k,m) = RealType(sign) * HFrom.getMatrixElement(k,m);
                }
	        }
        }
    }

// Workaround for Eigen issue 1224
// https://gitlab.com/libeigen/eigen/-/issues/1224
//
// Affected versions are some betas of 3.3 but not the 3.3 release
#if EIGEN_VERSION_AT_LEAST(3,2,90) && EIGEN_MAJOR_VERSION<3
    elementsRowMajor = MatrixType(LeftMat * RightMat).sparseView(MatrixElementTolerance);
#else
    elementsRowMajor = (LeftMat * RightMat).sparseView(MatrixElementTolerance);
#endif

    #ifndef POMEROL_COMPLEX_MATRIX_ELEMENTS
    elementsRowMajor.prune(MatrixElementTolerance);
    #endif
    elementsColMajor = elementsRowMajor;
    Status = Computed;
}

const ColMajorMatrixType& FieldOperatorPart::getColMajorValue(void) const
{
    return elementsColMajor;
}

const RowMajorMatrixType& FieldOperatorPart::getRowMajorValue(void) const
{
    return elementsRowMajor;
}

void FieldOperatorPart::print_to_screen() const  //print to screen C and CX
{
    BlockNumber to   = HTo.getBlockNumber();
    BlockNumber from = HFrom.getBlockNumber();
    INFO(S.getQuantumNumbers(from) << "->" << S.getQuantumNumbers(to));
    for (size_t P=0; P<elementsColMajor.outerSize(); ++P)
	for (ColMajorMatrixType::InnerIterator it(elementsColMajor,P); it; ++it) {
	    FockState N = S.getFockState(to, it.row());
	    FockState M = S.getFockState(from, it.col());
	    INFO(N <<" " << M << " : " << it.value());
        }
}

BlockNumber FieldOperatorPart::getLeftIndex(void) const
{
    return HTo.getBlockNumber();
}

BlockNumber FieldOperatorPart::getRightIndex(void) const
{
    return HFrom.getBlockNumber();
}

// Specialized methods

AnnihilationOperatorPart::AnnihilationOperatorPart(const IndexClassification &IndexInfo, const StatesClassification &S,
                                                  const HamiltonianPart &HFrom, const HamiltonianPart &HTo, ParticleIndex PIndex) :
    FieldOperatorPart(IndexInfo,S,HFrom,HTo,PIndex)
{
    O = new Pomerol::OperatorPresets::C(PIndex);
}

CreationOperatorPart::CreationOperatorPart(const IndexClassification &IndexInfo, const StatesClassification &S,
                                                  const HamiltonianPart &HFrom, const HamiltonianPart &HTo, ParticleIndex PIndex) :
    FieldOperatorPart(IndexInfo,S,HFrom,HTo,PIndex)
{
    O = new Pomerol::OperatorPresets::Cdag(PIndex);
}

const CreationOperatorPart& AnnihilationOperatorPart::transpose() const
{
    CreationOperatorPart *CX = new CreationOperatorPart(IndexInfo, S, HTo, HFrom, PIndex); // swapped h_to and h_from
    CX->elementsRowMajor = elementsRowMajor.transpose();
    CX->elementsColMajor = elementsColMajor.transpose();
    return *CX;
}

const AnnihilationOperatorPart& CreationOperatorPart::transpose() const
{
    AnnihilationOperatorPart *C = new AnnihilationOperatorPart(IndexInfo, S, HTo, HFrom, PIndex); // swapped h_to and h_from
    C->elementsRowMajor = elementsRowMajor.transpose();
    C->elementsColMajor = elementsColMajor.transpose();
    return *C;
}

QuadraticOperatorPart::QuadraticOperatorPart(const IndexClassification &IndexInfo, const StatesClassification &S,
                                             const HamiltonianPart &HFrom, const HamiltonianPart &HTo,
                                             ParticleIndex PIndex1, ParticleIndex PIndex2) :
        FieldOperatorPart(IndexInfo,S,HFrom,HTo,9999), Index1(PIndex1), Index2(PIndex2)
        // Index=9999 dummy
{
    O = new Pomerol::OperatorPresets::N_offdiag(PIndex1, PIndex2);
}

} // end of namespace Pomerol
<|endoftext|>


<commit_before>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "SkScalerContext.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkDescriptor.h"
#include "SkFDot6.h"
#include "SkFontHost.h"
#include "SkMask.h"
#include "SkStream.h"
#include "SkString.h"
#include "SkThread.h"
#include "SkTemplates.h"

#include <acaapi.h>

//////////////////////////////////////////////////////////////////////////

class SkScalerContext_Ascender : public SkScalerContext {
public:
    SkScalerContext_Ascender(const SkDescriptor* desc);
    virtual ~SkScalerContext_Ascender();

protected:
    virtual unsigned generateGlyphCount();
    virtual uint16_t generateCharToGlyph(SkUnichar uni);
    virtual void generateMetrics(SkGlyph* glyph);
    virtual void generateImage(const SkGlyph& glyph);
    virtual void generatePath(const SkGlyph& glyph, SkPath* path);
    virtual void generateFontMetrics(SkPaint::FontMetrics* mx, SkPaint::FontMetrics* my);

private:
    aca_FontHandle  fHandle;
    void*   fWorkspace;
    void*   fGlyphWorkspace;
    SkStream*   fFontStream;
    SkStream*   fHintStream;
};

///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////

SkScalerContext_Ascender::SkScalerContext_Ascender(const SkDescriptor* desc)
    : SkScalerContext(desc)
{
    int size = aca_Get_FontHandleRec_Size();
    fHandle = (aca_FontHandle)sk_malloc_throw(size);

    // get the pointer to the font

    fFontStream = new SkMMAPStream("/UcsGB2312-Hei-H.FDL");
    fHintStream = new SkMMAPStream("/genv6-23.bin");

    void* hints = sk_malloc_throw(fHintStream->getLength());
    memcpy(hints, fHintStream->getMemoryBase(), fHintStream->getLength());

    aca_Create_Font_Handle(fHandle,
                           (void*)fFontStream->getMemoryBase(), fFontStream->getLength(),
                           "fred",
                           hints, fHintStream->getLength());

    // compute our factors from the record

    SkMatrix    m;

    fRec.getSingleMatrix(&m);

    //  now compute our scale factors
    SkScalar    sx = m.getScaleX();
    SkScalar    sy = m.getScaleY();

    int ppemX = SkScalarRound(sx);
    int ppemY = SkScalarRound(sy);

    size = aca_Find_Font_Memory_Required(fHandle, ppemX, ppemY);
    size *= 8;  // Jeff suggests this :)
    fWorkspace = sk_malloc_throw(size);
    aca_Set_Font_Memory(fHandle, (uint8_t*)fWorkspace, size);

    aca_GlyphAttribsRec rec;

    memset(&rec, 0, sizeof(rec));
    rec.xSize = ppemX;
    rec.ySize = ppemY;
    rec.doAdjust = true;
    rec.doExceptions = true;
    rec.doGlyphHints = true;
    rec.doInterpolate = true;
    rec.grayMode = 2;
    aca_Set_Font_Attributes(fHandle, &rec, &size);

    fGlyphWorkspace = sk_malloc_throw(size);
    aca_Set_Glyph_Memory(fHandle, fGlyphWorkspace);
}

SkScalerContext_Ascender::~SkScalerContext_Ascender()
{
    delete fHintStream;
    delete fFontStream;
    sk_free(fGlyphWorkspace);
    sk_free(fWorkspace);
    sk_free(fHandle);
}

unsigned SkScalerContext_Ascender::generateGlyphCount()
{
    return 1000;
}

uint16_t SkScalerContext_Ascender::generateCharToGlyph(SkUnichar uni)
{
    return (uint16_t)(uni & 0xFFFF);
}

void SkScalerContext_Ascender::generateMetrics(SkGlyph* glyph)
{
    glyph->fRsbDelta = 0;
    glyph->fLsbDelta = 0;

    aca_GlyphImageRec   rec;
    aca_Vector          topLeft;

    int adv = aca_Get_Adv_Width(fHandle, glyph->getGlyphID());
    if (aca_GLYPH_NOT_PRESENT == adv)
        goto ERROR;

    aca_Rasterize(glyph->getGlyphID(), fHandle, &rec, &topLeft);

    if (false)  // error
    {
ERROR:
        glyph->fWidth   = 0;
        glyph->fHeight  = 0;
        glyph->fTop     = 0;
        glyph->fLeft    = 0;
        glyph->fAdvanceX = 0;
        glyph->fAdvanceY = 0;
        return;
    }

    glyph->fWidth = rec.width;
    glyph->fHeight = rec.rows;
    glyph->fRowBytes = rec.width;
    glyph->fTop = -topLeft.y;
    glyph->fLeft = topLeft.x;
    glyph->fAdvanceX = SkIntToFixed(adv);
    glyph->fAdvanceY = SkIntToFixed(0);
}

void SkScalerContext_Ascender::generateImage(const SkGlyph& glyph)
{
    aca_GlyphImageRec   rec;
    aca_Vector          topLeft;

    aca_Rasterize(glyph.getGlyphID(), fHandle, &rec, &topLeft);

    const uint8_t* src = (const uint8_t*)rec.buffer;
    uint8_t* dst = (uint8_t*)glyph.fImage;
    int height = glyph.fHeight;

    src += rec.y0 * rec.pitch + rec.x0;
    while (--height >= 0)
    {
        memcpy(dst, src, glyph.fWidth);
        src += rec.pitch;
        dst += glyph.fRowBytes;
    }
}

///////////////////////////////////////////////////////////////////////////////////////////

void SkScalerContext_Ascender::generatePath(const SkGlyph& glyph, SkPath* path)
{
    SkRect r;

    r.set(0, 0, SkIntToScalar(4), SkIntToScalar(4));
    path->reset();
    path->addRect(r);
}

void SkScalerContext_Ascender::generateFontMetrics(SkPaint::FontMetrics* mx, SkPaint::FontMetrics* my)
{
    if (NULL == mx && NULL == my)
        return;

    if (mx)
    {
        mx->fTop = SkIntToScalar(-16);
        mx->fAscent = SkIntToScalar(-16);
        mx->fDescent = SkIntToScalar(4);
        mx->fBottom = SkIntToScalar(4);
        mx->fLeading = 0;

        // FIXME:
        mx->fAvgCharWidth = 0;
        mx->fXMin = 0;
        mx->fXMax = 0;
        mx->fXHeight = 0;
    }
    if (my)
    {
        my->fTop = SkIntToScalar(-16);
        my->fAscent = SkIntToScalar(-16);
        my->fDescent = SkIntToScalar(4);
        my->fBottom = SkIntToScalar(4);
        my->fLeading = 0;

        // FIXME:
        my->fAvgCharWidth = 0;
        my->fXMin = 0;
        my->fXMax = 0;
        my->fXHeight = 0;
    }
}

////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////

SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc)
{
    return SkNEW_ARGS(SkScalerContext_Ascender, (desc));
}
<commit_msg>remove obsolete/unsupported font backend<commit_after><|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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 "itkHeldIsotropicWavelet.h"
#include "itkTestingMacros.h"

#include <string>

int
itkHeldIsotropicWaveletTest( int, char *[] )
{
  bool testPassed = true;

  typedef double Double;
  typedef float  Float;

  const unsigned int D3 = 3;
  const unsigned int D2 = 2;
  const unsigned int D1 = 1;

  typedef itk::HeldIsotropicWavelet< > Default;
  Default::New();

  typedef itk::Point< itk::SpacePrecisionType, D3 > Point3D;
  typedef itk::Point< itk::SpacePrecisionType, D2 > Point2D;
  typedef itk::Point< itk::SpacePrecisionType, D1 > Point1D;

  typedef itk::HeldIsotropicWavelet< Double, D3, Point3D > Wavelet3D;
  typedef itk::HeldIsotropicWavelet< Double, D2, Point2D > Wavelet2D;
  typedef itk::HeldIsotropicWavelet< Double, D1, Point1D > Wavelet1D;
  Wavelet3D::New();
  Wavelet2D::New();
  Wavelet1D::New();

  typedef itk::HeldIsotropicWavelet< Float, D3, Point3D > Wavelet3DFloat;
  typedef itk::HeldIsotropicWavelet< Float, D2, Point2D > Wavelet2DFloat;
  typedef itk::HeldIsotropicWavelet< Float, D1, Point1D > Wavelet1DFloat;
  Wavelet3DFloat::New();
  Wavelet2DFloat::New();
  Wavelet1DFloat::New();

  Wavelet2DFloat::Pointer wavelet2Dfloat = Wavelet2DFloat::New();
  Point2D point2D;
  point2D[0] = 0.2;
  point2D[1] = 0.2;
  double freq2D = wavelet2Dfloat->Magnitude(point2D);
  std::cout << "freq2D: " << freq2D << std::endl;
  // Check that inherits from IsotropicFrequencyFunction
  unsigned int defaultBands = wavelet2Dfloat->GetHighPassSubBands();
  if ( defaultBands != 1 )
    {
    testPassed = false;
    }

  // Specific methods for this type:
  unsigned int maxPolynomialOrder = 5;
  for ( unsigned int p = 0; p < maxPolynomialOrder + 1; ++p )
    {
    wavelet2Dfloat->SetPolynomialOrder(p);
    TEST_SET_GET_VALUE(p, wavelet2Dfloat->GetPolynomialOrder());
    Wavelet2DFloat::FunctionValueType value = wavelet2Dfloat->EvaluateMagnitude(freq2D);
    std::cout << "Order: " << p << " ; Evaluate: " << value << std::endl;
    }

  if ( testPassed )
    {
    return EXIT_SUCCESS;
    }
  else
    {
    return EXIT_FAILURE;
    }
}
<commit_msg>ENH: Increase itk::HeldIsotropicWavelet coverage.<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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 "itkHeldIsotropicWavelet.h"
#include "itkTestingMacros.h"

#include <string>

int
itkHeldIsotropicWaveletTest( int, char *[] )
{
  bool testPassed = true;

  typedef double Double;
  typedef float  Float;

  const unsigned int D3 = 3;
  const unsigned int D2 = 2;
  const unsigned int D1 = 1;

  typedef itk::HeldIsotropicWavelet< > Default;
  Default::New();

  typedef itk::Point< itk::SpacePrecisionType, D3 > Point3D;
  typedef itk::Point< itk::SpacePrecisionType, D2 > Point2D;
  typedef itk::Point< itk::SpacePrecisionType, D1 > Point1D;

  typedef itk::HeldIsotropicWavelet< Double, D3, Point3D > Wavelet3D;
  typedef itk::HeldIsotropicWavelet< Double, D2, Point2D > Wavelet2D;
  typedef itk::HeldIsotropicWavelet< Double, D1, Point1D > Wavelet1D;
  Wavelet3D::New();
  Wavelet2D::New();
  Wavelet1D::New();

  typedef itk::HeldIsotropicWavelet< Float, D3, Point3D > Wavelet3DFloat;
  typedef itk::HeldIsotropicWavelet< Float, D2, Point2D > Wavelet2DFloat;
  typedef itk::HeldIsotropicWavelet< Float, D1, Point1D > Wavelet1DFloat;
  Wavelet3DFloat::New();
  Wavelet2DFloat::New();
  Wavelet1DFloat::New();

  Wavelet2DFloat::Pointer wavelet2Dfloat = Wavelet2DFloat::New();

  EXERCISE_BASIC_OBJECT_METHODS( wavelet2Dfloat, HeldIsotropicWavelet,
    IsotropicWaveletFrequencyFunction );

  Point2D point2D;
  point2D[0] = 0.2;
  point2D[1] = 0.2;
  double freq2D = wavelet2Dfloat->Magnitude(point2D);
  std::cout << "freq2D: " << freq2D << std::endl;
  // Check that inherits from IsotropicFrequencyFunction
  unsigned int defaultBands = wavelet2Dfloat->GetHighPassSubBands();
  if ( defaultBands != 1 )
    {
    testPassed = false;
    }

  // Specific methods for this type:
  unsigned int maxPolynomialOrder = 5;
  for ( unsigned int p = 0; p < maxPolynomialOrder + 1; ++p )
    {
    wavelet2Dfloat->SetPolynomialOrder(p);
    TEST_SET_GET_VALUE(p, wavelet2Dfloat->GetPolynomialOrder());
    Wavelet2DFloat::FunctionValueType value = wavelet2Dfloat->EvaluateMagnitude(freq2D);
    std::cout << "Order: " << p << " ; Evaluate: " << value << std::endl;
    }

  // Test exception cases
  unsigned int polynomialOrder = 6;
  wavelet2Dfloat->SetPolynomialOrder( polynomialOrder );
  TEST_SET_GET_VALUE(polynomialOrder, wavelet2Dfloat->GetPolynomialOrder());

  TRY_EXPECT_EXCEPTION( wavelet2Dfloat->EvaluateMagnitude(freq2D) );

  if ( testPassed )
    {
    return EXIT_SUCCESS;
    }
  else
    {
    return EXIT_FAILURE;
    }
}
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2015 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Testing/ModuleTestBase/ModuleTestBase.h>
#include <Modules/Factory/HardCodedModuleFactory.h>
#include <Dataflow/Engine/Controller/NetworkEditorController.h>
#include <Dataflow/Network/ConnectionId.h>
#include <Core/Python/PythonInterpreter.h>
#include <Modules/Legacy/Fields/CreateLatVol.h>
#include <Dataflow/State/SimpleMapModuleState.h>
#include <Dataflow/Engine/Scheduler/DesktopExecutionStrategyFactory.h>

using namespace SCIRun;
using namespace Core;
using namespace Testing;
using namespace Modules::Factory;
using namespace Modules::Fields;
using namespace Dataflow::Networks;
using namespace Dataflow::Engine;
using namespace ReplacementImpl;
using namespace Dataflow::Engine;
using namespace Dataflow::State;
using namespace Algorithms;

class PythonControllerFunctionalTests : public ModuleTest
{
public:
  PythonControllerFunctionalTests()
  {
    PythonInterpreter::Instance().initialize(false);
    PythonInterpreter::Instance().run_string("import SCIRunPythonAPI; from SCIRunPythonAPI import *");
  }
};

TEST_F(PythonControllerFunctionalTests, CanAddModule)
{
  ModuleFactoryHandle mf(new HardCodedModuleFactory);
  NetworkEditorController controller(mf, nullptr, nullptr, nullptr, nullptr);
  initModuleParameters(false);

  ASSERT_EQ(0, controller.getNetwork()->nmodules());

  std::string command = "addModule(\"CreateLatVol\")";
  PythonInterpreter::Instance().run_string(command);
  //TODO: expose API directly on NEC?
  //controller.runPython("addModule(\"CreateLatVol\")");

  ASSERT_EQ(1, controller.getNetwork()->nmodules());
}

TEST_F(PythonControllerFunctionalTests, CanAddMultipleModule)
{
  ModuleFactoryHandle mf(new HardCodedModuleFactory);
  NetworkEditorController controller(mf, nullptr, nullptr, nullptr, nullptr);
  initModuleParameters(false);

  ASSERT_EQ(0, controller.getNetwork()->nmodules());

  std::string command = "addModule(\"CreateLatVol\")";
  PythonInterpreter::Instance().run_string(command);
  PythonInterpreter::Instance().run_string(command);

  ASSERT_EQ(2, controller.getNetwork()->nmodules());
}

TEST_F(PythonControllerFunctionalTests, CanChangeModuleState)
{
  ModuleFactoryHandle mf(new HardCodedModuleFactory);
  ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory);
  NetworkEditorController controller(mf, sf, nullptr, nullptr, nullptr);
  initModuleParameters(false);

  ASSERT_EQ(0, controller.getNetwork()->nmodules());

  std::string command = "m = addModule(\"CreateLatVol\")";
  PythonInterpreter::Instance().run_string(command);

  ASSERT_EQ(1, controller.getNetwork()->nmodules());
  auto mod = controller.getNetwork()->module(0);
  ASSERT_TRUE(mod != nullptr);
  EXPECT_EQ(16, mod->get_state()->getValue(CreateLatVol::XSize).toInt());
  command = "m.XSize = 14";
  PythonInterpreter::Instance().run_string(command);
  EXPECT_EQ(14, mod->get_state()->getValue(CreateLatVol::XSize).toInt());
}

TEST_F(PythonControllerFunctionalTests, CanConnectModules)
{
  ModuleFactoryHandle mf(new HardCodedModuleFactory);
  NetworkEditorController controller(mf, nullptr, nullptr, nullptr, nullptr);
  initModuleParameters(false);

  ASSERT_EQ(0, controller.getNetwork()->nmodules());

  PythonInterpreter::Instance().run_string("m1 = addModule(\"CreateLatVol\")");
  PythonInterpreter::Instance().run_string("m2 = addModule(\"CreateLatVol\")");

  ASSERT_EQ(2, controller.getNetwork()->nmodules());

  ASSERT_EQ(0, controller.getNetwork()->nconnections());

  PythonInterpreter::Instance().run_string("m1.output[0] >> m2.input[0]");
  ASSERT_EQ(1, controller.getNetwork()->nconnections());
}

//TODO: this test is unstable
TEST_F(PythonControllerFunctionalTests, DISABLED_CanExecuteNetwork)
{
  ModuleFactoryHandle mf(new HardCodedModuleFactory);
  ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory);
  ExecutionStrategyFactoryHandle exe(new DesktopExecutionStrategyFactory(boost::none));
  NetworkEditorController controller(mf, sf, exe, nullptr, nullptr);
  initModuleParameters(false);

  PythonInterpreter::Instance().run_string("m1 = addModule(\"CreateLatVol\")");
  ASSERT_TRUE(controller.getNetwork()->module(0)->executionState().currentState() == ModuleExecutionState::NotExecuted);
  PythonInterpreter::Instance().run_string("m2 = addModule(\"CreateLatVol\")");
  PythonInterpreter::Instance().run_string("m1.output[0] >> m2.input[0]");
  PythonInterpreter::Instance().run_string("executeAll()");
 // boost::this_thread::sleep(boost::posix_time::milliseconds(500));
  ASSERT_TRUE(controller.getNetwork()->module(0)->executionState().currentState() == ModuleExecutionState::Completed);
  //TODO: how do i assert on
}<commit_msg>Mac compile problem (python/boost name collision)<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2015 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Testing/ModuleTestBase/ModuleTestBase.h>
#include <Modules/Factory/HardCodedModuleFactory.h>
#include <Dataflow/Engine/Controller/NetworkEditorController.h>
#include <Dataflow/Network/ConnectionId.h>
#include <Modules/Legacy/Fields/CreateLatVol.h>
#include <Dataflow/State/SimpleMapModuleState.h>
#include <Dataflow/Engine/Scheduler/DesktopExecutionStrategyFactory.h>
#include <Core/Python/PythonInterpreter.h>

using namespace SCIRun;
using namespace Core;
using namespace Testing;
using namespace Modules::Factory;
using namespace Modules::Fields;
using namespace Dataflow::Networks;
using namespace Dataflow::Engine;
using namespace ReplacementImpl;
using namespace Dataflow::Engine;
using namespace Dataflow::State;
using namespace Algorithms;

class PythonControllerFunctionalTests : public ModuleTest
{
public:
  PythonControllerFunctionalTests()
  {
    PythonInterpreter::Instance().initialize(false);
    PythonInterpreter::Instance().run_string("import SCIRunPythonAPI; from SCIRunPythonAPI import *");
  }
};

TEST_F(PythonControllerFunctionalTests, CanAddModule)
{
  ModuleFactoryHandle mf(new HardCodedModuleFactory);
  NetworkEditorController controller(mf, nullptr, nullptr, nullptr, nullptr);
  initModuleParameters(false);

  ASSERT_EQ(0, controller.getNetwork()->nmodules());

  std::string command = "addModule(\"CreateLatVol\")";
  PythonInterpreter::Instance().run_string(command);
  //TODO: expose API directly on NEC?
  //controller.runPython("addModule(\"CreateLatVol\")");

  ASSERT_EQ(1, controller.getNetwork()->nmodules());
}

TEST_F(PythonControllerFunctionalTests, CanAddMultipleModule)
{
  ModuleFactoryHandle mf(new HardCodedModuleFactory);
  NetworkEditorController controller(mf, nullptr, nullptr, nullptr, nullptr);
  initModuleParameters(false);

  ASSERT_EQ(0, controller.getNetwork()->nmodules());

  std::string command = "addModule(\"CreateLatVol\")";
  PythonInterpreter::Instance().run_string(command);
  PythonInterpreter::Instance().run_string(command);

  ASSERT_EQ(2, controller.getNetwork()->nmodules());
}

TEST_F(PythonControllerFunctionalTests, CanChangeModuleState)
{
  ModuleFactoryHandle mf(new HardCodedModuleFactory);
  ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory);
  NetworkEditorController controller(mf, sf, nullptr, nullptr, nullptr);
  initModuleParameters(false);

  ASSERT_EQ(0, controller.getNetwork()->nmodules());

  std::string command = "m = addModule(\"CreateLatVol\")";
  PythonInterpreter::Instance().run_string(command);

  ASSERT_EQ(1, controller.getNetwork()->nmodules());
  auto mod = controller.getNetwork()->module(0);
  ASSERT_TRUE(mod != nullptr);
  EXPECT_EQ(16, mod->get_state()->getValue(CreateLatVol::XSize).toInt());
  command = "m.XSize = 14";
  PythonInterpreter::Instance().run_string(command);
  EXPECT_EQ(14, mod->get_state()->getValue(CreateLatVol::XSize).toInt());
}

TEST_F(PythonControllerFunctionalTests, CanConnectModules)
{
  ModuleFactoryHandle mf(new HardCodedModuleFactory);
  NetworkEditorController controller(mf, nullptr, nullptr, nullptr, nullptr);
  initModuleParameters(false);

  ASSERT_EQ(0, controller.getNetwork()->nmodules());

  PythonInterpreter::Instance().run_string("m1 = addModule(\"CreateLatVol\")");
  PythonInterpreter::Instance().run_string("m2 = addModule(\"CreateLatVol\")");

  ASSERT_EQ(2, controller.getNetwork()->nmodules());

  ASSERT_EQ(0, controller.getNetwork()->nconnections());

  PythonInterpreter::Instance().run_string("m1.output[0] >> m2.input[0]");
  ASSERT_EQ(1, controller.getNetwork()->nconnections());
}

//TODO: this test is unstable
TEST_F(PythonControllerFunctionalTests, DISABLED_CanExecuteNetwork)
{
  ModuleFactoryHandle mf(new HardCodedModuleFactory);
  ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory);
  ExecutionStrategyFactoryHandle exe(new DesktopExecutionStrategyFactory(boost::none));
  NetworkEditorController controller(mf, sf, exe, nullptr, nullptr);
  initModuleParameters(false);

  PythonInterpreter::Instance().run_string("m1 = addModule(\"CreateLatVol\")");
  ASSERT_TRUE(controller.getNetwork()->module(0)->executionState().currentState() == ModuleExecutionState::NotExecuted);
  PythonInterpreter::Instance().run_string("m2 = addModule(\"CreateLatVol\")");
  PythonInterpreter::Instance().run_string("m1.output[0] >> m2.input[0]");
  PythonInterpreter::Instance().run_string("executeAll()");
 // boost::this_thread::sleep(boost::posix_time::milliseconds(500));
  ASSERT_TRUE(controller.getNetwork()->module(0)->executionState().currentState() == ModuleExecutionState::Completed);
  //TODO: how do i assert on
}
<|endoftext|>


<commit_before>// @(#)root/win32:$Name$:$Id$
// Author: Valery Fine   18/03/96

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TVirtualMenuItem                                                     //
//                                                                      //
// This class defines the menu items.                                   //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TVirtualMenuItem.h"

#include "TWin32Menu.h"
#include "TCollection.h"

// ClassImp(TVirtualMenuItem)

//______________________________________________________________________________
TVirtualMenuItem::TVirtualMenuItem() {
    fItem.fItemID = -1;
    fMenuItem.wID = -1;
}

//______________________________________________________________________________
TVirtualMenuItem::TVirtualMenuItem(EMenuItemType custom){

//*-* special item to draw separators and break lines
      fMenuItem.cbSize = sizeof(MENUITEMINFO);

      fMenuItem.fType  = custom;
      fMenuItem.fState = MFS_ENABLED;
      fMenuItem.wID = 0;
      fMenuItem.hbmpChecked   = NULL;
      fMenuItem.hbmpUnchecked = NULL;

      fMenuItem.dwTypeData = (char *)GetTitle();
      if (fMenuItem.dwTypeData) fMenuItem.cch   = strlen(fMenuItem.dwTypeData);

      fMenuItem.hSubMenu = NULL;

      fType         = custom;
      fItem.fItemID = 0;
      fCanvasCB     = NULL;
      fBrowserCB    = NULL;

}
//______________________________________________________________________________
TVirtualMenuItem::TVirtualMenuItem(char *name, const char *label, UINT type, UINT state, Int_t id) : TNamed(name,label)
{
//*-*   Keep the type of the current Item:
//*-*    MF_STRING
//*-*    MF_BITMAP
//*-*    MF_OWNERDRAW
//*-*    MF_POPUP
   fType         = type;
   if (fType == kSubMenu)
       fMenuItem.fType = kString;
   else
       fMenuItem.fType = type;

//*-*   Keep the state of the current Item:
//*-*    MF_GRAYED
//*-*    MF_DISABLEd
//*-*    MF_ENABLED
//*-*    MF_CHECKED
//*-*    MF_UNCHECKED
   fMenuItem.cbSize = sizeof(MENUITEMINFO);
   fMenuItem.fState = state;
   fMenuItem.hbmpChecked   = NULL;
   fMenuItem.hbmpUnchecked = NULL;

   fMenuItem.dwTypeData = (char *)GetTitle();
   if (fMenuItem.dwTypeData) fMenuItem.cch   = strlen(fMenuItem.dwTypeData);

   fCanvasCB     = NULL;
   fBrowserCB    = NULL;

   fMenuItem.hSubMenu = NULL;

   if (type == kSubMenu) {
     fItem.fItemHandle = new TWin32Menu(name,label,kPopUpMenu);  // create SubMenu as the current item
     fMenuItem.hSubMenu = fItem.fItemHandle->GetMenuHandle();
   }
   else {
      fItem.fItemID       = id;
      fMenuItem.wID       = id;
   }
}

//______________________________________________________________________________
TVirtualMenuItem::TVirtualMenuItem(char *name, const char *label, Win32CanvasCB callback, UINT type, UINT state, Int_t id) : TNamed(name,label)
{
//*-*   Keep the type of the current Item:
//*-*    MF_STRING     = 0x0000L  !!!  be carefull  !!!
//*-*    MF_BITMAP     = 0x0004L
//*-*    MF_OWNERDRAW  = 0x0100L
//*-*    MF_POPUP      = 0x0010L
   fMenuItem.cbSize = sizeof(MENUITEMINFO);
   fType           = type;
   fMenuItem.fType = type;

//*-*   Keep the state of the current Item:
//*-*    MF_GRAYED     = 0x0001L
//*-*    MF_DISABLED   = 0x0002L
//*-*    MF_ENABLED    = 0x0000L  !!!  be carefull  !!!
//*-*    MF_CHECKED    = 0x0008L
//*-*    MF_UNCHECKED  = 0x0000L  !!!  be carefull  !!!

   fMenuItem.fState = state;

   fMenuItem.hbmpChecked   = NULL;
   fMenuItem.hbmpUnchecked = NULL;

   fMenuItem.dwTypeData = (char *)GetTitle();
   if (fMenuItem.dwTypeData) fMenuItem.cch   = strlen(fMenuItem.dwTypeData);

   fItem.fItemID       = id;
   fMenuItem.wID       = id;

   fMenuItem.hSubMenu = NULL;

   fCanvasCB = callback;
   fBrowserCB     = NULL;
}

//______________________________________________________________________________
TVirtualMenuItem::TVirtualMenuItem(char *name, const char *label, Win32BrowserImpCB callback, UINT type, UINT state, Int_t id) : TNamed(name,label)
{
//*-*   Keep the type of the current Item:
//*-*    MF_STRING     = 0x0000L  !!!  be carefull  !!!
//*-*    MF_BITMAP     = 0x0004L
//*-*    MF_OWNERDRAW  = 0x0100L
//*-*    MF_POPUP      = 0x0010L
    fMenuItem.cbSize = sizeof(MENUITEMINFO);

    fType         = type;
    fMenuItem.fType = type;

//*-*   Keep the state of the current Item:
//*-*    MF_GRAYED     = 0x0001L
//*-*    MF_DISABLED   = 0x0002L
//*-*    MF_ENABLED    = 0x0000L  !!!  be carefull  !!!
//*-*    MF_CHECKED    = 0x0008L
//*-*    MF_UNCHECKED  = 0x0000L  !!!  be carefull  !!!
   fMenuItem.fState = state;

   fMenuItem.hbmpChecked   = NULL;
   fMenuItem.hbmpUnchecked = NULL;

   fMenuItem.dwTypeData = (char *)GetTitle();
   if (fMenuItem.dwTypeData) fMenuItem.cch   = strlen(fMenuItem.dwTypeData);

   fItem.fItemID       = id;
   fMenuItem.wID       = id;

   fCanvasCB  = NULL;
   fBrowserCB = callback;
}

//______________________________________________________________________________
TVirtualMenuItem::~TVirtualMenuItem()
{

//*-* Remove this item from all menus and Command lists

   TIter next(&fMenuList);
   {
    TWin32Menu *menu;
    while (menu = (TWin32Menu *)next() )
       menu->DeleteTheItem(this);
   }

   if (fType ==  kSubMenu && fItem.fItemHandle) { //Delete PopUp Item
       delete fItem.fItemHandle;
       fItem.fItemHandle = 0;
       fMenuItem.hSubMenu = NULL;
   }
//*-*  We don't check here whether this item has been removed from the command list !!!
}

//______________________________________________________________________________
void TVirtualMenuItem::Checked(){
//*-*  Places a check mark next to the menu item
    fMenuItem.fState = fMenuItem.fState & ~(MFS_UNCHECKED) |  MFS_CHECKED ;
    SetItemStatus(kMenuChecked);
}

//______________________________________________________________________________
const char *TVirtualMenuItem::ClassName()
{
   return "TVirtualMenuItem";
}
//______________________________________________________________________________
void TVirtualMenuItem::Disable(){
//*-*   Disables the menu item so that it cannot be selected, but does not gray it.
    fMenuItem.fState = fMenuItem.fState & ~(MFS_ENABLED | MFS_GRAYED) |  MFS_DISABLED ;
    SetItemStatus(kMenuEnabled);
}
//______________________________________________________________________________
void TVirtualMenuItem::Enable(){
//*-*  Enables the menu item so that it can be selected
//*-*  and restores it from its grayed state.
    fMenuItem.fState = fMenuItem.fState & ~(MFS_DISABLED | MFS_GRAYED) | MFS_ENABLED;
    SetItemStatus(kMenuEnabled);
}

//______________________________________________________________________________
UINT TVirtualMenuItem::GetCommandId(){
    if (fMenuItem.hSubMenu)
      return (UINT) (fItem.fItemHandle->GetMenuHandle());
    else
      return fMenuItem.wID; // idfItem.fItemID;
}

//______________________________________________________________________________
TWin32Menu *TVirtualMenuItem::GetPopUpItem(){
    if (fMenuItem.hSubMenu)
        return fItem.fItemHandle;
    else
        return 0;
}
//______________________________________________________________________________
void TVirtualMenuItem::Join(TWin32Menu *menu)
{
    // Register the menu where this item is inserted in
    if(menu) {
        fMenuList.Add   ((TObject *)menu);
        fMenuItem.fMask = MIIM_DATA | MIIM_STATE | MIIM_TYPE | MIIM_SUBMENU | MIIM_ID ;
        if (InsertMenuItem(menu->GetMenuHandle(),99999,TRUE,&fMenuItem)==FALSE)
            printf(" Insert Menu Item Error: %d \n", GetLastError());
    }
}
//______________________________________________________________________________
void TVirtualMenuItem::ModifyTitle(char const *title){
    SetTitle(title);
    fMenuItem.dwTypeData = (char *)GetTitle();
    if (fMenuItem.dwTypeData)
        fMenuItem.cch   = 4;
//        fMenuItem.cch   = strlen(fMenuItem.dwTypeData);
    SetItemStatus(kMenuModified);
}

//______________________________________________________________________________
void TVirtualMenuItem::Grayed(){
//*-*  Disables the menu item and grays it so it cannot be selected.
   fMenuItem.fState = fMenuItem.fState & ~(MFS_DISABLED | MFS_ENABLED) | MFS_GRAYED;
   SetItemStatus(kMenuEnabled);
}

//______________________________________________________________________________
void TVirtualMenuItem::Remove()
{
   // I have no idea how this should work, other than to unmanage the widget
}

//______________________________________________________________________________
void TVirtualMenuItem::Remove(TWin32Menu *menu) {

  if (fMenuList.FindObject((TObject *)menu)) {
       menu->DeleteTheItem(this);
       fMenuList.Remove((TObject *)menu);
  }
}

//______________________________________________________________________________
UINT TVirtualMenuItem::SetCommandId(UINT id){
//*-*  Check whether the Command ID for this item was assigned
//*-*  If this is for the first time just assign the new value
//*-*  return the ID for this Item

// Check type of item.
// It is possible to set Id for the simple item only

//    cout << "TVirtualMenuItem::SetCommandId(" << id << ")" << endl;
    if (!fMenuItem.hSubMenu)
    {
        if (fItem.fItemID == -1)
        {
            fItem.fItemID = id;
            fMenuItem.wID = id;
        }
        else
            Error("TWin32MenuItem", "Impossible to set the Item ID twice");
    }

    return GetCommandId();
}

//______________________________________________________________________________
void TVirtualMenuItem::SetItemStatus(EMenuModified state){
//   if (fItem.fItemID == -1) Error("TWin23Menu", "There is no ID for the present item");
   if (fMenuItem.wID == -1) Error("TWin23Menu", "There is no ID for the present item");

   TIter next(&fMenuList);
   TWin32Menu *menu;

//*- change the appearance of this item in the all menu where this is presented in

  while (menu = (TWin32Menu *) next())
  {
      HMENU hMenu = menu->GetMenuHandle();
      fMenuItem.fMask = MIIM_STATE;
      if (state == kMenuModified) fMenuItem.fMask= MIIM_TYPE ;
      SetMenuItemInfo(hMenu,fMenuItem.wID,FALSE,&fMenuItem);
  }
}

//______________________________________________________________________________
void TVirtualMenuItem::SetLabel(const char *str){
}

//______________________________________________________________________________
void TVirtualMenuItem::SetPosition(int position, TWin32Menu *menu)
{
  if (!fMenuList.FindObject(menu)) fMenuList.Add((TObject *)menu);
#ifndef WIN32
  menu->InsertItemAtPosition(this,position);
#endif
}

//______________________________________________________________________________
void TVirtualMenuItem::UnChecked(){
//*-*  Does not place a check mark next to the menu item (default)
    fMenuItem.fState = fMenuItem.fState & ~(MFS_CHECKED) |  MFS_UNCHECKED ;
    SetItemStatus(kMenuChecked);
}
<commit_msg>initialize fMenuItem.hSubMenu in ctor.<commit_after>// @(#)root/win32:$Name:  $:$Id: TVirtualMenuItem.cxx,v 1.1.1.1 2000/05/16 17:00:46 rdm Exp $
// Author: Valery Fine   18/03/96

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TVirtualMenuItem                                                     //
//                                                                      //
// This class defines the menu items.                                   //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TVirtualMenuItem.h"

#include "TWin32Menu.h"
#include "TCollection.h"

// ClassImp(TVirtualMenuItem)

//______________________________________________________________________________
TVirtualMenuItem::TVirtualMenuItem() {
    fItem.fItemID = -1;
    fMenuItem.wID = -1;
}

//______________________________________________________________________________
TVirtualMenuItem::TVirtualMenuItem(EMenuItemType custom){

//*-* special item to draw separators and break lines
      fMenuItem.cbSize = sizeof(MENUITEMINFO);

      fMenuItem.fType  = custom;
      fMenuItem.fState = MFS_ENABLED;
      fMenuItem.wID = 0;
      fMenuItem.hbmpChecked   = NULL;
      fMenuItem.hbmpUnchecked = NULL;

      fMenuItem.dwTypeData = (char *)GetTitle();
      if (fMenuItem.dwTypeData) fMenuItem.cch   = strlen(fMenuItem.dwTypeData);

      fMenuItem.hSubMenu = NULL;

      fType         = custom;
      fItem.fItemID = 0;
      fCanvasCB     = NULL;
      fBrowserCB    = NULL;

}
//______________________________________________________________________________
TVirtualMenuItem::TVirtualMenuItem(char *name, const char *label, UINT type, UINT state, Int_t id) : TNamed(name,label)
{
//*-*   Keep the type of the current Item:
//*-*    MF_STRING
//*-*    MF_BITMAP
//*-*    MF_OWNERDRAW
//*-*    MF_POPUP
   fType         = type;
   if (fType == kSubMenu)
       fMenuItem.fType = kString;
   else
       fMenuItem.fType = type;

//*-*   Keep the state of the current Item:
//*-*    MF_GRAYED
//*-*    MF_DISABLEd
//*-*    MF_ENABLED
//*-*    MF_CHECKED
//*-*    MF_UNCHECKED
   fMenuItem.cbSize = sizeof(MENUITEMINFO);
   fMenuItem.fState = state;
   fMenuItem.hbmpChecked   = NULL;
   fMenuItem.hbmpUnchecked = NULL;

   fMenuItem.dwTypeData = (char *)GetTitle();
   if (fMenuItem.dwTypeData) fMenuItem.cch   = strlen(fMenuItem.dwTypeData);

   fCanvasCB     = NULL;
   fBrowserCB    = NULL;

   fMenuItem.hSubMenu = NULL;

   if (type == kSubMenu) {
     fItem.fItemHandle = new TWin32Menu(name,label,kPopUpMenu);  // create SubMenu as the current item
     fMenuItem.hSubMenu = fItem.fItemHandle->GetMenuHandle();
   }
   else {
      fItem.fItemID       = id;
      fMenuItem.wID       = id;
   }
}

//______________________________________________________________________________
TVirtualMenuItem::TVirtualMenuItem(char *name, const char *label, Win32CanvasCB callback, UINT type, UINT state, Int_t id) : TNamed(name,label)
{
//*-*   Keep the type of the current Item:
//*-*    MF_STRING     = 0x0000L  !!!  be carefull  !!!
//*-*    MF_BITMAP     = 0x0004L
//*-*    MF_OWNERDRAW  = 0x0100L
//*-*    MF_POPUP      = 0x0010L
   fMenuItem.cbSize = sizeof(MENUITEMINFO);
   fType           = type;
   fMenuItem.fType = type;

//*-*   Keep the state of the current Item:
//*-*    MF_GRAYED     = 0x0001L
//*-*    MF_DISABLED   = 0x0002L
//*-*    MF_ENABLED    = 0x0000L  !!!  be carefull  !!!
//*-*    MF_CHECKED    = 0x0008L
//*-*    MF_UNCHECKED  = 0x0000L  !!!  be carefull  !!!

   fMenuItem.fState = state;

   fMenuItem.hbmpChecked   = NULL;
   fMenuItem.hbmpUnchecked = NULL;

   fMenuItem.dwTypeData = (char *)GetTitle();
   if (fMenuItem.dwTypeData) fMenuItem.cch   = strlen(fMenuItem.dwTypeData);

   fItem.fItemID       = id;
   fMenuItem.wID       = id;

   fMenuItem.hSubMenu = NULL;

   fCanvasCB = callback;
   fBrowserCB     = NULL;
}

//______________________________________________________________________________
TVirtualMenuItem::TVirtualMenuItem(char *name, const char *label, Win32BrowserImpCB callback, UINT type, UINT state, Int_t id) : TNamed(name,label)
{
//*-*   Keep the type of the current Item:
//*-*    MF_STRING     = 0x0000L  !!!  be carefull  !!!
//*-*    MF_BITMAP     = 0x0004L
//*-*    MF_OWNERDRAW  = 0x0100L
//*-*    MF_POPUP      = 0x0010L
    fMenuItem.cbSize = sizeof(MENUITEMINFO);

    fType         = type;
    fMenuItem.fType = type;

//*-*   Keep the state of the current Item:
//*-*    MF_GRAYED     = 0x0001L
//*-*    MF_DISABLED   = 0x0002L
//*-*    MF_ENABLED    = 0x0000L  !!!  be carefull  !!!
//*-*    MF_CHECKED    = 0x0008L
//*-*    MF_UNCHECKED  = 0x0000L  !!!  be carefull  !!!
   fMenuItem.fState = state;

   fMenuItem.hbmpChecked   = NULL;
   fMenuItem.hbmpUnchecked = NULL;

   fMenuItem.dwTypeData = (char *)GetTitle();
   if (fMenuItem.dwTypeData) fMenuItem.cch   = strlen(fMenuItem.dwTypeData);

   fItem.fItemID       = id;
   fMenuItem.wID       = id;

   fMenuItem.hSubMenu = NULL;

   fCanvasCB  = NULL;
   fBrowserCB = callback;
}

//______________________________________________________________________________
TVirtualMenuItem::~TVirtualMenuItem()
{

//*-* Remove this item from all menus and Command lists

   TIter next(&fMenuList);
   {
    TWin32Menu *menu;
    while (menu = (TWin32Menu *)next() )
       menu->DeleteTheItem(this);
   }

   if (fType ==  kSubMenu && fItem.fItemHandle) { //Delete PopUp Item
       delete fItem.fItemHandle;
       fItem.fItemHandle = 0;
       fMenuItem.hSubMenu = NULL;
   }
//*-*  We don't check here whether this item has been removed from the command list !!!
}

//______________________________________________________________________________
void TVirtualMenuItem::Checked(){
//*-*  Places a check mark next to the menu item
    fMenuItem.fState = fMenuItem.fState & ~(MFS_UNCHECKED) |  MFS_CHECKED ;
    SetItemStatus(kMenuChecked);
}

//______________________________________________________________________________
const char *TVirtualMenuItem::ClassName()
{
   return "TVirtualMenuItem";
}
//______________________________________________________________________________
void TVirtualMenuItem::Disable(){
//*-*   Disables the menu item so that it cannot be selected, but does not gray it.
    fMenuItem.fState = fMenuItem.fState & ~(MFS_ENABLED | MFS_GRAYED) |  MFS_DISABLED ;
    SetItemStatus(kMenuEnabled);
}
//______________________________________________________________________________
void TVirtualMenuItem::Enable(){
//*-*  Enables the menu item so that it can be selected
//*-*  and restores it from its grayed state.
    fMenuItem.fState = fMenuItem.fState & ~(MFS_DISABLED | MFS_GRAYED) | MFS_ENABLED;
    SetItemStatus(kMenuEnabled);
}

//______________________________________________________________________________
UINT TVirtualMenuItem::GetCommandId(){
    if (fMenuItem.hSubMenu)
      return (UINT) (fItem.fItemHandle->GetMenuHandle());
    else
      return fMenuItem.wID; // idfItem.fItemID;
}

//______________________________________________________________________________
TWin32Menu *TVirtualMenuItem::GetPopUpItem(){
    if (fMenuItem.hSubMenu)
        return fItem.fItemHandle;
    else
        return 0;
}
//______________________________________________________________________________
void TVirtualMenuItem::Join(TWin32Menu *menu)
{
    // Register the menu where this item is inserted in
    if(menu) {
        fMenuList.Add   ((TObject *)menu);
        fMenuItem.fMask = MIIM_DATA | MIIM_STATE | MIIM_TYPE | MIIM_SUBMENU | MIIM_ID ;
        if (InsertMenuItem(menu->GetMenuHandle(),99999,TRUE,&fMenuItem)==FALSE)
            printf(" Insert Menu Item Error: %d \n", GetLastError());
    }
}
//______________________________________________________________________________
void TVirtualMenuItem::ModifyTitle(char const *title){
    SetTitle(title);
    fMenuItem.dwTypeData = (char *)GetTitle();
    if (fMenuItem.dwTypeData)
        fMenuItem.cch   = 4;
//        fMenuItem.cch   = strlen(fMenuItem.dwTypeData);
    SetItemStatus(kMenuModified);
}

//______________________________________________________________________________
void TVirtualMenuItem::Grayed(){
//*-*  Disables the menu item and grays it so it cannot be selected.
   fMenuItem.fState = fMenuItem.fState & ~(MFS_DISABLED | MFS_ENABLED) | MFS_GRAYED;
   SetItemStatus(kMenuEnabled);
}

//______________________________________________________________________________
void TVirtualMenuItem::Remove()
{
   // I have no idea how this should work, other than to unmanage the widget
}

//______________________________________________________________________________
void TVirtualMenuItem::Remove(TWin32Menu *menu) {

  if (fMenuList.FindObject((TObject *)menu)) {
       menu->DeleteTheItem(this);
       fMenuList.Remove((TObject *)menu);
  }
}

//______________________________________________________________________________
UINT TVirtualMenuItem::SetCommandId(UINT id){
//*-*  Check whether the Command ID for this item was assigned
//*-*  If this is for the first time just assign the new value
//*-*  return the ID for this Item

// Check type of item.
// It is possible to set Id for the simple item only

//    cout << "TVirtualMenuItem::SetCommandId(" << id << ")" << endl;
    if (!fMenuItem.hSubMenu)
    {
        if (fItem.fItemID == -1)
        {
            fItem.fItemID = id;
            fMenuItem.wID = id;
        }
        else
            Error("TWin32MenuItem", "Impossible to set the Item ID twice");
    }

    return GetCommandId();
}

//______________________________________________________________________________
void TVirtualMenuItem::SetItemStatus(EMenuModified state){
//   if (fItem.fItemID == -1) Error("TWin23Menu", "There is no ID for the present item");
   if (fMenuItem.wID == -1) Error("TWin23Menu", "There is no ID for the present item");

   TIter next(&fMenuList);
   TWin32Menu *menu;

//*- change the appearance of this item in the all menu where this is presented in

  while (menu = (TWin32Menu *) next())
  {
      HMENU hMenu = menu->GetMenuHandle();
      fMenuItem.fMask = MIIM_STATE;
      if (state == kMenuModified) fMenuItem.fMask= MIIM_TYPE ;
      SetMenuItemInfo(hMenu,fMenuItem.wID,FALSE,&fMenuItem);
  }
}

//______________________________________________________________________________
void TVirtualMenuItem::SetLabel(const char *str){
}

//______________________________________________________________________________
void TVirtualMenuItem::SetPosition(int position, TWin32Menu *menu)
{
  if (!fMenuList.FindObject(menu)) fMenuList.Add((TObject *)menu);
#ifndef WIN32
  menu->InsertItemAtPosition(this,position);
#endif
}

//______________________________________________________________________________
void TVirtualMenuItem::UnChecked(){
//*-*  Does not place a check mark next to the menu item (default)
    fMenuItem.fState = fMenuItem.fState & ~(MFS_CHECKED) |  MFS_UNCHECKED ;
    SetItemStatus(kMenuChecked);
}
<|endoftext|>


<commit_before>#include "stdafx.h"

struct Screen
{
    int32_t Width;
    int32_t Height;
    float fWidth;
    float fHeight;
    float fAspectRatio;
    float fHudScale;
    float fHudOffset;
    float fTextOffset;
    float fFMVOffset;
} Screen;

injector::memory_pointer_raw pfShowIntro;

//injector::hook_back<void(__fastcall*)(int _this, int edx, float a2, float a3, float a4, float a5, int a6)> hbDrawDerbyTriangles;
//void __fastcall DrawDerbyTrianglesHook(int _this, int edx, float a2, float a3, float a4, float a5, int a6)
//{
//    return hbDrawDerbyTriangles.fun(_this,edx, a2, a3, a4, a5, a6);
//}

uintptr_t* dword_4B4C72;
uintptr_t* dword_8DA718;
void __declspec(naked) sub_4B4C50()
{
    const static float flt_67DBE4 = 0.0015625f;
    _asm sub     esp, 0x34
    _asm test    eax, eax
    _asm mov     ecx, 0x8DA718
    _asm mov     ecx, [ecx]
    _asm fild    dword ptr [ecx+0x8]
    _asm mov     dword ptr [esp], 0
    _asm fild    dword ptr [ecx+0x0C]
    _asm fstp    dword ptr [esp+0x0C]
    _asm fld     ds:flt_67DBE4
    _asm jmp     dword_4B4C72
}

void __declspec(naked) sub_4B4BF0()
{
    _asm sub     esp, 8
    _asm movzx   eax, byte ptr [ecx+1Ch]
    _asm fld     dword ptr [esp+18h]
    _asm mov     edx, [ecx+4]
    _asm mov     ecx, [ecx+10h]
    _asm lea     edx, [edx+eax*8]
    _asm push    esi
    _asm push    edi
    _asm fmul    dword ptr [edx]
    _asm shl     eax, 4
    _asm lea     esi, [eax+ecx]
    _asm mov     eax, [esp+18h]
    _asm mov     ecx, [esp+14h]
    _asm fstp    dword ptr [esp+8]
    _asm fld     dword ptr [esp+20h]
    _asm lea     edi, [esp+8]
    _asm fmul    dword ptr [edx+4]
    _asm mov     edx, [esp+1Ch]
    _asm push    edx
    _asm push    eax
    _asm mov     eax, [esp+2Ch]
    _asm fstp    dword ptr [esp+14h]
    _asm lea     edx, [esi+8]
    _asm push    ecx
    _asm call    sub_4B4C50
    _asm pop     edi
    _asm pop     esi
    _asm add     esp, 8
    _asm retn    14h
}

void ShowIntroHook()
{
    CIniReader iniReader("");
    bool bSkipIntro = iniReader.ReadInteger("MAIN", "SkipIntro", 1) != 0;
    float fIniFOVFactor = iniReader.ReadFloat("MAIN", "FOVFactor", 1.0f);

    auto ptr = *hook::pattern("C7 05 ? ? ? ? 00 04 00 00 C7 05 ? ? ? ? 00 03 00 00 C7 05 ? ? ? ? 10 00 00 00").get_first<int32_t*>(2);
    Screen.Width = *ptr;
    Screen.Height = *(ptr + 1);

    Screen.fWidth = static_cast<float>(Screen.Width);
    Screen.fHeight = static_cast<float>(Screen.Height);
    Screen.fAspectRatio = Screen.fWidth / Screen.fHeight;
    Screen.fHudScale = 1.0f / (480.0f * Screen.fAspectRatio);
    Screen.fHudOffset = ((480.0f * Screen.fAspectRatio) - 640.0f) / 2.0f;

    //Aspect Ratio
    auto pattern = hook::pattern("D9 05 ? ? ? ? 8B 44 24 04 8B 4C 24");
    if (!pattern.empty())
    {
        injector::WriteMemory(pattern.get_first<float>(2), &Screen.fWidth, true);
        injector::WriteMemory(pattern.get_first<float>(18), &Screen.fHeight, true);
    }
    else
    {
        pattern = hook::pattern("8B 44 24 04 8B 4C 24 08 C7 00 00 00 80");
        if (!pattern.empty())
        {
            injector::WriteMemory<float>(pattern.get_first<float>(10 + 0), Screen.fWidth, true);
            injector::WriteMemory<float>(pattern.get_first<float>(10 + 6), Screen.fHeight, true);
            injector::WriteMemory<float>(pattern.get_first<float>(23 + 10 + 0), Screen.fWidth, true);
            injector::WriteMemory<float>(pattern.get_first<float>(23 + 10 + 6), Screen.fHeight, true);
        }
    }

    //Hud Scale
    pattern = hook::pattern("D9 05 ? ? ? ? 56 8B F1 8B 86"); //53BBF3
    injector::WriteMemory(pattern.get_first(2), &Screen.fHudOffset, true);
    pattern = hook::pattern("50 D8 0D ? ? ? ? D9 5C 24 20 DB 47 0C"); //4783C5
    //injector::WriteMemory<float>(*pattern.get_first<float*>(3), Screen.fHudScale, true);
    auto pf0015625 = *pattern.get_first<float*>(3);

    pattern = hook::pattern(pattern_str(0xD8, 0x0D, to_bytes(pf0015625)));
    for (size_t i = 0; i < pattern.size(); ++i) //http://pastebin.com/hrmrmkNq
    {
        if (i != 14 && i != 15 && i != 16 && i != 18 && i != 39 && i != 40 && i != 44 && i != 45 && i != 47 && i != 48)
        {
            injector::WriteMemory(pattern.get(i).get<uint32_t>(2), &Screen.fHudScale, true);
        }
    }

    pattern = hook::pattern(pattern_str(0xD9, 0x05, to_bytes(pf0015625)));
    injector::WriteMemory(pattern.count(2).get(0).get<uint32_t>(2), &Screen.fHudScale, true); // 0x00460217
    injector::WriteMemory(pattern.count(2).get(1).get<uint32_t>(2), &Screen.fHudScale, true); // 0x004B4C6C derby triangles etc

    pattern = hook::pattern("D8 C9 D9 44 24 0C D8 0D ? ? ? ? 75");
    dword_4B4C72 = pattern.get_first<uintptr_t>(0);
    pattern = hook::pattern("8B 0D ? ? ? ? 89 16 8B 01 6A 20");
    dword_8DA718 = *pattern.get_first<uintptr_t*>(2);

    pattern = hook::pattern("E8 ? ? ? ? EB 04 DD D8 DD D8"); // 0x4C0AE8
    injector::MakeCALL(pattern.get_first(0), sub_4B4BF0, true); //derby triangle restoration
    pattern = hook::pattern("E8 ? ? ? ? D9 44 24 24 0F B6 4E"); // 0x4BB548
    injector::MakeCALL(pattern.get_first(0), sub_4B4BF0, true);//text backround stripe (top right corner)

    //pattern = hook::pattern(""); //
    //struct CenterStuff
    //{
    //    void operator()(injector::reg_pack& regs)
    //    {
    //        if (*(float*)(regs.esp + 0x44) <= 640.0f)
    //            *(float*)(regs.esp + 0x44) += Screen.fHudOffset;
    //        regs.esi = regs.ecx;
    //        regs.eax = *(uint32_t*)(regs.esi + 0x60);
    //    }
    //}; injector::MakeInline<CenterStuff>(0x54F056);

    //FOV
    float fDynamicScreenFieldOfViewScale = 2.0f * RADIAN_TO_DEGREE(atan(tan(DEGREE_TO_RADIAN(SCREEN_FOV_VERTICAL * 0.5f)) * Screen.fAspectRatio)) * (1.0f / SCREEN_FOV_HORIZONTAL);
    static float fFOVFactor = fDynamicScreenFieldOfViewScale * 0.017453292f * fIniFOVFactor;
    auto pfSetFOV = hook::pattern("D8 0D ? ? ? ? 55 8B EF 2B DD C1 FB 02 8D 68 01 3B EB").get_first(2);
    injector::WriteMemory(pfSetFOV, &fFOVFactor, true);

    if (!bSkipIntro)
    {
        auto ShowIntro = pfShowIntro.as_int() + 6;
        _asm sub esp, 0x104
        _asm jmp ShowIntro
    }
}

DWORD WINAPI Init(LPVOID bDelay)
{
    auto pattern = hook::pattern("81 EC 04 01 00 00 8B 15");

    if (pattern.count_hint(1).empty() && !bDelay)
    {
        CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&Init, (LPVOID)true, 0, NULL);
        return 0;
    }

    if (bDelay)
        while (pattern.clear().count_hint(1).empty()) { Sleep(0); };

    pfShowIntro = pattern.get_first(0);
    injector::MakeJMP(pfShowIntro, ShowIntroHook, true);
    injector::MakeNOP(hook::get_pattern("6A 00 6A 00 E8 ? ? ? ? 83 C4 08 B8 01 00 00 00 5B", -7), 2, true);

    return 0;
}

BOOL APIENTRY DllMain(HMODULE /*hModule*/, DWORD reason, LPVOID /*lpReserved*/)
{
    if (reason == DLL_PROCESS_ATTACH)
    {
        Init(NULL);
    }
    return TRUE;
}
<commit_msg>fo2 update<commit_after>#include "stdafx.h"

struct Screen
{
    int32_t Width;
    int32_t Height;
    float fWidth;
    float fHeight;
    float fAspectRatio;
    float fHudScale;
    float fHudOffset;
    float fTextOffset;
    float fFMVOffset;
} Screen;

injector::memory_pointer_raw pfShowIntro;

//injector::hook_back<void(__fastcall*)(int _this, int edx, float a2, float a3, float a4, float a5, int a6)> hbDrawDerbyTriangles;
//void __fastcall DrawDerbyTrianglesHook(int _this, int edx, float a2, float a3, float a4, float a5, int a6)
//{
//    return hbDrawDerbyTriangles.fun(_this,edx, a2, a3, a4, a5, a6);
//}

uintptr_t* dword_4B4C72;
uintptr_t* dword_8DA718;
void __declspec(naked) sub_4B4C50()
{
    const static float flt_67DBE4 = 0.0015625f;
    _asm sub     esp, 0x34
    _asm test    eax, eax
    _asm mov     ecx, 0x8DA718
    _asm mov     ecx, [ecx]
    _asm fild    dword ptr [ecx+0x8]
    _asm mov     dword ptr [esp], 0
    _asm fild    dword ptr [ecx+0x0C]
    _asm fstp    dword ptr [esp+0x0C]
    _asm fld     ds:flt_67DBE4
    _asm jmp     dword_4B4C72
}

void __declspec(naked) sub_4B4BF0()
{
    _asm sub     esp, 8
    _asm movzx   eax, byte ptr [ecx+1Ch]
    _asm fld     dword ptr [esp+18h]
    _asm mov     edx, [ecx+4]
    _asm mov     ecx, [ecx+10h]
    _asm lea     edx, [edx+eax*8]
    _asm push    esi
    _asm push    edi
    _asm fmul    dword ptr [edx]
    _asm shl     eax, 4
    _asm lea     esi, [eax+ecx]
    _asm mov     eax, [esp+18h]
    _asm mov     ecx, [esp+14h]
    _asm fstp    dword ptr [esp+8]
    _asm fld     dword ptr [esp+20h]
    _asm lea     edi, [esp+8]
    _asm fmul    dword ptr [edx+4]
    _asm mov     edx, [esp+1Ch]
    _asm push    edx
    _asm push    eax
    _asm mov     eax, [esp+2Ch]
    _asm fstp    dword ptr [esp+14h]
    _asm lea     edx, [esi+8]
    _asm push    ecx
    _asm call    sub_4B4C50
    _asm pop     edi
    _asm pop     esi
    _asm add     esp, 8
    _asm retn    14h
}

void ShowIntroHook()
{
    CIniReader iniReader("");
    bool bSkipIntro = iniReader.ReadInteger("MAIN", "SkipIntro", 1) != 0;
    float fIniFOVFactor = iniReader.ReadFloat("MAIN", "FOVFactor", 1.0f);

    auto ptr = *hook::pattern("C7 05 ? ? ? ? 00 04 00 00 C7 05 ? ? ? ? 00 03 00 00 C7 05 ? ? ? ? 10 00 00 00").get_first<int32_t*>(2);
    Screen.Width = *ptr;
    Screen.Height = *(ptr + 1);

    Screen.fWidth = static_cast<float>(Screen.Width);
    Screen.fHeight = static_cast<float>(Screen.Height);
    Screen.fAspectRatio = Screen.fWidth / Screen.fHeight;
    Screen.fHudScale = 1.0f / (480.0f * Screen.fAspectRatio);
    Screen.fHudOffset = ((480.0f * Screen.fAspectRatio) - 640.0f) / 2.0f;

    //Aspect Ratio
    auto pattern = hook::pattern("D9 05 ? ? ? ? 8B 44 24 04 8B 4C 24");
    if (!pattern.empty())
    {
        injector::WriteMemory(pattern.get_first<float>(2), &Screen.fWidth, true);
        injector::WriteMemory(pattern.get_first<float>(18), &Screen.fHeight, true);
    }
    else
    {
        pattern = hook::pattern("8B 44 24 04 8B 4C 24 08 C7 00 00 00 80");
        if (!pattern.empty())
        {
            injector::WriteMemory<float>(pattern.get_first<float>(10 + 0), Screen.fWidth, true);
            injector::WriteMemory<float>(pattern.get_first<float>(10 + 6), Screen.fHeight, true);
            injector::WriteMemory<float>(pattern.get_first<float>(23 + 10 + 0), Screen.fWidth, true);
            injector::WriteMemory<float>(pattern.get_first<float>(23 + 10 + 6), Screen.fHeight, true);
        }
    }

    //Hud Scale
    pattern = hook::pattern("D9 05 ? ? ? ? 56 8B F1 8B 86"); //53BBF3
    injector::WriteMemory(pattern.get_first(2), &Screen.fHudOffset, true);
    pattern = hook::pattern("50 D8 0D ? ? ? ? D9 5C 24 20 DB 47 0C"); //4783C5
    //injector::WriteMemory<float>(*pattern.get_first<float*>(3), Screen.fHudScale, true);
    auto pf0015625 = *pattern.get_first<float*>(3);

    pattern = hook::pattern(pattern_str(0xD8, 0x0D, to_bytes(pf0015625)));
    for (size_t i = 0; i < pattern.size(); ++i) //http://pastebin.com/hrmrmkNq
    {
        if (i != 14 && i != 15 && i != 16 && i != 18 && i != 39 && i != 40 && i != 44 && i != 45 && i != 47 && i != 48)
        {
            injector::WriteMemory(pattern.get(i).get<uint32_t>(2), &Screen.fHudScale, true);
        }
    }

    pattern = hook::pattern(pattern_str(0xD9, 0x05, to_bytes(pf0015625)));
    injector::WriteMemory(pattern.count(2).get(0).get<uint32_t>(2), &Screen.fHudScale, true); // 0x00460217
    injector::WriteMemory(pattern.count(2).get(1).get<uint32_t>(2), &Screen.fHudScale, true); // 0x004B4C6C derby triangles etc

    pattern = hook::pattern("D8 C9 D9 44 24 0C D8 0D ? ? ? ? 75");
    dword_4B4C72 = pattern.get_first<uintptr_t>(0);
    pattern = hook::pattern("8B 0D ? ? ? ? 89 16 8B 01 6A 20");
    dword_8DA718 = *pattern.get_first<uintptr_t*>(2);

    pattern = hook::pattern("E8 ? ? ? ? EB 04 DD D8 DD D8"); // 0x4C0AE8
    injector::MakeCALL(pattern.get_first(0), sub_4B4BF0, true); //derby triangle restoration
    pattern = hook::pattern("E8 ? ? ? ? D9 44 24 24 0F B6 4E"); // 0x4BB548
    injector::MakeCALL(pattern.get_first(0), sub_4B4BF0, true);//text backround stripe (top right corner)

    //pattern = hook::pattern(""); //
    //struct CenterStuff
    //{
    //    void operator()(injector::reg_pack& regs)
    //    {
    //        if (*(float*)(regs.esp + 0x44) <= 640.0f)
    //            *(float*)(regs.esp + 0x44) += Screen.fHudOffset;
    //        regs.esi = regs.ecx;
    //        regs.eax = *(uint32_t*)(regs.esi + 0x60);
    //    }
    //}; injector::MakeInline<CenterStuff>(0x54F056);

    //FOV
    float fDynamicScreenFieldOfViewScale = 2.0f * RADIAN_TO_DEGREE(atan(tan(DEGREE_TO_RADIAN(SCREEN_FOV_VERTICAL * 0.5f)) * Screen.fAspectRatio)) * (1.0f / SCREEN_FOV_HORIZONTAL);
    static float fFOVFactor = fDynamicScreenFieldOfViewScale * 0.017453292f * fIniFOVFactor;
    auto pfSetFOV = hook::pattern("D8 0D ? ? ? ? 55 8B EF 2B DD C1 FB 02 8D 68 01 3B EB").get_first(2);
    injector::WriteMemory(pfSetFOV, &fFOVFactor, true);

    if (!bSkipIntro)
    {
        auto ShowIntro = pfShowIntro.as_int() + 6;
        _asm sub esp, 0x104
        _asm jmp ShowIntro
    }
}

DWORD WINAPI Init(LPVOID bDelay)
{
    auto pattern = hook::pattern("81 EC 04 01 00 00 8B 15");

    if (pattern.count_hint(1).empty() && !bDelay)
    {
        CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&Init, (LPVOID)true, 0, NULL);
        return 0;
    }

    if (bDelay)
        while (pattern.clear().count_hint(1).empty()) { Sleep(0); };

    pfShowIntro = pattern.get_first(0);
    injector::MakeJMP(pfShowIntro, ShowIntroHook, true);

    pattern = hook::pattern("6A 00 6A 00 E8 ? ? ? ? 83 C4 08 B8 01 00 00 00 5B");
    if (!pattern.empty())
        injector::MakeNOP(pattern.get_first(-7), 2, true);

    return 0;
}

BOOL APIENTRY DllMain(HMODULE /*hModule*/, DWORD reason, LPVOID /*lpReserved*/)
{
    if (reason == DLL_PROCESS_ATTACH)
    {
        Init(NULL);
    }
    return TRUE;
}
<|endoftext|>