<commit_before>////////////////////////////////////////////////////////////////////////
//
// Implementation of oscillations of neutrinos in matter in a
// three-neutrino framework with decoherence.
//
// This  class inherits from the PMNS_Fast class
//
// jcoelho@apc.in2p3.fr
////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <cassert>
#include <stdlib.h>

#include "PMNS_Deco.h"

using namespace OscProb;

using namespace std;

//......................................................................
///
/// Constructor. \sa PMNS_Base::PMNS_Base
///
/// This class is restricted to 3 neutrino flavours.
///
PMNS_Deco::PMNS_Deco() : PMNS_Fast(), fGamma(),
fRho(3, row(3,0))
{
  SetStdPath();
  SetGamma(2,0);
  SetGamma(3,0);
  SetGH(true);
}

//......................................................................
///
/// Nothing to clean.
///
PMNS_Deco::~PMNS_Deco(){}

//......................................................................
///
/// Set any given decoherence parameter.
///
/// This will check if value is changing to keep track of whether
/// the eigensystem needs to be recomputed.
///
/// Requires that j > 0. Will notify you if input is wrong.
///
/// @param j   - The second mass index
/// @param val - The absolute value of the parameter
///
void PMNS_Deco::SetGamma(int j, double val){

  if(j < 2 || j > 3){
    cout << "Gamma_" << j << 1 << " not valid for " << fNumNus;
    cout << " neutrinos. Doing nothing." << endl;
    return;
  }

  fGotES *= (fGamma[j-1] == val);

  fGamma[j-1] = val;

}

//......................................................................
///
/// Set the decoherence hierarchy. This will define the relationship:
///
///   \Gamma_{32} = (\sqrt{\Gamma_{31}} \pm \sqrt{\Gamma_{21}})^{2}
///
/// The + (-) sign will be refered to as IH (NH)
///
/// @param isNH - Is the hierarchy normal?
///
void PMNS_Deco::SetGH(bool isNH)
{

  fGamma[0] = isNH ? 1 : -1;

}

//......................................................................
///
/// Get any given decoherence parameter.
///
/// Requires that i > j. Will notify you if input is wrong.
/// If i < j, will assume reverse order and swap i and j.
///
/// @param i  - The first mass index
/// @param j  - The second mass index
///
double PMNS_Deco::GetGamma(int i, int j)
{

  if(i < j){
    cout << "First argument should be larger than second argument" << endl;
    cout << "Setting reverse order (Gamma_" << j << i << "). " << endl;
    int temp = i;
    i = j;
    j = temp;
  }
  if(i<1 || i>3 || i <= j || j < 1){
    cout << "Gamma_" << i << j << " not valid for " << fNumNus;
    cout << " neutrinos. Returning 0." << endl;
    return 0;
  }

  if(j == 1){
    return fGamma[i-1];
  }
  else {
    return pow( sqrt(fGamma[2]) - fGamma[0]*sqrt(fGamma[1]), 2);
  }

}

//.....................................................................
/// Dot product of two matrices.
///
/// @param A - input matrix A
/// @param B - input matrix B
///
/// @return - matrix A.B
///
PMNS_Deco::matrix PMNS_Deco::Dot(matrix A, matrix B)
{

  matrix out(3, row(3,0));

  for(int i=0; i<3; i++){
  for(int j=0; j<3; j++){
  for(int k=0; k<3; k++){

    out[i][j] += A[i][k] * B[k][j];

  }}}

  return out;

}

//.....................................................................
/// Product of elements of two matrices.
///
/// @param A - input matrix A
/// @param B - input matrix B
///
/// @return - matrix A * B
///
PMNS_Deco::matrix PMNS_Deco::Mult(matrix A, matrix B)
{

  matrix out(3, row(3,0));

  for(int i=0; i<3; i++){
  for(int j=0; j<3; j++){

    out[i][j] += A[i][j] * B[i][j];

  }}

  return out;

}

//.....................................................................
/// Conjugate transpose matrix.
///
/// @param A - input matrix A
///
/// @return - A^{\dagger}
///
PMNS_Deco::matrix PMNS_Deco::CTransp(matrix A)
{

  matrix out(3, row(3,0));

  for(int i=0; i<3; i++){
  for(int j=0; j<3; j++){

    out[i][j] += conj(A[j][i]);

  }}

  return out;

}

//.....................................................................
///
/// Propagate the current neutrino state through a given path
/// @param p - A neutrino path segment
///
void PMNS_Deco::PropagatePath(NuPath p)
{

  // Set the neutrino path
  SetCurPath(p);

  // Solve for eigensystem
  SolveHam();

  // Store rotation matrices
  matrix U = fEvec;
  matrix Ut = CTransp(fEvec);

  // Rotate to effective mass basis
  fRho = Dot(Ut, Dot(fRho, U));

  // Compute evolution matrix
  matrix evolve(3, row(3,1));

  // Some ugly way of matching gamma and dmsqr indices
  int maxdm = 0;
  if(fDm[1] > fDm[maxdm]) maxdm = 1;
  if(fDm[2] > fDm[maxdm]) maxdm = 2;

  int mindm = 0;
  if(fDm[1] < fDm[mindm]) mindm = 1;
  if(fDm[2] < fDm[mindm]) mindm = 2;

  int middm = 0;
  if(middm == maxdm || middm == mindm) middm = 1;
  if(middm == maxdm || middm == mindm) middm = 2;

  int maxev = 0;
  if(fEval[1] > fEval[maxev]) maxev = 1;
  if(fEval[2] > fEval[maxev]) maxev = 2;

  int minev = 0;
  if(fEval[1] < fEval[minev]) minev = 1;
  if(fEval[2] < fEval[minev]) minev = 2;

  int midev = 0;
  if(midev == maxev || midev == minev) midev = 1;
  if(midev == maxev || midev == minev) midev = 2;

  int idx[3];
  idx[minev] = mindm;
  idx[midev] = middm;
  idx[maxev] = maxdm;

  for(int j=0; j<3; j++){
  for(int i=0; i<j; i++){
    complex arg = complex(GetGamma(max(idx[i],idx[j])+1,min(idx[i],idx[j])+1) * kGeV2eV, fEval[i] - fEval[j]) * kKm2eV * p.length;
    evolve[i][j] = exp(-arg);
    evolve[j][i] = exp(-conj(arg));
  }}

  //cout << "  " << evolve[0][0] << "  " << evolve[0][1] << "  " << evolve[0][2] << endl;
  //cout << "  " << evolve[1][0] << "  " << evolve[1][1] << "  " << evolve[1][2] << endl;
  //cout << "  " << evolve[2][0] << "  " << evolve[2][1] << "  " << evolve[2][2] << endl;

  // Evolve density matrix
  fRho = Mult(fRho, evolve);

  // Rotate back to flavour basis
  fRho = Dot(U, Dot(fRho, Ut));

}

//......................................................................
///
/// Reset the neutrino state back to a pure flavour where it starts
///
/// Flavours are:
///

///   0 = nue, 1 = numu, 2 = nutau
///   3 = sterile_1, 4 = sterile_2, etc.
///

/// @param flv - The neutrino starting flavour.
///
void PMNS_Deco::ResetToFlavour(int flv)
{
  assert(flv>=0 && flv<fNumNus);
  for (int i=0; i<fNumNus; ++i){
  for (int j=0; j<fNumNus; ++j){
    if (i==flv && i==j) fRho[i][j] = one;
    else                fRho[i][j] = zero;
  }}
}

//......................................................................
///
/// Compute oscillation probability of flavour flv from current state
///
/// Flavours are:
///

///   0 = nue, 1 = numu, 2 = nutau
///   3 = sterile_1, 4 = sterile_2, etc.
///

/// @param flv - The neutrino final flavour.
///
/// @return Neutrino oscillation probability
///
double PMNS_Deco::P(int flv)
{
  assert(flv>=0 && flv<fNumNus);
  return sqrt(norm(fRho[flv][flv]));
}

////////////////////////////////////////////////////////////////////////
<commit_msg>Fix latex formulas<commit_after>////////////////////////////////////////////////////////////////////////
//
// Implementation of oscillations of neutrinos in matter in a
// three-neutrino framework with decoherence.
//
// This  class inherits from the PMNS_Fast class
//
// jcoelho@apc.in2p3.fr
////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <cassert>
#include <stdlib.h>

#include "PMNS_Deco.h"

using namespace OscProb;

using namespace std;

//......................................................................
///
/// Constructor. \sa PMNS_Base::PMNS_Base
///
/// This class is restricted to 3 neutrino flavours.
///
PMNS_Deco::PMNS_Deco() : PMNS_Fast(), fGamma(),
fRho(3, row(3,0))
{
  SetStdPath();
  SetGamma(2,0);
  SetGamma(3,0);
  SetGH(true);
}

//......................................................................
///
/// Nothing to clean.
///
PMNS_Deco::~PMNS_Deco(){}

//......................................................................
///
/// Set any given decoherence parameter.
///
/// This will check if value is changing to keep track of whether
/// the eigensystem needs to be recomputed.
///
/// Requires that j > 0. Will notify you if input is wrong.
///
/// @param j   - The second mass index
/// @param val - The absolute value of the parameter
///
void PMNS_Deco::SetGamma(int j, double val){

  if(j < 2 || j > 3){
    cout << "Gamma_" << j << 1 << " not valid for " << fNumNus;
    cout << " neutrinos. Doing nothing." << endl;
    return;
  }

  fGotES *= (fGamma[j-1] == val);

  fGamma[j-1] = val;

}

//......................................................................
///
/// Set the decoherence hierarchy. This will define the relationship:
///
///   \f$\Gamma_{32} = (\sqrt{\Gamma_{31}} \pm \sqrt{\Gamma_{21}})^{2}\f$
///
/// The + (-) sign will be refered to as IH (NH)
///
/// @param isNH - Is the hierarchy normal?
///
void PMNS_Deco::SetGH(bool isNH)
{

  fGamma[0] = isNH ? 1 : -1;

}

//......................................................................
///
/// Get any given decoherence parameter.
///
/// Requires that i > j. Will notify you if input is wrong.
/// If i < j, will assume reverse order and swap i and j.
///
/// @param i  - The first mass index
/// @param j  - The second mass index
///
double PMNS_Deco::GetGamma(int i, int j)
{

  if(i < j){
    cout << "First argument should be larger than second argument" << endl;
    cout << "Setting reverse order (Gamma_" << j << i << "). " << endl;
    int temp = i;
    i = j;
    j = temp;
  }
  if(i<1 || i>3 || i <= j || j < 1){
    cout << "Gamma_" << i << j << " not valid for " << fNumNus;
    cout << " neutrinos. Returning 0." << endl;
    return 0;
  }

  if(j == 1){
    return fGamma[i-1];
  }
  else {
    return pow( sqrt(fGamma[2]) - fGamma[0]*sqrt(fGamma[1]), 2);
  }

}

//.....................................................................
/// Dot product of two matrices.
///
/// @param A - input matrix A
/// @param B - input matrix B
///
/// @return - matrix A.B
///
PMNS_Deco::matrix PMNS_Deco::Dot(matrix A, matrix B)
{

  matrix out(3, row(3,0));

  for(int i=0; i<3; i++){
  for(int j=0; j<3; j++){
  for(int k=0; k<3; k++){

    out[i][j] += A[i][k] * B[k][j];

  }}}

  return out;

}

//.....................................................................
/// Product of elements of two matrices.
///
/// @param A - input matrix A
/// @param B - input matrix B
///
/// @return - matrix A * B
///
PMNS_Deco::matrix PMNS_Deco::Mult(matrix A, matrix B)
{

  matrix out(3, row(3,0));

  for(int i=0; i<3; i++){
  for(int j=0; j<3; j++){

    out[i][j] += A[i][j] * B[i][j];

  }}

  return out;

}

//.....................................................................
/// Conjugate transpose matrix.
///
/// @param A - input matrix A
///
/// @return - \f$A^{\dagger}\f$
///
PMNS_Deco::matrix PMNS_Deco::CTransp(matrix A)
{

  matrix out(3, row(3,0));

  for(int i=0; i<3; i++){
  for(int j=0; j<3; j++){

    out[i][j] += conj(A[j][i]);

  }}

  return out;

}

