<commit_before>/*
 * File:   KrakenBattle.cpp
 * Author: Kjell Hedstrom
 *
 * Created on November 24, 2015
 */

#include "KrakenBattle.h"
#include <algorithm>
#include <iterator>
#include <g3log/g3log.hpp>

namespace {
   const std::string emptyUUID = {"00000000-0000-0000-0000-000000000000"};
   const std::vector<uint8_t> emptyData = {};
}

namespace KrakenBattle {

   /**
   * formats the data to send to the Harpoon according to the specification for
   * data transfers
   * @param uuid
   * @param type one of Data, Done, Error, End
   * @param data to send (optional, used for SendType::Data)
   * @param error message (optional, used for SendType::Error)
   * @return merged data uuid<SendType>optional:data/optional:error_msg
   */
   Kraken::Chunks  MergeData(const std::string& uuid, const KrakenBattle::SendType& type, const Kraken::Chunks& data, const std::string& error_msg) {
      const std::string sendType = EnumToString(type);
      const std::string& uuidToSend = (SendType::End == type ? emptyUUID : uuid);
      std::vector<uint8_t> merged;
      merged.reserve(uuidToSend.size() + sendType.size() + data.size() + error_msg.size());
      // uuid, type, possible:data, possible:error
      std::copy(uuidToSend.begin(), uuidToSend.end(), std::back_inserter(merged));
      std::copy(sendType.begin(), sendType.end(), std::back_inserter(merged));

      if (SendType::Data == type) {
         std::copy(data.begin(), data.end(), std::back_inserter(merged));
      } else if (SendType::Error == type) {
         std::copy(error_msg.begin(), error_msg.end(), std::back_inserter(merged));
      }
      return merged;
   }

   /**
   *  Send  Chunks over Kraken to a Harpoon
   *  If chunks to send is more than the @ref Kraken::MaxChunkSizeInBytes() then
   *  it will split up the sending into several separate sends (@ref Kraken::SendTidalWave)
   * @param kraken to send over
   * @param uuid
   * @param sendState
   * @param chunk to send (optional content, for SendType::Data)
   * @param error to send (optional content, for SendType::Error)
   */
   Kraken::Battling SendChunks(Kraken* kraken, const std::string& uuid, const KrakenBattle::SendType& sendState, const Kraken::Chunks& chunk, const std::string& error) {
      const size_t kSplitSize = kraken->MaxChunkSizeInBytes();
      const auto kTotalToSend = MergeData(uuid, sendState, chunk, error);
      const size_t kTotalSize = kTotalToSend.size();
      const Kraken::Chunks kHeader = MergeData(uuid, sendState, {}, {}); // {}: ignored
      const size_t kSplitSizeAdjusted = kSplitSize - kHeader.size();
      CHECK(kSplitSize > kHeader.size());

      auto result = Kraken::Battling::CONTINUE;

      if (kTotalSize <= kSplitSize) {
         result = kraken->SendTidalWave(kTotalToSend);
      } else {

         std::vector<uint8_t> toSend;
         toSend.reserve(kSplitSize);
         toSend.assign(kTotalToSend.begin(), kTotalToSend.begin() + kSplitSize);

         CHECK(toSend.size() == kSplitSize);
         result = kraken->SendTidalWave(toSend);

         for (size_t i = kSplitSize; i <= kTotalSize; i += kSplitSizeAdjusted) {
            if (result != Kraken::Battling::CONTINUE) {
               LOG(WARNING) << "Sending UUID: " << uuid << ", #split break: " << i << ", kTotalSize: " << kTotalSize
                            << ", kSplitSizeAdjusted: " << kSplitSizeAdjusted << ", result: " << static_cast<int>(result);
               break;
            }

            toSend.assign(kHeader.begin(), kHeader.end());
            const size_t kLeftSize = kTotalSize - i;
            const size_t kChunkSize = std::min(kLeftSize, kSplitSizeAdjusted);
            std::copy(kTotalToSend.begin() + i,
                      kTotalToSend.begin() + i + kChunkSize,
                      std::back_inserter(toSend));
            LOG(INFO) << "Sending UUID: " << uuid << ", #split: " << i << ", toSend size: " << toSend.size();
            result = kraken->SendTidalWave(toSend);
         }
      }
      return result;
   }

   /**
   * Forward  chunks to the client. This will be repeatedly called until an error
   * occurrs (interrupt, timeout) or all is transmitted
   * @param kraken to send the harpoon/client
   * @param uuid to for unique identification
   * @param chunk to send to the client should have valid data on SendState::Data
   * @param sendState (End, Done, Data, Error)
   * @param error should have meaningful content on  SendState::Error
   */
   KrakenBattle::ProgressType  ForwardChunksToClient(Kraken* kraken, const std::string& uuid, const Kraken::Chunks& chunk,
         const KrakenBattle::SendType& sendState, const std::string& error) {
      auto sendingResult = SendChunks(kraken, uuid, sendState, chunk, error);
      bool result = (Kraken::Battling::CONTINUE == sendingResult);
      LOG_IF(WARNING, (!result)) << "Failed to send 'SendTidalWave'" << ", uuid: " << uuid
                                 << ", type: " << KrakenBattle::EnumToString(sendState);

      if (SendType::End == sendState) {
         sendingResult = kraken->FinalBreach();
         result = (Kraken::Battling::CONTINUE == sendingResult);
         LOG_IF(WARNING, (!result)) << "Failed to send 'FinalBreach'" << ", uuid: " << uuid
                                    << ", type: " << KrakenBattle::EnumToString(sendState);
      }

      auto status = KrakenBattle::ProgressType::Stop;
      if (result) {
         status = KrakenBattle::ProgressType::Continue;
      }
      return status;
   }

   std::string EnumToString(const KrakenBattle::SendType& type) {
      std::string textType = "<ERROR>";
      switch (type) {
         case SendType::Data : textType = "<DATA>"; break;
         case SendType::Done : textType = "<DONE>"; break;
         case SendType::Error : textType = "<ERROR>"; break;
         case SendType::End : textType = "<END>"; break;
         default:
            LOG(FATAL) << "Unknown Send::Type: " << static_cast<int>(type);
      }
      return textType;
   }

   std::string EnumToString(const KrakenBattle::ProgressType& type) {
      std::string textType = "<ERROR>";
      switch (type) {
         case ProgressType::Stop : textType = "ProgressType::Stop"; break;
         case ProgressType::Continue : textType = "ProgressType::Continue"; break;
         default:
            LOG(FATAL) << "Unknown Send::Type: " << static_cast<int>(type);
      }
      return textType;
   }
} // namespace KrakenBattle
<commit_msg>Fixed comment<commit_after>/*
 * File:   KrakenBattle.cpp
 * Author: Kjell Hedstrom
 *
 * Created on November 24, 2015
 */

#include "KrakenBattle.h"
#include <algorithm>
#include <iterator>
#include <g3log/g3log.hpp>

namespace {
   const std::string emptyUUID = {"00000000-0000-0000-0000-000000000000"};
   const std::vector<uint8_t> emptyData = {};
}

namespace KrakenBattle {

   /**
   * formats the data to send to the Harpoon according to the specification for
   * data transfers
   * @param uuid
   * @param type one of Data, Done, Error, End
   * @param data to send (optional, used for SendType::Data)
   * @param error message (optional, used for SendType::Error)
   * @return merged data uuid<SendType>optional:data/optional:error_msg
   */
   Kraken::Chunks  MergeData(const std::string& uuid, const KrakenBattle::SendType& type, const Kraken::Chunks& data, const std::string& error_msg) {
      const std::string sendType = EnumToString(type);
      const std::string& uuidToSend = (SendType::End == type ? emptyUUID : uuid);
      std::vector<uint8_t> merged;
      merged.reserve(uuidToSend.size() + sendType.size() + data.size() + error_msg.size());
      // uuid, type, possible:data, possible:error
      std::copy(uuidToSend.begin(), uuidToSend.end(), std::back_inserter(merged));
      std::copy(sendType.begin(), sendType.end(), std::back_inserter(merged));

      if (SendType::Data == type) {
         std::copy(data.begin(), data.end(), std::back_inserter(merged));
      } else if (SendType::Error == type) {
         std::copy(error_msg.begin(), error_msg.end(), std::back_inserter(merged));
      }
      return merged;
   }

   /**
   *  Send  Chunks over Kraken to a Harpoon
   *  If chunks to send is more than the @ref Kraken::MaxChunkSizeInBytes() then
   *  it will split up the sending into several separate sends (@ref Kraken::SendTidalWave)
   * @param kraken to send over
   * @param uuid
   * @param sendState
   * @param chunk to send (optional content, for SendType::Data)
   * @param error to send (optional content, for SendType::Error)
   */
   Kraken::Battling SendChunks(Kraken* kraken, const std::string& uuid, const KrakenBattle::SendType& sendState, const Kraken::Chunks& chunk, const std::string& error) {
      const size_t kSplitSize = kraken->MaxChunkSizeInBytes();
      const auto kTotalToSend = MergeData(uuid, sendState, chunk, error);
      const size_t kTotalSize = kTotalToSend.size();
      const Kraken::Chunks kHeader = MergeData(uuid, sendState, {}, {}); // {}: ignored
      const size_t kSplitSizeAdjusted = kSplitSize - kHeader.size();
      CHECK(kSplitSize > kHeader.size());

      auto result = Kraken::Battling::CONTINUE;

      if (kTotalSize <= kSplitSize) {
         result = kraken->SendTidalWave(kTotalToSend);
      } else {

         std::vector<uint8_t> toSend;
         toSend.reserve(kSplitSize);
         toSend.assign(kTotalToSend.begin(), kTotalToSend.begin() + kSplitSize);

         CHECK(toSend.size() == kSplitSize);
         result = kraken->SendTidalWave(toSend);

         for (size_t i = kSplitSize; i <= kTotalSize; i += kSplitSizeAdjusted) {
            if (result != Kraken::Battling::CONTINUE) {
               LOG(WARNING) << "Sending UUID: " << uuid << ", #split break: " << i << ", kTotalSize: " << kTotalSize
                            << ", kSplitSizeAdjusted: " << kSplitSizeAdjusted << ", result: " << static_cast<int>(result);
               break;
            }

            toSend.assign(kHeader.begin(), kHeader.end());
            const size_t kLeftSize = kTotalSize - i;
            const size_t kChunkSize = std::min(kLeftSize, kSplitSizeAdjusted);
            std::copy(kTotalToSend.begin() + i,
                      kTotalToSend.begin() + i + kChunkSize,
                      std::back_inserter(toSend));
            LOG(INFO) << "Sending UUID: " << uuid << ", #split: " << i << ", toSend size: " << toSend.size();
            result = kraken->SendTidalWave(toSend);
         }
      }
      return result;
   }

