<commit_before>// SafeArryGUID.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <objbase.h>
#include <string>
#include<atlsafe.h>
#include<iostream>
using namespace std;

string GuidToString(const GUID &guid)
{
	char buf[64] = { 0 };
	sprintf_s(buf, sizeof(buf), "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
		guid.Data1, guid.Data2, guid.Data3,
		guid.Data4[0], guid.Data4[1],
		guid.Data4[2], guid.Data4[3],
		guid.Data4[4], guid.Data4[5],
		guid.Data4[6], guid.Data4[7]);
	return string(buf);
}

void Put1GuidInSafeArry()
{
	GUID guid;
	CoCreateGuid(&guid);

	auto guidStri = GuidToString(guid);

	cout << guidStri << endl;

	//TODO... put the guid into safearry..
	SAFEARRAY* p_safe_arry;
	SAFEARRAYBOUND safe_arry_bound[2] = { 0 };
	auto guidsize = sizeof(GUID);
	safe_arry_bound[0].cElements = guidsize;
	safe_arry_bound[0].lLbound = 0;
	safe_arry_bound[1].cElements = guidsize;
	safe_arry_bound[1].lLbound = 0;

	p_safe_arry = SafeArrayCreate(VT_ARRAY, 1, safe_arry_bound);
	auto pnData = reinterpret_cast<char*>(p_safe_arry->pvData);
	memcpy_s(pnData, guidsize, guidStri.c_str(), guidsize);
	//TODO...
	//do something..
	SafeArrayDestroy(p_safe_arry);
}

void Put2GuidInSafeArry()
{
	GUID guid, guid2;
	CoCreateGuid(&guid);
	CoCreateGuid(&guid2);

	//TODO... put the guid into safearry..
	SAFEARRAY* p_safe_arry;
	SAFEARRAYBOUND safe_arry_bound[2] = { 0 };
	safe_arry_bound[0].cElements = 2;
	safe_arry_bound[0].lLbound = 0;
	safe_arry_bound[1].cElements = 16;
	safe_arry_bound[1].lLbound = 0;

	p_safe_arry = SafeArrayCreate(VT_CLSID, 2, safe_arry_bound);
	auto pnData = reinterpret_cast<GUID*>(p_safe_arry->pvData);
	pnData[0] = guid;
	pnData[1] = guid2;
	//TODO...
	//do something..
	//TODO...

	SafeArrayDestroy(p_safe_arry);
}

void Put1GuidInSafeArryByStack()
{
	GUID guid;

	//TODO... put the guid into safearry..
	SAFEARRAY* pArray = nullptr;
	auto hr = SafeArrayAllocDescriptorEx(VT_CLSID, 1, &pArray);
	pArray->cbElements = sizeof(GUID);
	pArray->rgsabound[0].cElements = 1;
	pArray->rgsabound[0].lLbound = 16;
	pArray->pvData = &guid;
	pArray->fFeatures = FADF_AUTO;
	//_bstr_t bstr;
}

void CComSafeArrayGUID()
{
	//CComSafeArray<GUID> comsafeguid(10);
}

void LearnSafeArray()
{
	SAFEARRAY *pArray = nullptr;
	HRESULT hr = SafeArrayAllocDescriptor(1, &pArray);//SAFEARRAYṹĶ
	pArray->cbElements = sizeof(GUID);
	pArray->rgsabound[0].cElements = 10;
	pArray->rgsabound[0].lLbound = 0;

	GUID guid, guid2;
	CoCreateGuid(&guid);
	CoCreateGuid(&guid2);
	GUID _guidarr[] = { guid,guid2 };
	pArray->pvData = _guidarr;
	pArray->fFeatures = FADF_AUTO | FADF_FIXEDSIZE;

	//CComSafeArray<VARIANT> saguid;
//	saguid.Attach(pArray);

	//auto count = saguid.GetCount();

	//auto t = saguid.GetType();

	GUID* p_GUIDArry = nullptr;
	SafeArrayAccessData(pArray, (PVOID*)&p_GUIDArry);

	auto retv = p_GUIDArry[0];
	auto retv1 = p_GUIDArry[1];

	long Low(0), High(0);
	hr = SafeArrayGetLBound(pArray, 1, &Low);//ά1ʼ
	hr = SafeArrayGetUBound(pArray, 1, &High);//ά1ʼ
	cin.get();
}

void TestSafeArry()
{
	LearnSafeArray();
	//CComSafeArrayBound bound(2);
	//CComSafeArray<GUID>  guid_Array;
	//GUID guid, guid2;
	//CoCreateGuid(&guid);
	//CoCreateGuid(&guid2);
	//guid_Array.Add(guid);
	//guid_Array.Add(guid2);

	//auto count = guid_Array.GetCount();
	//auto demention = guid_Array.GetDimensions();
	//auto upperbound = guid_Array.GetUpperBound();
	//auto p_safeArry = &guid_Array;
	//GUID guid3;
	//CoCreateGuid(&guid3);
	//p_safeArry->SetAt(1, guid3);
}

int _tmain(int argc, _TCHAR* argv[])
{
	TestSafeArry();
	Put1GuidInSafeArry();
	Put2GuidInSafeArry();
	Put1GuidInSafeArryByStack();
	return 0;
}<commit_msg>update using .<commit_after>// SafeArryGUID.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <objbase.h>
#include <string>
#include<atlsafe.h>
#include<iostream>
using namespace std;

string GuidToString(const GUID &guid)
{
	char buf[64] = { 0 };
	sprintf_s(buf, sizeof(buf), "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
		guid.Data1, guid.Data2, guid.Data3,
		guid.Data4[0], guid.Data4[1],
		guid.Data4[2], guid.Data4[3],
		guid.Data4[4], guid.Data4[5],
		guid.Data4[6], guid.Data4[7]);
	return string(buf);
}

void Put1GuidInSafeArry()
{
	GUID guid;
	CoCreateGuid(&guid);

	auto guidStri = GuidToString(guid);

	cout << guidStri << endl;

	//TODO... put the guid into safearry..
	SAFEARRAY* p_safe_arry;
	SAFEARRAYBOUND safe_arry_bound[2] = { 0 };
	auto guidsize = sizeof(GUID);
	safe_arry_bound[0].cElements = guidsize;
	safe_arry_bound[0].lLbound = 0;
	safe_arry_bound[1].cElements = guidsize;
	safe_arry_bound[1].lLbound = 0;

	p_safe_arry = SafeArrayCreate(VT_ARRAY, 1, safe_arry_bound);
	auto pnData = reinterpret_cast<char*>(p_safe_arry->pvData);
	memcpy_s(pnData, guidsize, guidStri.c_str(), guidsize);
	//TODO...
	//do something..
	SafeArrayDestroy(p_safe_arry);
}

void Put2GuidInSafeArry()
{
	GUID guid, guid2;
	CoCreateGuid(&guid);
	CoCreateGuid(&guid2);

	//TODO... put the guid into safearry..
	SAFEARRAY* p_safe_arry;
	SAFEARRAYBOUND safe_arry_bound[2] = { 0 };
	safe_arry_bound[0].cElements = 2;
	safe_arry_bound[0].lLbound = 0;
	safe_arry_bound[1].cElements = 16;
	safe_arry_bound[1].lLbound = 0;

	p_safe_arry = SafeArrayCreate(VT_CLSID, 2, safe_arry_bound);
	auto pnData = reinterpret_cast<GUID*>(p_safe_arry->pvData);
	pnData[0] = guid;
	pnData[1] = guid2;
	//TODO...
	//do something..
	//TODO...

	SafeArrayDestroy(p_safe_arry);
}

void Put1GuidInSafeArryByStack()
{
	GUID guid;

	//TODO... put the guid into safearry..
	SAFEARRAY* pArray = nullptr;
	auto hr = SafeArrayAllocDescriptorEx(VT_CLSID, 1, &pArray);
	pArray->cbElements = sizeof(GUID);
	pArray->rgsabound[0].cElements = 1;
	pArray->rgsabound[0].lLbound = 16;
	pArray->pvData = &guid;
	pArray->fFeatures = FADF_AUTO;
	//_bstr_t bstr;
}

void CComSafeArrayGUID()
{
	//CComSafeArray<GUID> comsafeguid(10);
}

void LearnSafeArray()
{
	SAFEARRAY *pArray = nullptr;
	HRESULT hr = SafeArrayAllocDescriptor(1, &pArray);//SAFEARRAYṹĶ
	pArray->cbElements = sizeof(GUID);
	pArray->rgsabound[0].cElements = 10;
	pArray->rgsabound[0].lLbound = 0;

	GUID guid, guid2;
	CoCreateGuid(&guid);
	CoCreateGuid(&guid2);
	GUID _guidarr[] = { guid,guid2 };
	pArray->pvData = _guidarr;
	pArray->fFeatures = FADF_AUTO | FADF_FIXEDSIZE;

	//CComSafeArray<VARIANT> saguid;
//	saguid.Attach(pArray);

	//auto count = saguid.GetCount();

	//auto t = saguid.GetType();

	GUID* p_GUIDArry = nullptr;
	SafeArrayAccessData(pArray, (PVOID*)&p_GUIDArry);

	auto retv = p_GUIDArry[0];
	auto retv1 = p_GUIDArry[1];

	long Low(0), High(0);
	hr = SafeArrayGetLBound(pArray, 1, &Low);//ά1ʼ
	hr = SafeArrayGetUBound(pArray, 1, &High);//ά1ʼ

	SafeArrayUnaccessData(pArray);
	SafeArrayDestroy(pArray);

	cin.get();
}

void TestSafeArry()
{
	LearnSafeArray();
	//CComSafeArrayBound bound(2);
	//CComSafeArray<GUID>  guid_Array;
	//GUID guid, guid2;
	//CoCreateGuid(&guid);
	//CoCreateGuid(&guid2);
	//guid_Array.Add(guid);
	//guid_Array.Add(guid2);

	//auto count = guid_Array.GetCount();
	//auto demention = guid_Array.GetDimensions();
	//auto upperbound = guid_Array.GetUpperBound();
	//auto p_safeArry = &guid_Array;
	//GUID guid3;
	//CoCreateGuid(&guid3);
	//p_safeArry->SetAt(1, guid3);
}

int _tmain(int argc, _TCHAR* argv[])
{
	TestSafeArry();
	Put1GuidInSafeArry();
	Put2GuidInSafeArry();
	Put1GuidInSafeArryByStack();
	return 0;
}<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2009 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

// interface header
#include "TimeKeeper.h"

// system headers
#include <time.h>
#include <string>
#include <string.h>
#ifdef HAVE_UNISTD_H
#  include <unistd.h>
#endif
#ifdef __BEOS__
#  include <OS.h>
#endif
#if !defined(_WIN32)
#  include <sys/time.h>
#  include <sys/types.h>
static int64_t lastTime = 0;
#  ifdef HAVE_SCHED_H
#    include <sched.h>
#  endif
#else // !defined(_WIN32)
#  include <mmsystem.h>
static unsigned long int lastTime = 0;
static LARGE_INTEGER     qpcLastTime;
static LONGLONG          qpcFrequency = 0;
static LONGLONG          qpcLastCalibration;
static DWORD             timeLastCalibration;
#endif // !defined(_WIN32)

// system threading headers
#ifndef _WIN32
#  include <sys/types.h>
#  include <dirent.h>
#endif
#ifdef HAVE_PTHREADS
#  include <pthread.h>
#endif

// common headers
#include "TextUtils.h"
#include "bzfio.h"

//============================================================================//

#if defined(HAVE_PTHREADS)
  static pthread_mutex_t    timer_mutex;