//.....................................................................
///
/// Propagate the current neutrino state through a given path
/// @param p - A neutrino path segment
///
void PMNS_Deco::PropagatePath(NuPath p)
{

  // Set the neutrino path
  SetCurPath(p);

  // Solve for eigensystem
  SolveHam();

  // Store rotation matrices
  matrix U = fEvec;
  matrix Ut = CTransp(fEvec);

  // Rotate to effective mass basis
  fRho = Dot(Ut, Dot(fRho, U));

  // Compute evolution matrix
  matrix evolve(3, row(3,1));

  // Some ugly way of matching gamma and dmsqr indices
  int maxdm = 0;
  if(fDm[1] > fDm[maxdm]) maxdm = 1;
  if(fDm[2] > fDm[maxdm]) maxdm = 2;

  int mindm = 0;
  if(fDm[1] < fDm[mindm]) mindm = 1;
  if(fDm[2] < fDm[mindm]) mindm = 2;

  int middm = 0;
  if(middm == maxdm || middm == mindm) middm = 1;
  if(middm == maxdm || middm == mindm) middm = 2;

  int maxev = 0;
  if(fEval[1] > fEval[maxev]) maxev = 1;
  if(fEval[2] > fEval[maxev]) maxev = 2;

  int minev = 0;
  if(fEval[1] < fEval[minev]) minev = 1;
  if(fEval[2] < fEval[minev]) minev = 2;

  int midev = 0;
  if(midev == maxev || midev == minev) midev = 1;
  if(midev == maxev || midev == minev) midev = 2;

  int idx[3];
  idx[minev] = mindm;
  idx[midev] = middm;
  idx[maxev] = maxdm;

  for(int j=0; j<3; j++){
  for(int i=0; i<j; i++){
    complex arg = complex(GetGamma(max(idx[i],idx[j])+1,min(idx[i],idx[j])+1) * kGeV2eV, fEval[i] - fEval[j]) * kKm2eV * p.length;
    evolve[i][j] = exp(-arg);
    evolve[j][i] = exp(-conj(arg));
  }}

  //cout << "  " << evolve[0][0] << "  " << evolve[0][1] << "  " << evolve[0][2] << endl;
  //cout << "  " << evolve[1][0] << "  " << evolve[1][1] << "  " << evolve[1][2] << endl;
  //cout << "  " << evolve[2][0] << "  " << evolve[2][1] << "  " << evolve[2][2] << endl;

  // Evolve density matrix
  fRho = Mult(fRho, evolve);

  // Rotate back to flavour basis
  fRho = Dot(U, Dot(fRho, Ut));

}

//......................................................................
///
/// Reset the neutrino state back to a pure flavour where it starts
///
/// Flavours are:
///

///   0 = nue, 1 = numu, 2 = nutau
///   3 = sterile_1, 4 = sterile_2, etc.
///

/// @param flv - The neutrino starting flavour.
///
void PMNS_Deco::ResetToFlavour(int flv)
{
  assert(flv>=0 && flv<fNumNus);
  for (int i=0; i<fNumNus; ++i){
  for (int j=0; j<fNumNus; ++j){
    if (i==flv && i==j) fRho[i][j] = one;
    else                fRho[i][j] = zero;
  }}
}

//......................................................................
///
/// Compute oscillation probability of flavour flv from current state
///
/// Flavours are:
///

///   0 = nue, 1 = numu, 2 = nutau
///   3 = sterile_1, 4 = sterile_2, etc.
///

/// @param flv - The neutrino final flavour.
///
/// @return Neutrino oscillation probability
///
double PMNS_Deco::P(int flv)
{
  assert(flv>=0 && flv<fNumNus);
  return sqrt(norm(fRho[flv][flv]));
}

////////////////////////////////////////////////////////////////////////
<|endoftext|>


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

#include "stdafx.h"

#include "PasswordSafe.h"
#include "ThisMfcApp.h"
#include "resource.h"
#include "resource3.h"  // String resources
#include "PWHistDlg.h"
#include "corelib/ItemData.h"
#include "corelib/PWSprefs.h"

// CPWHistDlg dialog

IMPLEMENT_DYNAMIC(CPWHistDlg, CDialog)
CPWHistDlg::CPWHistDlg(CWnd* pParent, bool IsReadOnly,
             CMyString &HistStr, PWHistList &PWHistList,
             size_t NumPWHistory, size_t &MaxPWHistory,
             BOOL &SavePWHistory)
: CDialog(CPWHistDlg::IDD, pParent),
  m_IsReadOnly(IsReadOnly),
  m_HistStr(HistStr), m_PWHistList(PWHistList),
  m_NumPWHistory(NumPWHistory), m_MaxPWHistory(MaxPWHistory),
  m_SavePWHistory(SavePWHistory),
  m_ClearPWHistory(false),
  m_iSortedColumn(-1), m_bSortAscending(TRUE)
{
  m_oldMaxPWHistory = m_MaxPWHistory;
}

CPWHistDlg::~CPWHistDlg()
{
}

void CPWHistDlg::DoDataExchange(CDataExchange* pDX)
{
  CDialog::DoDataExchange(pDX);
  DDX_Control(pDX, IDC_PWHISTORY_LIST, m_PWHistListCtrl);
  DDX_Check(pDX, IDC_SAVE_PWHIST, m_SavePWHistory);
  DDX_Text(pDX, IDC_MAXPWHISTORY, m_MaxPWHistory);
  DDV_MinMaxInt(pDX, m_MaxPWHistory, 1, 255);
}

BEGIN_MESSAGE_MAP(CPWHistDlg, CDialog)
ON_BN_CLICKED(IDC_CLEAR_PWHIST, OnBnClickedClearPWHist)
ON_BN_CLICKED(IDC_SAVE_PWHIST, OnCheckedSavePasswordHistory)
ON_NOTIFY(HDN_ITEMCLICKA, 0, OnHeaderClicked)
ON_NOTIFY(HDN_ITEMCLICKW, 0, OnHeaderClicked)
ON_NOTIFY(NM_CLICK, IDC_PWHISTORY_LIST, OnHistListClick)
ON_BN_CLICKED(IDC_PWH_COPY_ALL, OnBnClickedPwhCopyAll)
END_MESSAGE_MAP()

BOOL CPWHistDlg::OnInitDialog()
{
    CDialog::OnInitDialog();

    GetDlgItem(IDC_MAXPWHISTORY)->EnableWindow(m_SavePWHistory ? TRUE : FALSE);

    BOOL bpwh_count = m_PWHistList.empty() ? FALSE : TRUE;
    GetDlgItem(IDC_CLEAR_PWHIST)->EnableWindow(bpwh_count);
    GetDlgItem(IDC_PWHISTORY_LIST)->EnableWindow(bpwh_count);

    if (m_IsReadOnly) {
        GetDlgItem(IDC_MAXPWHISTORY)->EnableWindow(FALSE);
        GetDlgItem(IDC_PWHSPIN)->EnableWindow(FALSE);
        GetDlgItem(IDC_SAVE_PWHIST)->EnableWindow(FALSE);
        GetDlgItem(IDC_CLEAR_PWHIST)->EnableWindow(FALSE);  // overrides count
    }

    m_PWHistListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT);
    CString cs_text;
    cs_text.LoadString(IDS_SETDATETIME);
    m_PWHistListCtrl.InsertColumn(0, cs_text);
    cs_text.LoadString(IDS_PASSWORD);
    m_PWHistListCtrl.InsertColumn(1, cs_text);

    PWHistList::iterator iter;
    DWORD nIdx;
    for (iter = m_PWHistList.begin(), nIdx = 0;
         iter != m_PWHistList.end(); iter++, nIdx++) {
        int nPos;
        const PWHistEntry pwhentry = *iter;
        if (pwhentry.changedate != _T("1970-01-01 00:00:00"))
            nPos = m_PWHistListCtrl.InsertItem(nPos, pwhentry.changedate);
        else {
            cs_text.LoadString(IDS_UNKNOWN);
            cs_text.Trim();
            nPos = m_PWHistListCtrl.InsertItem(nPos, cs_text);
        }
        m_PWHistListCtrl.SetItemText(nPos, 1, pwhentry.password);
        m_PWHistListCtrl.SetItemData(nPos, nIdx);
    }

    m_PWHistListCtrl.SetRedraw(FALSE);
    for (int i = 0; i < 2; i++) {
        m_PWHistListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE);
        int nColumnWidth = m_PWHistListCtrl.GetColumnWidth(i);
        m_PWHistListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE_USEHEADER);
        int nHeaderWidth = m_PWHistListCtrl.GetColumnWidth(i);
        m_PWHistListCtrl.SetColumnWidth(i, max(nColumnWidth, nHeaderWidth));
    }
    m_PWHistListCtrl.SetRedraw(TRUE);

    TCHAR buffer[10];
#if _MSC_VER >= 1400
    _stprintf_s(buffer, 10, _T("%d"), m_NumPWHistory);
#else
    _stprintf(buffer, _T("%d"), m_NumPWHistory);
#endif

    CSpinButtonCtrl* pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_PWHSPIN);

    if (m_MaxPWHistory == 0)
        m_MaxPWHistory = PWSprefs::GetInstance()->
  			GetPref(PWSprefs::NumPWHistoryDefault);

    pspin->SetBuddy(GetDlgItem(IDC_MAXPWHISTORY));
    pspin->SetRange(1, 255);
    pspin->SetBase(10);
    pspin->SetPos(m_MaxPWHistory);

    return TRUE;
}

// CPWHistDlg message handlers
void CPWHistDlg::OnBnClickedClearPWHist()
{
  m_ClearPWHistory = true;
  m_PWHistListCtrl.DeleteAllItems();
}

void
CPWHistDlg::OnOK()
{
  if (UpdateData(TRUE) != TRUE)
	  return;

  /* Handle history header.
   * Header is in the form fmmnn, where:
   * f = {0,1} if password history is on/off
   * mm = 2 digits max size of history list
   * nn = 2 digits current size of history list
   *
   * Special case: history empty and password history off - do nothing
   */

  if (m_ClearPWHistory == TRUE) {
      m_PWHistList.erase(m_PWHistList.begin(), m_PWHistList.end());
      m_HistStr = m_HistStr.Left(5);
  }

  if (!(m_HistStr.IsEmpty() && m_SavePWHistory == FALSE)) {
    TCHAR buffer[6];
#if _MSC_VER >= 1400
    _stprintf_s
#else
      _stprintf
#endif
      (buffer,
#if _MSC_VER >= 1400
       6,
#endif
       _T("%1x%02x%02x"),
       (m_SavePWHistory == FALSE) ? 0 : 1,
       m_MaxPWHistory,
       m_PWHistList.size()
       );
    if (m_HistStr.GetLength() >= 5) {
      for (int i = 0; i < 5; i++) m_HistStr.SetAt(i, buffer[i]);
    } else {
      m_HistStr = buffer;
    }
  }
  CDialog::OnOK();
}

void
CPWHistDlg::OnCheckedSavePasswordHistory()
{
  m_SavePWHistory = ((CButton*)GetDlgItem(IDC_SAVE_PWHIST))->GetCheck();
  GetDlgItem(IDC_MAXPWHISTORY)->EnableWindow(m_SavePWHistory ? TRUE : FALSE);
}

void
CPWHistDlg::OnHistListClick(NMHDR* pNMHDR, LRESULT*)
{
  LPNMITEMACTIVATE lpnmitem = (LPNMITEMACTIVATE) pNMHDR;
  ASSERT(lpnmitem != NULL);
  int item = lpnmitem->iItem;
  if (item == -1)
	  return;
  size_t itempos = size_t(m_PWHistListCtrl.GetItemData(item));
  const PWHistEntry pwhentry = m_PWHistList[itempos];
  app.SetClipboardData(pwhentry.password);
}

void
CPWHistDlg::OnHeaderClicked(NMHDR* pNMHDR, LRESULT* pResult)
{
  HD_NOTIFY *phdn = (HD_NOTIFY *) pNMHDR;

  if(phdn->iButton == 0) {
    // User clicked on header using left mouse button
    if(phdn->iItem == m_iSortedColumn)
      m_bSortAscending = !m_bSortAscending;
    else
      m_bSortAscending = TRUE;

    m_iSortedColumn = phdn->iItem;
    m_PWHistListCtrl.SortItems(PWHistCompareFunc, (LPARAM)this);

    // Note: WINVER defines the minimum system level for which this is program compiled and
    // NOT the level of system it is running on!
    // In this case, these values are defined in Windows XP and later and supported
    // by V6 of comctl32.dll (supplied with Windows XP) and later.
    // They should be ignored by earlier levels of this dll or .....
    //     we can check the dll version (code available on request)!

#if (WINVER < 0x0501)	// These are already defined for WinXP and later
#define HDF_SORTUP 0x0400
#define HDF_SORTDOWN 0x0200
#endif
    HDITEM HeaderItem;
    HeaderItem.mask = HDI_FORMAT;
    m_PWHistListCtrl.GetHeaderCtrl()->GetItem(m_iSortedColumn, &HeaderItem);
    // Turn off all arrows
    HeaderItem.fmt &= ~(HDF_SORTUP | HDF_SORTDOWN);
    // Turn on the correct arrow
    HeaderItem.fmt |= ((m_bSortAscending == TRUE) ? HDF_SORTUP : HDF_SORTDOWN);
    m_PWHistListCtrl.GetHeaderCtrl()->SetItem(m_iSortedColumn, &HeaderItem);
  }

  *pResult = 0;
}