   /**
   * Forward  chunks to the client. This can be repeatedly called until an error
   * occurrs (interrupt, timeout) or all is transmitted
   * @param kraken to send the harpoon/client
   * @param uuid to for unique identification
   * @param chunk to send to the client should have valid data on SendState::Data
   * @param sendState (End, Done, Data, Error)
   * @param error should have meaningful content on  SendState::Error
   */
   KrakenBattle::ProgressType  ForwardChunksToClient(Kraken* kraken, const std::string& uuid, const Kraken::Chunks& chunk,
         const KrakenBattle::SendType& sendState, const std::string& error) {
      auto sendingResult = SendChunks(kraken, uuid, sendState, chunk, error);
      bool result = (Kraken::Battling::CONTINUE == sendingResult);
      LOG_IF(WARNING, (!result)) << "Failed to send 'SendTidalWave'" << ", uuid: " << uuid
                                 << ", type: " << KrakenBattle::EnumToString(sendState);

      if (SendType::End == sendState) {
         sendingResult = kraken->FinalBreach();
         result = (Kraken::Battling::CONTINUE == sendingResult);
         LOG_IF(WARNING, (!result)) << "Failed to send 'FinalBreach'" << ", uuid: " << uuid
                                    << ", type: " << KrakenBattle::EnumToString(sendState);
      }

      auto status = KrakenBattle::ProgressType::Stop;
      if (result) {
         status = KrakenBattle::ProgressType::Continue;
      }
      return status;
   }

   std::string EnumToString(const KrakenBattle::SendType& type) {
      std::string textType = "<ERROR>";
      switch (type) {
         case SendType::Data : textType = "<DATA>"; break;
         case SendType::Done : textType = "<DONE>"; break;
         case SendType::Error : textType = "<ERROR>"; break;
         case SendType::End : textType = "<END>"; break;
         default:
            LOG(FATAL) << "Unknown Send::Type: " << static_cast<int>(type);
      }
      return textType;
   }

   std::string EnumToString(const KrakenBattle::ProgressType& type) {
      std::string textType = "<ERROR>";
      switch (type) {
         case ProgressType::Stop : textType = "ProgressType::Stop"; break;
         case ProgressType::Continue : textType = "ProgressType::Continue"; break;
         default:
            LOG(FATAL) << "Unknown Send::Type: " << static_cast<int>(type);
      }
      return textType;
   }
} // namespace KrakenBattle
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version
 * 2 of the License, or (at your option) any later version.
 */
// DebugDlg.cpp : t@C
//

#include "stdafx.h"
#include "MZ3.h"
#include "DebugDlg.h"
#include "util.h"
#include "util_gui.h"
#include "MixiParserUtil.h"

// CDebugDlg _CAO

IMPLEMENT_DYNAMIC(CDebugDlg, CDialog)

CDebugDlg::CDebugDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CDebugDlg::IDD, pParent)
{

}

CDebugDlg::~CDebugDlg()
{
}

void CDebugDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_DEBUG_LIST, m_List);
}

BEGIN_MESSAGE_MAP(CDebugDlg, CDialog)
	ON_WM_SIZE()
	ON_NOTIFY(NM_CLICK, IDC_DEBUG_LIST, &CDebugDlg::OnNMClickDebugList)
	ON_NOTIFY(LVN_KEYDOWN, IDC_DEBUG_LIST, &CDebugDlg::OnLvnKeydownDebugList)
	ON_NOTIFY(NM_DBLCLK, IDC_DEBUG_LIST, &CDebugDlg::OnNMDblclkDebugList)
END_MESSAGE_MAP()

// CDebugDlg bZ[W nh

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

	// tHg
	m_List.SetFont( &theApp.m_font );

	// Jǉ
	m_List.InsertColumn( 0, L"", LVCFMT_LEFT, 150, -1 );
	m_List.InsertColumn( 1, L"e", LVCFMT_LEFT, 300, -1 );
	// sI[h̐ݒ
	ListView_SetExtendedListViewStyle((HWND)m_List.m_hWnd, LVS_EX_FULLROWSELECT);

	// vfǉ
	int idx = 0;

	CMixiData* data = m_data;

	m_List.InsertItem( idx, L"ANZX" );
	m_List.SetItemText( idx, 1, theApp.m_accessTypeInfo.getShortText( data->GetAccessType() ) );
	idx++;

	m_List.InsertItem( idx, L"VACYL[" );
	m_List.SetItemText( idx, 1, CString(theApp.m_accessTypeInfo.getSerializeKey( data->GetAccessType() )) );
	idx++;

	m_List.InsertItem( idx, L"Date" );
	m_List.SetItemText( idx, 1, data->GetDate() );
	idx++;

	m_List.InsertItem( idx, L"Name" );
	m_List.SetItemText( idx, 1, data->GetName() );
	idx++;

	m_List.InsertItem( idx, L"Author" );
	m_List.SetItemText( idx, 1, data->GetAuthor() );
	idx++;

	m_List.InsertItem( idx, L"AuthorID" );
	m_List.SetItemText( idx, 1, util::int2str( data->GetAuthorID() ) );
	idx++;

	m_List.InsertItem( idx, L"Title" );
	m_List.SetItemText( idx, 1, data->GetTitle() );
	idx++;

	m_List.InsertItem( idx, L"URL" );
	m_List.SetItemText( idx, 1, data->GetURL() );
	idx++;

	m_List.InsertItem( idx, L"POSTAhX" );
	m_List.SetItemText( idx, 1, data->GetPostAddress() );
	idx++;

	m_List.InsertItem( idx, L"LID" );
	m_List.SetItemText( idx, 1, util::int2str( data->GetID() ) );
	idx++;

	m_List.InsertItem( idx, L"Rgԍ" );
	m_List.SetItemText( idx, 1, util::int2str( data->GetCommentIndex() ) );
	idx++;

	m_List.InsertItem( idx, L"Rg" );
	m_List.SetItemText( idx, 1, util::int2str( data->GetCommentCount() ) );
	idx++;

	m_List.InsertItem( idx, L"ǃRgԍ" );
	int lastIndex = mixi::ParserUtil::GetLastIndexFromIniFile(*data);
	m_List.SetItemText( idx, 1, util::int2str( lastIndex ) );
	idx++;

	m_List.InsertItem( idx, L"POST" );
	m_List.SetItemText( idx, 1, data->GetContentType() );
	idx++;

	m_List.InsertItem( idx, L"I[i[ID" );
	m_List.SetItemText( idx, 1, util::int2str( data->GetOwnerID() ) );
	idx++;

	m_List.InsertItem( idx, L"}C~N" );
	m_List.SetItemText( idx, 1, data->IsMyMixi() ? L"true" : L"false" );
	idx++;

//	m_List.InsertItem( idx, L"OuO" );
//	m_List.SetItemText( idx, 1, data->IsOtherDiary() ? L"YES" : L"NO" );
//	idx++;

	m_List.InsertItem( idx, L"uEYURL" );
	m_List.SetItemText( idx, 1, data->GetBrowseUri() );
	idx++;

	m_List.InsertItem( idx, L"*BodyArray" );
	m_List.SetItemText( idx, 1, util::int2str( data->GetBodySize() ) );
	m_List.SetItemData( idx, (DWORD_PTR)L"body" );
	idx++;

	m_List.InsertItem( idx, L"*ImageArray" );
	m_List.SetItemText( idx, 1, util::int2str( data->GetImageCount() ) );
	m_List.SetItemData( idx, (DWORD_PTR)L"image" );
	idx++;

	m_List.InsertItem( idx, L"oN" );
	m_List.SetItemText( idx, 1, util::int2str( data->m_linkList.size() ) );
//	m_List.SetItemData( idx, (DWORD_PTR)L"link_list" );
	idx++;

	m_List.InsertItem( idx, L"y[WύXN" );
	m_List.SetItemText( idx, 1, util::int2str( data->m_linkPage.size() ) );
//	m_List.SetItemData( idx, (DWORD_PTR)L"link_page" );
	idx++;

	m_List.InsertItem( idx, L"qvf" );
	m_List.SetItemText( idx, 1, util::int2str( data->GetChildrenSize() ) );
	idx++;

	m_List.InsertItem( idx, L"logfile" );
	m_List.SetItemText( idx, 1, util::MakeLogfilePath(*data) );
	idx++;

	m_List.InsertItem( idx, L"logfile-exist" );
	m_List.SetItemText( idx, 1, util::ExistFile(util::MakeLogfilePath(*data)) ? L"true" : L"false" );
	idx++;

	m_List.InsertItem( idx, L"XLtH_" );
	m_List.SetItemText( idx, 1, theApp.m_filepath.skinFolder );
	idx++;

	m_List.InsertItem( idx, L"XL" );
	m_List.SetItemText( idx, 1, theApp.m_optionMng.m_strSkinname );
	idx++;

	m_List.InsertItem( idx, L"MZ3Data CX^X" );
	m_List.SetItemText( idx, 1, util::int2str( data->GetInstanceCount() ) );
	idx++;

	m_List.SetItemState( 0, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED );

#ifndef WINCE
	// ʃTCYύX
	int w = 360;
	int h = 480;
	SetWindowPos( NULL, 0, 0, w, h, SWP_NOMOVE | SWP_NOOWNERZORDER );
#endif

	return TRUE;  // return TRUE unless you set the focus to a control
	// O : OCX vpeB y[W͕K FALSE Ԃ܂B
}

void CDebugDlg::OnSize(UINT nType, int cx, int cy)
{
	CDialog::OnSize(nType, cx, cy);

	if (m_List.GetSafeHwnd()==NULL) {
		return;
	}

	m_List.MoveWindow( 0, 0, cx, cy );
}

void CDebugDlg::OnNMClickDebugList(NMHDR *pNMHDR, LRESULT *pResult)
{

	*pResult = 0;
}

void CDebugDlg::OnLvnKeydownDebugList(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMLVKEYDOWN pLVKeyDow = reinterpret_cast<LPNMLVKEYDOWN>(pNMHDR);
	if (pLVKeyDow->wVKey == VK_RETURN) {
		MyShowSelectedItemInfo();
	}

	*pResult = 0;
}

void CDebugDlg::OnNMDblclkDebugList(NMHDR *pNMHDR, LRESULT *pResult)
{
	MyShowSelectedItemInfo();

	*pResult = 0;
}

void CDebugDlg::MyShowSelectedItemInfo(void)
{
	int idx = util::MyGetListCtrlSelectedItemIndex( m_List );
	if( idx < 0 ) {
		return;
	}

	CString msg;

	// ItemData Ɏʎq΂ɏ]ĕ񐶐
	const CString& strType = (LPCTSTR)m_List.GetItemData(idx);
	if (strType==L"body") {
		msg.Format(L"[%s]", m_data->GetBody());
	} else if (strType==L"image") {
		for (int i=0; i<m_data->GetImageCount(); i++) {
			msg.AppendFormat(L"[%s]\r\n", m_data->GetImage(i));
		}
	} else {
		msg.Format(L"[%s]", m_List.GetItemText(idx,1) );
	}

	MessageBox( msg, m_List.GetItemText(idx,0) );
}
<commit_msg>IDの64bit対応<commit_after>/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version
 * 2 of the License, or (at your option) any later version.
 */