# define LOCK_TIMER_MUTEX   pthread_mutex_lock(&timer_mutex);
# define UNLOCK_TIMER_MUTEX pthread_mutex_unlock(&timer_mutex);
#elif defined(_WIN32)
  static CRITICAL_SECTION   timer_critical;
# define LOCK_TIMER_MUTEX   EnterCriticalSection(&timer_critical);
# define UNLOCK_TIMER_MUTEX LeaveCriticalSection(&timer_critical);
#else
# define LOCK_TIMER_MUTEX
# define UNLOCK_TIMER_MUTEX
#endif

//============================================================================//

static TimeKeeper currentTime;
static TimeKeeper tickTime;
static TimeKeeper sunExplodeTime;
static TimeKeeper sunGenesisTime;
static TimeKeeper nullTime;
static TimeKeeper startTime = TimeKeeper::getCurrent();

//============================================================================//

#if !defined(_WIN32)
static inline int64_t getEpochMicroseconds()
{
  struct timeval nowTime;
  gettimeofday(&nowTime, NULL);
  return (int64_t(nowTime.tv_sec) * int64_t(1000000))
        + int64_t(nowTime.tv_usec);
}
#endif

const TimeKeeper& TimeKeeper::getCurrent(void)
{
  LOCK_TIMER_MUTEX

  // if not first call then update current time, else use default initial time
#if !defined(_WIN32)
  if (lastTime == 0) {
    // time starts at 0 seconds from the first call to getCurrent()
    lastTime = getEpochMicroseconds();
  }
  else {
    const int64_t nowTime = getEpochMicroseconds();

    int64_t diff = (nowTime - lastTime);
    if (diff < 0) {
      logDebugMessage(5, "WARNING: went back in time %li microseconds\n",
                      (long int)diff);
      diff = 0; // eh, how'd we go back in time?
    }

    currentTime += double(diff) * 1.0e-6;;

    lastTime = nowTime;
  }
#else /* !defined(_WIN32) */
  if (qpcFrequency != 0) {

    // main timer is qpc
    LARGE_INTEGER now;
    QueryPerformanceCounter(&now);

    LONGLONG diff     = now.QuadPart - qpcLastTime.QuadPart;
    LONGLONG clkSpent = now.QuadPart - qpcLastCalibration;
    qpcLastTime = now;

    if (clkSpent > qpcFrequency) {
      // Recalibrate Frequency
      DWORD tgt	   = timeGetTime();
      DWORD deltaTgt      = tgt - timeLastCalibration;
      timeLastCalibration = tgt;
      qpcLastCalibration  = now.QuadPart;
      if (deltaTgt > 0) {
	LONGLONG oldqpcfreq = qpcFrequency;
	qpcFrequency	= (clkSpent * 1000) / deltaTgt;
	if (qpcFrequency != oldqpcfreq)
	  logDebugMessage(4, "Recalibrated QPC frequency.  Old: %f ; New: %f\n",
			  (double)oldqpcfreq, (double)qpcFrequency);
      }
    }

    currentTime += (double) diff / (double) qpcFrequency;
  } else if (lastTime != 0) {
    unsigned long int now = (unsigned long int)timeGetTime();
    unsigned long int diff;
    if (now < lastTime) {
      // eh, how'd we go back in time?
      diff = 0;
    } else {
      diff = now - lastTime;
    }
    currentTime += 1.0e-3 * (double)diff;
    lastTime = now;
  } else {
    static bool sane = true;

    // should only get into here once on app start
    if (!sane) {
      logDebugMessage(1,"Sanity check failure in TimeKeeper::getCurrent()\n");
    }
    sane = false;

    // make sure we're at our best timer resolution possible
    timeBeginPeriod(1);

    LARGE_INTEGER freq;
    if (QueryPerformanceFrequency(&freq)) {
      QueryPerformanceCounter(&qpcLastTime);
      qpcFrequency	= freq.QuadPart;
      logDebugMessage(4,"Actual reported QPC Frequency: %f\n", (double)qpcFrequency);
      qpcLastCalibration  = qpcLastTime.QuadPart;
      timeLastCalibration = timeGetTime();
    } else {
      logDebugMessage(1,"QueryPerformanceFrequency failed with error %d\n", GetLastError());

      lastTime = (unsigned long int)timeGetTime();
    }
  }
#endif /* !defined(_WIN32) */

  UNLOCK_TIMER_MUTEX

  return currentTime;
}

const TimeKeeper& TimeKeeper::getStartTime(void) // const
{
  return startTime;
}

const TimeKeeper& TimeKeeper::getTick(void) // const
{
  return tickTime;
}

void TimeKeeper::setTick(void)
{
  tickTime = getCurrent();
}

const TimeKeeper& TimeKeeper::getSunExplodeTime(void)
{
  sunExplodeTime.seconds = 10000.0 * 365 * 24 * 60 * 60;
  return sunExplodeTime;
}

const TimeKeeper& TimeKeeper::getSunGenesisTime(void)
{
  sunGenesisTime.seconds = -10000.0 * 365 * 24 * 60 * 60;
  return sunGenesisTime;
}

const TimeKeeper& TimeKeeper::getNullTime(void)
{
  nullTime.seconds = 0;
  return nullTime;
}

const char *TimeKeeper::timestamp(void) // const
{
  static char buffer[256]; // static, so that it doesn't vanish
  time_t tnow = time(0);
  struct tm *now = localtime(&tnow);
  now->tm_year += 1900;
  ++now->tm_mon;

  strncpy (buffer, TextUtils::format("%04d-%02d-%02d %02d:%02d:%02d",
				     now->tm_year, now->tm_mon, now->tm_mday,
				     now->tm_hour, now->tm_min, now->tm_sec).c_str(), 256);
  buffer[255] = '\0'; // safety

  return buffer;
}

/** returns a short string of the local time */
//static
std::string TimeKeeper::shortTimeStamp(void) {
  time_t tnow = time(0);
  struct tm *now = localtime(&tnow);

  std::string result( TextUtils::format("%02d:%02d", now->tm_hour, now->tm_min) );
  return result;
}

void TimeKeeper::localTime(int *year, int *month, int* day,
                           int* hour, int* min, int* sec, bool* dst) // const
{
  time_t tnow = time(0);
  struct tm *now = localtime(&tnow);
  now->tm_year += 1900;
  ++now->tm_mon;

  if (year)  { *year  = now->tm_year; }
  if (month) { *month = now->tm_mon;  }
  if (day)   { *day   = now->tm_mday; }
  if (hour)  { *hour  = now->tm_hour; }
  if (min)   { *min   = now->tm_min;  }
  if (sec)   { *sec   = now->tm_sec;  }
  if (dst)   { *dst   = (now->tm_isdst != 0); }
}

void TimeKeeper::localTimeDOW(int *year, int *month, int* day, int* wday,
                              int* hour, int* min, int* sec, bool* dst) // const
{
  time_t tnow = time(0);
  struct tm *now = localtime(&tnow);
  now->tm_year += 1900;
  ++now->tm_mon;

  if (year)  { *year  = now->tm_year; }
  if (month) { *month = now->tm_mon;  }
  if (day)   { *day   = now->tm_mday; }
  if (wday)  { *wday  = now->tm_wday; }
  if (hour)  { *hour  = now->tm_hour; }
  if (min)   { *min   = now->tm_min;  }
  if (sec)   { *sec   = now->tm_sec;  }
  if (dst)   { *dst   = (now->tm_isdst != 0); }
}

void TimeKeeper::UTCTime(int *year, int *month, int* day, int* wday,
                         int* hour, int* min, int* sec, bool* dst) // const
{
  time_t tnow = time(0);
  struct tm *now = gmtime(&tnow);
  now->tm_year += 1900;
  ++now->tm_mon;

  if (year)  { *year  = now->tm_year; }
  if (month) { *month = now->tm_mon;  }
  if (day)   { *day   = now->tm_mday; }
  if (wday)  { *wday  = now->tm_wday; }
  if (hour)  { *hour  = now->tm_hour; }
  if (min)   { *min   = now->tm_min;  }
  if (sec)   { *sec   = now->tm_sec;  }
  if (dst)   { *dst   = (now->tm_isdst != 0); }
}

// function for converting a float time (e.g. difference of two TimeKeepers)
// into an array of ints
void TimeKeeper::convertTime(double raw, long int convertedTimes[]) // const
{
  long int day, hour, min, sec, remainder;
  static const int secondsInDay = 86400;

  sec = (long int)raw;
  day = sec / secondsInDay;
  remainder = sec - (day * secondsInDay);
  hour = remainder / 3600;
  remainder = sec - ((hour * 3600) + (day * secondsInDay));
  min = remainder / 60;
  remainder = sec - ((hour * 3600) + (day * secondsInDay) + (min * 60));
  sec = remainder;

  convertedTimes[0] = day;
  convertedTimes[1] = hour;
  convertedTimes[2] = min;
  convertedTimes[3] = sec;

  return;
}

// function for printing an array of ints representing a time
// as a human-readable string
const std::string TimeKeeper::printTime(long int timeValue[])
{
  std::string valueNames;
  char temp[20];

  if (timeValue[0] > 0) {
    snprintf(temp, 20, "%ld day%s", timeValue[0], timeValue[0] == 1 ? "" : "s");
    valueNames.append(temp);
  }
  if (timeValue[1] > 0) {
    if (timeValue[0] > 0) {
      valueNames.append(", ");
    }
    snprintf(temp, 20, "%ld hour%s", timeValue[1], timeValue[1] == 1 ? "" : "s");
    valueNames.append(temp);
  }
  if (timeValue[2] > 0) {
    if ((timeValue[1] > 0) || (timeValue[0] > 0)) {
      valueNames.append(", ");
    }
    snprintf(temp, 20, "%ld min%s", timeValue[2], timeValue[2] == 1 ? "" : "s");
    valueNames.append(temp);
  }
  if (timeValue[3] > 0) {
    if ((timeValue[2] > 0) || (timeValue[1] > 0) || (timeValue[0] > 0)) {
      valueNames.append(", ");
    }
    snprintf(temp, 20, "%ld sec%s", timeValue[3], timeValue[3] == 1 ? "" : "s");
    valueNames.append(temp);
  }

  return valueNames;
}

// function for printing a float time difference as a human-readable string
const std::string TimeKeeper::printTime(double diff)
{
  long int temp[4];
  convertTime(diff, temp);
  return printTime(temp);
}

void TimeKeeper::sleep(double seconds)
{
  if (seconds <= 0.0) {
    return;
  }

#ifdef HAVE_USLEEP
  usleep((unsigned int)(1.0e6 * seconds));
  return;
#endif
#if defined(HAVE_SLEEP) && !defined(__APPLE__)
  // equivalent to _sleep() on win32 (not sleep(3))
  Sleep((DWORD)(seconds * 1000.0));
  return;
#endif
#ifdef HAVE_SNOOZE
  snooze((bigtime_t)(1.0e6 * seconds));
  return;
#endif
#ifdef HAVE_SELECT
  struct timeval tv;
  tv.tv_sec = (long)seconds;
  tv.tv_usec = (long)(1.0e6 * (seconds - tv.tv_sec));
  select(0, NULL, NULL, NULL, &tv);
  return;
#endif
#ifdef HAVE_WAITFORSINGLEOBJECT
  HANDLE dummyEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  WaitForSingleObject(dummyEvent, (DWORD)(1000.0 * seconds));
  CloseHandle(dummyEvent);
  return;
#endif

  // fall-back case is fugly manual timekeeping
  TimeKeeper now = TimeKeeper::getCurrent();
  while ((TimeKeeper::getCurrent() - now) < seconds) {
    continue;
  }
  return;
}