int CALLBACK CPWHistDlg::PWHistCompareFunc(LPARAM lParam1, LPARAM lParam2,
                                     LPARAM closure)
{
  CPWHistDlg *self = (CPWHistDlg*)closure;
  int nSortColumn = self->m_iSortedColumn;
  size_t Lpos = (size_t)lParam1;
  size_t Rpos = (size_t)lParam2;
  const PWHistEntry pLHS = self->m_PWHistList[Lpos];
  const PWHistEntry pRHS = self->m_PWHistList[Rpos];
  CMyString password1, changedate1;
  CMyString password2, changedate2;
  time_t t1, t2;

  int iResult;
  switch(nSortColumn) {
  case 0:
    t1 = pLHS.changetttdate;
    t2 = pRHS.changetttdate;
    iResult = ((long) t1 < (long) t2) ? -1 : 1;
    break;
  case 1:
    password1 = pLHS.password;
    password2 = pRHS.password;
    iResult = ((CString)password1).Compare(password2);
    break;
  default:
    iResult = 0; // should never happen - just keep compiler happy
    ASSERT(FALSE);
  }

  if (!self->m_bSortAscending)
    iResult *= -1;

  return iResult;
}

void CPWHistDlg::OnBnClickedPwhCopyAll()
{
  CMyString HistStr;
  PWHistList::iterator iter;

  for (iter = m_PWHistList.begin(); iter != m_PWHistList.end(); iter++) {
      const PWHistEntry &ent = *iter;
      HistStr += ent.changedate;
      HistStr += _T("\t");
      HistStr += ent.password;
      HistStr += _T("\r\n");
  }
  app.SetClipboardData(HistStr);
}
<commit_msg>murphy.<commit_after>/*
 * Copyright (c) 2003-2007 Rony Shapiro <ronys@users.sourceforge.net>.
 * All rights reserved. Use of the code is allowed under the
 * Artistic License terms, as specified in the LICENSE file
 * distributed with this code, or available from
 * http://www.opensource.org/licenses/artistic-license.php
 */
// PWHistDlg.cpp : implementation file
//

#include "stdafx.h"

#include "PasswordSafe.h"
#include "ThisMfcApp.h"
#include "resource.h"
#include "resource3.h"  // String resources
#include "PWHistDlg.h"
#include "corelib/ItemData.h"
#include "corelib/PWSprefs.h"

// CPWHistDlg dialog

IMPLEMENT_DYNAMIC(CPWHistDlg, CDialog)
CPWHistDlg::CPWHistDlg(CWnd* pParent, bool IsReadOnly,
             CMyString &HistStr, PWHistList &PWHistList,
             size_t NumPWHistory, size_t &MaxPWHistory,
             BOOL &SavePWHistory)
: CDialog(CPWHistDlg::IDD, pParent),
  m_IsReadOnly(IsReadOnly),
  m_HistStr(HistStr), m_PWHistList(PWHistList),
  m_NumPWHistory(NumPWHistory), m_MaxPWHistory(MaxPWHistory),
  m_SavePWHistory(SavePWHistory),
  m_ClearPWHistory(false),
  m_iSortedColumn(-1), m_bSortAscending(TRUE)
{
  m_oldMaxPWHistory = m_MaxPWHistory;
}

CPWHistDlg::~CPWHistDlg()
{
}

void CPWHistDlg::DoDataExchange(CDataExchange* pDX)
{
  CDialog::DoDataExchange(pDX);
  DDX_Control(pDX, IDC_PWHISTORY_LIST, m_PWHistListCtrl);
  DDX_Check(pDX, IDC_SAVE_PWHIST, m_SavePWHistory);
  DDX_Text(pDX, IDC_MAXPWHISTORY, m_MaxPWHistory);
  DDV_MinMaxInt(pDX, m_MaxPWHistory, 1, 255);
}

BEGIN_MESSAGE_MAP(CPWHistDlg, CDialog)
ON_BN_CLICKED(IDC_CLEAR_PWHIST, OnBnClickedClearPWHist)
ON_BN_CLICKED(IDC_SAVE_PWHIST, OnCheckedSavePasswordHistory)
ON_NOTIFY(HDN_ITEMCLICKA, 0, OnHeaderClicked)
ON_NOTIFY(HDN_ITEMCLICKW, 0, OnHeaderClicked)
ON_NOTIFY(NM_CLICK, IDC_PWHISTORY_LIST, OnHistListClick)
ON_BN_CLICKED(IDC_PWH_COPY_ALL, OnBnClickedPwhCopyAll)
END_MESSAGE_MAP()

BOOL CPWHistDlg::OnInitDialog()
{
    CDialog::OnInitDialog();

    GetDlgItem(IDC_MAXPWHISTORY)->EnableWindow(m_SavePWHistory ? TRUE : FALSE);

    BOOL bpwh_count = m_PWHistList.empty() ? FALSE : TRUE;
    GetDlgItem(IDC_CLEAR_PWHIST)->EnableWindow(bpwh_count);
    GetDlgItem(IDC_PWHISTORY_LIST)->EnableWindow(bpwh_count);

    if (m_IsReadOnly) {
        GetDlgItem(IDC_MAXPWHISTORY)->EnableWindow(FALSE);
        GetDlgItem(IDC_PWHSPIN)->EnableWindow(FALSE);
        GetDlgItem(IDC_SAVE_PWHIST)->EnableWindow(FALSE);
        GetDlgItem(IDC_CLEAR_PWHIST)->EnableWindow(FALSE);  // overrides count
    }

    m_PWHistListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT);
    CString cs_text;
    cs_text.LoadString(IDS_SETDATETIME);
    m_PWHistListCtrl.InsertColumn(0, cs_text);
    cs_text.LoadString(IDS_PASSWORD);
    m_PWHistListCtrl.InsertColumn(1, cs_text);

    PWHistList::iterator iter;
    DWORD nIdx;
    for (iter = m_PWHistList.begin(), nIdx = 0;
         iter != m_PWHistList.end(); iter++, nIdx++) {
        int nPos = 0;
        const PWHistEntry pwhentry = *iter;
        if (pwhentry.changedate != _T("1970-01-01 00:00:00"))
            nPos = m_PWHistListCtrl.InsertItem(nPos, pwhentry.changedate);
        else {
            cs_text.LoadString(IDS_UNKNOWN);
            cs_text.Trim();
            nPos = m_PWHistListCtrl.InsertItem(nPos, cs_text);
        }
        m_PWHistListCtrl.SetItemText(nPos, 1, pwhentry.password);
        m_PWHistListCtrl.SetItemData(nPos, nIdx);
    }

    m_PWHistListCtrl.SetRedraw(FALSE);
    for (int i = 0; i < 2; i++) {
        m_PWHistListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE);
        int nColumnWidth = m_PWHistListCtrl.GetColumnWidth(i);
        m_PWHistListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE_USEHEADER);
        int nHeaderWidth = m_PWHistListCtrl.GetColumnWidth(i);
        m_PWHistListCtrl.SetColumnWidth(i, max(nColumnWidth, nHeaderWidth));
    }
    m_PWHistListCtrl.SetRedraw(TRUE);

    TCHAR buffer[10];
#if _MSC_VER >= 1400
    _stprintf_s(buffer, 10, _T("%d"), m_NumPWHistory);
#else
    _stprintf(buffer, _T("%d"), m_NumPWHistory);
#endif

    CSpinButtonCtrl* pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_PWHSPIN);

    if (m_MaxPWHistory == 0)
        m_MaxPWHistory = PWSprefs::GetInstance()->
  			GetPref(PWSprefs::NumPWHistoryDefault);

    pspin->SetBuddy(GetDlgItem(IDC_MAXPWHISTORY));
    pspin->SetRange(1, 255);
    pspin->SetBase(10);
    pspin->SetPos(m_MaxPWHistory);

    return TRUE;
}

// CPWHistDlg message handlers
void CPWHistDlg::OnBnClickedClearPWHist()
{
  m_ClearPWHistory = true;
  m_PWHistListCtrl.DeleteAllItems();
}

void
CPWHistDlg::OnOK()
{
  if (UpdateData(TRUE) != TRUE)
	  return;

  /* Handle history header.
   * Header is in the form fmmnn, where:
   * f = {0,1} if password history is on/off
   * mm = 2 digits max size of history list
   * nn = 2 digits current size of history list
   *
   * Special case: history empty and password history off - do nothing
   */

  if (m_ClearPWHistory == TRUE) {
      m_PWHistList.erase(m_PWHistList.begin(), m_PWHistList.end());
      m_HistStr = m_HistStr.Left(5);
  }

  if (!(m_HistStr.IsEmpty() && m_SavePWHistory == FALSE)) {
    TCHAR buffer[6];
#if _MSC_VER >= 1400
    _stprintf_s
#else
      _stprintf
#endif
      (buffer,
#if _MSC_VER >= 1400
       6,
#endif
       _T("%1x%02x%02x"),
       (m_SavePWHistory == FALSE) ? 0 : 1,
       m_MaxPWHistory,
       m_PWHistList.size()
       );
    if (m_HistStr.GetLength() >= 5) {
      for (int i = 0; i < 5; i++) m_HistStr.SetAt(i, buffer[i]);
    } else {
      m_HistStr = buffer;
    }
  }
  CDialog::OnOK();
}

void
CPWHistDlg::OnCheckedSavePasswordHistory()
{
  m_SavePWHistory = ((CButton*)GetDlgItem(IDC_SAVE_PWHIST))->GetCheck();
  GetDlgItem(IDC_MAXPWHISTORY)->EnableWindow(m_SavePWHistory ? TRUE : FALSE);
}

void
CPWHistDlg::OnHistListClick(NMHDR* pNMHDR, LRESULT*)
{
  LPNMITEMACTIVATE lpnmitem = (LPNMITEMACTIVATE) pNMHDR;
  ASSERT(lpnmitem != NULL);
  int item = lpnmitem->iItem;
  if (item == -1)
	  return;
  size_t itempos = size_t(m_PWHistListCtrl.GetItemData(item));
  const PWHistEntry pwhentry = m_PWHistList[itempos];
  app.SetClipboardData(pwhentry.password);
}

void
CPWHistDlg::OnHeaderClicked(NMHDR* pNMHDR, LRESULT* pResult)
{
  HD_NOTIFY *phdn = (HD_NOTIFY *) pNMHDR;

  if(phdn->iButton == 0) {
    // User clicked on header using left mouse button
    if(phdn->iItem == m_iSortedColumn)
      m_bSortAscending = !m_bSortAscending;
    else
      m_bSortAscending = TRUE;

    m_iSortedColumn = phdn->iItem;
    m_PWHistListCtrl.SortItems(PWHistCompareFunc, (LPARAM)this);

    // Note: WINVER defines the minimum system level for which this is program compiled and
    // NOT the level of system it is running on!
    // In this case, these values are defined in Windows XP and later and supported
    // by V6 of comctl32.dll (supplied with Windows XP) and later.
    // They should be ignored by earlier levels of this dll or .....
    //     we can check the dll version (code available on request)!

#if (WINVER < 0x0501)	// These are already defined for WinXP and later
#define HDF_SORTUP 0x0400
#define HDF_SORTDOWN 0x0200
#endif
    HDITEM HeaderItem;
    HeaderItem.mask = HDI_FORMAT;
    m_PWHistListCtrl.GetHeaderCtrl()->GetItem(m_iSortedColumn, &HeaderItem);
    // Turn off all arrows
    HeaderItem.fmt &= ~(HDF_SORTUP | HDF_SORTDOWN);
    // Turn on the correct arrow
    HeaderItem.fmt |= ((m_bSortAscending == TRUE) ? HDF_SORTUP : HDF_SORTDOWN);
    m_PWHistListCtrl.GetHeaderCtrl()->SetItem(m_iSortedColumn, &HeaderItem);
  }

  *pResult = 0;
}