// DebugDlg.cpp : t@C
//

#include "stdafx.h"
#include "MZ3.h"
#include "DebugDlg.h"
#include "util.h"
#include "util_gui.h"
#include "MixiParserUtil.h"

// CDebugDlg _CAO

IMPLEMENT_DYNAMIC(CDebugDlg, CDialog)

CDebugDlg::CDebugDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CDebugDlg::IDD, pParent)
{

}

CDebugDlg::~CDebugDlg()
{
}

void CDebugDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_DEBUG_LIST, m_List);
}

BEGIN_MESSAGE_MAP(CDebugDlg, CDialog)
	ON_WM_SIZE()
	ON_NOTIFY(NM_CLICK, IDC_DEBUG_LIST, &CDebugDlg::OnNMClickDebugList)
	ON_NOTIFY(LVN_KEYDOWN, IDC_DEBUG_LIST, &CDebugDlg::OnLvnKeydownDebugList)
	ON_NOTIFY(NM_DBLCLK, IDC_DEBUG_LIST, &CDebugDlg::OnNMDblclkDebugList)
END_MESSAGE_MAP()

// CDebugDlg bZ[W nh

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

	// tHg
	m_List.SetFont( &theApp.m_font );

	// Jǉ
	m_List.InsertColumn( 0, L"", LVCFMT_LEFT, 150, -1 );
	m_List.InsertColumn( 1, L"e", LVCFMT_LEFT, 300, -1 );
	// sI[h̐ݒ
	ListView_SetExtendedListViewStyle((HWND)m_List.m_hWnd, LVS_EX_FULLROWSELECT);

	// vfǉ
	int idx = 0;

	CMixiData* data = m_data;

	m_List.InsertItem( idx, L"ANZX" );
	m_List.SetItemText( idx, 1, theApp.m_accessTypeInfo.getShortText( data->GetAccessType() ) );
	idx++;

	m_List.InsertItem( idx, L"VACYL[" );
	m_List.SetItemText( idx, 1, CString(theApp.m_accessTypeInfo.getSerializeKey( data->GetAccessType() )) );
	idx++;

	m_List.InsertItem( idx, L"Date" );
	m_List.SetItemText( idx, 1, data->GetDate() );
	idx++;

	m_List.InsertItem( idx, L"Name" );
	m_List.SetItemText( idx, 1, data->GetName() );
	idx++;

	m_List.InsertItem( idx, L"Author" );
	m_List.SetItemText( idx, 1, data->GetAuthor() );
	idx++;

	m_List.InsertItem( idx, L"AuthorID" );
	m_List.SetItemText( idx, 1, util::int2str( data->GetAuthorID() ) );
	idx++;

	m_List.InsertItem( idx, L"Title" );
	m_List.SetItemText( idx, 1, data->GetTitle() );
	idx++;

	m_List.InsertItem( idx, L"URL" );
	m_List.SetItemText( idx, 1, data->GetURL() );
	idx++;

	m_List.InsertItem( idx, L"POSTAhX" );
	m_List.SetItemText( idx, 1, data->GetPostAddress() );
	idx++;

	m_List.InsertItem( idx, L"LID" );
	m_List.SetItemText( idx, 1, util::FormatString(L"%I64d", data->GetID()) );
	idx++;

	m_List.InsertItem( idx, L"Rgԍ" );
	m_List.SetItemText( idx, 1, util::int2str( data->GetCommentIndex() ) );
	idx++;

	m_List.InsertItem( idx, L"Rg" );
	m_List.SetItemText( idx, 1, util::int2str( data->GetCommentCount() ) );
	idx++;

	m_List.InsertItem( idx, L"ǃRgԍ" );
	int lastIndex = mixi::ParserUtil::GetLastIndexFromIniFile(*data);
	m_List.SetItemText( idx, 1, util::int2str( lastIndex ) );
	idx++;

	m_List.InsertItem( idx, L"POST" );
	m_List.SetItemText( idx, 1, data->GetContentType() );
	idx++;

	m_List.InsertItem( idx, L"I[i[ID" );
	m_List.SetItemText( idx, 1, util::int2str( data->GetOwnerID() ) );
	idx++;

	m_List.InsertItem( idx, L"}C~N" );
	m_List.SetItemText( idx, 1, data->IsMyMixi() ? L"true" : L"false" );
	idx++;

//	m_List.InsertItem( idx, L"OuO" );
//	m_List.SetItemText( idx, 1, data->IsOtherDiary() ? L"YES" : L"NO" );
//	idx++;

	m_List.InsertItem( idx, L"uEYURL" );
	m_List.SetItemText( idx, 1, data->GetBrowseUri() );
	idx++;

	m_List.InsertItem( idx, L"*BodyArray" );
	m_List.SetItemText( idx, 1, util::int2str( data->GetBodySize() ) );
	m_List.SetItemData( idx, (DWORD_PTR)L"body" );
	idx++;

	m_List.InsertItem( idx, L"*ImageArray" );
	m_List.SetItemText( idx, 1, util::int2str( data->GetImageCount() ) );
	m_List.SetItemData( idx, (DWORD_PTR)L"image" );
	idx++;

	m_List.InsertItem( idx, L"oN" );
	m_List.SetItemText( idx, 1, util::int2str( data->m_linkList.size() ) );
//	m_List.SetItemData( idx, (DWORD_PTR)L"link_list" );
	idx++;

	m_List.InsertItem( idx, L"y[WύXN" );
	m_List.SetItemText( idx, 1, util::int2str( data->m_linkPage.size() ) );
//	m_List.SetItemData( idx, (DWORD_PTR)L"link_page" );
	idx++;

	m_List.InsertItem( idx, L"qvf" );
	m_List.SetItemText( idx, 1, util::int2str( data->GetChildrenSize() ) );
	idx++;

	m_List.InsertItem( idx, L"logfile" );
	m_List.SetItemText( idx, 1, util::MakeLogfilePath(*data) );
	idx++;

	m_List.InsertItem( idx, L"logfile-exist" );
	m_List.SetItemText( idx, 1, util::ExistFile(util::MakeLogfilePath(*data)) ? L"true" : L"false" );
	idx++;

	m_List.InsertItem( idx, L"XLtH_" );
	m_List.SetItemText( idx, 1, theApp.m_filepath.skinFolder );
	idx++;

	m_List.InsertItem( idx, L"XL" );
	m_List.SetItemText( idx, 1, theApp.m_optionMng.m_strSkinname );
	idx++;

	m_List.InsertItem( idx, L"MZ3Data CX^X" );
	m_List.SetItemText( idx, 1, util::int2str( data->GetInstanceCount() ) );
	idx++;

	m_List.SetItemState( 0, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED );

#ifndef WINCE
	// ʃTCYύX
	int w = 360;
	int h = 480;
	SetWindowPos( NULL, 0, 0, w, h, SWP_NOMOVE | SWP_NOOWNERZORDER );
#endif

	return TRUE;  // return TRUE unless you set the focus to a control
	// O : OCX vpeB y[W͕K FALSE Ԃ܂B
}

void CDebugDlg::OnSize(UINT nType, int cx, int cy)
{
	CDialog::OnSize(nType, cx, cy);

	if (m_List.GetSafeHwnd()==NULL) {
		return;
	}

	m_List.MoveWindow( 0, 0, cx, cy );
}

void CDebugDlg::OnNMClickDebugList(NMHDR *pNMHDR, LRESULT *pResult)
{

	*pResult = 0;
}

void CDebugDlg::OnLvnKeydownDebugList(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMLVKEYDOWN pLVKeyDow = reinterpret_cast<LPNMLVKEYDOWN>(pNMHDR);
	if (pLVKeyDow->wVKey == VK_RETURN) {
		MyShowSelectedItemInfo();
	}

	*pResult = 0;
}

void CDebugDlg::OnNMDblclkDebugList(NMHDR *pNMHDR, LRESULT *pResult)
{
	MyShowSelectedItemInfo();

	*pResult = 0;
}

void CDebugDlg::MyShowSelectedItemInfo(void)
{
	int idx = util::MyGetListCtrlSelectedItemIndex( m_List );
	if( idx < 0 ) {
		return;
	}

	CString msg;

	// ItemData Ɏʎq΂ɏ]ĕ񐶐
	const CString& strType = (LPCTSTR)m_List.GetItemData(idx);
	if (strType==L"body") {
		msg.Format(L"[%s]", m_data->GetBody());
	} else if (strType==L"image") {
		for (int i=0; i<m_data->GetImageCount(); i++) {
			msg.AppendFormat(L"[%s]\r\n", m_data->GetImage(i));
		}
	} else {
		msg.Format(L"[%s]", m_List.GetItemText(idx,1) );
	}

	MessageBox( msg, m_List.GetItemText(idx,0) );
}
<|endoftext|>


<commit_before>
#pragma once

#include "physics/body_centred_body_direction_dynamic_frame.hpp"

#include "geometry/barycentre_calculator.hpp"
#include "geometry/named_quantities.hpp"
#include "geometry/r3x3_matrix.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"