void TimeKeeper::setProcessorAffinity(int processor)
{
#ifdef HAVE_SCHED_SETAFFINITY
  /* linuxy fix for time travel */
  cpu_set_t mask;
  CPU_ZERO(&mask);
  CPU_SET(processor, &mask);
  sched_setaffinity(0, sizeof(mask), &mask);
#elif defined(WIN32)
  /* windowsy fix for time travel */
  HANDLE hThread = GetCurrentThread();
  DWORD_PTR dwMask = 1 << processor;
  DWORD_PTR dwProcs = 0;
  GetProcessAffinityMask(NULL, NULL, &dwProcs);
  if (dwMask < dwProcs) {
    logDebugMessage(1, "Unable to set process affinity mask (specified processor does not exist).\n");
    return;
  }
  SetThreadAffinityMask(hThread, dwMask);
#else
  logDebugMessage(1, "Unable to set processor affinity to %d - function not implemented on this platform.\n", processor);
#endif
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>* informative comment<commit_after>/* bzflag
 * Copyright (c) 1993 - 2009 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

// interface header
#include "TimeKeeper.h"

// system headers
#include <time.h>
#include <string>
#include <string.h>
#ifdef HAVE_UNISTD_H
#  include <unistd.h>
#endif
#ifdef __BEOS__
#  include <OS.h>
#endif
#if !defined(_WIN32)
#  include <sys/time.h>
#  include <sys/types.h>
static int64_t lastTime = 0;
#  ifdef HAVE_SCHED_H
#    include <sched.h>
#  endif
#else // !defined(_WIN32)
#  include <mmsystem.h>
static unsigned long int lastTime = 0;
static LARGE_INTEGER     qpcLastTime;
static LONGLONG          qpcFrequency = 0;
static LONGLONG          qpcLastCalibration;
static DWORD             timeLastCalibration;
#endif // !defined(_WIN32)

// system threading headers
#ifndef _WIN32
#  include <sys/types.h>
#  include <dirent.h>
#endif
#ifdef HAVE_PTHREADS
#  include <pthread.h>
#endif

// common headers
#include "TextUtils.h"
#include "bzfio.h"

//============================================================================//

#if defined(HAVE_PTHREADS)
  static pthread_mutex_t    timer_mutex;
# define LOCK_TIMER_MUTEX   pthread_mutex_lock(&timer_mutex);
# define UNLOCK_TIMER_MUTEX pthread_mutex_unlock(&timer_mutex);
#elif defined(_WIN32)
  static CRITICAL_SECTION   timer_critical;
# define LOCK_TIMER_MUTEX   EnterCriticalSection(&timer_critical);
# define UNLOCK_TIMER_MUTEX LeaveCriticalSection(&timer_critical);
#else
# define LOCK_TIMER_MUTEX
# define UNLOCK_TIMER_MUTEX
#endif

//============================================================================//

static TimeKeeper currentTime;
static TimeKeeper tickTime;
static TimeKeeper sunExplodeTime;
static TimeKeeper sunGenesisTime;
static TimeKeeper nullTime;
static TimeKeeper startTime = TimeKeeper::getCurrent();

//============================================================================//

#if !defined(_WIN32)
static inline int64_t getEpochMicroseconds()
{
  struct timeval nowTime;
  gettimeofday(&nowTime, NULL);
  return (int64_t(nowTime.tv_sec) * int64_t(1000000))
        + int64_t(nowTime.tv_usec);
}
#endif

const TimeKeeper& TimeKeeper::getCurrent(void)
{
  // a mutex lock is used because this routine
  // is called from the client's sound thread
  LOCK_TIMER_MUTEX

  // if not first call then update current time, else use default initial time
#if !defined(_WIN32)
  if (lastTime == 0) {
    // time starts at 0 seconds from the first call to getCurrent()
    lastTime = getEpochMicroseconds();
  }
  else {
    const int64_t nowTime = getEpochMicroseconds();

    int64_t diff = (nowTime - lastTime);
    if (diff < 0) {
      logDebugMessage(5, "WARNING: went back in time %li microseconds\n",
                      (long int)diff);
      diff = 0; // eh, how'd we go back in time?
    }

    currentTime += double(diff) * 1.0e-6;;

    lastTime = nowTime;
  }
#else /* !defined(_WIN32) */
  if (qpcFrequency != 0) {

    // main timer is qpc
    LARGE_INTEGER now;
    QueryPerformanceCounter(&now);

    LONGLONG diff     = now.QuadPart - qpcLastTime.QuadPart;
    LONGLONG clkSpent = now.QuadPart - qpcLastCalibration;
    qpcLastTime = now;

    if (clkSpent > qpcFrequency) {
      // Recalibrate Frequency
      DWORD tgt	   = timeGetTime();
      DWORD deltaTgt      = tgt - timeLastCalibration;
      timeLastCalibration = tgt;
      qpcLastCalibration  = now.QuadPart;
      if (deltaTgt > 0) {
	LONGLONG oldqpcfreq = qpcFrequency;
	qpcFrequency	= (clkSpent * 1000) / deltaTgt;
	if (qpcFrequency != oldqpcfreq)
	  logDebugMessage(4, "Recalibrated QPC frequency.  Old: %f ; New: %f\n",
			  (double)oldqpcfreq, (double)qpcFrequency);
      }
    }

    currentTime += (double) diff / (double) qpcFrequency;
  } else if (lastTime != 0) {
    unsigned long int now = (unsigned long int)timeGetTime();
    unsigned long int diff;
    if (now < lastTime) {
      // eh, how'd we go back in time?
      diff = 0;
    } else {
      diff = now - lastTime;
    }
    currentTime += 1.0e-3 * (double)diff;
    lastTime = now;
  } else {
    static bool sane = true;

    // should only get into here once on app start
    if (!sane) {
      logDebugMessage(1,"Sanity check failure in TimeKeeper::getCurrent()\n");
    }
    sane = false;

    // make sure we're at our best timer resolution possible
    timeBeginPeriod(1);

    LARGE_INTEGER freq;
    if (QueryPerformanceFrequency(&freq)) {
      QueryPerformanceCounter(&qpcLastTime);
      qpcFrequency	= freq.QuadPart;
      logDebugMessage(4,"Actual reported QPC Frequency: %f\n", (double)qpcFrequency);
      qpcLastCalibration  = qpcLastTime.QuadPart;
      timeLastCalibration = timeGetTime();
    } else {
      logDebugMessage(1,"QueryPerformanceFrequency failed with error %d\n", GetLastError());

      lastTime = (unsigned long int)timeGetTime();
    }
  }
#endif /* !defined(_WIN32) */

  UNLOCK_TIMER_MUTEX

  return currentTime;
}

const TimeKeeper& TimeKeeper::getStartTime(void) // const
{
  return startTime;
}

const TimeKeeper& TimeKeeper::getTick(void) // const
{
  return tickTime;
}

void TimeKeeper::setTick(void)
{
  tickTime = getCurrent();
}

const TimeKeeper& TimeKeeper::getSunExplodeTime(void)
{
  sunExplodeTime.seconds = 10000.0 * 365 * 24 * 60 * 60;
  return sunExplodeTime;
}

const TimeKeeper& TimeKeeper::getSunGenesisTime(void)
{
  sunGenesisTime.seconds = -10000.0 * 365 * 24 * 60 * 60;
  return sunGenesisTime;
}

const TimeKeeper& TimeKeeper::getNullTime(void)
{
  nullTime.seconds = 0;
  return nullTime;
}

const char *TimeKeeper::timestamp(void) // const
{
  static char buffer[256]; // static, so that it doesn't vanish
  time_t tnow = time(0);
  struct tm *now = localtime(&tnow);
  now->tm_year += 1900;
  ++now->tm_mon;

  strncpy (buffer, TextUtils::format("%04d-%02d-%02d %02d:%02d:%02d",
				     now->tm_year, now->tm_mon, now->tm_mday,
				     now->tm_hour, now->tm_min, now->tm_sec).c_str(), 256);
  buffer[255] = '\0'; // safety

  return buffer;
}

/** returns a short string of the local time */
//static
std::string TimeKeeper::shortTimeStamp(void) {
  time_t tnow = time(0);
  struct tm *now = localtime(&tnow);

  std::string result( TextUtils::format("%02d:%02d", now->tm_hour, now->tm_min) );
  return result;
}

void TimeKeeper::localTime(int *year, int *month, int* day,
                           int* hour, int* min, int* sec, bool* dst) // const
{
  time_t tnow = time(0);
  struct tm *now = localtime(&tnow);
  now->tm_year += 1900;
  ++now->tm_mon;

  if (year)  { *year  = now->tm_year; }
  if (month) { *month = now->tm_mon;  }
  if (day)   { *day   = now->tm_mday; }
  if (hour)  { *hour  = now->tm_hour; }
  if (min)   { *min   = now->tm_min;  }
  if (sec)   { *sec   = now->tm_sec;  }
  if (dst)   { *dst   = (now->tm_isdst != 0); }
}

void TimeKeeper::localTimeDOW(int *year, int *month, int* day, int* wday,
                              int* hour, int* min, int* sec, bool* dst) // const
{
  time_t tnow = time(0);
  struct tm *now = localtime(&tnow);
  now->tm_year += 1900;
  ++now->tm_mon;

  if (year)  { *year  = now->tm_year; }
  if (month) { *month = now->tm_mon;  }
  if (day)   { *day   = now->tm_mday; }
  if (wday)  { *wday  = now->tm_wday; }
  if (hour)  { *hour  = now->tm_hour; }
  if (min)   { *min   = now->tm_min;  }
  if (sec)   { *sec   = now->tm_sec;  }
  if (dst)   { *dst   = (now->tm_isdst != 0); }
}

void TimeKeeper::UTCTime(int *year, int *month, int* day, int* wday,
                         int* hour, int* min, int* sec, bool* dst) // const
{
  time_t tnow = time(0);
  struct tm *now = gmtime(&tnow);
  now->tm_year += 1900;
  ++now->tm_mon;

  if (year)  { *year  = now->tm_year; }
  if (month) { *month = now->tm_mon;  }
  if (day)   { *day   = now->tm_mday; }
  if (wday)  { *wday  = now->tm_wday; }
  if (hour)  { *hour  = now->tm_hour; }
  if (min)   { *min   = now->tm_min;  }
  if (sec)   { *sec   = now->tm_sec;  }
  if (dst)   { *dst   = (now->tm_isdst != 0); }
}

// function for converting a float time (e.g. difference of two TimeKeepers)
// into an array of ints
void TimeKeeper::convertTime(double raw, long int convertedTimes[]) // const
{
  long int day, hour, min, sec, remainder;
  static const int secondsInDay = 86400;

  sec = (long int)raw;
  day = sec / secondsInDay;
  remainder = sec - (day * secondsInDay);
  hour = remainder / 3600;
  remainder = sec - ((hour * 3600) + (day * secondsInDay));
  min = remainder / 60;
  remainder = sec - ((hour * 3600) + (day * secondsInDay) + (min * 60));
  sec = remainder;

  convertedTimes[0] = day;
  convertedTimes[1] = hour;
  convertedTimes[2] = min;
  convertedTimes[3] = sec;

  return;
}

// function for printing an array of ints representing a time
// as a human-readable string
const std::string TimeKeeper::printTime(long int timeValue[])
{
  std::string valueNames;
  char temp[20];

  if (timeValue[0] > 0) {
    snprintf(temp, 20, "%ld day%s", timeValue[0], timeValue[0] == 1 ? "" : "s");
    valueNames.append(temp);
  }
  if (timeValue[1] > 0) {
    if (timeValue[0] > 0) {
      valueNames.append(", ");
    }
    snprintf(temp, 20, "%ld hour%s", timeValue[1], timeValue[1] == 1 ? "" : "s");
    valueNames.append(temp);
  }
  if (timeValue[2] > 0) {
    if ((timeValue[1] > 0) || (timeValue[0] > 0)) {
      valueNames.append(", ");
    }
    snprintf(temp, 20, "%ld min%s", timeValue[2], timeValue[2] == 1 ? "" : "s");
    valueNames.append(temp);
  }
  if (timeValue[3] > 0) {
    if ((timeValue[2] > 0) || (timeValue[1] > 0) || (timeValue[0] > 0)) {
      valueNames.append(", ");
    }
    snprintf(temp, 20, "%ld sec%s", timeValue[3], timeValue[3] == 1 ? "" : "s");
    valueNames.append(temp);
  }

  return valueNames;
}