int CALLBACK CPWHistDlg::PWHistCompareFunc(LPARAM lParam1, LPARAM lParam2,
                                     LPARAM closure)
{
  CPWHistDlg *self = (CPWHistDlg*)closure;
  int nSortColumn = self->m_iSortedColumn;
  size_t Lpos = (size_t)lParam1;
  size_t Rpos = (size_t)lParam2;
  const PWHistEntry pLHS = self->m_PWHistList[Lpos];
  const PWHistEntry pRHS = self->m_PWHistList[Rpos];
  CMyString password1, changedate1;
  CMyString password2, changedate2;
  time_t t1, t2;

  int iResult;
  switch(nSortColumn) {
  case 0:
    t1 = pLHS.changetttdate;
    t2 = pRHS.changetttdate;
    iResult = ((long) t1 < (long) t2) ? -1 : 1;
    break;
  case 1:
    password1 = pLHS.password;
    password2 = pRHS.password;
    iResult = ((CString)password1).Compare(password2);
    break;
  default:
    iResult = 0; // should never happen - just keep compiler happy
    ASSERT(FALSE);
  }

  if (!self->m_bSortAscending)
    iResult *= -1;

  return iResult;
}

void CPWHistDlg::OnBnClickedPwhCopyAll()
{
  CMyString HistStr;
  PWHistList::iterator iter;

  for (iter = m_PWHistList.begin(); iter != m_PWHistList.end(); iter++) {
      const PWHistEntry &ent = *iter;
      HistStr += ent.changedate;
      HistStr += _T("\t");
      HistStr += ent.password;
      HistStr += _T("\r\n");
  }
  app.SetClipboardData(HistStr);
}
<|endoftext|>


<commit_before>#include "HalideRuntime.h"
#include "printer.h"
#include "scoped_mutex_lock.h"

#define USE_AGL 0
#if USE_AGL
extern "C" void *aglChoosePixelFormat(void *, int, const int *);
extern "C" void *aglCreateContext(void *, void *);
extern "C" int aglGetError();
extern "C" void aglDestroyPixelFormat(void *);
extern "C" unsigned char aglSetCurrentContext(void *);
#endif

extern "C" {

#if !USE_AGL
namespace Halide { namespace Runtime { namespace Internal { namespace OpenGL {

WEAK halide_mutex cgl_functions_mutex;
WEAK bool cgl_initialized = false;
WEAK int (*CGLChoosePixelFormat)(int *attributes, void **pixel_format_result, int *num_formats);
WEAK int (*CGLCreateContext)(void *pixel_format, void *share_context, void **context_Result);
WEAK int (*CGLDestroyPixelFormat)(void *);
WEAK int (*CGLSetCurrentContext)(void *);

}}}}

using namespace Halide::Runtime::Internal::OpenGL;
#endif

WEAK void *halide_opengl_get_proc_address(void *user_context, const char *name) {
    static void *dylib = NULL;
    if (!dylib) {
        dylib = halide_load_library(
            "/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL");
        if (!dylib) return NULL;
    }
    return halide_get_library_symbol(dylib, name);
}

// Initialize OpenGL
WEAK int halide_opengl_create_context(void *user_context) {
#if USE_AGL
    void *ctx = NULL;

    int attrib[] = {4 /* AGL_RGBA */, 0 /* Sentinel */};
    void *pf = aglChoosePixelFormat(NULL, 0, attrib);
    if (!pf) {
        halide_error(user_context, "Could not create pixel format\n");
        return -1;
    }
    ctx = aglCreateContext(pf, NULL);
    if (!ctx || aglGetError()) {
        halide_error(user_context, "Could not create context\n");
        return -1;
    }
    aglDestroyPixelFormat(pf);
    if (!aglSetCurrentContext(ctx)) {
        halide_error(user_context, "Could not activate OpenGL context\n");
        return -1;
    }
#else
    { // locking scope
        ScopedMutexLock lock(&cgl_functions_mutex);

        if (!cgl_initialized) {
            if ((CGLChoosePixelFormat =
                 (int (*)(int *, void **, int *))halide_opengl_get_proc_address(user_context, "CGLChoosePixelFormat")) == NULL) {
                return -1;
            }
            if ((CGLCreateContext =
                 (int (*)(void *, void *, void**))halide_opengl_get_proc_address(user_context, "CGLCreateContext")) == NULL) {
                return -1;
            }
            if ((CGLDestroyPixelFormat =
                 (int (*)(void *))halide_opengl_get_proc_address(user_context, "CGLDestroyPixelFormat")) == NULL) {
                return -1;
            }
            if ((CGLSetCurrentContext =
                 (int (*)(void *))halide_opengl_get_proc_address(user_context, "CGLSetCurrentContext")) == NULL) {
                return -1;
            }
        }
        cgl_initialized = true;
    }

    void *ctx = NULL;
    int attribs[] = { /* 5 kCGLPFADoubleBuffer */
        72, // kCGLPFANoRecovery
        96, // kCGLPFAAllowOfflineRenderers
        99, // kCGLPFAOpenGLProfile
        0x1000, // kCGLOGLPVersion_Legacy -- 0x3200 is kCGLOGLPVersion_3_2_Core -- kCGLOGLPVersion_GL4_Core is 0x4100
        0 // sentinel ending list
    };

    void *fmt;
    int numFormats = 0;
    if (CGLChoosePixelFormat(attribs, &fmt, &numFormats) != 0) {
        return -1;
    }
    if (CGLCreateContext(fmt, NULL, &ctx) != 0) {
        CGLDestroyPixelFormat(fmt);
        return -1;
    }
    CGLSetCurrentContext(ctx);
#endif
    return 0;
}

}
<commit_msg>Remove extern “C” from symbols defined in  Halide::Runtime::Internal::OpenGL <commit_after>#include "HalideRuntime.h"
#include "printer.h"
#include "scoped_mutex_lock.h"

#define USE_AGL 0
#if USE_AGL
extern "C" void *aglChoosePixelFormat(void *, int, const int *);
extern "C" void *aglCreateContext(void *, void *);
extern "C" int aglGetError();
extern "C" void aglDestroyPixelFormat(void *);
extern "C" unsigned char aglSetCurrentContext(void *);
#endif

#if !USE_AGL
namespace Halide { namespace Runtime { namespace Internal { namespace OpenGL {

WEAK halide_mutex cgl_functions_mutex;
WEAK bool cgl_initialized = false;
WEAK int (*CGLChoosePixelFormat)(int *attributes, void **pixel_format_result, int *num_formats);
WEAK int (*CGLCreateContext)(void *pixel_format, void *share_context, void **context_Result);
WEAK int (*CGLDestroyPixelFormat)(void *);
WEAK int (*CGLSetCurrentContext)(void *);

}}}}

using namespace Halide::Runtime::Internal::OpenGL;
#endif

extern "C" {

WEAK void *halide_opengl_get_proc_address(void *user_context, const char *name) {
    static void *dylib = NULL;
    if (!dylib) {
        dylib = halide_load_library(
            "/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL");
        if (!dylib) return NULL;
    }
    return halide_get_library_symbol(dylib, name);
}

// Initialize OpenGL
WEAK int halide_opengl_create_context(void *user_context) {
#if USE_AGL
    void *ctx = NULL;

    int attrib[] = {4 /* AGL_RGBA */, 0 /* Sentinel */};
    void *pf = aglChoosePixelFormat(NULL, 0, attrib);
    if (!pf) {
        halide_error(user_context, "Could not create pixel format\n");
        return -1;
    }
    ctx = aglCreateContext(pf, NULL);
    if (!ctx || aglGetError()) {
        halide_error(user_context, "Could not create context\n");
        return -1;
    }
    aglDestroyPixelFormat(pf);
    if (!aglSetCurrentContext(ctx)) {
        halide_error(user_context, "Could not activate OpenGL context\n");
        return -1;
    }
#else
    { // locking scope
        ScopedMutexLock lock(&cgl_functions_mutex);

        if (!cgl_initialized) {
            if ((CGLChoosePixelFormat =
                 (int (*)(int *, void **, int *))halide_opengl_get_proc_address(user_context, "CGLChoosePixelFormat")) == NULL) {
                return -1;
            }
            if ((CGLCreateContext =
                 (int (*)(void *, void *, void**))halide_opengl_get_proc_address(user_context, "CGLCreateContext")) == NULL) {
                return -1;
            }
            if ((CGLDestroyPixelFormat =
                 (int (*)(void *))halide_opengl_get_proc_address(user_context, "CGLDestroyPixelFormat")) == NULL) {
                return -1;
            }
            if ((CGLSetCurrentContext =
                 (int (*)(void *))halide_opengl_get_proc_address(user_context, "CGLSetCurrentContext")) == NULL) {
                return -1;
            }
        }
        cgl_initialized = true;
    }

    void *ctx = NULL;
    int attribs[] = { /* 5 kCGLPFADoubleBuffer */
        72, // kCGLPFANoRecovery
        96, // kCGLPFAAllowOfflineRenderers
        99, // kCGLPFAOpenGLProfile
        0x1000, // kCGLOGLPVersion_Legacy -- 0x3200 is kCGLOGLPVersion_3_2_Core -- kCGLOGLPVersion_GL4_Core is 0x4100
        0 // sentinel ending list
    };

    void *fmt;
    int numFormats = 0;
    if (CGLChoosePixelFormat(attribs, &fmt, &numFormats) != 0) {
        return -1;
    }
    if (CGLCreateContext(fmt, NULL, &ctx) != 0) {
        CGLDestroyPixelFormat(fmt);
        return -1;
    }
    CGLSetCurrentContext(ctx);
#endif
    return 0;
}

}
<|endoftext|>


<commit_before>#ifndef __STAN__MATH__MATRIX__SORT_INDICES_HPP__
#define __STAN__MATH__MATRIX__SORT_INDICES_HPP__

#include <stan/math/matrix/Eigen.hpp>
#include <vector>
#include <algorithm>    // std::sort
#include <iostream>

namespace stan {
  namespace math {

    /**
     * A comparator that works for any container type that has the
     * brackets operator.
     *
     * @tparam ascending true if sorting in ascending order
     * @tparam C container type
     */
    namespace {
      template <bool ascending, typename C>
      class index_comparator {
         const C& xs_;
      public:
        /**
         * Construct an index comparator holding a reference
         * to the specified container.
         *
         * @patam xs Container
         */
         index_comparator(const C& xs) : xs_(xs) { }

        /**
         * Return true if the value at the first index is sorted in
         * front of the value at the second index;  this will depend
         * on the template parameter ascending.
         *
         * @param i Index of first value for comparison
         * @param j Index of second value for comparison
         */
        bool operator()(int i, int j) const {
           if (ascending)
             return xs_[i-1] < xs_[j-1];
           else
             return xs_[i-1] > xs_[j-1];
         }
      };

      /**
       * Return an integer array of indices of the specified container
       * sorting the values in ascending or descending order based on
       * the value of the first template prameter.
       *
       * @tparam ascending true if sort is in ascending order
       * @tparam C type of container
       * @param xs Container to sort
       * @return sorted version of container
       */
      template <bool ascending, typename C>
      std::vector<int> sort_indices(const C& xs) {
        size_t size = xs.size();
        std::vector<int> idxs;
        idxs.resize(size);
        for (int i = 0; i < size; ++i)
          idxs[i] = i + 1;
        index_comparator<ascending,C> comparator(xs);
        std::sort(idxs.begin(), idxs.end(), comparator);
        return idxs;
      }

    }

    /**
     * Return a sorted copy of the argument container in ascending order.
     *
     * @tparam C type of container
     * @param xs Container to sort
     * @return sorted version of container
     */
    template <typename C>
    std::vector<int> sort_indices_asc(const C& xs) {
      return sort_indices<true>(xs);
    }

    /**
     * Return a sorted copy of the argument container in ascending order.
     *
     * @tparam C type of container
     * @param xs Container to sort
     * @return sorted version of container
     */
    template <typename C>
    std::vector<int> sort_indices_desc(const C& xs) {
      return sort_indices<false>(xs);
    }

  }
}
#endif
<commit_msg>A possible way to use to solve sign-compare warnings<commit_after>#ifndef __STAN__MATH__MATRIX__SORT_INDICES_HPP__
#define __STAN__MATH__MATRIX__SORT_INDICES_HPP__

#include <stan/math/matrix/Eigen.hpp>
#include <vector>
#include <algorithm>    // std::sort
#include <iostream>

namespace stan {
  namespace math {