namespace principia {
namespace physics {
namespace internal_body_centred_body_direction_dynamic_frame {

using geometry::Barycentre;
using geometry::Bivector;
using geometry::Displacement;
using geometry::R3x3Matrix;
using geometry::Velocity;
using geometry::Wedge;
using quantities::GravitationalParameter;
using quantities::Length;
using quantities::Pow;
using quantities::Product;
using quantities::Speed;
using quantities::si::Radian;

template<typename InertialFrame, typename ThisFrame>
BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::
BodyCentredBodyDirectionDynamicFrame(
    not_null<Ephemeris<InertialFrame> const*> const ephemeris,
    not_null<MassiveBody const*> const primary,
    not_null<MassiveBody const*> const secondary)
    : ephemeris_(ephemeris),
      primary_(primary),
      secondary_(secondary),
      primary_trajectory_(ephemeris_->trajectory(primary_)),
      secondary_trajectory_(ephemeris_->trajectory(secondary_)) {}

template<typename InertialFrame, typename ThisFrame>
RigidMotion<InertialFrame, ThisFrame>
BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::
    ToThisFrameAtTime(Instant const& t) const {
  DegreesOfFreedom<InertialFrame> const primary_degrees_of_freedom =
      primary_trajectory_->EvaluateDegreesOfFreedom(t, &primary_hint_);
  DegreesOfFreedom<InertialFrame> const secondary_degrees_of_freedom =
      secondary_trajectory_->EvaluateDegreesOfFreedom(t, &secondary_hint_);

  Rotation<InertialFrame, ThisFrame> rotation =
          Rotation<InertialFrame, ThisFrame>::Identity();
  AngularVelocity<InertialFrame> angular_velocity;
  ComputeAngularDegreesOfFreedom(primary_degrees_of_freedom,
                                 secondary_degrees_of_freedom,
                                 &rotation,
                                 &angular_velocity);

  RigidTransformation<InertialFrame, ThisFrame> const
      rigid_transformation(primary_degrees_of_freedom.position(),
                           ThisFrame::origin,
                           rotation.Forget());
  return RigidMotion<InertialFrame, ThisFrame>(
             rigid_transformation,
             angular_velocity,
             primary_degrees_of_freedom.velocity());
}

template<typename InertialFrame, typename ThisFrame>
void BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::
WriteToMessage(not_null<serialization::DynamicFrame*> const message) const {
  auto* const extension =
      message->MutableExtension(
          serialization::BodyCentredBodyDirectionDynamicFrame::extension);
  extension->set_primary(ephemeris_->serialization_index_for_body(primary_));
  extension->set_secondary(
      ephemeris_->serialization_index_for_body(secondary_));
}

template<typename InertialFrame, typename ThisFrame>
not_null<std::unique_ptr<
    BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>>>
BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::ReadFromMessage(
    not_null<Ephemeris<InertialFrame> const*> const ephemeris,
    serialization::BodyCentredBodyDirectionDynamicFrame const & message) {
  return std::make_unique<BodyCentredBodyDirectionDynamicFrame>(
      ephemeris,
      ephemeris->body_for_serialization_index(message.primary()),
      ephemeris->body_for_serialization_index(message.secondary()));
}

template<typename InertialFrame, typename ThisFrame>
Vector<Acceleration, InertialFrame>
BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::
GravitationalAcceleration(Instant const& t,
                          Position<InertialFrame> const& q) const {
  return ephemeris_->ComputeGravitationalAccelerationOnMasslessBody(q, t);
}

template<typename InertialFrame, typename ThisFrame>
AcceleratedRigidMotion<InertialFrame, ThisFrame>
BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::
MotionOfThisFrame(Instant const& t) const {
  DegreesOfFreedom<InertialFrame> const primary_degrees_of_freedom =
      primary_trajectory_->EvaluateDegreesOfFreedom(t, &primary_hint_);
  DegreesOfFreedom<InertialFrame> const secondary_degrees_of_freedom =
      secondary_trajectory_->EvaluateDegreesOfFreedom(t, &secondary_hint_);

  Vector<Acceleration, InertialFrame> const primary_acceleration =
      ephemeris_->ComputeGravitationalAccelerationOnMassiveBody(primary_, t);
  Vector<Acceleration, InertialFrame> const secondary_acceleration =
      ephemeris_->ComputeGravitationalAccelerationOnMassiveBody(secondary_, t);

  auto const to_this_frame = ToThisFrameAtTime(t);

  // TODO(egg): TeX and reference.
  RelativeDegreesOfFreedom<InertialFrame> const primary_secondary =
      primary_degrees_of_freedom - secondary_degrees_of_freedom;
  Displacement<InertialFrame> const& r = primary_secondary.displacement();
  Velocity<InertialFrame> const& ṙ = primary_secondary.velocity();
  Vector<Acceleration, InertialFrame> const r̈ =
      primary_acceleration - secondary_acceleration;
  AngularVelocity<InertialFrame> const& ω =
      to_this_frame.angular_velocity_of_to_frame();
  Variation<AngularVelocity<InertialFrame>> const
      angular_acceleration_of_to_frame =
          (Wedge(r, r̈) * Radian - 2 * ω * InnerProduct(r, ṙ)) /
          InnerProduct(r, r);

  Vector<Acceleration, InertialFrame> const& acceleration_of_to_frame_origin =
      primary_acceleration;
  return AcceleratedRigidMotion<InertialFrame, ThisFrame>(
             to_this_frame,
             angular_acceleration_of_to_frame,
             acceleration_of_to_frame_origin);
}

template<typename InertialFrame, typename ThisFrame>
void BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::
ComputeAngularDegreesOfFreedom(
    DegreesOfFreedom<InertialFrame> const& primary_degrees_of_freedom,
    DegreesOfFreedom<InertialFrame> const& secondary_degrees_of_freedom,
    not_null<Rotation<InertialFrame, ThisFrame>*> const rotation,
    not_null<AngularVelocity<InertialFrame>*> const angular_velocity) {
  RelativeDegreesOfFreedom<InertialFrame> const reference =
       secondary_degrees_of_freedom - primary_degrees_of_freedom;
  Displacement<InertialFrame> const& reference_direction =
      reference.displacement();
  Velocity<InertialFrame> reference_normal = reference.velocity();
  reference_direction.template Orthogonalize<Speed>(&reference_normal);
  Bivector<Product<Length, Speed>, InertialFrame> const reference_binormal =
      Wedge(reference_direction, reference_normal);
  *rotation = Rotation<InertialFrame, ThisFrame>(Normalize(reference_direction),
                                                 Normalize(reference_normal),
                                                 Normalize(reference_binormal));
  *angular_velocity = reference_binormal * Radian /
                      InnerProduct(reference_direction, reference_direction);
}

}  // namespace internal_body_centred_body_direction_dynamic_frame
}  // namespace physics
}  // namespace principia
<commit_msg>Cleanup.<commit_after>
#pragma once

#include "physics/body_centred_body_direction_dynamic_frame.hpp"

#include "geometry/barycentre_calculator.hpp"
#include "geometry/named_quantities.hpp"
#include "geometry/r3x3_matrix.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"

namespace principia {
namespace physics {
namespace internal_body_centred_body_direction_dynamic_frame {

using geometry::Barycentre;
using geometry::Bivector;
using geometry::Displacement;
using geometry::R3x3Matrix;
using geometry::Velocity;
using geometry::Wedge;
using quantities::GravitationalParameter;
using quantities::Length;
using quantities::Pow;
using quantities::Product;
using quantities::Speed;
using quantities::si::Radian;

template<typename InertialFrame, typename ThisFrame>
BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::
BodyCentredBodyDirectionDynamicFrame(
    not_null<Ephemeris<InertialFrame> const*> const ephemeris,
    not_null<MassiveBody const*> const primary,
    not_null<MassiveBody const*> const secondary)
    : ephemeris_(ephemeris),
      primary_(primary),
      secondary_(secondary),
      primary_trajectory_(ephemeris_->trajectory(primary_)),
      secondary_trajectory_(ephemeris_->trajectory(secondary_)) {}

template<typename InertialFrame, typename ThisFrame>
RigidMotion<InertialFrame, ThisFrame>
BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::
    ToThisFrameAtTime(Instant const& t) const {
  DegreesOfFreedom<InertialFrame> const primary_degrees_of_freedom =
      primary_trajectory_->EvaluateDegreesOfFreedom(t, &primary_hint_);
  DegreesOfFreedom<InertialFrame> const secondary_degrees_of_freedom =
      secondary_trajectory_->EvaluateDegreesOfFreedom(t, &secondary_hint_);

  Rotation<InertialFrame, ThisFrame> rotation =
          Rotation<InertialFrame, ThisFrame>::Identity();
  AngularVelocity<InertialFrame> angular_velocity;
  ComputeAngularDegreesOfFreedom(primary_degrees_of_freedom,
                                 secondary_degrees_of_freedom,
                                 &rotation,
                                 &angular_velocity);

  RigidTransformation<InertialFrame, ThisFrame> const
      rigid_transformation(primary_degrees_of_freedom.position(),
                           ThisFrame::origin,
                           rotation.Forget());
  return RigidMotion<InertialFrame, ThisFrame>(
             rigid_transformation,
             angular_velocity,
             primary_degrees_of_freedom.velocity());
}

template<typename InertialFrame, typename ThisFrame>
void BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::
WriteToMessage(not_null<serialization::DynamicFrame*> const message) const {
  auto* const extension =
      message->MutableExtension(
          serialization::BodyCentredBodyDirectionDynamicFrame::extension);
  extension->set_primary(ephemeris_->serialization_index_for_body(primary_));
  extension->set_secondary(
      ephemeris_->serialization_index_for_body(secondary_));
}

template<typename InertialFrame, typename ThisFrame>
not_null<std::unique_ptr<
    BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>>>
BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::ReadFromMessage(
    not_null<Ephemeris<InertialFrame> const*> const ephemeris,
    serialization::BodyCentredBodyDirectionDynamicFrame const & message) {
  return std::make_unique<BodyCentredBodyDirectionDynamicFrame>(
      ephemeris,
      ephemeris->body_for_serialization_index(message.primary()),
      ephemeris->body_for_serialization_index(message.secondary()));
}

template<typename InertialFrame, typename ThisFrame>
Vector<Acceleration, InertialFrame>
BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::
GravitationalAcceleration(Instant const& t,
                          Position<InertialFrame> const& q) const {
  return ephemeris_->ComputeGravitationalAccelerationOnMasslessBody(q, t);
}

template<typename InertialFrame, typename ThisFrame>
AcceleratedRigidMotion<InertialFrame, ThisFrame>
BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::
MotionOfThisFrame(Instant const& t) const {
  DegreesOfFreedom<InertialFrame> const primary_degrees_of_freedom =
      primary_trajectory_->EvaluateDegreesOfFreedom(t, &primary_hint_);
  DegreesOfFreedom<InertialFrame> const secondary_degrees_of_freedom =
      secondary_trajectory_->EvaluateDegreesOfFreedom(t, &secondary_hint_);

  Vector<Acceleration, InertialFrame> const primary_acceleration =
      ephemeris_->ComputeGravitationalAccelerationOnMassiveBody(primary_, t);
  Vector<Acceleration, InertialFrame> const secondary_acceleration =
      ephemeris_->ComputeGravitationalAccelerationOnMassiveBody(secondary_, t);

  auto const to_this_frame = ToThisFrameAtTime(t);

  // TODO(egg): TeX and reference.
  RelativeDegreesOfFreedom<InertialFrame> const secondary_primary =
      secondary_degrees_of_freedom - primary_degrees_of_freedom;
  Displacement<InertialFrame> const& r = secondary_primary.displacement();
  Velocity<InertialFrame> const& ṙ = secondary_primary.velocity();
  Vector<Acceleration, InertialFrame> const r̈ =
      secondary_acceleration - primary_acceleration;
  AngularVelocity<InertialFrame> const& ω =
      to_this_frame.angular_velocity_of_to_frame();
  Variation<AngularVelocity<InertialFrame>> const
      angular_acceleration_of_to_frame =
          (Wedge(r, r̈) * Radian - 2 * ω * InnerProduct(r, ṙ)) /
          InnerProduct(r, r);

  Vector<Acceleration, InertialFrame> const& acceleration_of_to_frame_origin =
      primary_acceleration;
  return AcceleratedRigidMotion<InertialFrame, ThisFrame>(
             to_this_frame,
             angular_acceleration_of_to_frame,
             acceleration_of_to_frame_origin);
}

template<typename InertialFrame, typename ThisFrame>
void BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::
ComputeAngularDegreesOfFreedom(
    DegreesOfFreedom<InertialFrame> const& primary_degrees_of_freedom,
    DegreesOfFreedom<InertialFrame> const& secondary_degrees_of_freedom,
    not_null<Rotation<InertialFrame, ThisFrame>*> const rotation,
    not_null<AngularVelocity<InertialFrame>*> const angular_velocity) {
  RelativeDegreesOfFreedom<InertialFrame> const reference =
       secondary_degrees_of_freedom - primary_degrees_of_freedom;
  Displacement<InertialFrame> const& reference_direction =
      reference.displacement();
  Velocity<InertialFrame> reference_normal = reference.velocity();
  reference_direction.template Orthogonalize<Speed>(&reference_normal);
  Bivector<Product<Length, Speed>, InertialFrame> const reference_binormal =
      Wedge(reference_direction, reference_normal);
  *rotation = Rotation<InertialFrame, ThisFrame>(Normalize(reference_direction),
                                                 Normalize(reference_normal),
                                                 Normalize(reference_binormal));
  *angular_velocity = reference_binormal * Radian /
                      InnerProduct(reference_direction, reference_direction);
}

}  // namespace internal_body_centred_body_direction_dynamic_frame
}  // namespace physics
}  // namespace principia
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
//-----------------------------------------------------------------------------
#include <SDL2/SDL.h>
//-----------------------------------------------------------------------------
#include "parser_yaml/parser_yaml.h"
#include "log/logger.h"
#include "game.h"
#include "gfx/game_window.h"
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
int main(int argc, char* args[]) {

	Logger::getInstance()->writeError("Error");
	Logger::getInstance()->writeInformation("Info");
	Logger::getInstance()->writeWarning("Warning");

	{
		GameWindow gameWin = GameWindow();
		gameWin.start();
	}

	Logger::getInstance()->writeInformation("Closing down");

	//
	delete (Logger::getInstance());
	//
	exit(0);
}
//-----------------------------------------------------------------------------
<commit_msg>Así también se despacha en seguida<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
//-----------------------------------------------------------------------------
#include <SDL2/SDL.h>
//-----------------------------------------------------------------------------
#include "parser_yaml/parser_yaml.h"
#include "log/logger.h"
#include "game.h"
#include "gfx/game_window.h"
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
int main(int argc, char* args[]) {

	Logger::getInstance()->writeError("Error");
	Logger::getInstance()->writeInformation("Info");
	Logger::getInstance()->writeWarning("Warning");

	GameWindow().start();

	Logger::getInstance()->writeInformation("Closing down");

	//
	delete (Logger::getInstance());
	//
	exit(0);
}
//-----------------------------------------------------------------------------
<|endoftext|>