// function for printing a float time difference as a human-readable string
const std::string TimeKeeper::printTime(double diff)
{
  long int temp[4];
  convertTime(diff, temp);
  return printTime(temp);
}

void TimeKeeper::sleep(double seconds)
{
  if (seconds <= 0.0) {
    return;
  }

#ifdef HAVE_USLEEP
  usleep((unsigned int)(1.0e6 * seconds));
  return;
#endif
#if defined(HAVE_SLEEP) && !defined(__APPLE__)
  // equivalent to _sleep() on win32 (not sleep(3))
  Sleep((DWORD)(seconds * 1000.0));
  return;
#endif
#ifdef HAVE_SNOOZE
  snooze((bigtime_t)(1.0e6 * seconds));
  return;
#endif
#ifdef HAVE_SELECT
  struct timeval tv;
  tv.tv_sec = (long)seconds;
  tv.tv_usec = (long)(1.0e6 * (seconds - tv.tv_sec));
  select(0, NULL, NULL, NULL, &tv);
  return;
#endif
#ifdef HAVE_WAITFORSINGLEOBJECT
  HANDLE dummyEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  WaitForSingleObject(dummyEvent, (DWORD)(1000.0 * seconds));
  CloseHandle(dummyEvent);
  return;
#endif

  // fall-back case is fugly manual timekeeping
  TimeKeeper now = TimeKeeper::getCurrent();
  while ((TimeKeeper::getCurrent() - now) < seconds) {
    continue;
  }
  return;
}

void TimeKeeper::setProcessorAffinity(int processor)
{
#ifdef HAVE_SCHED_SETAFFINITY
  /* linuxy fix for time travel */
  cpu_set_t mask;
  CPU_ZERO(&mask);
  CPU_SET(processor, &mask);
  sched_setaffinity(0, sizeof(mask), &mask);
#elif defined(WIN32)
  /* windowsy fix for time travel */
  HANDLE hThread = GetCurrentThread();
  DWORD_PTR dwMask = 1 << processor;
  DWORD_PTR dwProcs = 0;
  GetProcessAffinityMask(NULL, NULL, &dwProcs);
  if (dwMask < dwProcs) {
    logDebugMessage(1, "Unable to set process affinity mask (specified processor does not exist).\n");
    return;
  }
  SetThreadAffinityMask(hThread, dwMask);
#else
  logDebugMessage(1, "Unable to set processor affinity to %d - function not implemented on this platform.\n", processor);
#endif
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>#include "file_utils.h"
#include "log/log.h"

#include <wordexp.h>
#include <fstream>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>

LOG_DECLARE_NAMESPACE("client.common.file_utils");

namespace Cthun {
namespace Common {
namespace FileUtils {

// HERE(ale): copied from Pegasus

// TODO(ale): look for boost alternatives

std::string expandAsDoneByShell(std::string txt) {
    // This will store the expansion outcome
    wordexp_t result;

    // Expand and check the success
    if (wordexp(txt.c_str(), &result, 0) != 0) {
        wordfree(&result);
        return "";
    }

    // Get the expanded text and free the memory
    std::string expanded_txt { result.we_wordv[0] };
    wordfree(&result);
    return expanded_txt;
}

bool fileExists(const std::string& file_path) {
    bool exists { false };
    if (file_path.empty()) {
        LOG_WARNING("file path is an empty string");
    } else {
        std::ifstream file_stream { file_path };
        exists = file_stream.good();
        file_stream.close();
    }
    return exists;
}

void removeFile(const std::string& file_path) {
    if (FileUtils::fileExists(file_path)) {
        if (std::remove(file_path.c_str()) != 0) {
            throw file_error { "failed to remove " + file_path };
        }
    }
}

void streamToFile(const std::string& text,
                  const std::string& file_path,
                  std::ios_base::openmode mode) {
    std::ofstream ofs;
    ofs.open(file_path, mode);
    if (!ofs.is_open()) {
        throw file_error { "failed to open " + file_path };
    }
    ofs << text;
}

void writeToFile(const std::string& text, const std::string& file_path) {
    streamToFile(text, file_path, std::ofstream::out
                                | std::ofstream::trunc);
}

}  // namespace FileUtils
}  // namespace Common
}  // namespace Cthun
<commit_msg>(maint) - Relative path to log.h in file_utils.cpp<commit_after>#include "file_utils.h"
#include "../log/log.h"

#include <wordexp.h>
#include <fstream>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>

LOG_DECLARE_NAMESPACE("client.common.file_utils");

namespace Cthun {
namespace Common {
namespace FileUtils {

// HERE(ale): copied from Pegasus

// TODO(ale): look for boost alternatives

std::string expandAsDoneByShell(std::string txt) {
    // This will store the expansion outcome
    wordexp_t result;

    // Expand and check the success
    if (wordexp(txt.c_str(), &result, 0) != 0) {
        wordfree(&result);
        return "";
    }

    // Get the expanded text and free the memory
    std::string expanded_txt { result.we_wordv[0] };
    wordfree(&result);
    return expanded_txt;
}

bool fileExists(const std::string& file_path) {
    bool exists { false };
    if (file_path.empty()) {
        LOG_WARNING("file path is an empty string");
    } else {
        std::ifstream file_stream { file_path };
        exists = file_stream.good();
        file_stream.close();
    }
    return exists;
}

void removeFile(const std::string& file_path) {
    if (FileUtils::fileExists(file_path)) {
        if (std::remove(file_path.c_str()) != 0) {
            throw file_error { "failed to remove " + file_path };
        }
    }
}

void streamToFile(const std::string& text,
                  const std::string& file_path,
                  std::ios_base::openmode mode) {
    std::ofstream ofs;
    ofs.open(file_path, mode);
    if (!ofs.is_open()) {
        throw file_error { "failed to open " + file_path };
    }
    ofs << text;
}

void writeToFile(const std::string& text, const std::string& file_path) {
    streamToFile(text, file_path, std::ofstream::out
                                | std::ofstream::trunc);
}

}  // namespace FileUtils
}  // namespace Common
}  // namespace Cthun
<|endoftext|>


<commit_before>#include <QObject>
#include <QGraphicsSceneMouseEvent>

#include <dcpappletpage.h>
#include <dcpappletobject.h>

#include "ut_dcpappletpage.h"

void Ut_DcpAppletPage::init()
{
    m_subject = new DcpAppletPage(0);
}

void Ut_DcpAppletPage::cleanup()
{
    delete m_subject;
    m_subject = 0;
}

void Ut_DcpAppletPage::initTestCase()
{
    QSKIP("incomplete", SkipSingle);   // remove this when you've finished
}

void Ut_DcpAppletPage::cleanupTestCase()
{
}

QTEST_MAIN(Ut_DcpAppletPage)
<commit_msg>ut_dcpappletpage first pass (no cases really)<commit_after>#include <QObject>
#include <QGraphicsSceneMouseEvent>

#include <dcpappletpage.h>
#include <dcpappletobject.h>

#include "ut_dcpappletpage.h"

void Ut_DcpAppletPage::init()
{
    m_subject = new DcpAppletPage(0);
}

void Ut_DcpAppletPage::cleanup()
{
    delete m_subject;
    m_subject = 0;
}

void Ut_DcpAppletPage::initTestCase()
{
    QSKIP("incomplete", SkipSingle);   // remove this when you've finished
}

void Ut_DcpAppletPage::cleanupTestCase()
{
}

QTEST_APPLESS_MAIN(Ut_DcpAppletPage)
<|endoftext|>


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

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _BGFX_MATRIX_B3DHOMMATRIX_HXX
#include <basegfx/matrix/b3dhommatrix.hxx>
#endif

// header for class TabPage
#ifndef _SV_TABPAGE_HXX
#include <vcl/tabpage.hxx>
#endif
// header for class FixedLine
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
// header for class MetricField
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
// header for class OKButton
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif

#include "ControllerLockGuard.hxx"

//.............................................................................
namespace chart
{
//.............................................................................

class ThreeD_SceneGeometry_TabPage : public TabPage
{
public:
    ThreeD_SceneGeometry_TabPage( Window* pWindow,
                                  const ::com::sun::star::uno::Reference<
                                      ::com::sun::star::beans::XPropertySet > & xSceneProperties,
                                  ControllerLockHelper & rControllerLockHelper );
    virtual ~ThreeD_SceneGeometry_TabPage();

    // has to be called in case the dialog was closed with OK
    void commitPendingChanges();

    // is called by timer to apply changes to model
    DECL_LINK( AngleChanged, void* );
    // is called immediately when a field changes
    DECL_LINK( AngleEdited, void* );

    // is called by timer to apply changes to model
    DECL_LINK( PerspectiveChanged, void* );
    // is called immediately when a field changes
    DECL_LINK( PerspectiveEdited, void* );
    DECL_LINK( PerspectiveToggled, void* );

private:
    void fillDialogAnglesFromModel() const;
    void applyAnglesToModel();
    void applyPerspectiveToModel();

    double CameraDistanceToPerspective( double fCameraDistance );
    double PerspectiveToCameraDistance( double fPerspective );

    void shiftAngleToValidRange( double& rfAngleDegree );

    ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet > m_xSceneProperties;

    FixedText       m_aFtXRotation;
    MetricField     m_aMFXRotation;

    FixedText       m_aFtYRotation;
    MetricField     m_aMFYRotation;

    FixedText       m_aFtZRotation;
    MetricField     m_aMFZRotation;

    CheckBox        m_aCbxPerspective;
    MetricField     m_aMFPerspective;

    bool            m_bAngleChangePending;
    bool            m_bPerspectiveChangePending;

    ControllerLockHelper & m_rControllerLockHelper;
};

//.............................................................................
} //namespace chart
//.............................................................................

#endif
<commit_msg>INTEGRATION: CWS chart06 (1.2.8); FILE MERGED 2007/06/15 12:47:31 iha 1.2.8.2: #i67754# for right-angled-axes restrict angles to meaningful values 2007/06/11 09:10:18 iha 1.2.8.1: #i67754# right-angled-axes option for 3D charts<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tp_3D_SceneGeometry.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-03 13:39:43 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _CHART2_TP_3D_SCENE_GEOMETRY_HXX
#define _CHART2_TP_3D_SCENE_GEOMETRY_HXX

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _BGFX_MATRIX_B3DHOMMATRIX_HXX
#include <basegfx/matrix/b3dhommatrix.hxx>
#endif

// header for class TabPage
#ifndef _SV_TABPAGE_HXX
#include <vcl/tabpage.hxx>
#endif
// header for class FixedLine
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
// header for class MetricField
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
// header for class OKButton
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif

#include "ControllerLockGuard.hxx"

//.............................................................................
namespace chart
{
//.............................................................................

class ThreeD_SceneGeometry_TabPage : public TabPage
{
public:
    ThreeD_SceneGeometry_TabPage( Window* pWindow,
                                  const ::com::sun::star::uno::Reference<
                                      ::com::sun::star::beans::XPropertySet > & xSceneProperties,
                                  ControllerLockHelper & rControllerLockHelper );
    virtual ~ThreeD_SceneGeometry_TabPage();

    // has to be called in case the dialog was closed with OK
    void commitPendingChanges();

    // is called by timer to apply changes to model
    DECL_LINK( AngleChanged, void* );
    // is called immediately when a field changes
    DECL_LINK( AngleEdited, void* );

    // is called by timer to apply changes to model
    DECL_LINK( PerspectiveChanged, void* );
    // is called immediately when a field changes
    DECL_LINK( PerspectiveEdited, void* );
    DECL_LINK( PerspectiveToggled, void* );
    DECL_LINK( RightAngledAxesToggled, void* );

private:
    void fillDialogAnglesFromModel() const;
    void applyAnglesToModel();
    void applyPerspectiveToModel();

    ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet > m_xSceneProperties;

    CheckBox        m_aCbxRightAngledAxes;

    FixedText       m_aFtXRotation;
    MetricField     m_aMFXRotation;

    FixedText       m_aFtYRotation;
    MetricField     m_aMFYRotation;

    FixedText       m_aFtZRotation;
    MetricField     m_aMFZRotation;

    CheckBox        m_aCbxPerspective;
    MetricField     m_aMFPerspective;

    //to keep old values when switching to right angled axes
    sal_Int64       m_nXRotation;
    sal_Int64       m_nYRotation;
    sal_Int64       m_nZRotation;

    bool            m_bAngleChangePending;
    bool            m_bPerspectiveChangePending;

    ControllerLockHelper & m_rControllerLockHelper;
};

//.............................................................................
} //namespace chart
//.............................................................................

#endif
<|endoftext|>


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

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _BGFX_MATRIX_B3DHOMMATRIX_HXX
#include <basegfx/matrix/b3dhommatrix.hxx>
#endif

// header for class TabPage
#ifndef _SV_TABPAGE_HXX
#include <vcl/tabpage.hxx>
#endif
// header for class FixedLine
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
// header for class MetricField
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
// header for class OKButton
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif

#include "ControllerLockGuard.hxx"

//.............................................................................
namespace chart
{
//.............................................................................

class ThreeD_SceneGeometry_TabPage : public TabPage
{
public:
    ThreeD_SceneGeometry_TabPage( Window* pWindow,
                                  const ::com::sun::star::uno::Reference<
                                      ::com::sun::star::beans::XPropertySet > & xSceneProperties,
                                  ControllerLockHelper & rControllerLockHelper );
    virtual ~ThreeD_SceneGeometry_TabPage();

    // has to be called in case the dialog was closed with OK
    void commitPendingChanges();

    // is called by timer to apply changes to model
    DECL_LINK( AngleChanged, void* );
    // is called immediately when a field changes
    DECL_LINK( AngleEdited, void* );

    // is called by timer to apply changes to model
    DECL_LINK( PerspectiveChanged, void* );
    // is called immediately when a field changes
    DECL_LINK( PerspectiveEdited, void* );
    DECL_LINK( PerspectiveToggled, void* );
    DECL_LINK( RightAngledAxesToggled, void* );

private:
    void fillDialogAnglesFromModel() const;
    void applyAnglesToModel();
    void applyPerspectiveToModel();

    ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet > m_xSceneProperties;

    CheckBox        m_aCbxRightAngledAxes;

    FixedText       m_aFtXRotation;
    MetricField     m_aMFXRotation;

    FixedText       m_aFtYRotation;
    MetricField     m_aMFYRotation;

    FixedText       m_aFtZRotation;
    MetricField     m_aMFZRotation;

    CheckBox        m_aCbxPerspective;
    MetricField     m_aMFPerspective;

    //to keep old values when switching to right angled axes
    sal_Int64       m_nXRotation;
    sal_Int64       m_nYRotation;
    sal_Int64       m_nZRotation;

    bool            m_bAngleChangePending;
    bool            m_bPerspectiveChangePending;

    ControllerLockHelper & m_rControllerLockHelper;
};

//.............................................................................
} //namespace chart
//.............................................................................

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.106); FILE MERGED 2008/04/01 15:04:02 thb 1.3.106.3: #i85898# Stripping all external header guards 2008/04/01 10:50:19 thb 1.3.106.2: #i85898# Stripping all external header guards 2008/03/28 16:43:30 rt 1.3.106.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: tp_3D_SceneGeometry.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _CHART2_TP_3D_SCENE_GEOMETRY_HXX
#define _CHART2_TP_3D_SCENE_GEOMETRY_HXX