    /**
     * A comparator that works for any container type that has the
     * brackets operator.
     *
     * @tparam ascending true if sorting in ascending order
     * @tparam C container type
     */
    namespace {
      template <bool ascending, typename C>
      class index_comparator {
         const C& xs_;
      public:
        /**
         * Construct an index comparator holding a reference
         * to the specified container.
         *
         * @patam xs Container
         */
         index_comparator(const C& xs) : xs_(xs) { }

        /**
         * Return true if the value at the first index is sorted in
         * front of the value at the second index;  this will depend
         * on the template parameter ascending.
         *
         * @param i Index of first value for comparison
         * @param j Index of second value for comparison
         */
        bool operator()(int i, int j) const {
           if (ascending)
             return xs_[i-1] < xs_[j-1];
           else
             return xs_[i-1] > xs_[j-1];
         }
      };

      /**
       * Return an integer array of indices of the specified container
       * sorting the values in ascending or descending order based on
       * the value of the first template prameter.
       *
       * @tparam ascending true if sort is in ascending order
       * @tparam C type of container
       * @param xs Container to sort
       * @return sorted version of container
       */
      template <bool ascending, typename C, typename signal>
      std::vector<int> sort_indices(const C& xs, const signal size) {
        std::vector<int> idxs;
        idxs.resize(size);
        for (signal i(0); i < size; ++i)
          idxs[i] = i + 1;
        index_comparator<ascending,C> comparator(xs);
        std::sort(idxs.begin(), idxs.end(), comparator);
        return idxs;
      }

    }

    /**
     * Return a sorted copy of the argument container in ascending order.
     *
     * @tparam C type of container
     * @param xs Container to sort
     * @return sorted version of container
     */
    template <typename C>
    std::vector<int> sort_indices_asc(const C& xs) {
      return sort_indices<true>(xs, xs.size());
    }

    /**
     * Return a sorted copy of the argument container in ascending order.
     *
     * @tparam C type of container
     * @param xs Container to sort
     * @return sorted version of container
     */
    template <typename C>
    std::vector<int> sort_indices_desc(const C& xs) {
      return sort_indices<false>(xs, xs.size());
    }

  }
}
#endif
<|endoftext|>


<commit_before>
#include "swganh/command/command_service.h"

#include <cctype>

#include "anh/app/kernel_interface.h"

#include <cppconn/exception.h>
#include <cppconn/connection.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/sqlstring.h>
#include <glog/logging.h>

#include "anh/crc.h"
#include "anh/event_dispatcher.h"
#include "anh/database/database_manager_interface.h"
#include "anh/service/service_manager.h"

#include "swganh/command/command_filter.h"

#include "swganh/messages/controllers/command_queue_enqueue.h"
#include "swganh/messages/controllers/command_queue_remove.h"
#include "swganh/messages/controllers/combat_action_message.h"

#include "swganh/object/creature/creature.h"
#include "swganh/object/object_controller.h"

#include "python_command.h"
#include "swganh/simulation/simulation_service.h"

using namespace anh::app;
using namespace anh::service;
using namespace std;
using namespace swganh::command;
using namespace swganh::messages;
using namespace swganh::messages::controllers;
using namespace swganh::object;
using namespace swganh::object::creature;
using namespace swganh::scripting;
using namespace swganh::simulation;

using boost::asio::deadline_timer;
using boost::posix_time::milliseconds;

CommandService::CommandService(KernelInterface* kernel)
: BaseService(kernel)
{}

ServiceDescription CommandService::GetServiceDescription()
{
    ServiceDescription service_description(
        "CommandService",
        "command",
        "0.1",
        "127.0.0.1",
        0,
        0,
        0);

    return service_description;
}

void CommandService::AddCommandEnqueueFilter(CommandFilter&& filter)
{
	enqueue_filters_.push_back(move(filter));
}

void CommandService::AddCommandProcessFilter(CommandFilter&& filter)
{
    process_filters_.push_back(move(filter));
}

void CommandService::SetCommandHandler(uint32_t command_crc, CommandHandler&& handler)
{
    handlers_[command_crc] = move(handler);
}

void CommandService::EnqueueCommand(
    const shared_ptr<Creature>& actor,
	const shared_ptr<Object>& target,
    CommandQueueEnqueue command)
{
    bool is_valid;
    uint32_t error = 0, action = 0;

    tie(is_valid, error, action) = ValidateCommand(actor, target, command, command_properties_map_[command.command_crc], enqueue_filters_);

    if (!is_valid)
    {
        LOG(WARNING) << "Invalid command";
        SendCommandQueueRemove(actor, command.action_counter, 0.0f, error, action);
        return;
    }
	auto object_id = actor->GetObjectId();
    command_queues_[object_id].push(command);

    if (!command_queue_timers_[object_id])
    {
        command_queue_timers_[object_id] = make_shared<deadline_timer>(kernel()->GetIoService());
        command_queue_timers_[object_id]->expires_from_now(
                milliseconds(command_properties_map_[command.command_crc].default_time));

        command_queue_timers_[object_id]->async_wait(bind(&CommandService::ProcessNextCommand, this, actor));
    }
}

void CommandService::HandleCommandQueueEnqueue(
    const shared_ptr<ObjectController>& controller,
    const ObjControllerMessage& message)
{
    auto actor = dynamic_pointer_cast<Creature>(controller->GetObject());

    CommandQueueEnqueue enqueue;
    enqueue.Deserialize(message.data);

	auto target = simulation_service_->GetObjectById(enqueue.target_id);

    auto find_iter = command_properties_map_.find(enqueue.command_crc);

    if (find_iter == command_properties_map_.end())
    {
        LOG(WARNING) << "Invalid handler requested: " << hex << enqueue.command_crc;
        return;
    }

    if (find_iter->second.add_to_combat_queue)
    {
        EnqueueCommand(actor, target, enqueue);
    }
    else
    {
        ProcessCommand(actor, target, enqueue);
    }
}

void CommandService::HandleCommandQueueRemove(
    const shared_ptr<ObjectController>& controller,
    const ObjControllerMessage& message)
{}

void CommandService::ProcessNextCommand(const shared_ptr<Creature>& actor)
{
    auto find_iter = command_queues_.find(actor->GetObjectId());

    CommandQueueEnqueue command;

    if (!find_iter->second.try_pop(command))
    {
        return;
    }

    auto target = simulation_service_->GetObjectById(command.target_id);

    ProcessCommand(actor, target, command);

    command_queue_timers_[actor->GetObjectId()]->expires_from_now(
        milliseconds(command_properties_map_[command.command_crc].default_time));

    command_queue_timers_[actor->GetObjectId()]->async_wait(bind(&CommandService::ProcessNextCommand, this, actor));
}

void CommandService::ProcessCommand(const shared_ptr<Creature>& actor, const shared_ptr<Object>& target, const swganh::messages::controllers::CommandQueueEnqueue& command)
{
    auto find_iter = handlers_.find(command.command_crc);
    if (find_iter == handlers_.end())
    {
        LOG(WARNING) << "No handler for command: " << std::hex << command.command_crc;
        return;
    }

    bool is_valid;
    uint32_t error = 0, action = 0;
    float default_time = 0.0f;

    tie(is_valid, error, action) = ValidateCommand(actor, target, command, command_properties_map_[command.command_crc], process_filters_);

    if (is_valid)
    {
		find_iter->second(actor, target, command);
        default_time = command_properties_map_[command.command_crc].default_time / 1000;
    }

    SendCommandQueueRemove(actor, command.action_counter, default_time, error, action);
}

void CommandService::onStart()
{
	LoadProperties();

    simulation_service_ = kernel()->GetServiceManager()
        ->GetService<SimulationService>("SimulationService");

    simulation_service_->RegisterControllerHandler(0x00000116, [this] (
        const std::shared_ptr<ObjectController>& controller,
        const swganh::messages::ObjControllerMessage& message)
    {
        HandleCommandQueueEnqueue(controller, message);
    });

    simulation_service_->RegisterControllerHandler(0x00000117, [this] (
        const std::shared_ptr<ObjectController>& controller,
        const swganh::messages::ObjControllerMessage& message)
    {
        HandleCommandQueueRemove(controller, message);
    });

	auto event_dispatcher = kernel()->GetEventDispatcher();
	event_dispatcher->Dispatch(
        make_shared<anh::ValueEvent<CommandPropertiesMap>>("CommandServiceReady", GetCommandProperties()));
}

void CommandService::LoadProperties()
{
    try {
        auto db_manager = kernel()->GetDatabaseManager();

        auto conn = db_manager->getConnection("galaxy");
        auto statement =  unique_ptr<sql::PreparedStatement>(conn->prepareStatement("CALL sp_LoadCommandProperties();"));

        auto result = unique_ptr<sql::ResultSet>(statement->executeQuery());

        while (result->next())
        {
            CommandProperties properties;

            properties.name = result->getString("name");

            string tmp = properties.name;
            transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower);
            properties.name_crc = anh::memcrc(tmp);

            properties.ability = result->getString("ability");
            properties.ability_crc = anh::memcrc(properties.ability);
            properties.deny_in_states = result->getUInt64("deny_in_states");
            properties.script_hook = result->getString("script_hook");
            properties.fail_script_hook = result->getString("fail_script_hook");
            properties.default_time = result->getUInt64("default_time");
            properties.command_group = result->getUInt("command_group");
            properties.max_range_to_target = result->getDouble("max_range_to_target");
            properties.add_to_combat_queue = result->getUInt("add_to_combat_queue");
            properties.health_cost = result->getUInt("health_cost");
            properties.health_cost_multiplier = result->getUInt("health_cost_multiplier");
            properties.action_cost = result->getUInt("action_cost");
            properties.action_cost_multiplier = result->getUInt("action_cost_multiplier");
            properties.mind_cost = result->getUInt("mind_cost");
            properties.mind_cost_multiplier = result->getUInt("mind_cost");
            properties.damage_multiplier = result->getDouble("damage_multiplier");
            properties.delay_multiplier = result->getDouble("delay_multiplier");
            properties.force_cost = result->getUInt("force_cost");
            properties.force_cost_multiplier = result->getUInt("force_cost_multiplier");
            properties.animation_crc = result->getUInt("animation_crc");
            properties.required_weapon_group = result->getUInt("required_weapon_group");
            properties.combat_spam = result->getString("combat_spam");
            properties.trail1 = result->getUInt("trail1");
            properties.trail2 = result->getUInt("trail2");
            properties.allow_in_posture = result->getUInt("allow_in_posture");
            properties.health_hit_chance = result->getDouble("health_hit_chance");
            properties.action_hit_chance = result->getDouble("action_hit_chance");
            properties.mind_hit_chance = result->getDouble("mind_hit_chance");
            properties.knockdown_hit_chance = result->getDouble("knockdown_chance");
            properties.dizzy_hit_chance = result->getDouble("dizzy_chance");
            properties.blind_chance = result->getDouble("blind_chance");
            properties.stun_chance = result->getDouble("stun_chance");
            properties.intimidate_chance = result->getDouble("intimidate_chance");
            properties.posture_down_chance = result->getDouble("posture_down_chance");
            properties.extended_range = result->getDouble("extended_range");
            properties.cone_angle = result->getDouble("cone_angle");
            properties.deny_in_locomotion = result->getUInt64("deny_in_locomotion");

            command_properties_map_.insert(make_pair(properties.name_crc, move(properties)));

            RegisterCommandScript(properties);
        }

        DLOG(WARNING) << "Loaded (" << command_properties_map_.size() << ") Commands";
    }
    catch(sql::SQLException &e)
    {
        DLOG(ERROR) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")";
        DLOG(ERROR) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what();
    }
}

void CommandService::RegisterCommandScript(const CommandProperties& properties)
{
    if (properties.script_hook.length() != 0)
    {
        SetCommandHandler(properties.name_crc, PythonCommand(properties));
    }
}

tuple<bool, uint32_t, uint32_t> CommandService::ValidateCommand(
    const shared_ptr<Creature>& actor,
	const shared_ptr<Object>& target,
    const swganh::messages::controllers::CommandQueueEnqueue& command,
    const CommandProperties& command_properties,
    const std::vector<CommandFilter>& filters)
{
	tuple<bool, uint32_t, uint32_t> result;
    bool all_run = all_of(
        begin(filters),
        end(filters),
        [&result, actor, target, &command, &command_properties] (const CommandFilter& filter)->bool
    {
        result =  filter(actor, target, command, command_properties);
		return get<0>(result);
    });

    return result;
}