<commit_before>/*
 * D-Bus AT-SPI, Qt Adaptor
 *
 * Copyright 2008, 2009      Nokia.
 * Copyright 2008, 2009      Codethink Ltd.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include "cache.h"
#include "generated/cache_adaptor.h"

#include "bridge.h"
#include "adaptor.h"

#define QSPI_OBJECT_PATH_CACHE "/org/a11y/atspi/cache"

QSpiDBusCache::QSpiDBusCache(QObject* parent)
    : QObject(parent)
{
    CacheAdaptor *adaptor;
    adaptor = new CacheAdaptor(this);
    QDBusConnection c = QSpiAccessibleBridge::instance()->dBusConnection();
    c.registerObject(QSPI_OBJECT_PATH_CACHE, this, QDBusConnection::ExportAdaptors);
}

void QSpiDBusCache::emitAddAccessible(const QSpiAccessibleCacheItem& item)
{
    emit AddAccessible(item);
}

QSpiAccessibleCacheArray QSpiDBusCache::GetItems()
{
    QList <QSpiAccessibleCacheItem> cacheArray;

    foreach (QSpiAdaptor* obj, spiBridge->cacheObjects()) {
        cacheArray << obj->getCacheItem();
    }
    return cacheArray;
}
<commit_msg>Remove unneded temporary var.<commit_after>/*
 * D-Bus AT-SPI, Qt Adaptor
 *
 * Copyright 2008, 2009      Nokia.
 * Copyright 2008, 2009      Codethink Ltd.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include "cache.h"
#include "generated/cache_adaptor.h"

#include "bridge.h"
#include "adaptor.h"

#define QSPI_OBJECT_PATH_CACHE "/org/a11y/atspi/cache"

QSpiDBusCache::QSpiDBusCache(QObject* parent)
    : QObject(parent)
{
    new CacheAdaptor(this);
    QDBusConnection c = QSpiAccessibleBridge::instance()->dBusConnection();
    c.registerObject(QSPI_OBJECT_PATH_CACHE, this, QDBusConnection::ExportAdaptors);
}

void QSpiDBusCache::emitAddAccessible(const QSpiAccessibleCacheItem& item)
{
    emit AddAccessible(item);
}

QSpiAccessibleCacheArray QSpiDBusCache::GetItems()
{
    QList <QSpiAccessibleCacheItem> cacheArray;

    foreach (QSpiAdaptor* obj, spiBridge->cacheObjects()) {
        cacheArray << obj->getCacheItem();
    }
    return cacheArray;
}
<|endoftext|>


<commit_before>#ifndef RETRIEVER_CACHE_HPP
#define RETRIEVER_CACHE_HPP

#include "list.hpp"
#include <memory>
#include <shared_mutex>
#include <unordered_map>

template <typename K, typename V> class CacheItem : public Item {
public:
  CacheItem(K k, V v) : key(k), value(v){};
  K key;
  V value;
};

template <typename K, typename V> class Cache {
public:
  explicit Cache(const int capacity) : capacity(capacity) {
    lookUpTable = std::unordered_map<K, CacheItem<K, V> *>(capacity);
  };

  void set(const K key, const V value) {
    std::unique_lock<std::shared_mutex> lock(tableSMutex);

    auto mapIt = lookUpTable.find(key);
    if (mapIt == lookUpTable.end()) {
      std::unique_ptr<CacheItem<K, V>> item(new CacheItem<K, V>(key, value));
      if (lookUpTable.size() == capacity) {
        auto toRemove = kList.back;
        kList.remove(toRemove);
        lookUpTable.erase(
            lookUpTable.find(dynamic_cast<CacheItem<K, V> *>(toRemove)->key));
      }
      kList.pushFront(dynamic_cast<Item *>(item.get()));
    } else {
      auto item = mapIt->second;
      item->value = value;
      kList.moveToFront(dynamic_cast<Item *>(item.get()));
    }
  };

  V get(const K key) {
    std::shared_lock<std::shared_mutex> lock(tableSMutex);

    auto mapIt = lookUpTable.find(key);
    if (mapIt == lookUpTable.end()) {
      return V();
    }
    kList.moveToFront(dynamic_cast<Item *>(mapIt->second->get()));
    return mapIt->second->value;
  };

private:
  Cache(){};

  int capacity;
  std::unordered_map<K, std::unique_ptr<CacheItem<K, V>>> lookUpTable;
  std::shared_mutex tableSMutex;
  List kList;
};

#endif
<commit_msg>fix: initialize lookuptable with correct type<commit_after>#ifndef RETRIEVER_CACHE_HPP
#define RETRIEVER_CACHE_HPP

#include "list.hpp"
#include <memory>
#include <shared_mutex>
#include <unordered_map>

template <typename K, typename V> class CacheItem : public Item {
public:
  CacheItem(K k, V v) : key(k), value(v){};
  K key;
  V value;
};

template <typename K, typename V> class Cache {
public:
  explicit Cache(const int capacity) : capacity(capacity) {
    lookUpTable =
        std::unordered_map<K, std::unique_ptr<CacheItem<K, V>>>(capacity);
  };

  void set(const K key, const V value) {
    std::unique_lock<std::shared_mutex> lock(tableSMutex);

    auto mapIt = lookUpTable.find(key);
    if (mapIt == lookUpTable.end()) {
      std::unique_ptr<CacheItem<K, V>> item(new CacheItem<K, V>(key, value));
      if (lookUpTable.size() == capacity) {
        auto toRemove = kList.back;
        kList.remove(toRemove);
        lookUpTable.erase(
            lookUpTable.find(dynamic_cast<CacheItem<K, V> *>(toRemove)->key));
      }
      kList.pushFront(dynamic_cast<Item *>(item.get()));
    } else {
      auto item = mapIt->second;
      item->value = value;
      kList.moveToFront(dynamic_cast<Item *>(item.get()));
    }
  };

  V get(const K key) {
    std::shared_lock<std::shared_mutex> lock(tableSMutex);

    auto mapIt = lookUpTable.find(key);
    if (mapIt == lookUpTable.end()) {
      return V();
    }
    kList.moveToFront(dynamic_cast<Item *>(mapIt->second->get()));
    return mapIt->second->value;
  };

private:
  Cache(){};

  int capacity;
  std::unordered_map<K, std::unique_ptr<CacheItem<K, V>>> lookUpTable;
  std::shared_mutex tableSMutex;
  List kList;
};

#endif
<|endoftext|>


<commit_before>#include "client.hh"

#include "face_registry.hh"
#include "context.hh"
#include "buffer_manager.hh"
#include "buffer_utils.hh"
#include "file.hh"
#include "remote.hh"
#include "option.hh"
#include "option_types.hh"
#include "client_manager.hh"
#include "command_manager.hh"
#include "event_manager.hh"
#include "user_interface.hh"
#include "window.hh"
#include "hash_map.hh"

#include <csignal>
#include <unistd.h>

#include <utility>

namespace Kakoune
{

Client::Client(std::unique_ptr<UserInterface>&& ui,
               std::unique_ptr<Window>&& window,
               SelectionList selections, int pid,
               EnvVarMap env_vars,
               String name,
               OnExitCallback on_exit)
    : m_ui{std::move(ui)}, m_window{std::move(window)},
      m_pid{pid},
      m_on_exit{std::move(on_exit)},
      m_input_handler{std::move(selections), Context::Flags::None,
                      std::move(name)},
      m_env_vars(std::move(env_vars))
{
    m_window->set_client(this);

    context().set_client(*this);
    context().set_window(*m_window);

    m_window->set_dimensions(m_ui->dimensions());
    m_window->options().register_watcher(*this);

    m_ui->set_ui_options(m_window->options()["ui_options"].get<UserInterface::Options>());
    m_ui->set_on_key([this](Key key) {
        if (key == ctrl('c'))
            killpg(getpgrp(), SIGINT);
        else if (key.modifiers & Key::Modifiers::Resize)
        {
            m_window->set_dimensions(key.coord());
            force_redraw();
        }
        else
            m_pending_keys.push_back(key);
    });

    m_window->hooks().run_hook("WinDisplay", m_window->buffer().name(), context());

    force_redraw();
}

Client::~Client()
{
    m_window->options().unregister_watcher(*this);
    m_window->set_client(nullptr);
    // Do not move the selections here, as we need them to be valid
    // in order to correctly destroy the input handler
    ClientManager::instance().add_free_window(std::move(m_window),
                                              context().selections());
}

bool Client::is_ui_ok() const
{
    return m_ui->is_ok();
}

bool Client::process_pending_inputs()
{
    const bool debug_keys = (bool)(context().options()["debug"].get<DebugFlags>() & DebugFlags::Keys);
    // steal keys as we might receive new keys while handling them.
    Vector<Key, MemoryDomain::Client> keys = std::move(m_pending_keys);
    for (auto& key : keys)
    {
        try
        {
            if (debug_keys)
                write_to_debug_buffer(format("Client '{}' got key '{}'",
                                             context().name(), key_to_str(key)));

            if (key == Key::FocusIn)
                context().hooks().run_hook("FocusIn", context().name(), context());
            else if (key == Key::FocusOut)
                context().hooks().run_hook("FocusOut", context().name(), context());
            else
                m_input_handler.handle_key(key);

            context().hooks().run_hook("RawKey", key_to_str(key), context());
        }
        catch (Kakoune::runtime_error& error)
        {
            write_to_debug_buffer(format("Error: {}", error.what()));
            context().print_status({ fix_atom_text(error.what().str()),
                                     context().faces()["Error"] });
            context().hooks().run_hook("RuntimeError", error.what(), context());
        }
    }
    return not keys.empty();
}

void Client::print_status(DisplayLine status_line)
{
    m_status_line = std::move(status_line);
    m_ui_pending |= StatusLine;
}

DisplayCoord Client::dimensions() const
{
    return m_ui->dimensions();
}

String generate_context_info(const Context& context)
{
    String s = "";
    if (context.buffer().is_modified())
        s += "[+]";
    if (context.client().input_handler().is_recording())
        s += format("[recording ({})]", context.client().input_handler().recording_reg());
    if (context.hooks_disabled())
        s += "[no-hooks]";
    if (not(context.buffer().flags() & (Buffer::Flags::File | Buffer::Flags::Debug)))
        s += "[scratch]";
    if (context.buffer().flags() & Buffer::Flags::New)
        s += "[new file]";
    if (context.buffer().flags() & Buffer::Flags::Fifo)
        s += "[fifo]";
    if (context.buffer().flags() & Buffer::Flags::Debug)
        s += "[debug]";
    return s;
}

DisplayLine Client::generate_mode_line() const
{
    DisplayLine modeline;
    try
    {
        const String& modelinefmt = context().options()["modelinefmt"].get<String>();
        HashMap<String, DisplayLine> atoms{{ "mode_info", context().client().input_handler().mode_line() },
                                           { "context_info", {generate_context_info(context()),
                                                              context().faces()["Information"]}}};
        auto expanded = expand(modelinefmt, context(), ShellContext{},
                               [](String s) { return escape(s, '{', '\\'); });
        modeline = parse_display_line(expanded, context().faces(), atoms);
    }
    catch (runtime_error& err)
    {
        write_to_debug_buffer(format("Error while parsing modelinefmt: {}", err.what()));
        modeline.push_back({ "modelinefmt error, see *debug* buffer", context().faces()["Error"] });
    }

    return modeline;
}

void Client::change_buffer(Buffer& buffer)
{
    if (m_buffer_reload_dialog_opened)
        close_buffer_reload_dialog();

    auto* current = &m_window->buffer();
    m_last_buffer = contains(BufferManager::instance(), current) ? current : nullptr;

    auto& client_manager = ClientManager::instance();
    m_window->options().unregister_watcher(*this);
    m_window->set_client(nullptr);
    client_manager.add_free_window(std::move(m_window),
                                   std::move(context().selections()));
    WindowAndSelections ws = client_manager.get_free_window(buffer);

    m_window = std::move(ws.window);
    m_window->set_client(this);
    m_window->options().register_watcher(*this);
    m_ui->set_ui_options(m_window->options()["ui_options"].get<UserInterface::Options>());

    context().selections_write_only() = std::move(ws.selections);
    context().set_window(*m_window);
    m_window->set_dimensions(m_ui->dimensions());

    m_window->hooks().run_hook("WinDisplay", buffer.name(), context());
    force_redraw();
}

static bool is_inline(InfoStyle style)
{
    return style == InfoStyle::Inline or
           style == InfoStyle::InlineAbove or
           style == InfoStyle::InlineBelow;
}

void Client::redraw_ifn()
{
    Window& window = context().window();
    if (window.needs_redraw(context()))
        m_ui_pending |= Draw;

    DisplayLine mode_line = generate_mode_line();
    if (mode_line.atoms() != m_mode_line.atoms())
    {
        m_ui_pending |= StatusLine;
        m_mode_line = std::move(mode_line);
    }

    if (m_ui_pending == 0)
        return;

    auto& faces = context().faces();

    if (m_ui_pending & Draw)
        m_ui->draw(window.update_display_buffer(context()),
                   faces["Default"], faces["BufferPadding"]);

    const bool update_menu_anchor = (m_ui_pending & Draw) and not (m_ui_pending & MenuHide) and
                                    not m_menu.items.empty() and m_menu.style == MenuStyle::Inline;
    if ((m_ui_pending & MenuShow) or update_menu_anchor)
    {
        auto anchor = m_menu.style == MenuStyle::Inline ?
            window.display_position(m_menu.anchor) : DisplayCoord{};
        if (not (m_ui_pending & MenuShow) and m_menu.ui_anchor != anchor)
            m_ui_pending |= anchor ? (MenuShow | MenuSelect) : MenuHide;
        m_menu.ui_anchor = anchor;
    }

    if (m_ui_pending & MenuShow and m_menu.ui_anchor)
        m_ui->menu_show(m_menu.items, *m_menu.ui_anchor,
                        faces["MenuForeground"], faces["MenuBackground"],
                        m_menu.style);
    if (m_ui_pending & MenuSelect and m_menu.ui_anchor)
        m_ui->menu_select(m_menu.selected);
    if (m_ui_pending & MenuHide)
        m_ui->menu_hide();

    const bool update_info_anchor = (m_ui_pending & Draw) and not (m_ui_pending & InfoHide) and
                                    not m_info.content.empty() and is_inline(m_info.style);
    if ((m_ui_pending & InfoShow) or update_info_anchor)
    {
        auto anchor = is_inline(m_info.style) ?
             window.display_position(m_info.anchor) : DisplayCoord{};
        if (not (m_ui_pending & MenuShow) and m_info.ui_anchor != anchor)
            m_ui_pending |= anchor ? InfoShow : InfoHide;
        m_info.ui_anchor = anchor;
    }

    if (m_ui_pending & InfoShow and m_info.ui_anchor)
        m_ui->info_show(m_info.title, m_info.content, *m_info.ui_anchor,
                        faces["Information"], m_info.style);
    if (m_ui_pending & InfoHide)
        m_ui->info_hide();

    if (m_ui_pending & StatusLine)
        m_ui->draw_status(m_status_line, m_mode_line, faces["StatusLine"]);

    auto cursor = m_input_handler.get_cursor_info();
    m_ui->set_cursor(cursor.first, cursor.second);

    m_ui->refresh(m_ui_pending | Refresh);
    m_ui_pending = 0;
}

void Client::force_redraw()
{
    m_ui_pending |= Refresh | Draw | StatusLine |
        (m_menu.items.empty() ? MenuHide : MenuShow | MenuSelect) |
        (m_info.content.empty() ? InfoHide : InfoShow);
}

void Client::reload_buffer()
{
    Buffer& buffer = context().buffer();
    try
    {
        reload_file_buffer(buffer);
        context().print_status({ format("'{}' reloaded", buffer.display_name()),
                                 context().faces()["Information"] });

        m_window->hooks().run_hook("BufReload", buffer.name(), context());
    }
    catch (runtime_error& error)
    {
        context().print_status({ format("error while reloading buffer: '{}'", error.what()),
                                 context().faces()["Error"] });
        buffer.set_fs_timestamp(get_fs_timestamp(buffer.name()));
    }
}

void Client::on_buffer_reload_key(Key key)
{
    auto& buffer = context().buffer();

    auto set_autoreload = [this](Autoreload autoreload) {
        auto* option = &context().options()["autoreload"];
        // Do not touch global autoreload, set it at least at buffer level
        if (&option->manager() == &GlobalScope::instance().options())
            option = &context().buffer().options().get_local_option("autoreload");
        option->set(autoreload);
    };

    if (key == 'y' or key == 'Y' or key == Key::Return)
    {
        reload_buffer();
        if (key == 'Y')
            set_autoreload(Autoreload::Yes);
    }
    else if (key == 'n' or key == 'N' or key == Key::Escape)
    {
        // reread timestamp in case the file was modified again
        buffer.set_fs_timestamp(get_fs_timestamp(buffer.name()));
        print_status({ format("'{}' kept", buffer.display_name()),
                       context().faces()["Information"] });
        if (key == 'N')
            set_autoreload(Autoreload::No);
    }
    else
    {
        print_status({ format("'{}' is not a valid choice", key_to_str(key)),
                       context().faces()["Error"] });
        m_input_handler.on_next_key(KeymapMode::None, [this](Key key, Context&){ on_buffer_reload_key(key); });
        return;
    }

    for (auto& client : ClientManager::instance())
    {
        if (&client->context().buffer() == &buffer and
            client->m_buffer_reload_dialog_opened)
            client->close_buffer_reload_dialog();
    }
}

void Client::close_buffer_reload_dialog()
{
    kak_assert(m_buffer_reload_dialog_opened);
    // Reset first as this might check for reloading.
    m_input_handler.reset_normal_mode();
    m_buffer_reload_dialog_opened = false;
    info_hide(true);
}

void Client::check_if_buffer_needs_reloading()
{
    if (m_buffer_reload_dialog_opened)
        return;

    Buffer& buffer = context().buffer();
    auto reload = context().options()["autoreload"].get<Autoreload>();
    if (not (buffer.flags() & Buffer::Flags::File) or reload == Autoreload::No)
        return;

    const String& filename = buffer.name();
    timespec ts = get_fs_timestamp(filename);
    if (ts == InvalidTime or ts == buffer.fs_timestamp())
        return;
    if (reload == Autoreload::Ask)
    {
        StringView bufname = buffer.display_name();
        info_show(format("reload '{}' ?", bufname),
                  format("'{}' was modified externally\n"
                         " y, <ret>: reload | n, <esc>: keep\n"
                         " Y: always reload | N: always keep\n",
                         bufname), {}, InfoStyle::Modal);

        m_buffer_reload_dialog_opened = true;
        m_input_handler.on_next_key(KeymapMode::None, [this](Key key, Context&){ on_buffer_reload_key(key); });
    }
    else
        reload_buffer();
}

StringView Client::get_env_var(StringView name) const
{
    auto it = m_env_vars.find(name);
    if (it == m_env_vars.end())
        return {};
    return it->value;
}

void Client::on_option_changed(const Option& option)
{
    if (option.name() == "ui_options")
    {
        m_ui->set_ui_options(option.get<UserInterface::Options>());
        m_ui_pending |= Draw;
    }
}

void Client::menu_show(Vector<DisplayLine> choices, BufferCoord anchor, MenuStyle style)
{
    m_menu = Menu{ std::move(choices), anchor, {}, style, -1 };
    m_ui_pending |= MenuShow;
    m_ui_pending &= ~MenuHide;
}

void Client::menu_select(int selected)
{
    m_menu.selected = selected;
    m_ui_pending |= MenuSelect;
    m_ui_pending &= ~MenuHide;
}

void Client::menu_hide()
{
    m_menu = Menu{};
    m_ui_pending |= MenuHide;
    m_ui_pending &= ~(MenuShow | MenuSelect);
}

void Client::info_show(String title, String content, BufferCoord anchor, InfoStyle style)
{
    if (m_info.style == InfoStyle::Modal) // We already have a modal info opened, do not touch it.
        return;

    m_info = Info{ std::move(title), std::move(content), anchor, {}, style };
    m_ui_pending |= InfoShow;
    m_ui_pending &= ~InfoHide;
}

void Client::info_hide(bool even_modal)
{
    if (not even_modal and m_info.style == InfoStyle::Modal)
        return;

    m_info = Info{};
    m_ui_pending |= InfoHide;
    m_ui_pending &= ~InfoShow;
}

}
<commit_msg>Obtain a new window for a client before releasing the current one<commit_after>#include "client.hh"

#include "face_registry.hh"
#include "context.hh"
#include "buffer_manager.hh"
#include "buffer_utils.hh"
#include "file.hh"
#include "remote.hh"
#include "option.hh"
#include "option_types.hh"
#include "client_manager.hh"
#include "command_manager.hh"
#include "event_manager.hh"
#include "user_interface.hh"
#include "window.hh"
#include "hash_map.hh"

#include <csignal>
#include <unistd.h>

#include <utility>

namespace Kakoune
{

Client::Client(std::unique_ptr<UserInterface>&& ui,
               std::unique_ptr<Window>&& window,
               SelectionList selections, int pid,
               EnvVarMap env_vars,
               String name,
               OnExitCallback on_exit)
    : m_ui{std::move(ui)}, m_window{std::move(window)},
      m_pid{pid},
      m_on_exit{std::move(on_exit)},
      m_input_handler{std::move(selections), Context::Flags::None,
                      std::move(name)},
      m_env_vars(std::move(env_vars))
{
    m_window->set_client(this);

    context().set_client(*this);
    context().set_window(*m_window);

    m_window->set_dimensions(m_ui->dimensions());
    m_window->options().register_watcher(*this);

    m_ui->set_ui_options(m_window->options()["ui_options"].get<UserInterface::Options>());
    m_ui->set_on_key([this](Key key) {
        if (key == ctrl('c'))
            killpg(getpgrp(), SIGINT);
        else if (key.modifiers & Key::Modifiers::Resize)
        {
            m_window->set_dimensions(key.coord());
            force_redraw();
        }
        else
            m_pending_keys.push_back(key);
    });

    m_window->hooks().run_hook("WinDisplay", m_window->buffer().name(), context());

    force_redraw();
}

Client::~Client()
{
    m_window->options().unregister_watcher(*this);
    m_window->set_client(nullptr);
    // Do not move the selections here, as we need them to be valid
    // in order to correctly destroy the input handler
    ClientManager::instance().add_free_window(std::move(m_window),
                                              context().selections());
}

bool Client::is_ui_ok() const
{
    return m_ui->is_ok();
}

bool Client::process_pending_inputs()
{
    const bool debug_keys = (bool)(context().options()["debug"].get<DebugFlags>() & DebugFlags::Keys);
    // steal keys as we might receive new keys while handling them.
    Vector<Key, MemoryDomain::Client> keys = std::move(m_pending_keys);
    for (auto& key : keys)
    {
        try
        {
            if (debug_keys)
                write_to_debug_buffer(format("Client '{}' got key '{}'",
                                             context().name(), key_to_str(key)));

            if (key == Key::FocusIn)
                context().hooks().run_hook("FocusIn", context().name(), context());
            else if (key == Key::FocusOut)
                context().hooks().run_hook("FocusOut", context().name(), context());
            else
                m_input_handler.handle_key(key);

            context().hooks().run_hook("RawKey", key_to_str(key), context());
        }
        catch (Kakoune::runtime_error& error)
        {
            write_to_debug_buffer(format("Error: {}", error.what()));
            context().print_status({ fix_atom_text(error.what().str()),
                                     context().faces()["Error"] });
            context().hooks().run_hook("RuntimeError", error.what(), context());
        }
    }
    return not keys.empty();
}

void Client::print_status(DisplayLine status_line)
{
    m_status_line = std::move(status_line);
    m_ui_pending |= StatusLine;
}

DisplayCoord Client::dimensions() const
{
    return m_ui->dimensions();
}

String generate_context_info(const Context& context)
{
    String s = "";
    if (context.buffer().is_modified())
        s += "[+]";
    if (context.client().input_handler().is_recording())
        s += format("[recording ({})]", context.client().input_handler().recording_reg());
    if (context.hooks_disabled())
        s += "[no-hooks]";
    if (not(context.buffer().flags() & (Buffer::Flags::File | Buffer::Flags::Debug)))
        s += "[scratch]";
    if (context.buffer().flags() & Buffer::Flags::New)
        s += "[new file]";
    if (context.buffer().flags() & Buffer::Flags::Fifo)
        s += "[fifo]";
    if (context.buffer().flags() & Buffer::Flags::Debug)
        s += "[debug]";
    return s;
}

DisplayLine Client::generate_mode_line() const
{
    DisplayLine modeline;
    try
    {
        const String& modelinefmt = context().options()["modelinefmt"].get<String>();
        HashMap<String, DisplayLine> atoms{{ "mode_info", context().client().input_handler().mode_line() },
                                           { "context_info", {generate_context_info(context()),
                                                              context().faces()["Information"]}}};
        auto expanded = expand(modelinefmt, context(), ShellContext{},
                               [](String s) { return escape(s, '{', '\\'); });
        modeline = parse_display_line(expanded, context().faces(), atoms);
    }
    catch (runtime_error& err)
    {
        write_to_debug_buffer(format("Error while parsing modelinefmt: {}", err.what()));
        modeline.push_back({ "modelinefmt error, see *debug* buffer", context().faces()["Error"] });
    }

    return modeline;
}

void Client::change_buffer(Buffer& buffer)
{
    if (m_buffer_reload_dialog_opened)
        close_buffer_reload_dialog();

    auto* current = &m_window->buffer();
    m_last_buffer = contains(BufferManager::instance(), current) ? current : nullptr;

    auto& client_manager = ClientManager::instance();
    m_window->options().unregister_watcher(*this);
    m_window->set_client(nullptr);

    WindowAndSelections ws = client_manager.get_free_window(buffer);
    client_manager.add_free_window(std::move(m_window),
                                   std::move(context().selections()));
    m_window = std::move(ws.window);
    m_window->set_client(this);
    m_window->options().register_watcher(*this);
    m_ui->set_ui_options(m_window->options()["ui_options"].get<UserInterface::Options>());

    context().selections_write_only() = std::move(ws.selections);
    context().set_window(*m_window);
    m_window->set_dimensions(m_ui->dimensions());

    m_window->hooks().run_hook("WinDisplay", buffer.name(), context());
    force_redraw();
}

static bool is_inline(InfoStyle style)
{
    return style == InfoStyle::Inline or
           style == InfoStyle::InlineAbove or
           style == InfoStyle::InlineBelow;
}

void Client::redraw_ifn()
{
    Window& window = context().window();
    if (window.needs_redraw(context()))
        m_ui_pending |= Draw;

    DisplayLine mode_line = generate_mode_line();
    if (mode_line.atoms() != m_mode_line.atoms())
    {
        m_ui_pending |= StatusLine;
        m_mode_line = std::move(mode_line);
    }

    if (m_ui_pending == 0)
        return;

    auto& faces = context().faces();

    if (m_ui_pending & Draw)
        m_ui->draw(window.update_display_buffer(context()),
                   faces["Default"], faces["BufferPadding"]);

    const bool update_menu_anchor = (m_ui_pending & Draw) and not (m_ui_pending & MenuHide) and
                                    not m_menu.items.empty() and m_menu.style == MenuStyle::Inline;
    if ((m_ui_pending & MenuShow) or update_menu_anchor)
    {
        auto anchor = m_menu.style == MenuStyle::Inline ?
            window.display_position(m_menu.anchor) : DisplayCoord{};
        if (not (m_ui_pending & MenuShow) and m_menu.ui_anchor != anchor)
            m_ui_pending |= anchor ? (MenuShow | MenuSelect) : MenuHide;
        m_menu.ui_anchor = anchor;
    }

    if (m_ui_pending & MenuShow and m_menu.ui_anchor)
        m_ui->menu_show(m_menu.items, *m_menu.ui_anchor,
                        faces["MenuForeground"], faces["MenuBackground"],
                        m_menu.style);
    if (m_ui_pending & MenuSelect and m_menu.ui_anchor)
        m_ui->menu_select(m_menu.selected);
    if (m_ui_pending & MenuHide)
        m_ui->menu_hide();

    const bool update_info_anchor = (m_ui_pending & Draw) and not (m_ui_pending & InfoHide) and
                                    not m_info.content.empty() and is_inline(m_info.style);
    if ((m_ui_pending & InfoShow) or update_info_anchor)
    {
        auto anchor = is_inline(m_info.style) ?
             window.display_position(m_info.anchor) : DisplayCoord{};
        if (not (m_ui_pending & MenuShow) and m_info.ui_anchor != anchor)
            m_ui_pending |= anchor ? InfoShow : InfoHide;
        m_info.ui_anchor = anchor;
    }

    if (m_ui_pending & InfoShow and m_info.ui_anchor)
        m_ui->info_show(m_info.title, m_info.content, *m_info.ui_anchor,
                        faces["Information"], m_info.style);
    if (m_ui_pending & InfoHide)
        m_ui->info_hide();

    if (m_ui_pending & StatusLine)
        m_ui->draw_status(m_status_line, m_mode_line, faces["StatusLine"]);

    auto cursor = m_input_handler.get_cursor_info();
    m_ui->set_cursor(cursor.first, cursor.second);

    m_ui->refresh(m_ui_pending | Refresh);
    m_ui_pending = 0;
}

void Client::force_redraw()
{
    m_ui_pending |= Refresh | Draw | StatusLine |
        (m_menu.items.empty() ? MenuHide : MenuShow | MenuSelect) |
        (m_info.content.empty() ? InfoHide : InfoShow);
}

void Client::reload_buffer()
{
    Buffer& buffer = context().buffer();
    try
    {
        reload_file_buffer(buffer);
        context().print_status({ format("'{}' reloaded", buffer.display_name()),
                                 context().faces()["Information"] });

        m_window->hooks().run_hook("BufReload", buffer.name(), context());
    }
    catch (runtime_error& error)
    {
        context().print_status({ format("error while reloading buffer: '{}'", error.what()),
                                 context().faces()["Error"] });
        buffer.set_fs_timestamp(get_fs_timestamp(buffer.name()));
    }
}

void Client::on_buffer_reload_key(Key key)
{
    auto& buffer = context().buffer();

    auto set_autoreload = [this](Autoreload autoreload) {
        auto* option = &context().options()["autoreload"];
        // Do not touch global autoreload, set it at least at buffer level
        if (&option->manager() == &GlobalScope::instance().options())
            option = &context().buffer().options().get_local_option("autoreload");
        option->set(autoreload);
    };

    if (key == 'y' or key == 'Y' or key == Key::Return)
    {
        reload_buffer();
        if (key == 'Y')
            set_autoreload(Autoreload::Yes);
    }
    else if (key == 'n' or key == 'N' or key == Key::Escape)
    {
        // reread timestamp in case the file was modified again
        buffer.set_fs_timestamp(get_fs_timestamp(buffer.name()));
        print_status({ format("'{}' kept", buffer.display_name()),
                       context().faces()["Information"] });
        if (key == 'N')
            set_autoreload(Autoreload::No);
    }
    else
    {
        print_status({ format("'{}' is not a valid choice", key_to_str(key)),
                       context().faces()["Error"] });
        m_input_handler.on_next_key(KeymapMode::None, [this](Key key, Context&){ on_buffer_reload_key(key); });
        return;
    }

    for (auto& client : ClientManager::instance())
    {
        if (&client->context().buffer() == &buffer and
            client->m_buffer_reload_dialog_opened)
            client->close_buffer_reload_dialog();
    }
}

void Client::close_buffer_reload_dialog()
{
    kak_assert(m_buffer_reload_dialog_opened);
    // Reset first as this might check for reloading.
    m_input_handler.reset_normal_mode();
    m_buffer_reload_dialog_opened = false;
    info_hide(true);
}

void Client::check_if_buffer_needs_reloading()
{
    if (m_buffer_reload_dialog_opened)
        return;

    Buffer& buffer = context().buffer();
    auto reload = context().options()["autoreload"].get<Autoreload>();
    if (not (buffer.flags() & Buffer::Flags::File) or reload == Autoreload::No)
        return;

    const String& filename = buffer.name();
    timespec ts = get_fs_timestamp(filename);
    if (ts == InvalidTime or ts == buffer.fs_timestamp())
        return;
    if (reload == Autoreload::Ask)
    {
        StringView bufname = buffer.display_name();
        info_show(format("reload '{}' ?", bufname),
                  format("'{}' was modified externally\n"
                         " y, <ret>: reload | n, <esc>: keep\n"
                         " Y: always reload | N: always keep\n",
                         bufname), {}, InfoStyle::Modal);

        m_buffer_reload_dialog_opened = true;
        m_input_handler.on_next_key(KeymapMode::None, [this](Key key, Context&){ on_buffer_reload_key(key); });
    }
    else
        reload_buffer();
}

StringView Client::get_env_var(StringView name) const
{
    auto it = m_env_vars.find(name);
    if (it == m_env_vars.end())
        return {};
    return it->value;
}

void Client::on_option_changed(const Option& option)
{
    if (option.name() == "ui_options")
    {
        m_ui->set_ui_options(option.get<UserInterface::Options>());
        m_ui_pending |= Draw;
    }
}

void Client::menu_show(Vector<DisplayLine> choices, BufferCoord anchor, MenuStyle style)
{
    m_menu = Menu{ std::move(choices), anchor, {}, style, -1 };
    m_ui_pending |= MenuShow;
    m_ui_pending &= ~MenuHide;
}

void Client::menu_select(int selected)
{
    m_menu.selected = selected;
    m_ui_pending |= MenuSelect;
    m_ui_pending &= ~MenuHide;
}

void Client::menu_hide()
{
    m_menu = Menu{};
    m_ui_pending |= MenuHide;
    m_ui_pending &= ~(MenuShow | MenuSelect);
}

void Client::info_show(String title, String content, BufferCoord anchor, InfoStyle style)
{
    if (m_info.style == InfoStyle::Modal) // We already have a modal info opened, do not touch it.
        return;

    m_info = Info{ std::move(title), std::move(content), anchor, {}, style };
    m_ui_pending |= InfoShow;
    m_ui_pending &= ~InfoHide;
}

void Client::info_hide(bool even_modal)
{
    if (not even_modal and m_info.style == InfoStyle::Modal)
        return;

    m_info = Info{};
    m_ui_pending |= InfoHide;
    m_ui_pending &= ~InfoShow;
}

}
<|endoftext|>


<commit_before><commit_msg>fix bug in setting min file size for logger<commit_after><|endoftext|>


<commit_before>/* dtk3DView.cpp ---
 *
 * Author: Julien Wintz
 * Created: Fri Mar 22 09:41:43 2013 (+0100)
 * Version:
 * Last-Updated: Mon Mar 25 17:29:47 2013 (+0100)
 *           By: Julien Wintz
 *     Update #: 32
 */