#include <com/sun/star/beans/XPropertySet.hpp>
#include <basegfx/matrix/b3dhommatrix.hxx>

// header for class TabPage
#include <vcl/tabpage.hxx>
// header for class FixedLine
#include <vcl/fixed.hxx>
// header for class MetricField
#include <vcl/field.hxx>
// header for class OKButton
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif

#include "ControllerLockGuard.hxx"

//.............................................................................
namespace chart
{
//.............................................................................

class ThreeD_SceneGeometry_TabPage : public TabPage
{
public:
    ThreeD_SceneGeometry_TabPage( Window* pWindow,
                                  const ::com::sun::star::uno::Reference<
                                      ::com::sun::star::beans::XPropertySet > & xSceneProperties,
                                  ControllerLockHelper & rControllerLockHelper );
    virtual ~ThreeD_SceneGeometry_TabPage();

    // has to be called in case the dialog was closed with OK
    void commitPendingChanges();

    // is called by timer to apply changes to model
    DECL_LINK( AngleChanged, void* );
    // is called immediately when a field changes
    DECL_LINK( AngleEdited, void* );

    // is called by timer to apply changes to model
    DECL_LINK( PerspectiveChanged, void* );
    // is called immediately when a field changes
    DECL_LINK( PerspectiveEdited, void* );
    DECL_LINK( PerspectiveToggled, void* );
    DECL_LINK( RightAngledAxesToggled, void* );

private:
    void fillDialogAnglesFromModel() const;
    void applyAnglesToModel();
    void applyPerspectiveToModel();

    ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet > m_xSceneProperties;

    CheckBox        m_aCbxRightAngledAxes;

    FixedText       m_aFtXRotation;
    MetricField     m_aMFXRotation;

    FixedText       m_aFtYRotation;
    MetricField     m_aMFYRotation;

    FixedText       m_aFtZRotation;
    MetricField     m_aMFZRotation;

    CheckBox        m_aCbxPerspective;
    MetricField     m_aMFPerspective;

    //to keep old values when switching to right angled axes
    sal_Int64       m_nXRotation;
    sal_Int64       m_nYRotation;
    sal_Int64       m_nZRotation;

    bool            m_bAngleChangePending;
    bool            m_bPerspectiveChangePending;

    ControllerLockHelper & m_rControllerLockHelper;
};

//.............................................................................
} //namespace chart
//.............................................................................

#endif
<|endoftext|>


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

#include "chrome/browser/dom_ui/shown_sections_handler.h"

#include "base/scoped_ptr.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/prefs/pref_value_store.h"
#include "chrome/common/json_pref_store.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/testing_pref_service.h"
#include "testing/gtest/include/gtest/gtest.h"

class ShownSectionsHandlerTest : public testing::Test {
};

// http://crbug.com/53405
TEST_F(ShownSectionsHandlerTest, DISABLED_MigrateUserPrefs) {
  scoped_ptr<PrefService> pref(new TestingPrefService);

  // Set an *old* value
  pref->RegisterIntegerPref(prefs::kNTPShownSections, 0);
  pref->SetInteger(prefs::kNTPShownSections, THUMB);

  ShownSectionsHandler::MigrateUserPrefs(pref.get(), 0, 1);

  int shown_sections = pref->GetInteger(prefs::kNTPShownSections);

  EXPECT_TRUE(shown_sections & THUMB);
  EXPECT_FALSE(shown_sections & LIST);
  EXPECT_FALSE(shown_sections & RECENT);
  EXPECT_TRUE(shown_sections & TIPS);
  EXPECT_TRUE(shown_sections & SYNC);
}

// http://crbug.com/53405
TEST_F(ShownSectionsHandlerTest, DISABLED_MigrateUserPrefs1To2) {
  scoped_ptr<PrefService> pref(new TestingPrefService);

  // Set an *old* value
  pref->RegisterIntegerPref(prefs::kNTPShownSections, 0);
  pref->SetInteger(prefs::kNTPShownSections, LIST);

  ShownSectionsHandler::MigrateUserPrefs(pref.get(), 1, 2);

  int shown_sections = pref->GetInteger(prefs::kNTPShownSections);

  EXPECT_TRUE(shown_sections & THUMB);
  EXPECT_FALSE(shown_sections & LIST);
}
<commit_msg>Re-enable 2 uni_tests. They started passing again after a revert.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/dom_ui/shown_sections_handler.h"

#include "base/scoped_ptr.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/prefs/pref_value_store.h"
#include "chrome/common/json_pref_store.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/testing_pref_service.h"
#include "testing/gtest/include/gtest/gtest.h"

class ShownSectionsHandlerTest : public testing::Test {
};

TEST_F(ShownSectionsHandlerTest, MigrateUserPrefs) {
  scoped_ptr<PrefService> pref(new TestingPrefService);

  // Set an *old* value
  pref->RegisterIntegerPref(prefs::kNTPShownSections, 0);
  pref->SetInteger(prefs::kNTPShownSections, THUMB);

  ShownSectionsHandler::MigrateUserPrefs(pref.get(), 0, 1);

  int shown_sections = pref->GetInteger(prefs::kNTPShownSections);

  EXPECT_TRUE(shown_sections & THUMB);
  EXPECT_FALSE(shown_sections & LIST);
  EXPECT_FALSE(shown_sections & RECENT);
  EXPECT_TRUE(shown_sections & TIPS);
  EXPECT_TRUE(shown_sections & SYNC);
}

TEST_F(ShownSectionsHandlerTest, MigrateUserPrefs1To2) {
  scoped_ptr<PrefService> pref(new TestingPrefService);

  // Set an *old* value
  pref->RegisterIntegerPref(prefs::kNTPShownSections, 0);
  pref->SetInteger(prefs::kNTPShownSections, LIST);

  ShownSectionsHandler::MigrateUserPrefs(pref.get(), 1, 2);

  int shown_sections = pref->GetInteger(prefs::kNTPShownSections);

  EXPECT_TRUE(shown_sections & THUMB);
  EXPECT_FALSE(shown_sections & LIST);
}
<|endoftext|>


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

#include "chrome/browser/extensions/extension_apitest.h"

// TODO(rafaelw,erikkay) disabled due to flakiness
// BUG=22668 (probably the same bug)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Toolstrip) {
  ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_;
}
<commit_msg>Enable ExtensionApiTest.Toolstrip<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"

// TODO(rafaelw,erikkay) disabled due to flakiness
// BUG=22668 (probably the same bug)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Toolstrip) {
  ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_;
}
<|endoftext|>


<commit_before>//==============================================================================
/// Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved.
/// \author AMD Developer Tools Team
/// \file   vktTimestampedCmdBuf.cpp
/// \brief  A wrapper for internal command buffer which holds 1 timestamp.
//==============================================================================

#include "vktTimestampedCmdBuf.h"

//-----------------------------------------------------------------------------
/// Static method that instantiates a VktTimestampedCmdBuf.
/// \param config A configuration structure.
/// \returns A new VktTimestampedCmdBuf instance.
//-----------------------------------------------------------------------------
VktTimestampedCmdBuf* VktTimestampedCmdBuf::Create(const TimestampedCmdBufConfig& config)
{
    VktTimestampedCmdBuf* pOut = new VktTimestampedCmdBuf();

    if (pOut != nullptr)
    {
        if (pOut->Init(config) != VK_SUCCESS)
        {
            delete pOut;
            pOut = nullptr;
        }
    }

    return pOut;
}
//-----------------------------------------------------------------------------
/// Constructor.
//-----------------------------------------------------------------------------
VktTimestampedCmdBuf::VktTimestampedCmdBuf() :
    m_pInstanceDT(nullptr),
    m_pDeviceDT(nullptr),
    m_cmdPool(VK_NULL_HANDLE),
    m_cmdBuf(VK_NULL_HANDLE)
{
}