void CommandService::SendCommandQueueRemove(
    const shared_ptr<Creature>& actor,
    uint32_t action_counter,
    float default_time_sec,
    uint32_t error,
    uint32_t action)
{
    CommandQueueRemove remove;
    remove.action_counter = action_counter;
    remove.timer = default_time_sec;
    remove.error = error;
    remove.action = action;

	actor->GetController()->Notify(ObjControllerMessage(0x0000000B, remove));
}
<commit_msg>Set a default expiration time and and trigger an async wait if nothing is waiting.<commit_after>
#include "swganh/command/command_service.h"

#include <cctype>

#include "anh/app/kernel_interface.h"

#include <cppconn/exception.h>
#include <cppconn/connection.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/sqlstring.h>
#include <glog/logging.h>

#include "anh/crc.h"
#include "anh/event_dispatcher.h"
#include "anh/database/database_manager_interface.h"
#include "anh/service/service_manager.h"

#include "swganh/command/command_filter.h"

#include "swganh/messages/controllers/command_queue_enqueue.h"
#include "swganh/messages/controllers/command_queue_remove.h"
#include "swganh/messages/controllers/combat_action_message.h"

#include "swganh/object/creature/creature.h"
#include "swganh/object/object_controller.h"

#include "python_command.h"
#include "swganh/simulation/simulation_service.h"

using namespace anh::app;
using namespace anh::service;
using namespace std;
using namespace swganh::command;
using namespace swganh::messages;
using namespace swganh::messages::controllers;
using namespace swganh::object;
using namespace swganh::object::creature;
using namespace swganh::scripting;
using namespace swganh::simulation;

using boost::asio::deadline_timer;
using boost::posix_time::milliseconds;

CommandService::CommandService(KernelInterface* kernel)
: BaseService(kernel)
{}

ServiceDescription CommandService::GetServiceDescription()
{
    ServiceDescription service_description(
        "CommandService",
        "command",
        "0.1",
        "127.0.0.1",
        0,
        0,
        0);

    return service_description;
}

void CommandService::AddCommandEnqueueFilter(CommandFilter&& filter)
{
	enqueue_filters_.push_back(move(filter));
}

void CommandService::AddCommandProcessFilter(CommandFilter&& filter)
{
    process_filters_.push_back(move(filter));
}

void CommandService::SetCommandHandler(uint32_t command_crc, CommandHandler&& handler)
{
    handlers_[command_crc] = move(handler);
}

void CommandService::EnqueueCommand(
    const shared_ptr<Creature>& actor,
	const shared_ptr<Object>& target,
    CommandQueueEnqueue command)
{
    bool is_valid;
    uint32_t error = 0, action = 0;

    tie(is_valid, error, action) = ValidateCommand(actor, target, command, command_properties_map_[command.command_crc], enqueue_filters_);

    if (!is_valid)
    {
        LOG(WARNING) << "Invalid command";
        SendCommandQueueRemove(actor, command.action_counter, 0.0f, error, action);
        return;
    }
	auto object_id = actor->GetObjectId();
    command_queues_[object_id].push(command);

    if (!command_queue_timers_[object_id])
    {
        command_queue_timers_[object_id] = make_shared<deadline_timer>(kernel()->GetIoService());
        command_queue_timers_[object_id]->expires_at(boost::posix_time::second_clock::universal_time());
    }

    if (command_queue_timers_[object_id]->expires_at() <= boost::posix_time::second_clock::universal_time())
    {
        command_queue_timers_[object_id]->expires_from_now(
                milliseconds(command_properties_map_[command.command_crc].default_time));
        command_queue_timers_[object_id]->async_wait(bind(&CommandService::ProcessNextCommand, this, actor));
    }
}

void CommandService::HandleCommandQueueEnqueue(
    const shared_ptr<ObjectController>& controller,
    const ObjControllerMessage& message)
{
    auto actor = dynamic_pointer_cast<Creature>(controller->GetObject());

    CommandQueueEnqueue enqueue;
    enqueue.Deserialize(message.data);

	auto target = simulation_service_->GetObjectById(enqueue.target_id);

    auto find_iter = command_properties_map_.find(enqueue.command_crc);

    if (find_iter == command_properties_map_.end())
    {
        LOG(WARNING) << "Invalid handler requested: " << hex << enqueue.command_crc;
        return;
    }

    if (find_iter->second.add_to_combat_queue)
    {
        EnqueueCommand(actor, target, enqueue);
    }
    else
    {
        ProcessCommand(actor, target, enqueue);
    }
}

void CommandService::HandleCommandQueueRemove(
    const shared_ptr<ObjectController>& controller,
    const ObjControllerMessage& message)
{}

void CommandService::ProcessNextCommand(const shared_ptr<Creature>& actor)
{
    auto find_iter = command_queues_.find(actor->GetObjectId());

    CommandQueueEnqueue command;

    if (!find_iter->second.try_pop(command))
    {
        return;
    }

    auto target = simulation_service_->GetObjectById(command.target_id);

    ProcessCommand(actor, target, command);

    command_queue_timers_[actor->GetObjectId()]->expires_from_now(
        milliseconds(command_properties_map_[command.command_crc].default_time));
    command_queue_timers_[actor->GetObjectId()]->async_wait(bind(&CommandService::ProcessNextCommand, this, actor));
}

void CommandService::ProcessCommand(const shared_ptr<Creature>& actor, const shared_ptr<Object>& target, const swganh::messages::controllers::CommandQueueEnqueue& command)
{
    auto find_iter = handlers_.find(command.command_crc);
    if (find_iter == handlers_.end())
    {
        LOG(WARNING) << "No handler for command: " << std::hex << command.command_crc;
        return;
    }

    bool is_valid;
    uint32_t error = 0, action = 0;
    float default_time = 0.0f;

    tie(is_valid, error, action) = ValidateCommand(actor, target, command, command_properties_map_[command.command_crc], process_filters_);

    if (is_valid)
    {
		find_iter->second(actor, target, command);
        default_time = command_properties_map_[command.command_crc].default_time / 1000;
    }

    SendCommandQueueRemove(actor, command.action_counter, default_time, error, action);
}

void CommandService::onStart()
{
	LoadProperties();

    simulation_service_ = kernel()->GetServiceManager()
        ->GetService<SimulationService>("SimulationService");

    simulation_service_->RegisterControllerHandler(0x00000116, [this] (
        const std::shared_ptr<ObjectController>& controller,
        const swganh::messages::ObjControllerMessage& message)
    {
        HandleCommandQueueEnqueue(controller, message);
    });

    simulation_service_->RegisterControllerHandler(0x00000117, [this] (
        const std::shared_ptr<ObjectController>& controller,
        const swganh::messages::ObjControllerMessage& message)
    {
        HandleCommandQueueRemove(controller, message);
    });

	auto event_dispatcher = kernel()->GetEventDispatcher();
	event_dispatcher->Dispatch(
        make_shared<anh::ValueEvent<CommandPropertiesMap>>("CommandServiceReady", GetCommandProperties()));
}

void CommandService::LoadProperties()
{
    try {
        auto db_manager = kernel()->GetDatabaseManager();

        auto conn = db_manager->getConnection("galaxy");
        auto statement =  unique_ptr<sql::PreparedStatement>(conn->prepareStatement("CALL sp_LoadCommandProperties();"));

        auto result = unique_ptr<sql::ResultSet>(statement->executeQuery());

        while (result->next())
        {
            CommandProperties properties;

            properties.name = result->getString("name");

            string tmp = properties.name;
            transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower);
            properties.name_crc = anh::memcrc(tmp);

            properties.ability = result->getString("ability");
            properties.ability_crc = anh::memcrc(properties.ability);
            properties.deny_in_states = result->getUInt64("deny_in_states");
            properties.script_hook = result->getString("script_hook");
            properties.fail_script_hook = result->getString("fail_script_hook");
            properties.default_time = result->getUInt64("default_time");
            properties.command_group = result->getUInt("command_group");
            properties.max_range_to_target = result->getDouble("max_range_to_target");
            properties.add_to_combat_queue = result->getUInt("add_to_combat_queue");
            properties.health_cost = result->getUInt("health_cost");
            properties.health_cost_multiplier = result->getUInt("health_cost_multiplier");
            properties.action_cost = result->getUInt("action_cost");
            properties.action_cost_multiplier = result->getUInt("action_cost_multiplier");
            properties.mind_cost = result->getUInt("mind_cost");
            properties.mind_cost_multiplier = result->getUInt("mind_cost");
            properties.damage_multiplier = result->getDouble("damage_multiplier");
            properties.delay_multiplier = result->getDouble("delay_multiplier");
            properties.force_cost = result->getUInt("force_cost");
            properties.force_cost_multiplier = result->getUInt("force_cost_multiplier");
            properties.animation_crc = result->getUInt("animation_crc");
            properties.required_weapon_group = result->getUInt("required_weapon_group");
            properties.combat_spam = result->getString("combat_spam");
            properties.trail1 = result->getUInt("trail1");
            properties.trail2 = result->getUInt("trail2");
            properties.allow_in_posture = result->getUInt("allow_in_posture");
            properties.health_hit_chance = result->getDouble("health_hit_chance");
            properties.action_hit_chance = result->getDouble("action_hit_chance");
            properties.mind_hit_chance = result->getDouble("mind_hit_chance");
            properties.knockdown_hit_chance = result->getDouble("knockdown_chance");
            properties.dizzy_hit_chance = result->getDouble("dizzy_chance");
            properties.blind_chance = result->getDouble("blind_chance");
            properties.stun_chance = result->getDouble("stun_chance");
            properties.intimidate_chance = result->getDouble("intimidate_chance");
            properties.posture_down_chance = result->getDouble("posture_down_chance");
            properties.extended_range = result->getDouble("extended_range");
            properties.cone_angle = result->getDouble("cone_angle");
            properties.deny_in_locomotion = result->getUInt64("deny_in_locomotion");

            command_properties_map_.insert(make_pair(properties.name_crc, move(properties)));

            RegisterCommandScript(properties);
        }

        DLOG(WARNING) << "Loaded (" << command_properties_map_.size() << ") Commands";
    }
    catch(sql::SQLException &e)
    {
        DLOG(ERROR) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")";
        DLOG(ERROR) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what();
    }
}

void CommandService::RegisterCommandScript(const CommandProperties& properties)
{
    if (properties.script_hook.length() != 0)
    {
        SetCommandHandler(properties.name_crc, PythonCommand(properties));
    }
}

tuple<bool, uint32_t, uint32_t> CommandService::ValidateCommand(
    const shared_ptr<Creature>& actor,
	const shared_ptr<Object>& target,
    const swganh::messages::controllers::CommandQueueEnqueue& command,
    const CommandProperties& command_properties,
    const std::vector<CommandFilter>& filters)
{
	tuple<bool, uint32_t, uint32_t> result;
    bool all_run = all_of(
        begin(filters),
        end(filters),
        [&result, actor, target, &command, &command_properties] (const CommandFilter& filter)->bool
    {
        result =  filter(actor, target, command, command_properties);
		return get<0>(result);
    });

    return result;
}

void CommandService::SendCommandQueueRemove(
    const shared_ptr<Creature>& actor,
    uint32_t action_counter,
    float default_time_sec,
    uint32_t error,
    uint32_t action)
{
    CommandQueueRemove remove;
    remove.action_counter = action_counter;
    remove.timer = default_time_sec;
    remove.error = error;
    remove.action = action;

	actor->GetController()->Notify(ObjControllerMessage(0x0000000B, remove));
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** Copyright (C) 2014 BlackBerry Limited. All rights reserved.
**
** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://www.qt.io/licensing.  For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "bardescriptorfilenodemanager.h"

#include "bardescriptorfilenode.h"
#include "blackberrydeployconfiguration.h"
#include "blackberrydeployinformation.h"
#include "blackberrycreatepackagestep.h"
#include "blackberryqtversion.h"
#include "bardescriptordocument.h"
#include "qnxconstants.h"

#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
#include <projectexplorer/buildstep.h>
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projecttree.h>
#include <projectexplorer/target.h>
#include <projectexplorer/buildconfiguration.h>
#include <qmakeprojectmanager/qmakenodes.h>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>
#include <utils/checkablemessagebox.h>
#include <utils/qtcassert.h>

using namespace Qnx;
using namespace Qnx::Internal;

namespace {
const char SKIP_BAR_DESCRIPTOR_CREATION_KEY[] = "Qnx.BlackBerry.BarDescriptorFileNodeManager.SkipCreation";
}

BarDescriptorFileNodeManager::BarDescriptorFileNodeManager(QObject *parent)
    : QObject(parent)
{
    connect(ProjectExplorer::ProjectTree::instance(), &ProjectExplorer::ProjectTree::currentProjectChanged,
            this, &BarDescriptorFileNodeManager::setCurrentProject);
}

void BarDescriptorFileNodeManager::setCurrentProject(ProjectExplorer::Project *project)
{
    if (!project)
        return;

    connect(project, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)),
            this, SLOT(updateBarDescriptorNodes(ProjectExplorer::Target*)), Qt::UniqueConnection);

    updateBarDescriptorNodes(project->activeTarget());
}