/* Change Log:
 *
 */

#include "dtk3DView.h"
#include "dtk3DScene.h"

#include <QtGui>

class dtk3DViewPrivate
{
public:
    dtk3DScene *scene;
};

dtk3DView::dtk3DView(QWindow *parent) : QGLView(parent), d(new dtk3DViewPrivate)
{
    d->scene = NULL;

    this->setOption(QGLView::ObjectPicking, true);
}

dtk3DView::~dtk3DView(void)
{
    delete d;

    d = NULL;
}

void dtk3DView::setScene(dtk3DScene *scene)
{
    d->scene = scene;
}

void dtk3DView::initializeGL(QGLPainter *painter)
{
    if (d->scene)
	d->scene->initialize(this, painter);

    QGLView::initializeGL(painter);
}

void dtk3DView::paintGL(QGLPainter *painter)
{
    painter->setStandardEffect(QGL::LitMaterial);
    painter->setFaceColor(QGL::AllFaces, QColor(170, 202, 0));

    if (d->scene)
	d->scene->paint(this, painter);

    QGLView::paintGL(painter);
}

void dtk3DView::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Tab) {
        this->setOption(QGLView::ShowPicking, ((this->options() & QGLView::ShowPicking) == 0));
        this->update();
    }

    QGLView::keyPressEvent(event);
}
<commit_msg>Do not set a default material for objects in view. Handle scene viewing in initialization.<commit_after>/* dtk3DView.cpp ---
 *
 * Author: Julien Wintz
 * Created: Fri Mar 22 09:41:43 2013 (+0100)
 * Version:
 * Last-Updated: Wed Mar 27 15:33:56 2013 (+0100)
 *           By: Julien Wintz
 *     Update #: 42
 */