//-----------------------------------------------------------------------------
/// Destructor.
//-----------------------------------------------------------------------------
VktTimestampedCmdBuf::~VktTimestampedCmdBuf()
{
    if (m_gpuRes.timestampQueryPool != NULL)
    {
        m_pDeviceDT->DestroyQueryPool(m_config.device, m_gpuRes.timestampQueryPool, nullptr);
        m_gpuRes.timestampQueryPool = NULL;
    }

    if (m_gpuRes.timestampBuffer != NULL)
    {
        m_pDeviceDT->DestroyBuffer(m_config.device, m_gpuRes.timestampBuffer, nullptr);
        m_gpuRes.timestampBuffer = NULL;
    }

    if (m_gpuRes.timestampMem != NULL)
    {
        m_pDeviceDT->FreeMemory(m_config.device, m_gpuRes.timestampMem, nullptr);
        m_gpuRes.timestampMem = NULL;
    }

    if (m_cmdBuf != VK_NULL_HANDLE)
    {
        m_pDeviceDT->FreeCommandBuffers(m_config.device, m_cmdPool, 1, &m_cmdBuf);
        m_cmdBuf = VK_NULL_HANDLE;
    }
}

//-----------------------------------------------------------------------------
/// Perform all initialization.
/// \param config A pointer to a profiler configuration structure.
/// \returns The result code for initialization.
//-----------------------------------------------------------------------------
VkResult VktTimestampedCmdBuf::Init(const TimestampedCmdBufConfig& config)   ///< [in] Pointer to profiler configuration
{
    VkResult result = VK_INCOMPLETE;

    memcpy(&m_config, &config, sizeof(m_config));

    if ((m_config.physicalDevice != VK_NULL_HANDLE) && (m_config.device != VK_NULL_HANDLE))
    {
        m_pInstanceDT = instance_dispatch_table(config.physicalDevice);
        m_pDeviceDT = device_dispatch_table(config.device);

        m_pInstanceDT->GetPhysicalDeviceMemoryProperties(m_config.physicalDevice, &m_memProps);

        // Create command pool
        VkCommandPoolCreateInfo cmdPoolCreateInfo = {};
        cmdPoolCreateInfo.sType            = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
        cmdPoolCreateInfo.pNext            = nullptr;
        cmdPoolCreateInfo.queueFamilyIndex = m_config.queueFamilyIndex;
        cmdPoolCreateInfo.flags            = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
        result = m_pDeviceDT->CreateCommandPool(m_config.device, &cmdPoolCreateInfo, nullptr, &m_cmdPool);

        // Create command buffer
        if (result == VK_SUCCESS)
        {
            VkCommandBufferAllocateInfo cmdBufAllocInfo = {};
            cmdBufAllocInfo.sType              = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
            cmdBufAllocInfo.pNext              = nullptr;
            cmdBufAllocInfo.commandPool        = m_cmdPool;
            cmdBufAllocInfo.level              = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
            cmdBufAllocInfo.commandBufferCount = 1;
            result = m_pDeviceDT->AllocateCommandBuffers(m_config.device, &cmdBufAllocInfo, &m_cmdBuf);
        }

        // Create query pool
        if (result == VK_SUCCESS)
        {
            VkQueryPoolCreateInfo queryPoolCreateInfo = {};
            queryPoolCreateInfo.sType      = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
            queryPoolCreateInfo.pNext      = nullptr;
            queryPoolCreateInfo.queryType  = VK_QUERY_TYPE_TIMESTAMP;
            queryPoolCreateInfo.queryCount = 1;
            result = m_pDeviceDT->CreateQueryPool(m_config.device, &queryPoolCreateInfo, nullptr, &m_gpuRes.timestampQueryPool);
        }

        // Create timestamp buffer
        if (result == VK_SUCCESS)
        {
            VkBufferCreateInfo bufferCreateInfo = {};
            bufferCreateInfo.sType                 = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
            bufferCreateInfo.pNext                 = nullptr;
            bufferCreateInfo.usage                 = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
            bufferCreateInfo.size                  = sizeof(UINT64);
            bufferCreateInfo.queueFamilyIndexCount = 0;
            bufferCreateInfo.pQueueFamilyIndices   = nullptr;
            bufferCreateInfo.sharingMode           = VK_SHARING_MODE_EXCLUSIVE;
            bufferCreateInfo.flags                 = 0;
            result = m_pDeviceDT->CreateBuffer(m_config.device, &bufferCreateInfo, nullptr, &m_gpuRes.timestampBuffer);

            if (result == VK_SUCCESS)
            {
                VkMemoryRequirements memReqs = {};
                m_pDeviceDT->GetBufferMemoryRequirements(m_config.device, m_gpuRes.timestampBuffer, &memReqs);

                VkMemoryAllocateInfo allocInfo = {};
                allocInfo.sType          = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
                allocInfo.pNext          = nullptr;
                allocInfo.allocationSize = memReqs.size;

                result = MemTypeFromProps(
                    memReqs.memoryTypeBits,
                    VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
                    &allocInfo.memoryTypeIndex);

                if (result == VK_SUCCESS)
                {
                    result = m_pDeviceDT->AllocateMemory(m_config.device, &allocInfo, nullptr, &m_gpuRes.timestampMem);

                    if (result == VK_SUCCESS)
                    {
                        result = m_pDeviceDT->BindBufferMemory(m_config.device, m_gpuRes.timestampBuffer, m_gpuRes.timestampMem, 0);

                        if (result == VK_SUCCESS)
                        {
                            void* pMappedMem = nullptr;

                            result = m_pDeviceDT->MapMemory(
                                m_config.device,
                                m_gpuRes.timestampMem,
                                0,
                                VK_WHOLE_SIZE,
                                0,
                                &pMappedMem);

                            if (result == VK_SUCCESS)
                            {
                                memset(pMappedMem, 0, memReqs.size);
                                m_pDeviceDT->UnmapMemory(m_config.device, m_gpuRes.timestampMem);
                            }
                        }
                    }
                }
            }
        }

        // Fill in the command buffer
        if (result == VK_SUCCESS)
        {
            VkCommandBufferInheritanceInfo cmdBufInheritInfo = {};
            cmdBufInheritInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO;
            cmdBufInheritInfo.pNext = nullptr;
            cmdBufInheritInfo.renderPass = VK_NULL_HANDLE;
            cmdBufInheritInfo.subpass = 0;
            cmdBufInheritInfo.framebuffer = VK_NULL_HANDLE;
            cmdBufInheritInfo.occlusionQueryEnable = VK_FALSE;
            cmdBufInheritInfo.queryFlags = 0;
            cmdBufInheritInfo.pipelineStatistics = 0;

            VkCommandBufferBeginInfo cmdBufBeginInfo = {};
            cmdBufBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
            cmdBufBeginInfo.pNext = nullptr;
            cmdBufBeginInfo.flags = 0;
            cmdBufBeginInfo.pInheritanceInfo = &cmdBufInheritInfo;

            result = m_pDeviceDT->BeginCommandBuffer(m_cmdBuf, &cmdBufBeginInfo);

            m_pDeviceDT->CmdResetQueryPool(m_cmdBuf, m_gpuRes.timestampQueryPool, 0, 1);

            // Inject timestamp
            m_pDeviceDT->CmdWriteTimestamp(
                m_cmdBuf,
                m_config.pipelineLoc,
                m_gpuRes.timestampQueryPool,
                0);

            if (m_config.mapTimestampMem == true)
            {
                m_pDeviceDT->CmdCopyQueryPoolResults(
                    m_cmdBuf,
                    m_gpuRes.timestampQueryPool,
                    0,
                    1,
                    m_gpuRes.timestampBuffer,
                    0,
                    sizeof(UINT64),
                    VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT);
            }

            result = m_pDeviceDT->EndCommandBuffer(m_cmdBuf);

        }
    }

    return result;
}

//-----------------------------------------------------------------------------
/// Find a memory type from available heaps.
/// \param typeBits The requested mem type.
/// \param reqsMask Mem requirements.
/// \param pTypeIdx The output heap index.
/// \returns A Vulkan result code.
//-----------------------------------------------------------------------------
VkResult VktTimestampedCmdBuf::MemTypeFromProps(
    UINT    typeBits,
    VkFlags reqsMask,
    UINT*   pTypeIdx)
{
    // Search memory types to find first index with those properties
    for (UINT i = 0; i < 32; i++)
    {
        if ((typeBits & 1) == 1)
        {
            // Type is available, does it match user properties?
            if ((m_memProps.memoryTypes[i].propertyFlags & reqsMask) == reqsMask)
            {
                *pTypeIdx = i;
                return VK_SUCCESS;
            }
        }

        typeBits >>= 1;
    }

    // No memory types matched, return failure
    return VK_INCOMPLETE;
}

//-----------------------------------------------------------------------------
/// GetTimestampResult
/// \param pOutClock A pointer to a UINT64 which will hold our clock value.
/// \returns The result code for initialization.
//-----------------------------------------------------------------------------
VkResult VktTimestampedCmdBuf::GetTimestampResult(UINT64* pOutClock)
{
    VkResult result = VK_INCOMPLETE;

    if (pOutClock != nullptr)
    {
        UINT64* pTimestampData = nullptr;

        // We use vkCmdCopyQueryPoolResults
        if (m_config.mapTimestampMem == true)
        {
            result = m_pDeviceDT->MapMemory(
                m_config.device,
                m_gpuRes.timestampMem,
                0,
                VK_WHOLE_SIZE,
                0,
                (void**)&pTimestampData);

            *pOutClock = *pTimestampData;
        }

        // We use vkGetQueryPoolResults
        else
        {
            result = m_pDeviceDT->GetQueryPoolResults(
                m_config.device,
                m_gpuRes.timestampQueryPool,
                0,
                1,
                sizeof(UINT64),
                pOutClock,
                sizeof(UINT64),
                VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT);
        }
    }

    return result;
}
<commit_msg>Implement Vulkan timestamp calibration for GPU/CPU sync.<commit_after>//==============================================================================
/// Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved.
/// \author AMD Developer Tools Team
/// \file   vktTimestampedCmdBuf.cpp
/// \brief  A wrapper for internal command buffer which holds 1 timestamp.
//==============================================================================

#include "vktTimestampedCmdBuf.h"

//-----------------------------------------------------------------------------
/// Static method that instantiates a VktTimestampedCmdBuf.
/// \param config A configuration structure.
/// \returns A new VktTimestampedCmdBuf instance.
//-----------------------------------------------------------------------------
VktTimestampedCmdBuf* VktTimestampedCmdBuf::Create(const TimestampedCmdBufConfig& config)
{
    VktTimestampedCmdBuf* pOut = new VktTimestampedCmdBuf();

    if (pOut != nullptr)
    {
        if (pOut->Init(config) != VK_SUCCESS)
        {
            delete pOut;
            pOut = nullptr;
        }
    }

    return pOut;
}
//-----------------------------------------------------------------------------
/// Constructor.
//-----------------------------------------------------------------------------
VktTimestampedCmdBuf::VktTimestampedCmdBuf() :
    m_pInstanceDT(nullptr),
    m_pDeviceDT(nullptr),
    m_cmdPool(VK_NULL_HANDLE),
    m_cmdBuf(VK_NULL_HANDLE)
{
}