void BarDescriptorFileNodeManager::updateBarDescriptorNodes(ProjectExplorer::Target *target)
{
    if (!target)
        return;

    // We are not consistently getting a signal when the current project changes,
    // so instead use target->project() to get access to the current project

    if (ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(target->kit()) != Constants::QNX_BB_OS_TYPE) {
        removeBarDescriptorNodes(target->project());
        return;
    }

    updateBarDescriptorNodes(target->project(), true);

    QList<ProjectExplorer::DeployConfiguration*> deployConfigurations = target->deployConfigurations();
    foreach (ProjectExplorer::DeployConfiguration *deployConfiguration, deployConfigurations) {
        BlackBerryDeployConfiguration *bbdc = qobject_cast<BlackBerryDeployConfiguration*>(deployConfiguration);
        if (!bbdc)
            continue;

        connect(bbdc->deploymentInfo(), SIGNAL(dataChanged(QModelIndex,QModelIndex)),
                this, SLOT(handleDeploymentDataChanged()), Qt::UniqueConnection);
        connect(bbdc->deploymentInfo(), SIGNAL(modelReset()),
                this, SLOT(handleDeploymentModelReset()), Qt::UniqueConnection);
    }
}

void BarDescriptorFileNodeManager::handleDeploymentDataChanged()
{
    handleDeploymentInfoChanged(false);
}

void BarDescriptorFileNodeManager::handleDeploymentModelReset()
{
    handleDeploymentInfoChanged(true);
}

void BarDescriptorFileNodeManager::handleDeploymentInfoChanged(bool modelReset)
{
    BlackBerryDeployInformation *deployInfo = qobject_cast<BlackBerryDeployInformation*>(sender());
    QTC_ASSERT(deployInfo, return);

    updateBarDescriptorNodes(deployInfo->target()->project(), modelReset);
}

void BarDescriptorFileNodeManager::updateBarDescriptorNodes(ProjectExplorer::Project *project, bool attemptCreate)
{
    if (!project)
        return;

    ProjectExplorer::ProjectNode *rootProject = project->rootProjectNode();
    if (!rootProject)
        return;

    BlackBerryDeployConfiguration *dc =
            qobject_cast<BlackBerryDeployConfiguration*>(project->activeTarget()->activeDeployConfiguration());
    if (!dc)
        return;

    QList<BarPackageDeployInformation> packages = dc->deploymentInfo()->allPackages();
    foreach (const BarPackageDeployInformation &package, packages) {
        ProjectExplorer::ProjectNode *projectNode = rootProject->path() == package.proFilePath ?
                    rootProject : findProjectNode(rootProject, package.proFilePath);
        if (!projectNode)
            continue;

        if (!QFileInfo::exists(package.appDescriptorPath())) {
            if (!attemptCreate)
                continue;

            if (!createBarDescriptor(project, package.appDescriptorPath(), projectNode))
                continue;
        } else {
            // Update the Qt environment if not matching the one in the deployment settings
            updateBarDescriptor(package.appDescriptorPath(), project->activeTarget());
        }

        BarDescriptorFileNode *existingNode = findBarDescriptorFileNode(projectNode);
        if (existingNode) {
            if (existingNode->path() != package.appDescriptorPath()) {
                // Reload the new bar-descriptor document in the existing editor (if there is one)
                Core::IDocument *oldDocument = Core::DocumentModel::documentForFilePath(existingNode->path());
                if (oldDocument) {
                    QString errorMessage;

                    if (!oldDocument->save(&errorMessage)) {
                        Core::MessageManager::write(tr("Cannot save bar descriptor file: %1").arg(errorMessage));
                        continue;
                    } else {
                        oldDocument->setFilePath(Utils::FileName::fromString(package.appDescriptorPath()));

                        if (!oldDocument->reload(&errorMessage, Core::IDocument::FlagReload, Core::IDocument::TypeContents))
                            Core::MessageManager::write(tr("Cannot reload bar descriptor file: %1").arg(errorMessage));
                    }
                }

                existingNode->setPath(package.appDescriptorPath());
            }
        } else {
            BarDescriptorFileNode *fileNode = new BarDescriptorFileNode(package.appDescriptorPath());
            projectNode->addFileNodes(QList<ProjectExplorer::FileNode*>() << fileNode);
        }
    }
}

bool BarDescriptorFileNodeManager::createBarDescriptor(ProjectExplorer::Project *project,
                                                       const QString &barDescriptorPath,
                                                       ProjectExplorer::ProjectNode *projectNode)
{
    const QString projectName = QFileInfo(projectNode->path()).completeBaseName();

    QmakeProjectManager::QmakeProFileNode *proFileNode =
            qobject_cast<QmakeProjectManager::QmakeProFileNode*>(projectNode);
    QTC_ASSERT(proFileNode, return false);
    const QString targetName = proFileNode->targetInformation().target;

    const QFile barDescriptorFile(barDescriptorPath);
    if (barDescriptorFile.exists())
        return false;

    bool skipFileCreation = project->namedSettings(QLatin1String(SKIP_BAR_DESCRIPTOR_CREATION_KEY)).toBool();

    if (skipFileCreation)
        return false;

    QDialogButtonBox::StandardButton button = Utils::CheckableMessageBox::question(Core::ICore::mainWindow(),
                                                tr("Setup Application Descriptor File"),
                                                tr("You need to set up a bar descriptor file to enable "
                                                   "packaging.\nDo you want Qt Creator to generate it for your project (%1)?")
                                                .arg(project->projectFilePath().toUserOutput()),
                                                tr("Don't ask again for this project"), &skipFileCreation);

    if (button != QDialogButtonBox::Yes) {
        project->setNamedSettings(QLatin1String(SKIP_BAR_DESCRIPTOR_CREATION_KEY), skipFileCreation);
        return false;
    }

    QString barDescriptorTemplate;
    QtSupport::QtVersionNumber qtVersion =
            QtSupport::QtKitInformation::qtVersion(project->activeTarget()->kit())->qtVersion();
    if (qtVersion >= QtSupport::QtVersionNumber(5, 0, 0))
        barDescriptorTemplate = Core::ICore::resourcePath()
                + QLatin1String("/templates/wizards/bb-qt5-bardescriptor/bar-descriptor.xml");
    else
        barDescriptorTemplate = Core::ICore::resourcePath()
                + QLatin1String("/templates/wizards/bb-bardescriptor/bar-descriptor.xml");

    Utils::FileReader reader;
    if (!reader.fetch(barDescriptorTemplate)) {
        Core::MessageManager::write(tr("Cannot set up application descriptor file: "
                                       "Reading the bar descriptor template failed."));
        return false;
    }

    QString content = QString::fromUtf8(reader.data());
    content.replace(QLatin1String("PROJECTNAME"), projectName);
    content.replace(QLatin1String("TARGETNAME"), targetName);
    content.replace(QLatin1String("ID"), QLatin1String("com.example.") + projectName);

    if (project->projectDirectory().appendPath(QLatin1String("qml")).exists())
        content.replace(QLatin1String("</qnx>"),
                        QLatin1String("    <asset path=\"qml\">qml</asset>\n</qnx>"));

    Utils::FileSaver writer(barDescriptorFile.fileName(), QIODevice::WriteOnly);
    writer.write(content.toUtf8());
    if (!writer.finalize()) {
        Core::MessageManager::write(tr("Cannot set up application descriptor file: "
                                       "Writing the bar descriptor file failed."));
        return false;
    }

    // Check if the Qt environment matches the Qt bundle mode in the deployment step
    updateBarDescriptor(barDescriptorPath, project->activeTarget(), true);

    return true;
}

void BarDescriptorFileNodeManager::updateBarDescriptor(const QString &barDescriptorPath,
                                                       ProjectExplorer::Target *target,
                                                       bool skipConfirmation)
{
    BarDescriptorDocument doc;
    QString errorString;
    if (!doc.open(&errorString, barDescriptorPath)) {
        QMessageBox::warning(Core::ICore::mainWindow(), tr("Error"),
                             tr("Cannot open BAR application descriptor file"));
        return;
    }

    QList<Utils::EnvironmentItem> envItems =
            doc.value(BarDescriptorDocument::env).value<QList<Utils::EnvironmentItem> >();

    BlackBerryQtVersion *qtVersion =
            dynamic_cast<BlackBerryQtVersion *>(QtSupport::QtKitInformation::qtVersion(target->kit()));
    if (!qtVersion)
        return;

    ProjectExplorer::BuildStepList *stepList = target->activeDeployConfiguration()->stepList();
    foreach (ProjectExplorer::BuildStep *step, stepList->steps()) {
        BlackBerryCreatePackageStep *createPackageStep = dynamic_cast<BlackBerryCreatePackageStep *>(step);
        if (createPackageStep) {
            createPackageStep->doUpdateAppDescriptorFile(barDescriptorPath,
                                                         BlackBerryCreatePackageStep::QtEnvironment,
                                                         skipConfirmation);
        }
    }
}

void BarDescriptorFileNodeManager::removeBarDescriptorNodes(ProjectExplorer::Project *project)
{
    if (!project)
        return;

    ProjectExplorer::ProjectNode *rootProject = project->rootProjectNode();
    if (!rootProject)
        return;

    BarDescriptorFileNode *existingNode = findBarDescriptorFileNode(rootProject);
    if (existingNode)
        rootProject->removeFileNodes(QList<ProjectExplorer::FileNode*>() << existingNode);

    // Also remove the bar descriptor nodes for sub-projects
    removeBarDescriptorNodes(rootProject);
}

void BarDescriptorFileNodeManager::removeBarDescriptorNodes(ProjectExplorer::ProjectNode *parent)
{
    QList<ProjectExplorer::ProjectNode*> projectNodes = parent->subProjectNodes();
    foreach (ProjectExplorer::ProjectNode *projectNode, projectNodes) {
        BarDescriptorFileNode *existingNode = findBarDescriptorFileNode(projectNode);
        if (existingNode)
            projectNode->removeFileNodes(QList<ProjectExplorer::FileNode*>() << existingNode);

        removeBarDescriptorNodes(projectNode);
    }
}

BarDescriptorFileNode *BarDescriptorFileNodeManager::findBarDescriptorFileNode(ProjectExplorer::ProjectNode *parent) const
{
    QTC_ASSERT(parent, return 0);

    QList<ProjectExplorer::FileNode*> fileNodes = parent->fileNodes();
    foreach (ProjectExplorer::FileNode *fileNode, fileNodes) {
        BarDescriptorFileNode *barDescriptorNode = qobject_cast<BarDescriptorFileNode*>(fileNode);
        if (barDescriptorNode)
            return barDescriptorNode;
    }

    return 0;
}