/* Change Log:
 *
 */

#include "dtk3DView.h"
#include "dtk3DScene.h"

#include <QtGui>

class dtk3DViewPrivate
{
public:
    dtk3DScene *scene;
};

dtk3DView::dtk3DView(QWindow *parent) : QGLView(parent), d(new dtk3DViewPrivate)
{
    d->scene = NULL;

    this->setOption(QGLView::ObjectPicking, true);
}

dtk3DView::~dtk3DView(void)
{
    delete d;

    d = NULL;
}

void dtk3DView::setScene(dtk3DScene *scene)
{
    d->scene = scene;
}

void dtk3DView::initializeGL(QGLPainter *painter)
{
    if (d->scene)
	d->scene->initialize(this, painter);

    QGLView::initializeGL(painter);

    if (d->scene) {
	this->camera()->setEye(QVector3D(0, 0, d->scene->boundingBox().size().length()*4));
	this->camera()->setCenter(d->scene->boundingBox().center());
    }
}

void dtk3DView::paintGL(QGLPainter *painter)
{
    if (d->scene)
	d->scene->paint(this, painter);

    QGLView::paintGL(painter);
}

void dtk3DView::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Tab) {
        this->setOption(QGLView::ShowPicking, ((this->options() & QGLView::ShowPicking) == 0));
        this->update();
    }

    QGLView::keyPressEvent(event);
}
<|endoftext|>