//-----------------------------------------------------------------------------
/// Destructor.
//-----------------------------------------------------------------------------
VktTimestampedCmdBuf::~VktTimestampedCmdBuf()
{
    if (m_gpuRes.timestampQueryPool != NULL)
    {
        m_pDeviceDT->DestroyQueryPool(m_config.device, m_gpuRes.timestampQueryPool, nullptr);
        m_gpuRes.timestampQueryPool = NULL;
    }

    if (m_gpuRes.timestampBuffer != NULL)
    {
        m_pDeviceDT->DestroyBuffer(m_config.device, m_gpuRes.timestampBuffer, nullptr);
        m_gpuRes.timestampBuffer = NULL;
    }

    if (m_gpuRes.timestampMem != NULL)
    {
        m_pDeviceDT->FreeMemory(m_config.device, m_gpuRes.timestampMem, nullptr);
        m_gpuRes.timestampMem = NULL;
    }

    if (m_cmdBuf != VK_NULL_HANDLE)
    {
        m_pDeviceDT->FreeCommandBuffers(m_config.device, m_cmdPool, 1, &m_cmdBuf);
        m_cmdBuf = VK_NULL_HANDLE;
    }
}

//-----------------------------------------------------------------------------
/// Perform all initialization.
/// \param config A pointer to a profiler configuration structure.
/// \returns The result code for initialization.
//-----------------------------------------------------------------------------
VkResult VktTimestampedCmdBuf::Init(const TimestampedCmdBufConfig& config)   ///< [in] Pointer to profiler configuration
{
    VkResult result = VK_INCOMPLETE;

    memcpy(&m_config, &config, sizeof(m_config));

    if ((m_config.physicalDevice != VK_NULL_HANDLE) && (m_config.device != VK_NULL_HANDLE))
    {
        m_pInstanceDT = instance_dispatch_table(config.physicalDevice);
        m_pDeviceDT = device_dispatch_table(config.device);

        m_pInstanceDT->GetPhysicalDeviceMemoryProperties(m_config.physicalDevice, &m_memProps);

        // Create command pool
        VkCommandPoolCreateInfo cmdPoolCreateInfo = {};
        cmdPoolCreateInfo.sType            = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
        cmdPoolCreateInfo.pNext            = nullptr;
        cmdPoolCreateInfo.queueFamilyIndex = m_config.queueFamilyIndex;
        cmdPoolCreateInfo.flags            = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
        result = m_pDeviceDT->CreateCommandPool(m_config.device, &cmdPoolCreateInfo, nullptr, &m_cmdPool);

        // Create command buffer
        if (result == VK_SUCCESS)
        {
            VkCommandBufferAllocateInfo cmdBufAllocInfo = {};
            cmdBufAllocInfo.sType              = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
            cmdBufAllocInfo.pNext              = nullptr;
            cmdBufAllocInfo.commandPool        = m_cmdPool;
            cmdBufAllocInfo.level              = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
            cmdBufAllocInfo.commandBufferCount = 1;
            result = m_pDeviceDT->AllocateCommandBuffers(m_config.device, &cmdBufAllocInfo, &m_cmdBuf);
        }

        // Create query pool
        if (result == VK_SUCCESS)
        {
            VkQueryPoolCreateInfo queryPoolCreateInfo = {};
            queryPoolCreateInfo.sType      = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
            queryPoolCreateInfo.pNext      = nullptr;
            queryPoolCreateInfo.queryType  = VK_QUERY_TYPE_TIMESTAMP;
            queryPoolCreateInfo.queryCount = 1;
            result = m_pDeviceDT->CreateQueryPool(m_config.device, &queryPoolCreateInfo, nullptr, &m_gpuRes.timestampQueryPool);
        }

        // Create timestamp buffer
        if (result == VK_SUCCESS)
        {
            VkBufferCreateInfo bufferCreateInfo = {};
            bufferCreateInfo.sType                 = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
            bufferCreateInfo.pNext                 = nullptr;
            bufferCreateInfo.usage                 = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
            bufferCreateInfo.size                  = sizeof(UINT64);
            bufferCreateInfo.queueFamilyIndexCount = 0;
            bufferCreateInfo.pQueueFamilyIndices   = nullptr;
            bufferCreateInfo.sharingMode           = VK_SHARING_MODE_EXCLUSIVE;
            bufferCreateInfo.flags                 = 0;
            result = m_pDeviceDT->CreateBuffer(m_config.device, &bufferCreateInfo, nullptr, &m_gpuRes.timestampBuffer);

            if (result == VK_SUCCESS)
            {
                VkMemoryRequirements memReqs = {};
                m_pDeviceDT->GetBufferMemoryRequirements(m_config.device, m_gpuRes.timestampBuffer, &memReqs);

                VkMemoryAllocateInfo allocInfo = {};
                allocInfo.sType          = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
                allocInfo.pNext          = nullptr;
                allocInfo.allocationSize = memReqs.size;

                result = MemTypeFromProps(
                    memReqs.memoryTypeBits,
                    VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
                    &allocInfo.memoryTypeIndex);

                if (result == VK_SUCCESS)
                {
                    result = m_pDeviceDT->AllocateMemory(m_config.device, &allocInfo, nullptr, &m_gpuRes.timestampMem);

                    if (result == VK_SUCCESS)
                    {
                        result = m_pDeviceDT->BindBufferMemory(m_config.device, m_gpuRes.timestampBuffer, m_gpuRes.timestampMem, 0);

                        if (result == VK_SUCCESS)
                        {
                            void* pMappedMem = nullptr;

                            result = m_pDeviceDT->MapMemory(
                                m_config.device,
                                m_gpuRes.timestampMem,
                                0,
                                VK_WHOLE_SIZE,
                                0,
                                &pMappedMem);

                            if (result == VK_SUCCESS)
                            {
                                memset(pMappedMem, 0, (size_t)memReqs.size);
                                m_pDeviceDT->UnmapMemory(m_config.device, m_gpuRes.timestampMem);
                            }
                        }
                    }
                }
            }
        }

        // Fill in the command buffer
        if (result == VK_SUCCESS)
        {
            VkCommandBufferInheritanceInfo cmdBufInheritInfo = {};
            cmdBufInheritInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO;
            cmdBufInheritInfo.pNext = nullptr;
            cmdBufInheritInfo.renderPass = VK_NULL_HANDLE;
            cmdBufInheritInfo.subpass = 0;
            cmdBufInheritInfo.framebuffer = VK_NULL_HANDLE;
            cmdBufInheritInfo.occlusionQueryEnable = VK_FALSE;
            cmdBufInheritInfo.queryFlags = 0;
            cmdBufInheritInfo.pipelineStatistics = 0;

            VkCommandBufferBeginInfo cmdBufBeginInfo = {};
            cmdBufBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
            cmdBufBeginInfo.pNext = nullptr;
            cmdBufBeginInfo.flags = 0;
            cmdBufBeginInfo.pInheritanceInfo = &cmdBufInheritInfo;

            result = m_pDeviceDT->BeginCommandBuffer(m_cmdBuf, &cmdBufBeginInfo);

            m_pDeviceDT->CmdResetQueryPool(m_cmdBuf, m_gpuRes.timestampQueryPool, 0, 1);

            // Inject timestamp
            m_pDeviceDT->CmdWriteTimestamp(
                m_cmdBuf,
                m_config.pipelineLoc,
                m_gpuRes.timestampQueryPool,
                0);

            if (m_config.mapTimestampMem == true)
            {
                m_pDeviceDT->CmdCopyQueryPoolResults(
                    m_cmdBuf,
                    m_gpuRes.timestampQueryPool,
                    0,
                    1,
                    m_gpuRes.timestampBuffer,
                    0,
                    sizeof(UINT64),
                    VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT);
            }

            result = m_pDeviceDT->EndCommandBuffer(m_cmdBuf);

        }
    }

    return result;
}

//-----------------------------------------------------------------------------
/// Find a memory type from available heaps.
/// \param typeBits The requested mem type.
/// \param reqsMask Mem requirements.
/// \param pTypeIdx The output heap index.
/// \returns A Vulkan result code.
//-----------------------------------------------------------------------------
VkResult VktTimestampedCmdBuf::MemTypeFromProps(
    UINT    typeBits,
    VkFlags reqsMask,
    UINT*   pTypeIdx)
{
    // Search memory types to find first index with those properties
    for (UINT i = 0; i < 32; i++)
    {
        if ((typeBits & 1) == 1)
        {
            // Type is available, does it match user properties?
            if ((m_memProps.memoryTypes[i].propertyFlags & reqsMask) == reqsMask)
            {
                *pTypeIdx = i;
                return VK_SUCCESS;
            }
        }

        typeBits >>= 1;
    }

    // No memory types matched, return failure
    return VK_INCOMPLETE;
}

//-----------------------------------------------------------------------------
/// GetTimestampResult
/// \param pOutClock A pointer to a UINT64 which will hold our clock value.
/// \returns The result code for initialization.
//-----------------------------------------------------------------------------
VkResult VktTimestampedCmdBuf::GetTimestampResult(UINT64* pOutClock)
{
    VkResult result = VK_INCOMPLETE;

    if (pOutClock != nullptr)
    {
        UINT64* pTimestampData = nullptr;

        // We use vkCmdCopyQueryPoolResults
        if (m_config.mapTimestampMem == true)
        {
            result = m_pDeviceDT->MapMemory(
                m_config.device,
                m_gpuRes.timestampMem,
                0,
                VK_WHOLE_SIZE,
                0,
                (void**)&pTimestampData);

            *pOutClock = *pTimestampData;
        }

        // We use vkGetQueryPoolResults
        else
        {
            result = m_pDeviceDT->GetQueryPoolResults(
                m_config.device,
                m_gpuRes.timestampQueryPool,
                0,
                1,
                sizeof(UINT64),
                pOutClock,
                sizeof(UINT64),
                VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT);
        }
    }

    return result;
}
<|endoftext|>


<commit_before>// Copyright 2016 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com

#include "core/fpdfapi/font/cpdf_type3font.h"

#include <utility>

#include "core/fpdfapi/font/cpdf_type3char.h"
#include "core/fpdfapi/page/cpdf_form.h"
#include "core/fpdfapi/page/pageint.h"
#include "core/fpdfapi/parser/cpdf_array.h"
#include "core/fpdfapi/parser/cpdf_dictionary.h"
#include "core/fpdfapi/parser/cpdf_stream.h"
#include "core/fxcrt/fx_system.h"
#include "third_party/base/stl_util.h"

#define FPDF_MAX_TYPE3_FORM_LEVEL 4

CPDF_Type3Font::CPDF_Type3Font()
    : m_pCharProcs(nullptr),
      m_pPageResources(nullptr),
      m_pFontResources(nullptr),
      m_CharLoadingDepth(0) {
  FXSYS_memset(m_CharWidthL, 0, sizeof(m_CharWidthL));
}

CPDF_Type3Font::~CPDF_Type3Font() {}

bool CPDF_Type3Font::IsType3Font() const {
  return true;
}

const CPDF_Type3Font* CPDF_Type3Font::AsType3Font() const {
  return this;
}

CPDF_Type3Font* CPDF_Type3Font::AsType3Font() {
  return this;
}