ProjectExplorer::ProjectNode *BarDescriptorFileNodeManager::findProjectNode(ProjectExplorer::ProjectNode *parent,
                                                                            const QString &projectFilePath) const
{
    QTC_ASSERT(parent, return 0);

    QList<ProjectExplorer::ProjectNode*> projectNodes = parent->subProjectNodes();
    foreach (ProjectExplorer::ProjectNode *projectNode, projectNodes) {
        if (projectNode->path() == projectFilePath) {
            return projectNode;
        } else if (!projectNode->subProjectNodes().isEmpty()) {
            ProjectExplorer::ProjectNode *hit = findProjectNode(projectNode, projectFilePath);
            if (hit)
                return hit;
        }
    }

    return 0;
}
<commit_msg>BlackBerry: Make current project behave like it used to<commit_after>/**************************************************************************
**
** Copyright (C) 2014 BlackBerry Limited. All rights reserved.
**
** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://www.qt.io/licensing.  For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "bardescriptorfilenodemanager.h"

#include "bardescriptorfilenode.h"
#include "blackberrydeployconfiguration.h"
#include "blackberrydeployinformation.h"
#include "blackberrycreatepackagestep.h"
#include "blackberryqtversion.h"
#include "bardescriptordocument.h"
#include "qnxconstants.h"

#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
#include <projectexplorer/buildstep.h>
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projecttree.h>
#include <projectexplorer/session.h>
#include <projectexplorer/target.h>
#include <projectexplorer/buildconfiguration.h>
#include <qmakeprojectmanager/qmakenodes.h>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>
#include <utils/checkablemessagebox.h>
#include <utils/qtcassert.h>

using namespace Qnx;
using namespace Qnx::Internal;

namespace {
const char SKIP_BAR_DESCRIPTOR_CREATION_KEY[] = "Qnx.BlackBerry.BarDescriptorFileNodeManager.SkipCreation";
}

BarDescriptorFileNodeManager::BarDescriptorFileNodeManager(QObject *parent)
    : QObject(parent)
{
    connect(ProjectExplorer::ProjectTree::instance(), &ProjectExplorer::ProjectTree::currentProjectChanged,
            this, &BarDescriptorFileNodeManager::setCurrentProject);
    connect(ProjectExplorer::SessionManager::instance(), &ProjectExplorer::SessionManager::startupProjectChanged,
            this, &BarDescriptorFileNodeManager::setCurrentProject);
}

void BarDescriptorFileNodeManager::setCurrentProject(ProjectExplorer::Project *project)
{
    if (!project)
        return;

    connect(project, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)),
            this, SLOT(updateBarDescriptorNodes(ProjectExplorer::Target*)), Qt::UniqueConnection);

    updateBarDescriptorNodes(project->activeTarget());
}

void BarDescriptorFileNodeManager::updateBarDescriptorNodes(ProjectExplorer::Target *target)
{
    if (!target)
        return;

    // We are not consistently getting a signal when the current project changes,
    // so instead use target->project() to get access to the current project

    if (ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(target->kit()) != Constants::QNX_BB_OS_TYPE) {
        removeBarDescriptorNodes(target->project());
        return;
    }

    updateBarDescriptorNodes(target->project(), true);

    QList<ProjectExplorer::DeployConfiguration*> deployConfigurations = target->deployConfigurations();
    foreach (ProjectExplorer::DeployConfiguration *deployConfiguration, deployConfigurations) {
        BlackBerryDeployConfiguration *bbdc = qobject_cast<BlackBerryDeployConfiguration*>(deployConfiguration);
        if (!bbdc)
            continue;

        connect(bbdc->deploymentInfo(), SIGNAL(dataChanged(QModelIndex,QModelIndex)),
                this, SLOT(handleDeploymentDataChanged()), Qt::UniqueConnection);
        connect(bbdc->deploymentInfo(), SIGNAL(modelReset()),
                this, SLOT(handleDeploymentModelReset()), Qt::UniqueConnection);
    }
}

void BarDescriptorFileNodeManager::handleDeploymentDataChanged()
{
    handleDeploymentInfoChanged(false);
}

void BarDescriptorFileNodeManager::handleDeploymentModelReset()
{
    handleDeploymentInfoChanged(true);
}

void BarDescriptorFileNodeManager::handleDeploymentInfoChanged(bool modelReset)
{
    BlackBerryDeployInformation *deployInfo = qobject_cast<BlackBerryDeployInformation*>(sender());
    QTC_ASSERT(deployInfo, return);

    updateBarDescriptorNodes(deployInfo->target()->project(), modelReset);
}

void BarDescriptorFileNodeManager::updateBarDescriptorNodes(ProjectExplorer::Project *project, bool attemptCreate)
{
    if (!project)
        return;

    ProjectExplorer::ProjectNode *rootProject = project->rootProjectNode();
    if (!rootProject)
        return;

    BlackBerryDeployConfiguration *dc =
            qobject_cast<BlackBerryDeployConfiguration*>(project->activeTarget()->activeDeployConfiguration());
    if (!dc)
        return;

    QList<BarPackageDeployInformation> packages = dc->deploymentInfo()->allPackages();
    foreach (const BarPackageDeployInformation &package, packages) {
        ProjectExplorer::ProjectNode *projectNode = rootProject->path() == package.proFilePath ?
                    rootProject : findProjectNode(rootProject, package.proFilePath);
        if (!projectNode)
            continue;

        if (!QFileInfo::exists(package.appDescriptorPath())) {
            if (!attemptCreate)
                continue;

            if (!createBarDescriptor(project, package.appDescriptorPath(), projectNode))
                continue;
        } else {
            // Update the Qt environment if not matching the one in the deployment settings
            updateBarDescriptor(package.appDescriptorPath(), project->activeTarget());
        }

        BarDescriptorFileNode *existingNode = findBarDescriptorFileNode(projectNode);
        if (existingNode) {
            if (existingNode->path() != package.appDescriptorPath()) {
                // Reload the new bar-descriptor document in the existing editor (if there is one)
                Core::IDocument *oldDocument = Core::DocumentModel::documentForFilePath(existingNode->path());
                if (oldDocument) {
                    QString errorMessage;

                    if (!oldDocument->save(&errorMessage)) {
                        Core::MessageManager::write(tr("Cannot save bar descriptor file: %1").arg(errorMessage));
                        continue;
                    } else {
                        oldDocument->setFilePath(Utils::FileName::fromString(package.appDescriptorPath()));

                        if (!oldDocument->reload(&errorMessage, Core::IDocument::FlagReload, Core::IDocument::TypeContents))
                            Core::MessageManager::write(tr("Cannot reload bar descriptor file: %1").arg(errorMessage));
                    }
                }

                existingNode->setPath(package.appDescriptorPath());
            }
        } else {
            BarDescriptorFileNode *fileNode = new BarDescriptorFileNode(package.appDescriptorPath());
            projectNode->addFileNodes(QList<ProjectExplorer::FileNode*>() << fileNode);
        }
    }
}

bool BarDescriptorFileNodeManager::createBarDescriptor(ProjectExplorer::Project *project,
                                                       const QString &barDescriptorPath,
                                                       ProjectExplorer::ProjectNode *projectNode)
{
    const QString projectName = QFileInfo(projectNode->path()).completeBaseName();

    QmakeProjectManager::QmakeProFileNode *proFileNode =
            qobject_cast<QmakeProjectManager::QmakeProFileNode*>(projectNode);
    QTC_ASSERT(proFileNode, return false);
    const QString targetName = proFileNode->targetInformation().target;

    const QFile barDescriptorFile(barDescriptorPath);
    if (barDescriptorFile.exists())
        return false;

    bool skipFileCreation = project->namedSettings(QLatin1String(SKIP_BAR_DESCRIPTOR_CREATION_KEY)).toBool();

    if (skipFileCreation)
        return false;

    QDialogButtonBox::StandardButton button = Utils::CheckableMessageBox::question(Core::ICore::mainWindow(),
                                                tr("Setup Application Descriptor File"),
                                                tr("You need to set up a bar descriptor file to enable "
                                                   "packaging.\nDo you want Qt Creator to generate it for your project (%1)?")
                                                .arg(project->projectFilePath().toUserOutput()),
                                                tr("Don't ask again for this project"), &skipFileCreation);

    if (button != QDialogButtonBox::Yes) {
        project->setNamedSettings(QLatin1String(SKIP_BAR_DESCRIPTOR_CREATION_KEY), skipFileCreation);
        return false;
    }

    QString barDescriptorTemplate;
    QtSupport::QtVersionNumber qtVersion =
            QtSupport::QtKitInformation::qtVersion(project->activeTarget()->kit())->qtVersion();
    if (qtVersion >= QtSupport::QtVersionNumber(5, 0, 0))
        barDescriptorTemplate = Core::ICore::resourcePath()
                + QLatin1String("/templates/wizards/bb-qt5-bardescriptor/bar-descriptor.xml");
    else
        barDescriptorTemplate = Core::ICore::resourcePath()
                + QLatin1String("/templates/wizards/bb-bardescriptor/bar-descriptor.xml");

    Utils::FileReader reader;
    if (!reader.fetch(barDescriptorTemplate)) {
        Core::MessageManager::write(tr("Cannot set up application descriptor file: "
                                       "Reading the bar descriptor template failed."));
        return false;
    }

    QString content = QString::fromUtf8(reader.data());
    content.replace(QLatin1String("PROJECTNAME"), projectName);
    content.replace(QLatin1String("TARGETNAME"), targetName);
    content.replace(QLatin1String("ID"), QLatin1String("com.example.") + projectName);

    if (project->projectDirectory().appendPath(QLatin1String("qml")).exists())
        content.replace(QLatin1String("</qnx>"),
                        QLatin1String("    <asset path=\"qml\">qml</asset>\n</qnx>"));

    Utils::FileSaver writer(barDescriptorFile.fileName(), QIODevice::WriteOnly);
    writer.write(content.toUtf8());
    if (!writer.finalize()) {
        Core::MessageManager::write(tr("Cannot set up application descriptor file: "
                                       "Writing the bar descriptor file failed."));
        return false;
    }

    // Check if the Qt environment matches the Qt bundle mode in the deployment step
    updateBarDescriptor(barDescriptorPath, project->activeTarget(), true);

    return true;
}

void BarDescriptorFileNodeManager::updateBarDescriptor(const QString &barDescriptorPath,
                                                       ProjectExplorer::Target *target,
                                                       bool skipConfirmation)
{
    BarDescriptorDocument doc;
    QString errorString;
    if (!doc.open(&errorString, barDescriptorPath)) {
        QMessageBox::warning(Core::ICore::mainWindow(), tr("Error"),
                             tr("Cannot open BAR application descriptor file"));
        return;
    }

    QList<Utils::EnvironmentItem> envItems =
            doc.value(BarDescriptorDocument::env).value<QList<Utils::EnvironmentItem> >();

    BlackBerryQtVersion *qtVersion =
            dynamic_cast<BlackBerryQtVersion *>(QtSupport::QtKitInformation::qtVersion(target->kit()));
    if (!qtVersion)
        return;

    ProjectExplorer::BuildStepList *stepList = target->activeDeployConfiguration()->stepList();
    foreach (ProjectExplorer::BuildStep *step, stepList->steps()) {
        BlackBerryCreatePackageStep *createPackageStep = dynamic_cast<BlackBerryCreatePackageStep *>(step);
        if (createPackageStep) {
            createPackageStep->doUpdateAppDescriptorFile(barDescriptorPath,
                                                         BlackBerryCreatePackageStep::QtEnvironment,
                                                         skipConfirmation);
        }
    }
}

void BarDescriptorFileNodeManager::removeBarDescriptorNodes(ProjectExplorer::Project *project)
{
    if (!project)
        return;

    ProjectExplorer::ProjectNode *rootProject = project->rootProjectNode();
    if (!rootProject)
        return;

    BarDescriptorFileNode *existingNode = findBarDescriptorFileNode(rootProject);
    if (existingNode)
        rootProject->removeFileNodes(QList<ProjectExplorer::FileNode*>() << existingNode);

    // Also remove the bar descriptor nodes for sub-projects
    removeBarDescriptorNodes(rootProject);
}

void BarDescriptorFileNodeManager::removeBarDescriptorNodes(ProjectExplorer::ProjectNode *parent)
{
    QList<ProjectExplorer::ProjectNode*> projectNodes = parent->subProjectNodes();
    foreach (ProjectExplorer::ProjectNode *projectNode, projectNodes) {
        BarDescriptorFileNode *existingNode = findBarDescriptorFileNode(projectNode);
        if (existingNode)
            projectNode->removeFileNodes(QList<ProjectExplorer::FileNode*>() << existingNode);

        removeBarDescriptorNodes(projectNode);
    }
}

BarDescriptorFileNode *BarDescriptorFileNodeManager::findBarDescriptorFileNode(ProjectExplorer::ProjectNode *parent) const
{
    QTC_ASSERT(parent, return 0);

    QList<ProjectExplorer::FileNode*> fileNodes = parent->fileNodes();
    foreach (ProjectExplorer::FileNode *fileNode, fileNodes) {
        BarDescriptorFileNode *barDescriptorNode = qobject_cast<BarDescriptorFileNode*>(fileNode);
        if (barDescriptorNode)
            return barDescriptorNode;
    }

    return 0;
}

ProjectExplorer::ProjectNode *BarDescriptorFileNodeManager::findProjectNode(ProjectExplorer::ProjectNode *parent,
                                                                            const QString &projectFilePath) const
{
    QTC_ASSERT(parent, return 0);

    QList<ProjectExplorer::ProjectNode*> projectNodes = parent->subProjectNodes();
    foreach (ProjectExplorer::ProjectNode *projectNode, projectNodes) {
        if (projectNode->path() == projectFilePath) {
            return projectNode;
        } else if (!projectNode->subProjectNodes().isEmpty()) {
            ProjectExplorer::ProjectNode *hit = findProjectNode(projectNode, projectFilePath);
            if (hit)
                return hit;
        }
    }

    return 0;
}
<|endoftext|>