<commit_before>#pragma once

#include <cstdlib>
#include <cstdio>
#include <sstream>

#ifdef __GNUC__
#define DUKE_LIKELY(x) (__builtin_expect((x), 1))
#define DUKE_UNLIKELY(x) (__builtin_expect((x), 0))
#else
#define DUKE_LIKELY(x) (x)
#define DUKE_UNLIKELY(x) (x)
#endif

#define TRACE_MSG(X) fprintf(stderr, "CHECK FAILED '" #X "' in %s() [%s:%d]\n", __func__, __FILE__, __LINE__)

struct Tracer {
  Tracer(const char* cond, const char* func, const char* file, const int line) {
    msg << "CHECK FAILED '" << cond << "' in " << func << "() [" << file << ":" << line << "] ";
  }
  std::ostream& getStream() { return msg; }
  ~Tracer() {
    fprintf(stderr, "%s\n", msg.str().c_str());
    abort();
  }

 private:
  std::ostringstream msg;
};

#define CHECK(X) \
  if (DUKE_UNLIKELY(!(X))) Tracer(#X, __func__, __FILE__, __LINE__).getStream()
<commit_msg>Adding check not null<commit_after>#pragma once

#include <cstdlib>
#include <cstdio>
#include <sstream>

#ifdef __GNUC__
#define DUKE_LIKELY(x) (__builtin_expect((x), 1))
#define DUKE_UNLIKELY(x) (__builtin_expect((x), 0))
#else
#define DUKE_LIKELY(x) (x)
#define DUKE_UNLIKELY(x) (x)
#endif

#define LOG_FATAL(COND,FUNC,FILE,LINE) fprintf(stderr, "CHECK FAILED '%s' in %s() [%s:%d]\n", COND, FUNC, FILE, LINE); abort();
#define TRACE_MSG(X) fprintf(stderr, "CHECK FAILED '" #X "' in %s() [%s:%d]\n", __func__, __FILE__, __LINE__)

struct Tracer {
  Tracer(const char* cond, const char* func, const char* file, const int line) {
    msg << "CHECK FAILED '" << cond << "' in " << func << "() [" << file << ":" << line << "] ";
  }

  std::ostream& getStream() { return msg; }
  ~Tracer() {
    fprintf(stderr, "%s\n", msg.str().c_str());
    abort();
  }

 private:
  std::ostringstream msg;
};

#define CHECK(X) \
  if (DUKE_UNLIKELY(!(X))) Tracer(#X, __func__, __FILE__, __LINE__).getStream()

template<typename T>
inline T& _checkNotNull(const char* cond, const char* func, const char* file, const int line, T& ptr){ if (DUKE_UNLIKELY(!ptr)) LOG_FATAL(cond, func, file, line); return ptr; }

#define CHECK_NOTNULL(X) \
    _checkNotNull(#X " must not be nullptr", __func__, __FILE__, __LINE__, X)
<|endoftext|>