bool CPDF_Type3Font::Load() {
  m_pFontResources = m_pFontDict->GetDictFor("Resources");
  CPDF_Array* pMatrix = m_pFontDict->GetArrayFor("FontMatrix");
  FX_FLOAT xscale = 1.0f, yscale = 1.0f;
  if (pMatrix) {
    m_FontMatrix = pMatrix->GetMatrix();
    xscale = m_FontMatrix.a;
    yscale = m_FontMatrix.d;
  }
  CPDF_Array* pBBox = m_pFontDict->GetArrayFor("FontBBox");
  if (pBBox) {
    m_FontBBox.left = (int32_t)(pBBox->GetNumberAt(0) * xscale * 1000);
    m_FontBBox.bottom = (int32_t)(pBBox->GetNumberAt(1) * yscale * 1000);
    m_FontBBox.right = (int32_t)(pBBox->GetNumberAt(2) * xscale * 1000);
    m_FontBBox.top = (int32_t)(pBBox->GetNumberAt(3) * yscale * 1000);
  }
  int StartChar = m_pFontDict->GetIntegerFor("FirstChar");
  CPDF_Array* pWidthArray = m_pFontDict->GetArrayFor("Widths");
  if (pWidthArray && (StartChar >= 0 && StartChar < 256)) {
    size_t count = pWidthArray->GetCount();
    if (count > 256)
      count = 256;
    if (StartChar + count > 256)
      count = 256 - StartChar;
    for (size_t i = 0; i < count; i++) {
      m_CharWidthL[StartChar + i] =
          FXSYS_round(pWidthArray->GetNumberAt(i) * xscale * 1000);
    }
  }
  m_pCharProcs = m_pFontDict->GetDictFor("CharProcs");
  CPDF_Object* pEncoding = m_pFontDict->GetDirectObjectFor("Encoding");
  if (pEncoding) {
    LoadPDFEncoding(pEncoding, m_BaseEncoding, &m_CharNames, false, false);
    if (!m_CharNames.empty()) {
      for (int i = 0; i < 256; i++) {
        m_Encoding.m_Unicodes[i] =
            PDF_UnicodeFromAdobeName(m_CharNames[i].c_str());
        if (m_Encoding.m_Unicodes[i] == 0) {
          m_Encoding.m_Unicodes[i] = i;
        }
      }
    }
  }
  return true;
}

void CPDF_Type3Font::CheckType3FontMetrics() {
  CheckFontMetrics();
}

CPDF_Type3Char* CPDF_Type3Font::LoadChar(uint32_t charcode) {
  if (m_CharLoadingDepth >= FPDF_MAX_TYPE3_FORM_LEVEL)
    return nullptr;

  auto it = m_CacheMap.find(charcode);
  if (it != m_CacheMap.end())
    return it->second.get();

  const FX_CHAR* name = GetAdobeCharName(m_BaseEncoding, m_CharNames, charcode);
  if (!name)
    return nullptr;

  CPDF_Stream* pStream =
      ToStream(m_pCharProcs ? m_pCharProcs->GetDirectObjectFor(name) : nullptr);
  if (!pStream)
    return nullptr;

  std::unique_ptr<CPDF_Type3Char> pNewChar(new CPDF_Type3Char(new CPDF_Form(
      m_pDocument, m_pFontResources ? m_pFontResources : m_pPageResources,
      pStream, nullptr)));

  // This can trigger recursion into this method. The content of |m_CacheMap|
  // can change as a result. Thus after it returns, check the cache again for
  // a cache hit.
  m_CharLoadingDepth++;
  pNewChar->m_pForm->ParseContent(nullptr, nullptr, pNewChar.get());
  m_CharLoadingDepth--;
  it = m_CacheMap.find(charcode);
  if (it != m_CacheMap.end())
    return it->second.get();

  FX_FLOAT scale = m_FontMatrix.GetXUnit();
  pNewChar->m_Width = (int32_t)(pNewChar->m_Width * scale + 0.5f);
  FX_RECT& rcBBox = pNewChar->m_BBox;
  CFX_FloatRect char_rect(
      (FX_FLOAT)rcBBox.left / 1000.0f, (FX_FLOAT)rcBBox.bottom / 1000.0f,
      (FX_FLOAT)rcBBox.right / 1000.0f, (FX_FLOAT)rcBBox.top / 1000.0f);
  if (rcBBox.right <= rcBBox.left || rcBBox.bottom >= rcBBox.top)
    char_rect = pNewChar->m_pForm->CalcBoundingBox();

  char_rect.Transform(&m_FontMatrix);
  rcBBox.left = FXSYS_round(char_rect.left * 1000);
  rcBBox.right = FXSYS_round(char_rect.right * 1000);
  rcBBox.top = FXSYS_round(char_rect.top * 1000);
  rcBBox.bottom = FXSYS_round(char_rect.bottom * 1000);

  ASSERT(!pdfium::ContainsKey(m_CacheMap, charcode));
  m_CacheMap[charcode] = std::move(pNewChar);
  CPDF_Type3Char* pCachedChar = m_CacheMap[charcode].get();
  if (pCachedChar->m_pForm->GetPageObjectList()->empty())
    pCachedChar->m_pForm.reset();
  return pCachedChar;
}

int CPDF_Type3Font::GetCharWidthF(uint32_t charcode) {
  if (charcode >= FX_ArraySize(m_CharWidthL))
    charcode = 0;

  if (m_CharWidthL[charcode])
    return m_CharWidthL[charcode];

  const CPDF_Type3Char* pChar = LoadChar(charcode);
  return pChar ? pChar->m_Width : 0;
}

FX_RECT CPDF_Type3Font::GetCharBBox(uint32_t charcode) {
  const CPDF_Type3Char* pChar = LoadChar(charcode);
  return pChar ? pChar->m_BBox : FX_RECT();
}
<commit_msg>Stop using Encoding array to get unicode from charcode in Type 3 fonts<commit_after>// Copyright 2016 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com

#include "core/fpdfapi/font/cpdf_type3font.h"

#include <utility>

#include "core/fpdfapi/font/cpdf_type3char.h"
#include "core/fpdfapi/page/cpdf_form.h"
#include "core/fpdfapi/page/pageint.h"
#include "core/fpdfapi/parser/cpdf_array.h"
#include "core/fpdfapi/parser/cpdf_dictionary.h"
#include "core/fpdfapi/parser/cpdf_stream.h"
#include "core/fxcrt/fx_system.h"
#include "third_party/base/stl_util.h"

#define FPDF_MAX_TYPE3_FORM_LEVEL 4

CPDF_Type3Font::CPDF_Type3Font()
    : m_pCharProcs(nullptr),
      m_pPageResources(nullptr),
      m_pFontResources(nullptr),
      m_CharLoadingDepth(0) {
  FXSYS_memset(m_CharWidthL, 0, sizeof(m_CharWidthL));
}

CPDF_Type3Font::~CPDF_Type3Font() {}

bool CPDF_Type3Font::IsType3Font() const {
  return true;
}

const CPDF_Type3Font* CPDF_Type3Font::AsType3Font() const {
  return this;
}

CPDF_Type3Font* CPDF_Type3Font::AsType3Font() {
  return this;
}

bool CPDF_Type3Font::Load() {
  m_pFontResources = m_pFontDict->GetDictFor("Resources");
  CPDF_Array* pMatrix = m_pFontDict->GetArrayFor("FontMatrix");
  FX_FLOAT xscale = 1.0f, yscale = 1.0f;
  if (pMatrix) {
    m_FontMatrix = pMatrix->GetMatrix();
    xscale = m_FontMatrix.a;
    yscale = m_FontMatrix.d;
  }
  CPDF_Array* pBBox = m_pFontDict->GetArrayFor("FontBBox");
  if (pBBox) {
    m_FontBBox.left = (int32_t)(pBBox->GetNumberAt(0) * xscale * 1000);
    m_FontBBox.bottom = (int32_t)(pBBox->GetNumberAt(1) * yscale * 1000);
    m_FontBBox.right = (int32_t)(pBBox->GetNumberAt(2) * xscale * 1000);
    m_FontBBox.top = (int32_t)(pBBox->GetNumberAt(3) * yscale * 1000);
  }
  int StartChar = m_pFontDict->GetIntegerFor("FirstChar");
  CPDF_Array* pWidthArray = m_pFontDict->GetArrayFor("Widths");
  if (pWidthArray && (StartChar >= 0 && StartChar < 256)) {
    size_t count = pWidthArray->GetCount();
    if (count > 256)
      count = 256;
    if (StartChar + count > 256)
      count = 256 - StartChar;
    for (size_t i = 0; i < count; i++) {
      m_CharWidthL[StartChar + i] =
          FXSYS_round(pWidthArray->GetNumberAt(i) * xscale * 1000);
    }
  }
  m_pCharProcs = m_pFontDict->GetDictFor("CharProcs");
  CPDF_Object* pEncoding = m_pFontDict->GetDirectObjectFor("Encoding");
  if (pEncoding)
    LoadPDFEncoding(pEncoding, m_BaseEncoding, &m_CharNames, false, false);
  return true;
}

void CPDF_Type3Font::CheckType3FontMetrics() {
  CheckFontMetrics();
}

CPDF_Type3Char* CPDF_Type3Font::LoadChar(uint32_t charcode) {
  if (m_CharLoadingDepth >= FPDF_MAX_TYPE3_FORM_LEVEL)
    return nullptr;

  auto it = m_CacheMap.find(charcode);
  if (it != m_CacheMap.end())
    return it->second.get();

  const FX_CHAR* name = GetAdobeCharName(m_BaseEncoding, m_CharNames, charcode);
  if (!name)
    return nullptr;

  CPDF_Stream* pStream =
      ToStream(m_pCharProcs ? m_pCharProcs->GetDirectObjectFor(name) : nullptr);
  if (!pStream)
    return nullptr;

  std::unique_ptr<CPDF_Type3Char> pNewChar(new CPDF_Type3Char(new CPDF_Form(
      m_pDocument, m_pFontResources ? m_pFontResources : m_pPageResources,
      pStream, nullptr)));

  // This can trigger recursion into this method. The content of |m_CacheMap|
  // can change as a result. Thus after it returns, check the cache again for
  // a cache hit.
  m_CharLoadingDepth++;
  pNewChar->m_pForm->ParseContent(nullptr, nullptr, pNewChar.get());
  m_CharLoadingDepth--;
  it = m_CacheMap.find(charcode);
  if (it != m_CacheMap.end())
    return it->second.get();

  FX_FLOAT scale = m_FontMatrix.GetXUnit();
  pNewChar->m_Width = (int32_t)(pNewChar->m_Width * scale + 0.5f);
  FX_RECT& rcBBox = pNewChar->m_BBox;
  CFX_FloatRect char_rect(
      (FX_FLOAT)rcBBox.left / 1000.0f, (FX_FLOAT)rcBBox.bottom / 1000.0f,
      (FX_FLOAT)rcBBox.right / 1000.0f, (FX_FLOAT)rcBBox.top / 1000.0f);
  if (rcBBox.right <= rcBBox.left || rcBBox.bottom >= rcBBox.top)
    char_rect = pNewChar->m_pForm->CalcBoundingBox();

  char_rect.Transform(&m_FontMatrix);
  rcBBox.left = FXSYS_round(char_rect.left * 1000);
  rcBBox.right = FXSYS_round(char_rect.right * 1000);
  rcBBox.top = FXSYS_round(char_rect.top * 1000);
  rcBBox.bottom = FXSYS_round(char_rect.bottom * 1000);

  ASSERT(!pdfium::ContainsKey(m_CacheMap, charcode));
  m_CacheMap[charcode] = std::move(pNewChar);
  CPDF_Type3Char* pCachedChar = m_CacheMap[charcode].get();
  if (pCachedChar->m_pForm->GetPageObjectList()->empty())
    pCachedChar->m_pForm.reset();
  return pCachedChar;
}

int CPDF_Type3Font::GetCharWidthF(uint32_t charcode) {
  if (charcode >= FX_ArraySize(m_CharWidthL))
    charcode = 0;

  if (m_CharWidthL[charcode])
    return m_CharWidthL[charcode];

  const CPDF_Type3Char* pChar = LoadChar(charcode);
  return pChar ? pChar->m_Width : 0;
}

FX_RECT CPDF_Type3Font::GetCharBBox(uint32_t charcode) {
  const CPDF_Type3Char* pChar = LoadChar(charcode);
  return pChar ? pChar->m_BBox : FX_RECT();
}
<|endoftext|>