<commit_before>// Copyright (c) 2012, Steinwurf ApS
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Steinwurf ApS nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL Steinwurf ApS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "file_input_stream.hpp"
#include "error.hpp"

#include <fstream>
#include <cassert>

namespace sak
{

    file_input_stream::file_input_stream()
        : m_filesize(0)
    {
    }

    file_input_stream::file_input_stream(const std::string& filename)
        : m_filesize(0)
    {
        open(filename);
    }

    void file_input_stream::open(const std::string& filename)
    {
        assert(!m_file.is_open());

        boost::system::error_code ec;
        open(filename, ec);

        // If an error throw
        error::throw_error(ec);
    }

    void file_input_stream::open(const std::string& filename,
                                 boost::system::error_code& ec)
    {
        assert(!m_file.is_open());

        m_file.open(filename.c_str(),
                    std::ios::in | std::ios::binary);

        if (!m_file.is_open())
        {
            ec = error::make_error_code(error::failed_open_file);
            return;
        }

        m_file.seekg(0, std::ios::end);
        assert(m_file);

        // We cannot use the read_position function here due to a
        // problem on the iOS platform described in the read_position
        // function.
        auto pos = m_file.tellg();
        assert(pos >= 0);

        m_filesize = (uint32_t) pos;

        m_file.seekg(0, std::ios::beg);
        assert(m_file);
    }

    void file_input_stream::seek(uint32_t pos)
    {
        assert(m_file.is_open());
        m_file.seekg(pos, std::ios::beg);
        assert(m_file);

        // if(m_file.fail())
        // {
        //     ec = error::make_error_code(error::failed_open_file);
        //     return;
        // }
    }

    uint32_t file_input_stream::read_position()
    {
        assert(m_file.is_open());

        // Work around for problem on iOS where tellg returned -1 when
        // reading the last byte. However the EOF flag was correctly
        // set. So here we check for EOF if true we set the
        // read_position = m_file_size

        if(m_file.eof())
        {
            return m_file_size;
        }
        else
        {
            std::streamoff pos = m_file.tellg();
            std::cout << "tellg = " << (int32_t) pos << std::endl;

            assert(pos >= 0);

            return static_cast<uint32_t>(pos);
        }
    }

    void file_input_stream::read(uint8_t* buffer, uint32_t bytes)
    {
        assert(m_file.is_open());
        std::cout << "file_input_stream::read " << bytes << std::endl;

        m_file.read(reinterpret_cast<char*>(buffer), bytes);

        assert(bytes == static_cast<uint32_t>(m_file.gcount()));
    }

    uint32_t file_input_stream::bytes_available()
    {
        assert(m_file.is_open());
        std::cout << "file_input_stream::bytes_available " << std::endl;

        uint32_t pos = read_position();
        assert(pos <= m_filesize);

        return m_filesize - pos;
    }

    uint32_t file_input_stream::size()
    {
        assert(m_file.is_open());
        return m_filesize;
    }

}
<commit_msg>Fix typo in variable name<commit_after>// Copyright (c) 2012, Steinwurf ApS
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Steinwurf ApS nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL Steinwurf ApS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "file_input_stream.hpp"
#include "error.hpp"

#include <fstream>
#include <cassert>

namespace sak
{

    file_input_stream::file_input_stream()
        : m_filesize(0)
    {
    }

    file_input_stream::file_input_stream(const std::string& filename)
        : m_filesize(0)
    {
        open(filename);
    }

    void file_input_stream::open(const std::string& filename)
    {
        assert(!m_file.is_open());

        boost::system::error_code ec;
        open(filename, ec);

        // If an error throw
        error::throw_error(ec);
    }

    void file_input_stream::open(const std::string& filename,
                                 boost::system::error_code& ec)
    {
        assert(!m_file.is_open());

        m_file.open(filename.c_str(),
                    std::ios::in | std::ios::binary);

        if (!m_file.is_open())
        {
            ec = error::make_error_code(error::failed_open_file);
            return;
        }

        m_file.seekg(0, std::ios::end);
        assert(m_file);

        // We cannot use the read_position function here due to a
        // problem on the iOS platform described in the read_position
        // function.
        auto pos = m_file.tellg();
        assert(pos >= 0);

        m_filesize = (uint32_t) pos;

        m_file.seekg(0, std::ios::beg);
        assert(m_file);
    }

    void file_input_stream::seek(uint32_t pos)
    {
        assert(m_file.is_open());
        m_file.seekg(pos, std::ios::beg);
        assert(m_file);

        // if(m_file.fail())
        // {
        //     ec = error::make_error_code(error::failed_open_file);
        //     return;
        // }
    }

    uint32_t file_input_stream::read_position()
    {
        assert(m_file.is_open());

        // Work around for problem on iOS where tellg returned -1 when
        // reading the last byte. However the EOF flag was correctly
        // set. So here we check for EOF if true we set the
        // read_position = m_file_size

        if(m_file.eof())
        {
            return m_filesize;
        }
        else
        {
            std::streamoff pos = m_file.tellg();
            std::cout << "tellg = " << (int32_t) pos << std::endl;

            assert(pos >= 0);

            return static_cast<uint32_t>(pos);
        }
    }

    void file_input_stream::read(uint8_t* buffer, uint32_t bytes)
    {
        assert(m_file.is_open());
        std::cout << "file_input_stream::read " << bytes << std::endl;

        m_file.read(reinterpret_cast<char*>(buffer), bytes);

        assert(bytes == static_cast<uint32_t>(m_file.gcount()));
    }

    uint32_t file_input_stream::bytes_available()
    {
        assert(m_file.is_open());
        std::cout << "file_input_stream::bytes_available " << std::endl;

        uint32_t pos = read_position();
        assert(pos <= m_filesize);

        return m_filesize - pos;
    }

    uint32_t file_input_stream::size()
    {
        assert(m_file.is_open());
        return m_filesize;
    }

}
<|endoftext|>


<commit_before><commit_msg>Very confused...<commit_after><|endoftext|>


<commit_before>#include "defines.h"
#include "DcxDWMModule.h"

PFNDWMISCOMPOSITIONENABLED DcxDWMModule::DwmIsCompositionEnabledUx = nullptr;
PFNDWMGETWINDOWATTRIBUTE DcxDWMModule::DwmGetWindowAttributeUx = nullptr;
PFNDWMSETWINDOWATTRIBUTE DcxDWMModule::DwmSetWindowAttributeUx = nullptr;
PFNDWMEXTENDFRAMEINTOCLIENTAREA DcxDWMModule::DwmExtendFrameIntoClientAreaUx = nullptr;
PFNDWMENABLEBLURBEHINDWINDOW DcxDWMModule::DwmEnableBlurBehindWindowUx = nullptr;
PFNDWMGETCOLORIZATIONCOLOR DcxDWMModule::DwmGetColorizationColorUx = nullptr;

DcxDWMModule::DcxDWMModule(void) :
m_bAero(false),
m_bVista(false),
m_bWin7(false),
m_bWin8(false)
{
}

DcxDWMModule::~DcxDWMModule(void)
{
	if (isUseable()) unload();
}

bool DcxDWMModule::load(void)
{
	if (isUseable())
		return false;

	DWORD winMajor = 0;
	if (!GetWindowVersion(&winMajor, nullptr))
		return false;

	this->m_bVista = (winMajor >= 6);	// OS is Vista+
	this->m_bWin7 = (winMajor > 6);		// OS is Windows7+
	this->m_bWin8 = (winMajor > 7);		// OS is Windows8+
	this->m_bWin10 = (winMajor > 8);	// OS is Windows10+

	DCX_DEBUG(mIRCLinker::debug, TEXT("LoadDLL"), TEXT("Loading DWMAPI.DLL..."));
	m_hModule = LoadLibrary(TEXT("dwmapi.dll"));
	if (m_hModule != nullptr) {
		DCX_DEBUG(mIRCLinker::debug, TEXT("LoadDLL"), TEXT("DWMAPI.DLL Loaded, Vista+ OS Assumed"));

		DwmIsCompositionEnabledUx = (PFNDWMISCOMPOSITIONENABLED) GetProcAddress(m_hModule, "DwmIsCompositionEnabled"); // Vista ONLY!
		DwmGetWindowAttributeUx = (PFNDWMGETWINDOWATTRIBUTE) GetProcAddress(m_hModule, "DwmGetWindowAttribute"); // Vista ONLY!
		DwmSetWindowAttributeUx = (PFNDWMSETWINDOWATTRIBUTE) GetProcAddress(m_hModule, "DwmSetWindowAttribute"); // Vista ONLY!
		DwmExtendFrameIntoClientAreaUx = (PFNDWMEXTENDFRAMEINTOCLIENTAREA) GetProcAddress(m_hModule, "DwmExtendFrameIntoClientArea"); // Vista ONLY!
		DwmEnableBlurBehindWindowUx = (PFNDWMENABLEBLURBEHINDWINDOW) GetProcAddress(m_hModule, "DwmEnableBlurBehindWindow"); // Vista ONLY!
		DwmGetColorizationColorUx = (PFNDWMGETCOLORIZATIONCOLOR) GetProcAddress(m_hModule, "DwmGetColorizationColor"); // Vista ONLY!

#if DCX_DEBUG_OUTPUT
		if (DwmIsCompositionEnabledUx != nullptr)
			mIRCLinker::debug(TEXT("LoadDLL"), TEXT("Found Vista DWM Functions"));
#endif

		refreshComposite();
	}
	return isUseable();
}

bool DcxDWMModule::unload(void)
{
	if (m_hModule != nullptr) {
		FreeLibrary(m_hModule);
		m_hModule = nullptr;
		DwmIsCompositionEnabledUx = nullptr;
		DwmGetWindowAttributeUx = nullptr;
		DwmSetWindowAttributeUx = nullptr;
		DwmExtendFrameIntoClientAreaUx = nullptr;
		DwmEnableBlurBehindWindowUx = nullptr;
		DwmGetColorizationColorUx = nullptr;
	}
	return isUseable();
}

bool DcxDWMModule::refreshComposite() {
	BOOL bAero;
	if (FAILED(dcxDwmIsCompositionEnabled(&bAero)))
		bAero = FALSE;

	m_bAero = (bAero != FALSE);
	return m_bAero;
}

HRESULT DcxDWMModule::dcxDwmSetWindowAttribute(HWND hwnd, DWORD dwAttribute, LPCVOID pvAttribute, DWORD cbAttribute)
{
	if (DwmSetWindowAttributeUx != nullptr)
		return DwmSetWindowAttributeUx(hwnd, dwAttribute, pvAttribute, cbAttribute);
	return DWM_E_COMPOSITIONDISABLED;
}

HRESULT DcxDWMModule::dcxDwmGetWindowAttribute(HWND hwnd, DWORD dwAttribute, PVOID pvAttribute, DWORD cbAttribute)
{
	if (DwmGetWindowAttributeUx != nullptr)
		return DwmGetWindowAttributeUx(hwnd, dwAttribute, pvAttribute, cbAttribute);
	return DWM_E_COMPOSITIONDISABLED;
}

HRESULT DcxDWMModule::dcxDwmIsCompositionEnabled(BOOL *pfEnabled)
{
	if (DwmIsCompositionEnabledUx != nullptr)
		return DwmIsCompositionEnabledUx(pfEnabled);
	*pfEnabled = FALSE;
	return DWM_E_COMPOSITIONDISABLED;
}

HRESULT DcxDWMModule::dcxDwmExtendFrameIntoClientArea(HWND hwnd, const MARGINS *pMarInset)
{
	if (DwmExtendFrameIntoClientAreaUx != nullptr)
		return DwmExtendFrameIntoClientAreaUx(hwnd, pMarInset);
	return DWM_E_COMPOSITIONDISABLED;
}

HRESULT DcxDWMModule::dcxDwmEnableBlurBehindWindow(HWND hwnd, __in const DWM_BLURBEHIND *pBlurBehind)
{
	if (DwmEnableBlurBehindWindowUx != nullptr)
		return DwmEnableBlurBehindWindowUx(hwnd, pBlurBehind);
	return DWM_E_COMPOSITIONDISABLED;
}

HRESULT DcxDWMModule::dcxDwmGetColorizationColor( __out  DWORD *pcrColorization, __out  BOOL *pfOpaqueBlend)
{
	if (DwmGetColorizationColorUx != nullptr)
		return DwmGetColorizationColorUx(pcrColorization, pfOpaqueBlend);
	return DWM_E_COMPOSITIONDISABLED;
}
<commit_msg>[modules] forgot to initialize bWin10<commit_after>#include "defines.h"
#include "DcxDWMModule.h"

PFNDWMISCOMPOSITIONENABLED DcxDWMModule::DwmIsCompositionEnabledUx = nullptr;
PFNDWMGETWINDOWATTRIBUTE DcxDWMModule::DwmGetWindowAttributeUx = nullptr;
PFNDWMSETWINDOWATTRIBUTE DcxDWMModule::DwmSetWindowAttributeUx = nullptr;
PFNDWMEXTENDFRAMEINTOCLIENTAREA DcxDWMModule::DwmExtendFrameIntoClientAreaUx = nullptr;
PFNDWMENABLEBLURBEHINDWINDOW DcxDWMModule::DwmEnableBlurBehindWindowUx = nullptr;
PFNDWMGETCOLORIZATIONCOLOR DcxDWMModule::DwmGetColorizationColorUx = nullptr;

DcxDWMModule::DcxDWMModule(void) :
m_bAero(false),
m_bVista(false),
m_bWin7(false),
m_bWin8(false),
m_bWin10(false)
{
}

DcxDWMModule::~DcxDWMModule(void)
{
	if (isUseable()) unload();
}

bool DcxDWMModule::load(void)
{
	if (isUseable())
		return false;

	DWORD winMajor = 0;
	if (!GetWindowVersion(&winMajor, nullptr))
		return false;

	this->m_bVista = (winMajor >= 6);	// OS is Vista+
	this->m_bWin7 = (winMajor > 6);		// OS is Windows7+
	this->m_bWin8 = (winMajor > 7);		// OS is Windows8+
	this->m_bWin10 = (winMajor > 8);	// OS is Windows10+

	DCX_DEBUG(mIRCLinker::debug, TEXT("LoadDLL"), TEXT("Loading DWMAPI.DLL..."));
	m_hModule = LoadLibrary(TEXT("dwmapi.dll"));
	if (m_hModule != nullptr) {
		DCX_DEBUG(mIRCLinker::debug, TEXT("LoadDLL"), TEXT("DWMAPI.DLL Loaded, Vista+ OS Assumed"));

		DwmIsCompositionEnabledUx = (PFNDWMISCOMPOSITIONENABLED) GetProcAddress(m_hModule, "DwmIsCompositionEnabled"); // Vista ONLY!
		DwmGetWindowAttributeUx = (PFNDWMGETWINDOWATTRIBUTE) GetProcAddress(m_hModule, "DwmGetWindowAttribute"); // Vista ONLY!
		DwmSetWindowAttributeUx = (PFNDWMSETWINDOWATTRIBUTE) GetProcAddress(m_hModule, "DwmSetWindowAttribute"); // Vista ONLY!
		DwmExtendFrameIntoClientAreaUx = (PFNDWMEXTENDFRAMEINTOCLIENTAREA) GetProcAddress(m_hModule, "DwmExtendFrameIntoClientArea"); // Vista ONLY!
		DwmEnableBlurBehindWindowUx = (PFNDWMENABLEBLURBEHINDWINDOW) GetProcAddress(m_hModule, "DwmEnableBlurBehindWindow"); // Vista ONLY!
		DwmGetColorizationColorUx = (PFNDWMGETCOLORIZATIONCOLOR) GetProcAddress(m_hModule, "DwmGetColorizationColor"); // Vista ONLY!

#if DCX_DEBUG_OUTPUT
		if (DwmIsCompositionEnabledUx != nullptr)
			mIRCLinker::debug(TEXT("LoadDLL"), TEXT("Found Vista DWM Functions"));
#endif

		refreshComposite();
	}
	return isUseable();
}

bool DcxDWMModule::unload(void)
{
	if (m_hModule != nullptr) {
		FreeLibrary(m_hModule);
		m_hModule = nullptr;
		DwmIsCompositionEnabledUx = nullptr;
		DwmGetWindowAttributeUx = nullptr;
		DwmSetWindowAttributeUx = nullptr;
		DwmExtendFrameIntoClientAreaUx = nullptr;
		DwmEnableBlurBehindWindowUx = nullptr;
		DwmGetColorizationColorUx = nullptr;
	}
	return isUseable();
}

bool DcxDWMModule::refreshComposite() {
	BOOL bAero;
	if (FAILED(dcxDwmIsCompositionEnabled(&bAero)))
		bAero = FALSE;

	m_bAero = (bAero != FALSE);
	return m_bAero;
}

HRESULT DcxDWMModule::dcxDwmSetWindowAttribute(HWND hwnd, DWORD dwAttribute, LPCVOID pvAttribute, DWORD cbAttribute)
{
	if (DwmSetWindowAttributeUx != nullptr)
		return DwmSetWindowAttributeUx(hwnd, dwAttribute, pvAttribute, cbAttribute);
	return DWM_E_COMPOSITIONDISABLED;
}

HRESULT DcxDWMModule::dcxDwmGetWindowAttribute(HWND hwnd, DWORD dwAttribute, PVOID pvAttribute, DWORD cbAttribute)
{
	if (DwmGetWindowAttributeUx != nullptr)
		return DwmGetWindowAttributeUx(hwnd, dwAttribute, pvAttribute, cbAttribute);
	return DWM_E_COMPOSITIONDISABLED;
}

HRESULT DcxDWMModule::dcxDwmIsCompositionEnabled(BOOL *pfEnabled)
{
	if (DwmIsCompositionEnabledUx != nullptr)
		return DwmIsCompositionEnabledUx(pfEnabled);
	*pfEnabled = FALSE;
	return DWM_E_COMPOSITIONDISABLED;
}

HRESULT DcxDWMModule::dcxDwmExtendFrameIntoClientArea(HWND hwnd, const MARGINS *pMarInset)
{
	if (DwmExtendFrameIntoClientAreaUx != nullptr)
		return DwmExtendFrameIntoClientAreaUx(hwnd, pMarInset);
	return DWM_E_COMPOSITIONDISABLED;
}

HRESULT DcxDWMModule::dcxDwmEnableBlurBehindWindow(HWND hwnd, __in const DWM_BLURBEHIND *pBlurBehind)
{
	if (DwmEnableBlurBehindWindowUx != nullptr)
		return DwmEnableBlurBehindWindowUx(hwnd, pBlurBehind);
	return DWM_E_COMPOSITIONDISABLED;
}

HRESULT DcxDWMModule::dcxDwmGetColorizationColor( __out  DWORD *pcrColorization, __out  BOOL *pfOpaqueBlend)
{
	if (DwmGetColorizationColorUx != nullptr)
		return DwmGetColorizationColorUx(pcrColorization, pfOpaqueBlend);
	return DWM_E_COMPOSITIONDISABLED;
}
<|endoftext|>


<commit_before>#include "FSRespSource.h"

#include <type_traits>
#include <stdexcept>

#include <boost/locale.hpp>

#include "CommonErrorRespSource.h"
#include "detail/MimeDB.h"

using namespace HTTP;
using namespace HTTP::RespSource;

FS::Response::Response(const boost::filesystem::path &FileName, const char *MimeType, time_t IfModifiedSince) : MyMimeType(MimeType)
{
	time_t LastModTime=boost::filesystem::last_write_time(FileName);
	Header::FormatDateTime(LastModTime,LastModifiedStr);

	if ((!IfModifiedSince) || (LastModTime>IfModifiedSince))
	{
		FileSize=boost::filesystem::file_size(FileName);
		FilePos=0;

		InS.open(FileName.string().data(),std::ios_base::binary);
		if (!InS.is_open())
			throw std::runtime_error("Cannot open target file");
	}
	else
	{
		FileSize=NotModifiedSize;
		FilePos=0;
	}
}

bool FS::Response::GetExtraHeader(unsigned int Index,
	const char **OutHeader, const char **OutHeaderEnd,
	const char **OutHeaderVal, const char **OutHeaderValEnd)
{
	if (Index==0)
	{
		const std::string &HName=Header::GetHeaderName(HN_LAST_MODIFIED);
		*OutHeader=HName.data();
		*OutHeaderEnd=HName.data() + HName.size();
		*OutHeaderVal=LastModifiedStr;
		*OutHeaderValEnd=LastModifiedStr+sizeof(LastModifiedStr);

		return true;
	}
	else
		return false;
}

bool FS::Response::Read(unsigned char *TargetBuff, unsigned int MaxLength, unsigned int &OutLength,
		boost::asio::yield_context &Ctx)
{
	if (FileSize!=NotModifiedSize)
	{
		unsigned long long RemLength=FileSize-FilePos;
		if (MaxLength>RemLength)
			MaxLength=(unsigned int)RemLength;

		InS.read((char *)TargetBuff,MaxLength);

		OutLength=MaxLength;
		FilePos+=MaxLength;

		return (FilePos==FileSize) || (InS.fail());
	}
	else
	{
		OutLength=0;
		return true;
	}
}

FS::FS(const boost::filesystem::path &NewRoot) : Root(NewRoot)
{
}

IResponse *FS::Create(METHOD Method, const std::string &Resource, const QueryParams &Query, const std::vector<Header> &HeaderA,
		const unsigned char *ContentBuff, const unsigned char *ContentBuffEnd,
		boost::asio::io_service &ParentIOS, void *ParentConn)
{
	boost::filesystem::path Target;
	try
	{
		if (std::is_same<boost::filesystem::path::value_type,wchar_t>())
			Target=boost::filesystem::canonical(Root / boost::locale::conv::utf_to_utf<wchar_t,char>(Resource));
		else
			Target=boost::filesystem::canonical(Root / Resource);
	}
	catch (...)
	{ return new CommonError::Response(Resource,HeaderA,NULL,RC_NOTFOUND); }

  if ( (std::distance(Root.begin(), Root.end())<=std::distance(Target.begin(), Target.end())) &&
	  (std::equal(Root.begin(), Root.end(), Target.begin())) &&
	  (boost::filesystem::exists(Target)) )
  {
	  time_t IfModSinceTime=0;
	  try
	  {
		  for (const Header &CurrH : HeaderA)
		  {
			  if (CurrH.IntName==HN_IF_MOD_SINCE)
			  {
				  IfModSinceTime=CurrH.GetDateTime();
				  break;
			  }
		  }
	  }
	  catch (...) { }

	  if (!boost::filesystem::is_directory(Target))
		  return new Response(Target,GetMimeType(Target),IfModSinceTime);
	  else
		  return new CommonError::Response(Resource,HeaderA,NULL,RC_FORBIDDEN);
  }
  else
	  return new CommonError::Response(Resource,HeaderA,NULL,RC_NOTFOUND);
}

const char *FS::GetMimeType(const boost::filesystem::path &FileName)
{
	return detail::MimeDB::GetMimeType(FileName.extension().string());
}
<commit_msg>FSRespSource: indent fix<commit_after>#include "FSRespSource.h"

#include <type_traits>
#include <stdexcept>

#include <boost/locale.hpp>

#include "CommonErrorRespSource.h"
#include "detail/MimeDB.h"

using namespace HTTP;
using namespace HTTP::RespSource;

FS::Response::Response(const boost::filesystem::path &FileName, const char *MimeType, time_t IfModifiedSince) : MyMimeType(MimeType)
{
	time_t LastModTime=boost::filesystem::last_write_time(FileName);
	Header::FormatDateTime(LastModTime,LastModifiedStr);

	if ((!IfModifiedSince) || (LastModTime>IfModifiedSince))
	{
		FileSize=boost::filesystem::file_size(FileName);
		FilePos=0;

		InS.open(FileName.string().data(),std::ios_base::binary);
		if (!InS.is_open())
			throw std::runtime_error("Cannot open target file");
	}
	else
	{
		FileSize=NotModifiedSize;
		FilePos=0;
	}
}

bool FS::Response::GetExtraHeader(unsigned int Index,
	const char **OutHeader, const char **OutHeaderEnd,
	const char **OutHeaderVal, const char **OutHeaderValEnd)
{
	if (Index==0)
	{
		const std::string &HName=Header::GetHeaderName(HN_LAST_MODIFIED);
		*OutHeader=HName.data();
		*OutHeaderEnd=HName.data() + HName.size();
		*OutHeaderVal=LastModifiedStr;
		*OutHeaderValEnd=LastModifiedStr+sizeof(LastModifiedStr);

		return true;
	}
	else
		return false;
}

bool FS::Response::Read(unsigned char *TargetBuff, unsigned int MaxLength, unsigned int &OutLength,
		boost::asio::yield_context &Ctx)
{
	if (FileSize!=NotModifiedSize)
	{
		unsigned long long RemLength=FileSize-FilePos;
		if (MaxLength>RemLength)
			MaxLength=(unsigned int)RemLength;

		InS.read((char *)TargetBuff,MaxLength);

		OutLength=MaxLength;
		FilePos+=MaxLength;

		return (FilePos==FileSize) || (InS.fail());
	}
	else
	{
		OutLength=0;
		return true;
	}
}

FS::FS(const boost::filesystem::path &NewRoot) : Root(NewRoot)
{
}

IResponse *FS::Create(METHOD Method, const std::string &Resource, const QueryParams &Query, const std::vector<Header> &HeaderA,
		const unsigned char *ContentBuff, const unsigned char *ContentBuffEnd,
		boost::asio::io_service &ParentIOS, void *ParentConn)
{
	boost::filesystem::path Target;
	try
	{
		if (std::is_same<boost::filesystem::path::value_type,wchar_t>())
			Target=boost::filesystem::canonical(Root / boost::locale::conv::utf_to_utf<wchar_t,char>(Resource));
		else
			Target=boost::filesystem::canonical(Root / Resource);
	}
	catch (...)
	{ return new CommonError::Response(Resource,HeaderA,NULL,RC_NOTFOUND); }

	if ( (std::distance(Root.begin(), Root.end())<=std::distance(Target.begin(), Target.end())) &&
	  (std::equal(Root.begin(), Root.end(), Target.begin())) &&
	  (boost::filesystem::exists(Target)) )
	{
		time_t IfModSinceTime=0;
		try
		{
			for (const Header &CurrH : HeaderA)
			{
				if (CurrH.IntName==HN_IF_MOD_SINCE)
				{
					IfModSinceTime=CurrH.GetDateTime();
					break;
				}
			}
		}
		catch (...) { }

		if (!boost::filesystem::is_directory(Target))
			return new Response(Target,GetMimeType(Target),IfModSinceTime);
		else
			return new CommonError::Response(Resource,HeaderA,NULL,RC_FORBIDDEN);
	}
	else
		return new CommonError::Response(Resource,HeaderA,NULL,RC_NOTFOUND);
}

const char *FS::GetMimeType(const boost::filesystem::path &FileName)
{
	return detail::MimeDB::GetMimeType(FileName.extension().string());
}
<|endoftext|>


<commit_before>#include "condor_common.h"
#include <iostream.h>
#include "condor_config.h"
#include "condor_classad.h"
#include "condor_debug.h"
#include "condor_query.h"
#include "condor_q.h"
#include "condor_attributes.h"
#include "match_prefix.h"
#include "my_hostname.h"
#include "files.h"

extern 	"C" int SetSyscalls(int val){return val;}
extern  void short_print(int,int,const char*,int,int,int,int,int,const char *);
static  void processCommandLineArguments(int, char *[]);
extern 	"C" void set_debug_flags( char * );

static	char *_FileName_ = __FILE__;

static 	void short_header (void);
static 	void usage (char *);
static 	void displayJobShort (ClassAd *);
static 	void shorten (char *, int);

static 	int verbose = 0, summarize = 1, global = 0;
static 	int malformed, unexpanded, running, idle;

static	CondorQ 	Q;
static	QueryResult result;
static	CondorQuery	scheddQuery(SCHEDD_AD);
static	CondorQuery submittorQuery(SUBMITTOR_AD);
static	ClassAdList	scheddList;

static	bool		querySchedds 	= false;
static	bool		querySubmittors = false;
static	char		constraint[4096];

extern 	"C"	int		Termlog;

int main (int argc, char **argv)
{
	ClassAd     *job;
	ClassAd		*ad;
	bool		first = true;
	int         cluster, proc;
	char		scheddAddr[64];
	char		scheddName[64];
	char		scheddMachine[64];

	// load up configuration file
	config( 0 );

#if !defined(WIN32)
	install_sig_handler(SIGPIPE, SIG_IGN );
#endif

	// process arguments
	processCommandLineArguments (argc, argv);

	// make sure we are querying schedd's or submittors
	if (!global && !querySchedds && !querySubmittors) {
		char *host = my_hostname();
		querySchedds = true;
		result = scheddQuery.addConstraint (SCHEDD_NAME, host);
		if (result != Q_OK) {
			fprintf(stderr,"Error: Couldn't add constraint Name=\"%s\"\n",host);
			exit (1);
		}
	}

	// get the list of ads from the collector
	result = querySchedds ? scheddQuery.fetchAds(scheddList) :
							submittorQuery.fetchAds(scheddList);
	if (result != Q_OK)
	{
		fprintf (stderr, "Error %d: %s\n", result, getStrQueryResult(result));
		exit(1);
	}

	// get queue from each ScheddIpAddr in ad
	scheddList.Open();
	while ((ad = scheddList.Next()))
	{
		ClassAdList jobs;

		// get the address of the schedd
		if (!ad->LookupString(ATTR_SCHEDD_IP_ADDR, scheddAddr)	||
			!ad->LookupString(ATTR_NAME, scheddName)			||
			!ad->LookupString(ATTR_MACHINE, scheddMachine))
				continue;

		// fetch queue from schedd
		if (Q.fetchQueueFromHost (jobs, scheddAddr) != Q_OK) continue;

		// sort jobs by (cluster.proc)
		jobs.Sort( (SortFunctionType)JobSort );

		// display the jobs from this submittor
		if (jobs.MyLength() != 0)
		{
			// print header
			if (querySchedds) {
				printf ("\n\n-- Schedd: %s : %s\n", scheddName, scheddAddr);
			} else {
				printf ("\n\n-- Submittor: %s : %s : %s\n", scheddName,
							scheddAddr, scheddMachine);
			}

			// initialize counters
			malformed = 0; idle = 0; running = 0; unexpanded = 0;

			if (verbose)
			{
				jobs.fPrintAttrListList (stdout);
			}
			else
			{
				short_header ();
				jobs.Open ();
				while (job = jobs.Next())
				{
					displayJobShort (job);
				}
				jobs.Close ();
			}

			if (summarize)
			{
				printf("\n%d jobs; "
					"%d unexpanded, %d idle, %d running, %d malformed\n",
					unexpanded+idle+running+malformed,unexpanded,idle,running,
					malformed);
			}
		}

		first = false;
	}

	// close list
	scheddList.Close();

	if (first)
	{
		fprintf (stderr,"Error: Collector has no record of schedd/submittor\n");
		exit(1);
	}

	return 0;
}

static void
processCommandLineArguments (int argc, char *argv[])
{
	int i, cluster, proc;
	char *arg;

	for (i = 1; i < argc; i++)
	{
		// if the argument begins with a '-', use only the part following
		// the '-' for prefix matches
		if (*argv[i] == '-')
			arg = argv[i]+1;
		else
			arg = argv[i];

		if (match_prefix (arg, "long")) {
			verbose = 1;
			summarize = 0;
		}
		else
		if (match_prefix (arg, "D")) {
			Termlog = 1;
			set_debug_flags( argv[++i] );
		}
		else
		if (match_prefix (arg, "name")) {

			if (querySubmittors) {
				// cannot query both schedd's and submittors
				fprintf (stderr, "Cannot query both schedd's and submittors\n");
				exit(1);
			}

			// make sure we have at least one more argument
			if (argc <= i+1) {
				fprintf( stderr, "Argument -name requires another parameter\n");
				exit(1);
			}

			sprintf (constraint, "%s == \"%s\"", ATTR_NAME, argv[i+1]);
			result = scheddQuery.addConstraint (constraint);
			if (result != Q_OK) {
				fprintf (stderr, "Argument %d (%s): Error %s\n", i, argv[i],
							getStrQueryResult(result));
				exit (1);
			}
			i++;
			querySchedds = true;
		}
		else
		if (match_prefix (arg, "submittor")) {

			char *at;

			if (querySchedds) {
				// cannot query both schedd's and submittors
				fprintf (stderr, "Cannot query both schedd's and submittors\n");
				exit(1);
			}

			// make sure we have at least one more argument
			if (argc <= i+1) {
				fprintf( stderr, "Argument -submittor requires another "
							"parameter\n");
				exit(1);
			}

			i++;
			if ((at = strchr(argv[i],'@'))) {
				// is the name already qualified with a UID_DOMAIN?
				sprintf (constraint, "%s == \"%s\"", ATTR_NAME, argv[i]);
				*at = '\0';
			} else {
				// no ... add UID_DOMAIN
				char *uid_domain = param("UID_DOMAIN");
				if (uid_domain == NULL)
				{
					EXCEPT ("No 'UID_DOMAIN' found in config file");
				}
				sprintf (constraint, "%s == \"%s@%s\"", ATTR_NAME, argv[i],
							uid_domain);
				free (uid_domain);
			}

			// insert the constraints
			result = submittorQuery.addConstraint (constraint);
			if (result != Q_OK) {
				fprintf (stderr, "Argument %d (%s): Error %s\n", i, argv[i],
							getStrQueryResult(result));
				exit (1);
			}

			if (Q.add (CQ_OWNER, argv[i]) != Q_OK) {
				fprintf (stderr, "Error:  Argument %d (%s)\n", i, argv[i]);
				exit (1);
			}

			querySubmittors = true;
		}
		else
		if (match_prefix (arg, "constraint")) {
			// make sure we have at least one more argument
			if (argc <= i+1) {
				fprintf( stderr, "Argument -constraint requires another "
							"parameter\n");
				exit(1);
			}

			if (Q.add (argv[++i]) != Q_OK) {
				fprintf (stderr, "Error:  Argument %d (%s)\n", i, argv[i]);
				exit (1);
			}
			summarize = 0;
		}
		else
		if (sscanf (argv[i], "%d.%d", &cluster, &proc) == 2) {
			sprintf (constraint, "((%s == %d) && (%s == %d))",
									ATTR_CLUSTER_ID, cluster,
									ATTR_PROC_ID, proc);
			Q.add (constraint);
			summarize = 0;
		}
		else
		if (sscanf (argv[i], "%d", &cluster) == 1) {
			sprintf (constraint, "(%s == %d)", ATTR_CLUSTER_ID, cluster);
			Q.add (constraint);
			summarize = 0;
		}
		else
		if (match_prefix (arg, "global")) {
			global = 1;
		}
		else
		if (match_prefix (arg, "help")) {
			usage(argv[0]);
			exit(0);
		}
		else
		{
			// assume name of owner of job
			if (Q.add (CQ_OWNER, argv[i]) != Q_OK) {
				fprintf (stderr, "Error:  Argument %d (%s)\n", i, argv[i]);
				exit (1);
			}
		}
	}
}

static void
displayJobShort (ClassAd *ad)
{
	int cluster, proc, date, status, prio, image_size;
	float utime;
	char owner[64], cmd[2048], args[2048];

	if (!ad->EvalInteger (ATTR_CLUSTER_ID, NULL, cluster)		||
		!ad->EvalInteger (ATTR_PROC_ID, NULL, proc)				||
		!ad->EvalInteger (ATTR_Q_DATE, NULL, date)				||
		!ad->EvalFloat   (ATTR_JOB_REMOTE_USER_CPU, NULL, utime)||
		!ad->EvalInteger (ATTR_JOB_STATUS, NULL, status)		||
		!ad->EvalInteger (ATTR_JOB_PRIO, NULL, prio)			||
		!ad->EvalInteger (ATTR_IMAGE_SIZE, NULL, image_size)	||
		!ad->EvalString  (ATTR_OWNER, NULL, owner)				||
		!ad->EvalString  (ATTR_JOB_CMD, NULL, cmd) )
	{
		printf (" --- ???? --- \n");
		return;
	}

	shorten (owner, 14);
	if (ad->EvalString ("Args", NULL, args)) strcat (cmd, args);
	shorten (cmd, 18);
	short_print (cluster, proc, owner, date, (int)utime, status, prio,
					image_size, cmd);

	switch (status)
	{
		case UNEXPANDED: unexpanded++; break;
		case IDLE:       idle++;       break;
		case RUNNING:    running++;    break;
	}
}

static void
short_header (void)
{
    printf( " %-7s %-14s %11s %12s %-2s %-3s %-4s %-18s\n",
        "ID",
        "OWNER",
        "SUBMITTED",
        "CPU_USAGE",
        "ST",
        "PRI",
        "SIZE",
        "CMD"
    );
}

static void
shorten (char *buff, int len)
{
	if ((unsigned int)strlen (buff) > (unsigned int)len) buff[len] = '\0';
}

static void
usage (char *myName)
{
	printf ("Usage: %s [options]\n\twhere [options] are\n"
		"\t\t-global\t\t\tGet global queue\n"
		"\t\t-submittor <submittor>\tGet queue of specific submittor\n"
		"\t\t-help\t\t\tThis screen\n"
		"\t\t-name <name>\t\tName of schedd\n"
		"\t\t-constraint <expr>\tAdd constraint on classads\n"
		"\t\t-long\t\t\tVerbose output\n"
		"\t\t<cluster>\t\tGet information about specific cluster\n"
		"\t\t<cluster>.<proc>\tGet information about specific job\n"
		"\t\t<owner>\t\t\tInformation about jobs owned by <owner>\n", myName);
}
<commit_msg>unused variables cluster and proc<commit_after>#include "condor_common.h"
#include <iostream.h>
#include "condor_config.h"
#include "condor_classad.h"
#include "condor_debug.h"
#include "condor_query.h"
#include "condor_q.h"
#include "condor_attributes.h"
#include "match_prefix.h"
#include "my_hostname.h"
#include "files.h"

extern 	"C" int SetSyscalls(int val){return val;}
extern  void short_print(int,int,const char*,int,int,int,int,int,const char *);
static  void processCommandLineArguments(int, char *[]);
extern 	"C" void set_debug_flags( char * );

static	char *_FileName_ = __FILE__;

static 	void short_header (void);
static 	void usage (char *);
static 	void displayJobShort (ClassAd *);
static 	void shorten (char *, int);

static 	int verbose = 0, summarize = 1, global = 0;
static 	int malformed, unexpanded, running, idle;

static	CondorQ 	Q;
static	QueryResult result;
static	CondorQuery	scheddQuery(SCHEDD_AD);
static	CondorQuery submittorQuery(SUBMITTOR_AD);
static	ClassAdList	scheddList;

static	bool		querySchedds 	= false;
static	bool		querySubmittors = false;
static	char		constraint[4096];

extern 	"C"	int		Termlog;

int main (int argc, char **argv)
{
	ClassAd     *job;
	ClassAd		*ad;
	bool		first = true;
	char		scheddAddr[64];
	char		scheddName[64];
	char		scheddMachine[64];

	// load up configuration file
	config( 0 );

#if !defined(WIN32)
	install_sig_handler(SIGPIPE, SIG_IGN );
#endif

	// process arguments
	processCommandLineArguments (argc, argv);

	// make sure we are querying schedd's or submittors
	if (!global && !querySchedds && !querySubmittors) {
		char *host = my_hostname();
		querySchedds = true;
		result = scheddQuery.addConstraint (SCHEDD_NAME, host);
		if (result != Q_OK) {
			fprintf(stderr,"Error: Couldn't add constraint Name=\"%s\"\n",host);
			exit (1);
		}
	}

	// get the list of ads from the collector
	result = querySchedds ? scheddQuery.fetchAds(scheddList) :
							submittorQuery.fetchAds(scheddList);
	if (result != Q_OK)
	{
		fprintf (stderr, "Error %d: %s\n", result, getStrQueryResult(result));
		exit(1);
	}

	// get queue from each ScheddIpAddr in ad
	scheddList.Open();
	while ((ad = scheddList.Next()))
	{
		ClassAdList jobs;

		// get the address of the schedd
		if (!ad->LookupString(ATTR_SCHEDD_IP_ADDR, scheddAddr)	||
			!ad->LookupString(ATTR_NAME, scheddName)			||
			!ad->LookupString(ATTR_MACHINE, scheddMachine))
				continue;

		// fetch queue from schedd
		if (Q.fetchQueueFromHost (jobs, scheddAddr) != Q_OK) continue;

		// sort jobs by (cluster.proc)
		jobs.Sort( (SortFunctionType)JobSort );

		// display the jobs from this submittor
		if (jobs.MyLength() != 0)
		{
			// print header
			if (querySchedds) {
				printf ("\n\n-- Schedd: %s : %s\n", scheddName, scheddAddr);
			} else {
				printf ("\n\n-- Submittor: %s : %s : %s\n", scheddName,
							scheddAddr, scheddMachine);
			}

			// initialize counters
			malformed = 0; idle = 0; running = 0; unexpanded = 0;

			if (verbose)
			{
				jobs.fPrintAttrListList (stdout);
			}
			else
			{
				short_header ();
				jobs.Open ();
				while (job = jobs.Next())
				{
					displayJobShort (job);
				}
				jobs.Close ();
			}

			if (summarize)
			{
				printf("\n%d jobs; "
					"%d unexpanded, %d idle, %d running, %d malformed\n",
					unexpanded+idle+running+malformed,unexpanded,idle,running,
					malformed);
			}
		}

		first = false;
	}

	// close list
	scheddList.Close();

	if (first)
	{
		fprintf (stderr,"Error: Collector has no record of schedd/submittor\n");
		exit(1);
	}

	return 0;
}

static void
processCommandLineArguments (int argc, char *argv[])
{
	int i, cluster, proc;
	char *arg;

	for (i = 1; i < argc; i++)
	{
		// if the argument begins with a '-', use only the part following
		// the '-' for prefix matches
		if (*argv[i] == '-')
			arg = argv[i]+1;
		else
			arg = argv[i];

		if (match_prefix (arg, "long")) {
			verbose = 1;
			summarize = 0;
		}
		else
		if (match_prefix (arg, "D")) {
			Termlog = 1;
			set_debug_flags( argv[++i] );
		}
		else
		if (match_prefix (arg, "name")) {

			if (querySubmittors) {
				// cannot query both schedd's and submittors
				fprintf (stderr, "Cannot query both schedd's and submittors\n");
				exit(1);
			}

			// make sure we have at least one more argument
			if (argc <= i+1) {
				fprintf( stderr, "Argument -name requires another parameter\n");
				exit(1);
			}

			sprintf (constraint, "%s == \"%s\"", ATTR_NAME, argv[i+1]);
			result = scheddQuery.addConstraint (constraint);
			if (result != Q_OK) {
				fprintf (stderr, "Argument %d (%s): Error %s\n", i, argv[i],
							getStrQueryResult(result));
				exit (1);
			}
			i++;
			querySchedds = true;
		}
		else
		if (match_prefix (arg, "submittor")) {

			char *at;

			if (querySchedds) {
				// cannot query both schedd's and submittors
				fprintf (stderr, "Cannot query both schedd's and submittors\n");
				exit(1);
			}

			// make sure we have at least one more argument
			if (argc <= i+1) {
				fprintf( stderr, "Argument -submittor requires another "
							"parameter\n");
				exit(1);
			}

			i++;
			if ((at = strchr(argv[i],'@'))) {
				// is the name already qualified with a UID_DOMAIN?
				sprintf (constraint, "%s == \"%s\"", ATTR_NAME, argv[i]);
				*at = '\0';
			} else {
				// no ... add UID_DOMAIN
				char *uid_domain = param("UID_DOMAIN");
				if (uid_domain == NULL)
				{
					EXCEPT ("No 'UID_DOMAIN' found in config file");
				}
				sprintf (constraint, "%s == \"%s@%s\"", ATTR_NAME, argv[i],
							uid_domain);
				free (uid_domain);
			}

			// insert the constraints
			result = submittorQuery.addConstraint (constraint);
			if (result != Q_OK) {
				fprintf (stderr, "Argument %d (%s): Error %s\n", i, argv[i],
							getStrQueryResult(result));
				exit (1);
			}

			if (Q.add (CQ_OWNER, argv[i]) != Q_OK) {
				fprintf (stderr, "Error:  Argument %d (%s)\n", i, argv[i]);
				exit (1);
			}

			querySubmittors = true;
		}
		else
		if (match_prefix (arg, "constraint")) {
			// make sure we have at least one more argument
			if (argc <= i+1) {
				fprintf( stderr, "Argument -constraint requires another "
							"parameter\n");
				exit(1);
			}

			if (Q.add (argv[++i]) != Q_OK) {
				fprintf (stderr, "Error:  Argument %d (%s)\n", i, argv[i]);
				exit (1);
			}
			summarize = 0;
		}
		else
		if (sscanf (argv[i], "%d.%d", &cluster, &proc) == 2) {
			sprintf (constraint, "((%s == %d) && (%s == %d))",
									ATTR_CLUSTER_ID, cluster,
									ATTR_PROC_ID, proc);
			Q.add (constraint);
			summarize = 0;
		}
		else
		if (sscanf (argv[i], "%d", &cluster) == 1) {
			sprintf (constraint, "(%s == %d)", ATTR_CLUSTER_ID, cluster);
			Q.add (constraint);
			summarize = 0;
		}
		else
		if (match_prefix (arg, "global")) {
			global = 1;
		}
		else
		if (match_prefix (arg, "help")) {
			usage(argv[0]);
			exit(0);
		}
		else
		{
			// assume name of owner of job
			if (Q.add (CQ_OWNER, argv[i]) != Q_OK) {
				fprintf (stderr, "Error:  Argument %d (%s)\n", i, argv[i]);
				exit (1);
			}
		}
	}
}

static void
displayJobShort (ClassAd *ad)
{
	int cluster, proc, date, status, prio, image_size;
	float utime;
	char owner[64], cmd[2048], args[2048];

	if (!ad->EvalInteger (ATTR_CLUSTER_ID, NULL, cluster)		||
		!ad->EvalInteger (ATTR_PROC_ID, NULL, proc)				||
		!ad->EvalInteger (ATTR_Q_DATE, NULL, date)				||
		!ad->EvalFloat   (ATTR_JOB_REMOTE_USER_CPU, NULL, utime)||
		!ad->EvalInteger (ATTR_JOB_STATUS, NULL, status)		||
		!ad->EvalInteger (ATTR_JOB_PRIO, NULL, prio)			||
		!ad->EvalInteger (ATTR_IMAGE_SIZE, NULL, image_size)	||
		!ad->EvalString  (ATTR_OWNER, NULL, owner)				||
		!ad->EvalString  (ATTR_JOB_CMD, NULL, cmd) )
	{
		printf (" --- ???? --- \n");
		return;
	}

	shorten (owner, 14);
	if (ad->EvalString ("Args", NULL, args)) strcat (cmd, args);
	shorten (cmd, 18);
	short_print (cluster, proc, owner, date, (int)utime, status, prio,
					image_size, cmd);

	switch (status)
	{
		case UNEXPANDED: unexpanded++; break;
		case IDLE:       idle++;       break;
		case RUNNING:    running++;    break;
	}
}

static void
short_header (void)
{
    printf( " %-7s %-14s %11s %12s %-2s %-3s %-4s %-18s\n",
        "ID",
        "OWNER",
        "SUBMITTED",
        "CPU_USAGE",
        "ST",
        "PRI",
        "SIZE",
        "CMD"
    );
}

static void
shorten (char *buff, int len)
{
	if ((unsigned int)strlen (buff) > (unsigned int)len) buff[len] = '\0';
}

static void
usage (char *myName)
{
	printf ("Usage: %s [options]\n\twhere [options] are\n"
		"\t\t-global\t\t\tGet global queue\n"
		"\t\t-submittor <submittor>\tGet queue of specific submittor\n"
		"\t\t-help\t\t\tThis screen\n"
		"\t\t-name <name>\t\tName of schedd\n"
		"\t\t-constraint <expr>\tAdd constraint on classads\n"
		"\t\t-long\t\t\tVerbose output\n"
		"\t\t<cluster>\t\tGet information about specific cluster\n"
		"\t\t<cluster>.<proc>\tGet information about specific job\n"
		"\t\t<owner>\t\t\tInformation about jobs owned by <owner>\n", myName);
}
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2003 by Unai Garro                                      *
 *   ugarro@users.sourceforge.net                                                       *
 *                                                                         *
 *   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.                                   *
 ***************************************************************************/
#include "conversiontable.h"
#include <iostream>

ConversionTable::ConversionTable(QWidget* parent,int maxrows,int maxcols):QTable( maxrows, maxcols, parent, "table" )
{
editBoxValue=-1;
items.setAutoDelete(true);
widgets.setAutoDelete(true);

connect(this,SIGNAL(signalSymmetric(int,int,double)),this,SLOT(makeSymmetric(int,int,double)));
}

ConversionTable::~ConversionTable()
{
}

QTableItem* ConversionTable::item( int r, int c ) const
{
return items.find(indexOf(r,c));
}

void ConversionTable::setItem(int r, int c, QTableItem *i )
{
items.replace( indexOf( r, c ), i );
i->setRow(r); // Otherwise the item
i->setCol(c); //doesn't know where it is!
}

void ConversionTable::clearCell( int r, int c )
{
items.remove(indexOf(r,c));
}

void ConversionTable::takeItem(QTableItem *item)
{
items.setAutoDelete(false);
items.remove(indexOf(item->row(),item->col()));
items.setAutoDelete(true);
}

void ConversionTable::insertWidget(int r, int c, QWidget *w )
{
widgets.replace(indexOf(r,c),w);
}

QWidget* ConversionTable::cellWidget( int r, int c ) const
{
return widgets.find( indexOf( r, c ) );
}

void ConversionTable::clearCellWidget( int r, int c )
{
QWidget *w = widgets.take(indexOf(r,c));
if (w) w->deleteLater();
}

ConversionTableItem::ConversionTableItem( QTable *t, EditType et ):QTableItem( t, et), eb( 0 )
{
//wedonotwantthisitemtobereplaced
	setReplaceable( false );
}

void ConversionTableItem::paint( QPainter *p, const QColorGroup &cg, const QRect &cr, bool selected )
{
	QColorGroup g(cg);

	// Draw in gray all those cells which are not editable

	if (row() == col())
	g.setColor( QColorGroup::Base, gray );
	QTableItem::paint( p, g, cr, selected );
}

QWidget* ConversionTableItem::createEditor() const
{
	((ConversionTableItem*)this)->eb=new EditBox(table()->viewport());
	eb->setValue(text().toDouble()); // Initialize the box with this value
	QObject::connect(eb,SIGNAL(valueChanged(double)),table(),SLOT(acceptValueAndClose()));
	return eb;
}

void ConversionTable::acceptValueAndClose()
{
QTable::endEdit(currentRow(),currentColumn(),true,false);
}

void ConversionTableItem::setContentFromEditor( QWidget *w )
{
	// theuser changed the value of the combobox, so synchronize the
	// value of the item (its text), with the value of the combobox
    if ( w->inherits( "EditBox" ) )
	{
	if (eb->accepted)
		{
		setText(QString::number(eb->value())); // Only accept value if Ok was pressed before
		emit ratioChanged(row(),col(),eb->value()); // Signal to store
		if (row()!=col()) emit signalSymmetric(row(),col(),eb->value()); // Signal to make symmetric. just in case, check if row,col are different (it shouldn't be editable, anyway)
		}
	}
    else
	QTableItem::setContentFromEditor( w );
}

void ConversionTableItem::setText( const QString &s )
{

	if (eb) {
	// initializetheeditboxfromthetext
	eb->setValue(s.toDouble());
	}
	QTableItem::setText(s);
}
QString ConversionTable::text(int r, int c ) const			 // without this function, the usual (text(r,c)) won't work
{

return(item(r,c)->text());  //Note that item(r,c) was reimplemented here for large sparse tables...

}

void ConversionTable::initTable()
{

for (int r=0;r<numRows();r++)
{
this->createNewItem(r,r,1.0);
item(r,r)->setEnabled(false); // Diagonal is not editable
}
}

void ConversionTable::createNewItem(int r, int c, double amount)
{

ConversionTableItem *ci= new ConversionTableItem(this,QTableItem::WhenCurrent);
setItem(r,c, ci );
ci->setText(QString::number(amount));
// connect signal (forward) to know when it's actually changed
connect(ci, SIGNAL(ratioChanged(int,int,double)),this,SIGNAL(ratioChanged(int,int,double)));
connect(ci, SIGNAL(signalSymmetric(int,int,double)),this,SIGNAL(signalSymmetric(int,int,double)));
connect(ci, SIGNAL(signalRepaintCell(int,int)),this,SLOT(repaintCell(int,int)));

}

void ConversionTable::setUnitIDs(const IDList &idList)
{
unitIDs=idList;
}

void ConversionTable::setRatio(int ingID1, int ingID2, double ratio)
{
int indexID1=unitIDs.find(&ingID1);
int indexID2=unitIDs.find(&ingID2);
createNewItem(indexID1,indexID2,ratio);
}

int ConversionTable::getUnitID(int rc)
{
return(*(unitIDs.at(rc)));
return(1);
}

QWidget * ConversionTable::beginEdit ( int row, int col, bool replace )
{
// If there's no item, create it first.
if (!item(row,col))
	{
	createNewItem(row,col,0);
	}

	if (!(item(col,row)) && (row!=col)) createNewItem(col,row,0); // Create the symmetric one.It shouldn't be necessary to do this if (row,col) exists, but just in case, it's checked. row==col is neither supposed to be editable, but check anyway

// Then call normal beginEdit
QTable::beginEdit(row,col,replace);
}

void ConversionTable::makeSymmetric(int r,int c,double amount)
{
QTableItem *it;
it=item(c,r);
if (amount)
(( ConversionTableItem *) it)->setTextAndSave(QString::number(1.0/amount)); // Change value and store in database
else
(( ConversionTableItem *) it)->setTextAndSave(QString::number(0));// Change value and store in database
}

void ConversionTableItem::setTextAndSave(const QString &s)
{
setText(s); // Change text
emit signalRepaintCell(row(),col()); // Indicate to update the cell to the table. Otherwise it's not repainted
emit ratioChanged(row(),col(),s.toDouble()); // Signal to store
}

void ConversionTable::repaintCell(int r,int c)
{
QTable::updateCell(r,c);
}

void ConversionTable::resize(int r,int c)
{
setNumRows(r);
setNumCols(c);
initTable();
}

void ConversionTable::clear(void)
{
items.clear();
widgets.clear();
unitIDs.clear();
resize(0,0);

}<commit_msg>Fix compiling for Qt 3.1.2<commit_after>/***************************************************************************
 *   Copyright (C) 2003 by Unai Garro                                      *
 *   ugarro@users.sourceforge.net                                                       *
 *                                                                         *
 *   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.                                   *
 ***************************************************************************/
#include "conversiontable.h"
#include <iostream>

ConversionTable::ConversionTable(QWidget* parent,int maxrows,int maxcols):QTable( maxrows, maxcols, parent, "table" )
{
editBoxValue=-1;
items.setAutoDelete(true);
widgets.setAutoDelete(true);

connect(this,SIGNAL(signalSymmetric(int,int,double)),this,SLOT(makeSymmetric(int,int,double)));
}

ConversionTable::~ConversionTable()
{
}

QTableItem* ConversionTable::item( int r, int c ) const
{
return items.find(indexOf(r,c));
}

void ConversionTable::setItem(int r, int c, QTableItem *i )
{
items.replace( indexOf( r, c ), i );
i->setRow(r); // Otherwise the item
i->setCol(c); //doesn't know where it is!
}

void ConversionTable::clearCell( int r, int c )
{
items.remove(indexOf(r,c));
}

void ConversionTable::takeItem(QTableItem *item)
{
items.setAutoDelete(false);
items.remove(indexOf(item->row(),item->col()));
items.setAutoDelete(true);
}

void ConversionTable::insertWidget(int r, int c, QWidget *w )
{
widgets.replace(indexOf(r,c),w);
}

QWidget* ConversionTable::cellWidget( int r, int c ) const
{
return widgets.find( indexOf( r, c ) );
}

void ConversionTable::clearCellWidget( int r, int c )
{
QWidget *w = widgets.take(indexOf(r,c));
if (w) w->deleteLater();
}

ConversionTableItem::ConversionTableItem( QTable *t, EditType et ):QTableItem( t, et, QString::null), eb( 0 )
{
//wedonotwantthisitemtobereplaced
	setReplaceable( false );
}

void ConversionTableItem::paint( QPainter *p, const QColorGroup &cg, const QRect &cr, bool selected )
{
	QColorGroup g(cg);

	// Draw in gray all those cells which are not editable

	if (row() == col())
	g.setColor( QColorGroup::Base, gray );
	QTableItem::paint( p, g, cr, selected );
}

QWidget* ConversionTableItem::createEditor() const
{
	((ConversionTableItem*)this)->eb=new EditBox(table()->viewport());
	eb->setValue(text().toDouble()); // Initialize the box with this value
	QObject::connect(eb,SIGNAL(valueChanged(double)),table(),SLOT(acceptValueAndClose()));
	return eb;
}

void ConversionTable::acceptValueAndClose()
{
QTable::endEdit(currentRow(),currentColumn(),true,false);
}

void ConversionTableItem::setContentFromEditor( QWidget *w )
{
	// theuser changed the value of the combobox, so synchronize the
	// value of the item (its text), with the value of the combobox
    if ( w->inherits( "EditBox" ) )
	{
	if (eb->accepted)
		{
		setText(QString::number(eb->value())); // Only accept value if Ok was pressed before
		emit ratioChanged(row(),col(),eb->value()); // Signal to store
		if (row()!=col()) emit signalSymmetric(row(),col(),eb->value()); // Signal to make symmetric. just in case, check if row,col are different (it shouldn't be editable, anyway)
		}
	}
    else
	QTableItem::setContentFromEditor( w );
}

void ConversionTableItem::setText( const QString &s )
{

	if (eb) {
	// initializetheeditboxfromthetext
	eb->setValue(s.toDouble());
	}
	QTableItem::setText(s);
}
QString ConversionTable::text(int r, int c ) const			 // without this function, the usual (text(r,c)) won't work
{

return(item(r,c)->text());  //Note that item(r,c) was reimplemented here for large sparse tables...

}

void ConversionTable::initTable()
{

for (int r=0;r<numRows();r++)
{
this->createNewItem(r,r,1.0);
item(r,r)->setEnabled(false); // Diagonal is not editable
}
}

void ConversionTable::createNewItem(int r, int c, double amount)
{

ConversionTableItem *ci= new ConversionTableItem(this,QTableItem::WhenCurrent);
setItem(r,c, ci );
ci->setText(QString::number(amount));
// connect signal (forward) to know when it's actually changed
connect(ci, SIGNAL(ratioChanged(int,int,double)),this,SIGNAL(ratioChanged(int,int,double)));
connect(ci, SIGNAL(signalSymmetric(int,int,double)),this,SIGNAL(signalSymmetric(int,int,double)));
connect(ci, SIGNAL(signalRepaintCell(int,int)),this,SLOT(repaintCell(int,int)));

}

void ConversionTable::setUnitIDs(const IDList &idList)
{
unitIDs=idList;
}

void ConversionTable::setRatio(int ingID1, int ingID2, double ratio)
{
int indexID1=unitIDs.find(&ingID1);
int indexID2=unitIDs.find(&ingID2);
createNewItem(indexID1,indexID2,ratio);
}

int ConversionTable::getUnitID(int rc)
{
return(*(unitIDs.at(rc)));
return(1);
}

QWidget * ConversionTable::beginEdit ( int row, int col, bool replace )
{
// If there's no item, create it first.
if (!item(row,col))
	{
	createNewItem(row,col,0);
	}

	if (!(item(col,row)) && (row!=col)) createNewItem(col,row,0); // Create the symmetric one.It shouldn't be necessary to do this if (row,col) exists, but just in case, it's checked. row==col is neither supposed to be editable, but check anyway

// Then call normal beginEdit
QTable::beginEdit(row,col,replace);
}

void ConversionTable::makeSymmetric(int r,int c,double amount)
{
QTableItem *it;
it=item(c,r);
if (amount)
(( ConversionTableItem *) it)->setTextAndSave(QString::number(1.0/amount)); // Change value and store in database
else
(( ConversionTableItem *) it)->setTextAndSave(QString::number(0));// Change value and store in database
}

void ConversionTableItem::setTextAndSave(const QString &s)
{
setText(s); // Change text
emit signalRepaintCell(row(),col()); // Indicate to update the cell to the table. Otherwise it's not repainted
emit ratioChanged(row(),col(),s.toDouble()); // Signal to store
}

void ConversionTable::repaintCell(int r,int c)
{
QTable::updateCell(r,c);
}

void ConversionTable::resize(int r,int c)
{
setNumRows(r);
setNumCols(c);
initTable();
}

void ConversionTable::clear(void)
{
items.clear();
widgets.clear();
unitIDs.clear();
resize(0,0);

}<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/test/testsupport/gtest_disable.h"
#include "webrtc/video_engine/test/auto_test/automated/legacy_fixture.h"
#include "webrtc/video_engine/test/auto_test/interface/vie_autotest.h"

namespace {

// TODO(phoglund): These tests are generally broken on mac.
// http://code.google.com/p/webrtc/issues/detail?id=1268
class DISABLED_ON_MAC(ViEExtendedIntegrationTest) : public LegacyFixture {
};

TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest), RunsBaseTestWithoutErrors) {
  tests_->ViEBaseExtendedTest();
}

// TODO(phoglund): Crashes on the v4l2loopback camera.
TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest),
       DISABLED_RunsCaptureTestWithoutErrors) {
  tests_->ViECaptureExtendedTest();
}

TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest),
       RunsCodecTestWithoutErrors) {
  tests_->ViECodecExtendedTest();
}

TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest),
       RunsEncryptionTestWithoutErrors) {
  tests_->ViEEncryptionExtendedTest();
}

TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest),
       RunsFileTestWithoutErrors) {
  tests_->ViEFileExtendedTest();
}

TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest),
       RunsImageProcessTestWithoutErrors) {
  tests_->ViEImageProcessExtendedTest();
}

TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest),
       RunsRenderTestWithoutErrors) {
  tests_->ViERenderExtendedTest();
}

TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest),
       RunsRtpRtcpTestWithoutErrors) {
  tests_->ViERtpRtcpExtendedTest();
}

}  // namespace
<commit_msg>Disable ViEExtendedIntegrationTest.RunsCodecTestWithoutErrors test.<commit_after>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/test/testsupport/gtest_disable.h"
#include "webrtc/video_engine/test/auto_test/automated/legacy_fixture.h"
#include "webrtc/video_engine/test/auto_test/interface/vie_autotest.h"

namespace {

// TODO(phoglund): These tests are generally broken on mac.
// http://code.google.com/p/webrtc/issues/detail?id=1268
class DISABLED_ON_MAC(ViEExtendedIntegrationTest) : public LegacyFixture {
};

TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest), RunsBaseTestWithoutErrors) {
  tests_->ViEBaseExtendedTest();
}

// TODO(phoglund): Crashes on the v4l2loopback camera.
TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest),
       DISABLED_RunsCaptureTestWithoutErrors) {
  tests_->ViECaptureExtendedTest();
}

// Flaky on Windows: http://code.google.com/p/webrtc/issues/detail?id=1925
// (in addition to being disabled on Mac due to webrtc:1268).
#if defined(WEBRTC_MAC) || defined(_WIN32)
#define MAYBE_RunsCodecTestWithoutErrors DISABLED_RunsCodecTestWithoutErrors
#else
#define MAYBE_RunsCodecTestWithoutErrors RunsCodecTestWithoutErrors
#endif
TEST_F(ViEExtendedIntegrationTest, MAYBE_RunsCodecTestWithoutErrors) {
  tests_->ViECodecExtendedTest();
}

TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest),
       RunsEncryptionTestWithoutErrors) {
  tests_->ViEEncryptionExtendedTest();
}

TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest),
       RunsFileTestWithoutErrors) {
  tests_->ViEFileExtendedTest();
}

TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest),
       RunsImageProcessTestWithoutErrors) {
  tests_->ViEImageProcessExtendedTest();
}

TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest),
       RunsRenderTestWithoutErrors) {
  tests_->ViERenderExtendedTest();
}

TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest),
       RunsRtpRtcpTestWithoutErrors) {
  tests_->ViERtpRtcpExtendedTest();
}

}  // namespace
<|endoftext|>


<commit_before>#include "GUI.hpp"

#include <string>
#include <vector>

#include <QMessageBox>
#include <QAction>
#include <QCloseEvent>
#include <QFontDatabase>
#include "Game.hpp"

#include "NewGameDialog.hpp"
#include "VirtualView.hpp"
#include "AugmentedView.hpp"

namespace Go_GUI {

/**
 * @brief	Checks for gui elements and fonts and connects signals and slots
 * @param	QWidget/QMainWindow		parent widget that creates this
 */
GUI::GUI(QWidget *parent) : QMainWindow(parent), go_game(nullptr)
{
    ui_main.setupUi(this);

    QString texture_path = "res/textures/";
    whitebasket_pixmap = QPixmap(texture_path + "white_basket.png");
    blackbasket_pixmap = QPixmap(texture_path + "black_basket.png");
    closedbasket_pixmap = QPixmap(texture_path + "Closed_basket.png");
    gotable_pixmap = QPixmap(texture_path + "go_table.png");
    if (blackbasket_pixmap.isNull() || whitebasket_pixmap.isNull() || closedbasket_pixmap.isNull() || gotable_pixmap.isNull())
        QMessageBox::critical(this, "GUI element not found", QString("White and/or black basket textures not found!\n searched relative to exe in: " + texture_path));

    // loading font
    QFontDatabase fontDatabase;
    QString font_path = "res/fonts/SHOJUMARU-REGULAR.TTF";
    if (fontDatabase.addApplicationFont(font_path) == -1)
        QMessageBox::critical(this, "Font not found", QString("Shojumaru font was not found!\n searched relative to exe in: " + font_path));

    // connections
    connect(ui_main.open_action,		&QAction::triggered,	this, &GUI::slot_MenuOpen);
    connect(ui_main.save_action,		&QAction::triggered,	this, &GUI::slot_MenuSave);
    connect(ui_main.exit_action,		&QAction::triggered,	this, &QWidget::close);
    connect(ui_main.info_action,		&QAction::triggered,	this, &GUI::slot_MenuInfo);
    connect(ui_main.viewswitch_button,	&QPushButton::clicked,	this, &GUI::slot_ViewSwitch);
    connect(ui_main.newgame_button,	    &QPushButton::clicked,	this, &GUI::slot_ButtonNewGame);
    connect(ui_main.pass_button,	    &QPushButton::clicked,	this, &GUI::slot_ButtonPass);
    connect(ui_main.resign_button,	    &QPushButton::clicked,	this, &GUI::slot_ButtonResign);

    // setting initial values
    this->init();
}

/**
 * @brief	Sets initial settings, texts and windows
 */
void GUI::init(){
    this->setWindowTitle("Augmented Go");
    this->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    virtual_view = new VirtualView(this);
    augmented_view = new AugmentedView(this);

    // Attaching augmented view to big container
    augmented_view->setParent(ui_main.big_container);
    augmented_view->rescaleImage(ui_main.big_container->size());
    ui_main.big_container->setToolTip("augmented view");
    augmented_view->show();

    // Attaching virtual view to small container
    virtual_view->setParent(ui_main.small_container);
    ui_main.small_container->setToolTip("virtual view");
    virtual_view->show();

    ui_main.white_basket->setPixmap(closedbasket_pixmap);
    ui_main.black_basket->setPixmap(closedbasket_pixmap);
    ui_main.go_table_label->setPixmap(gotable_pixmap);

    ui_main.capturedwhite_label->setText(QString());
    ui_main.capturedblack_label->setText(QString());
}

/**
 * @brief	sets labels and variables for player names.
 * @param	QString		name of black player (default: "Black"
 * @param	QString		name of white player (default: "White"
 */
void GUI::setPlayerLabels(QString blackplayer_name, QString whiteplayer_name){
    ui_main.blackplayer_label->setText(blackplayer_name);
    ui_main.whiteplayer_label->setText(whiteplayer_name);
}

//////////
//Public Slots
//////////

/**
 * @brief   SLOT "new image"
 *          If a new image is sent to GUI, refresh and rescale picture.
 * @param   QImage  new image from scanner
 */
void GUI::slot_newImage(QImage image) {
        printf(">>> New Image arrived! '%d x %d' -- Format: %d <<<\n", image.width(), image.height(), image.format());

        augmented_view->setImage(image);
        augmented_view->rescaleImage(augmented_view->parentWidget()->size());
    }

/**
 * @brief   SLOT "new game data"
 *          If new game data is sent to GUI, refresh display of current player and captured stones.
 * @param   game     new game representation
 */
void GUI::slot_newGameData(const GoBackend::Game* game) {
    // update internal pointer if the board has been changed
    if (game != game)
        game = game;

    auto& board = game->getBoard();

    auto current_player = board.ToPlay();

    // Updating basket pictures
    switch (current_player) {
    case SG_WHITE:
        ui_main.white_basket->setPixmap(whitebasket_pixmap);
        ui_main.black_basket->setPixmap(closedbasket_pixmap);
        break;
    case SG_BLACK:
        ui_main.white_basket->setPixmap(closedbasket_pixmap);
        ui_main.black_basket->setPixmap(blackbasket_pixmap);
        break;
    default:
        assert(false);
        break;
    }

    // Updating Game-Settings
    ui_main.movenumber_label->setText(QString::number(board.MoveNumber()));
    ui_main.kominumber_label->setText(QString::number(board.Rules().Komi().ToFloat()));
    ui_main.handicapnumber_label->setText(QString::number(board.Rules().Handicap()));
    ui_main.capturedwhite_label->setText(QString::number(board.NumPrisoners(SG_WHITE)));
    ui_main.capturedblack_label->setText(QString::number(board.NumPrisoners(SG_BLACK)));

    // refresh virtual view
    if (ui_main.big_container->toolTip() == "virtual view")
        virtual_view->createAndSetScene(ui_main.big_container->size(), &board);

    else if (ui_main.big_container->toolTip() == "augmented view")
        virtual_view->createAndSetScene(ui_main.small_container->size(), &board);

    printf(">>> New Game data! <<<\n");
}

/**
 * @brief   SLOT "Show finished game results"
 *          If a game ended, the BackendThread sends a signal with the results.
 *          Here the results are shown to the user.
 */
void GUI::slot_showFinishedGameResults(QString result){
    QMessageBox::information(this, "Game results", result);
    auto answer = QMessageBox::question(this, "New Game?", "Do you want to start a new game?");
    if (answer == QMessageBox::Yes)
        this->slot_ButtonNewGame();
}

/**
 * @brief   SLOT "setup new game"
 *          When a new game has been started, setup game name and player names on gui.
 * @param   QString    game name
 * @param   QString    black player name
 * @param   QString    white player name
 */
void GUI::slot_setupNewGame(QString game_name, QString blackplayer_name, QString whiteplayer_name, float komi){

    // emit to backend that gui wants to set up a new game!
    auto rules = GoRules(0, GoKomi(komi), true, true);
    emit signal_newGame(rules);

    // Setting up new names for players
    ui_main.gamename_label->setText(game_name);
    ui_main.blackplayer_label->setText(blackplayer_name);
    ui_main.whiteplayer_label->setText(whiteplayer_name);
    ui_main.kominumber_label->setText(QString::number(komi));
    ui_main.handicapnumber_label->setText(QString::number(0));
}

//////////
//Private Slots
//////////

/**
 * @brief   SLOT "NewGame/Reset"
 *          Opens a Dialog that asks for game rules and names.
 */
void GUI::slot_ButtonNewGame(){
    NewGameDialog* newgame = new NewGameDialog(this);
    newgame->exec();
}

/**
 * @brief   SLOT "Resign"
 *          Opens a Dialog that asks for confirmation.
 *			If answered yes, a signal is sent to backend that the current player surrenders.
 */
void GUI::slot_ButtonResign(){
    if (QMessageBox::question(this, "Resign", "Do you really want to admit defeat?") == QMessageBox::Yes)
        emit signal_resign();
}

/**
 * @brief   SLOT "Pass"
 *          Opens a Dialog that asks for confirmation.
 *			If answered yes, a signal is sent to backend that the current player passes.
 */
void GUI::slot_ButtonPass(){
    if (QMessageBox::question(this, "Pass", "Do you really want to pass?") == QMessageBox::Yes)
        emit signal_pass();
}

/**
 * @brief	SLOT "ViewSwitch"
 *			Switches big view with small view.
 *			To assign a view to something a QWidget has to be created.
 */
void GUI::slot_ViewSwitch(){
    if (ui_main.big_container->toolTip() == "virtual view"){

        // switching augmented view to big container
        augmented_view->setParent(ui_main.big_container);
        augmented_view->rescaleImage(ui_main.big_container->size());
        ui_main.big_container->setToolTip("augmented view");
        augmented_view->show();		// when changing parent, it gets invisible -> show again! -.- !!

        // new style
        virtual_view->setParent(ui_main.small_container);
        virtual_view->createAndSetScene(ui_main.small_container->size(), &(go_game->getBoard()));
        ui_main.small_container->setToolTip("virtual view");
        virtual_view->show();

    }
    else if (ui_main.big_container->toolTip() == "augmented view"){
        // switching augmented view to small container
        augmented_view->setParent(ui_main.small_container);
        augmented_view->rescaleImage(ui_main.small_container->size());
        ui_main.small_container->setToolTip("augmented view");
        augmented_view->show();		// when changing parent, it gets invisible -> show again! -.- !!

        virtual_view->setParent(ui_main.big_container);
        virtual_view->createAndSetScene(ui_main.big_container->size(), &(go_game->getBoard()));
        ui_main.big_container->setToolTip("virtual view");
        virtual_view->show();
    }
}

/**
 * @brief	SLOT QAction "MenuOpen"
 *			opens a filedialog that lets the user choose an sgf-file.
 * @todo	loading sgf file
 */
void GUI::slot_MenuOpen(){
    QString selfilter = tr("SGF (*.sgf)");
    QString fileName = QFileDialog::getOpenFileName(
        this,
        "open sgf-file",
        NULL,
        tr("SGF (*.sgf)" ),
        &selfilter
    );

    if (!fileName.isNull()){
        // TODO ask if user wants to save the current game!
        emit signal_openGame(fileName);
    }
}

/**
 * @brief	SLOT QAction "MenuSave"
 *			opens a filedialog that lets the user choose an sgf-file.
 */
void GUI::slot_MenuSave(){
    QString selfilter = tr("SGF (*.sgf)");
    QString fileName = QFileDialog::getSaveFileName(
        this,
        "save sgf-file",
        NULL,
        tr("SGF (*.sgf)" ),
        &selfilter
    );

    if (!fileName.isNull())
        emit signal_saveGame(fileName, ui_main.blackplayer_label->text(), ui_main.whiteplayer_label->text(), this->game_name);
}

/**
 * @brief	SLOT QAction "MenuInfo"
 *			opens a window with information about the application.
 */
void GUI::slot_MenuInfo(){
    // Appliction Info
    std::string output = "Augmented Go - Interactive Game of Go as Augmented Reality Application\n\n\n";

    // Build date and time
    output += "This build of Augmented Go was compiled at " __DATE__ ", " __TIME__ ".\n";

    // Copyright
    std::string year = __DATE__;
    year = year.substr(year.find_last_of(" "));	// deleting day and month
    output += "Copyright " + year + "\n";

    // Licence
    output += "\nThis software is released under the \"MIT License\".\n"
        "See the file LICENSE for full license and copying terms.\n";

    // Final InfoBox
    QMessageBox::about(this, "Info", output.c_str());
}

/**
 * @brief	overridden SLOT QCloseEvent "closeEvent"
 *			When trying to close the application a window appears and asks if user is sure.
 *			If answered "yes" the a signal to the backend thread is sent to stop it.
 *			If answered "no" the close event is ignored.
 * @param	QCloseEvent		close event that shall or shall not be executed afterwards.
 */
void GUI::closeEvent(QCloseEvent *event){

    // If at least one move was was done
    // TODO If game loaded -> move number greater than start number!
    if (ui_main.movenumber_label->text().toInt() > 0){
        if (QMessageBox::question(this, "Save?", "Save current game?") == QMessageBox::Yes)
            this->slot_MenuSave();
    }

    // Ask if the user wants to quit
    if (QMessageBox::question(this, "Quit?", "Do you really want to quit?") == QMessageBox::Yes){
        emit stop_backend_thread();
        event->accept();
    }
    else
        event->ignore();

}

} // namespace Go_GUI<commit_msg>refs #104 changed button texts<commit_after>#include "GUI.hpp"

#include <string>
#include <vector>

#include <QMessageBox>
#include <QAction>
#include <QCloseEvent>
#include <QFontDatabase>
#include "Game.hpp"

#include "NewGameDialog.hpp"
#include "VirtualView.hpp"
#include "AugmentedView.hpp"

namespace Go_GUI {

/**
 * @brief	Checks for gui elements and fonts and connects signals and slots
 * @param	QWidget/QMainWindow		parent widget that creates this
 */
GUI::GUI(QWidget *parent) : QMainWindow(parent), go_game(nullptr)
{
    ui_main.setupUi(this);

    QString texture_path = "res/textures/";
    whitebasket_pixmap = QPixmap(texture_path + "white_basket.png");
    blackbasket_pixmap = QPixmap(texture_path + "black_basket.png");
    closedbasket_pixmap = QPixmap(texture_path + "Closed_basket.png");
    gotable_pixmap = QPixmap(texture_path + "go_table.png");
    if (blackbasket_pixmap.isNull() || whitebasket_pixmap.isNull() || closedbasket_pixmap.isNull() || gotable_pixmap.isNull())
        QMessageBox::critical(this, "GUI element not found", QString("White and/or black basket textures not found!\n searched relative to exe in: " + texture_path));

    // loading font
    QFontDatabase fontDatabase;
    QString font_path = "res/fonts/SHOJUMARU-REGULAR.TTF";
    if (fontDatabase.addApplicationFont(font_path) == -1)
        QMessageBox::critical(this, "Font not found", QString("Shojumaru font was not found!\n searched relative to exe in: " + font_path));

    // connections
    connect(ui_main.open_action,		&QAction::triggered,	this, &GUI::slot_MenuOpen);
    connect(ui_main.save_action,		&QAction::triggered,	this, &GUI::slot_MenuSave);
    connect(ui_main.exit_action,		&QAction::triggered,	this, &QWidget::close);
    connect(ui_main.info_action,		&QAction::triggered,	this, &GUI::slot_MenuInfo);
    connect(ui_main.viewswitch_button,	&QPushButton::clicked,	this, &GUI::slot_ViewSwitch);
    connect(ui_main.newgame_button,	    &QPushButton::clicked,	this, &GUI::slot_ButtonNewGame);
    connect(ui_main.pass_button,	    &QPushButton::clicked,	this, &GUI::slot_ButtonPass);
    connect(ui_main.resign_button,	    &QPushButton::clicked,	this, &GUI::slot_ButtonResign);

    // setting initial values
    this->init();
}

/**
 * @brief	Sets initial settings, texts and windows
 */
void GUI::init(){
    this->setWindowTitle("Augmented Go");
    this->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    virtual_view = new VirtualView(this);
    augmented_view = new AugmentedView(this);

    // Attaching augmented view to big container
    augmented_view->setParent(ui_main.big_container);
    augmented_view->rescaleImage(ui_main.big_container->size());
    ui_main.big_container->setToolTip("augmented view");
    augmented_view->show();

    // Attaching virtual view to small container
    virtual_view->setParent(ui_main.small_container);
    ui_main.small_container->setToolTip("virtual view");
    virtual_view->show();

    ui_main.white_basket->setPixmap(closedbasket_pixmap);
    ui_main.black_basket->setPixmap(closedbasket_pixmap);
    ui_main.go_table_label->setPixmap(gotable_pixmap);

    ui_main.capturedwhite_label->setText(QString());
    ui_main.capturedblack_label->setText(QString());
}

/**
 * @brief	sets labels and variables for player names.
 * @param	QString		name of black player (default: "Black"
 * @param	QString		name of white player (default: "White"
 */
void GUI::setPlayerLabels(QString blackplayer_name, QString whiteplayer_name){
    ui_main.blackplayer_label->setText(blackplayer_name);
    ui_main.whiteplayer_label->setText(whiteplayer_name);
}

//////////
//Public Slots
//////////

/**
 * @brief   SLOT "new image"
 *          If a new image is sent to GUI, refresh and rescale picture.
 * @param   QImage  new image from scanner
 */
void GUI::slot_newImage(QImage image) {
        printf(">>> New Image arrived! '%d x %d' -- Format: %d <<<\n", image.width(), image.height(), image.format());

        augmented_view->setImage(image);
        augmented_view->rescaleImage(augmented_view->parentWidget()->size());
    }

/**
 * @brief   SLOT "new game data"
 *          If new game data is sent to GUI, refresh display of current player and captured stones.
 * @param   game     new game representation
 */
void GUI::slot_newGameData(const GoBackend::Game* game) {
    // update internal pointer if the board has been changed
    if (game != game)
        game = game;

    auto& board = game->getBoard();

    auto current_player = board.ToPlay();

    // Updating basket pictures
    switch (current_player) {
    case SG_WHITE:
        ui_main.white_basket->setPixmap(whitebasket_pixmap);
        ui_main.black_basket->setPixmap(closedbasket_pixmap);
        break;
    case SG_BLACK:
        ui_main.white_basket->setPixmap(closedbasket_pixmap);
        ui_main.black_basket->setPixmap(blackbasket_pixmap);
        break;
    default:
        assert(false);
        break;
    }

    // Updating Game-Settings
    ui_main.movenumber_label->setText(QString::number(board.MoveNumber()));
    ui_main.kominumber_label->setText(QString::number(board.Rules().Komi().ToFloat()));
    ui_main.handicapnumber_label->setText(QString::number(board.Rules().Handicap()));
    ui_main.capturedwhite_label->setText(QString::number(board.NumPrisoners(SG_WHITE)));
    ui_main.capturedblack_label->setText(QString::number(board.NumPrisoners(SG_BLACK)));

    // refresh virtual view
    if (ui_main.big_container->toolTip() == "virtual view")
        virtual_view->createAndSetScene(ui_main.big_container->size(), &board);

    else if (ui_main.big_container->toolTip() == "augmented view")
        virtual_view->createAndSetScene(ui_main.small_container->size(), &board);

    printf(">>> New Game data! <<<\n");
}

/**
 * @brief   SLOT "Show finished game results"
 *          If a game ended, the BackendThread sends a signal with the results.
 *          Here the results are shown to the user.
 */
void GUI::slot_showFinishedGameResults(QString result){
    QMessageBox::information(this, "Game results", result);
    auto answer = QMessageBox::question(this, "New Game?", "Do you want to start a new game?");
    if (answer == QMessageBox::Yes)
        this->slot_ButtonNewGame();
}

/**
 * @brief   SLOT "setup new game"
 *          When a new game has been started, setup game name and player names on gui.
 * @param   QString    game name
 * @param   QString    black player name
 * @param   QString    white player name
 */
void GUI::slot_setupNewGame(QString game_name, QString blackplayer_name, QString whiteplayer_name, float komi){

    // emit to backend that gui wants to set up a new game!
    auto rules = GoRules(0, GoKomi(komi), true, true);
    emit signal_newGame(rules);

    // Setting up new names for players
    ui_main.gamename_label->setText(game_name);
    ui_main.blackplayer_label->setText(blackplayer_name);
    ui_main.whiteplayer_label->setText(whiteplayer_name);
    ui_main.kominumber_label->setText(QString::number(komi));
    ui_main.handicapnumber_label->setText(QString::number(0));
}

//////////
//Private Slots
//////////

/**
 * @brief   SLOT "NewGame/Reset"
 *          Opens a Dialog that asks for game rules and names.
 */
void GUI::slot_ButtonNewGame(){
    NewGameDialog* newgame = new NewGameDialog(this);
    newgame->exec();
}

/**
 * @brief   SLOT "Resign"
 *          Opens a Dialog that asks for confirmation.
 *			If answered yes, a signal is sent to backend that the current player surrenders.
 */
void GUI::slot_ButtonResign(){
    if (QMessageBox::question(this, "Resign", "Do you really want to admit defeat?") == QMessageBox::Yes)
        emit signal_resign();
}

/**
 * @brief   SLOT "Pass"
 *          Opens a Dialog that asks for confirmation.
 *			If answered yes, a signal is sent to backend that the current player passes.
 */
void GUI::slot_ButtonPass(){
    if (QMessageBox::question(this, "Pass", "Do you really want to pass?") == QMessageBox::Yes)
        emit signal_pass();
}

/**
 * @brief	SLOT "ViewSwitch"
 *			Switches big view with small view.
 *			To assign a view to something a QWidget has to be created.
 */
void GUI::slot_ViewSwitch(){
    if (ui_main.big_container->toolTip() == "virtual view"){

        // switching augmented view to big container
        augmented_view->setParent(ui_main.big_container);
        augmented_view->rescaleImage(ui_main.big_container->size());
        ui_main.big_container->setToolTip("augmented view");
        augmented_view->show();		// when changing parent, it gets invisible -> show again! -.- !!

        // new style
        virtual_view->setParent(ui_main.small_container);
        virtual_view->createAndSetScene(ui_main.small_container->size(), &(go_game->getBoard()));
        ui_main.small_container->setToolTip("virtual view");
        virtual_view->show();

    }
    else if (ui_main.big_container->toolTip() == "augmented view"){
        // switching augmented view to small container
        augmented_view->setParent(ui_main.small_container);
        augmented_view->rescaleImage(ui_main.small_container->size());
        ui_main.small_container->setToolTip("augmented view");
        augmented_view->show();		// when changing parent, it gets invisible -> show again! -.- !!

        virtual_view->setParent(ui_main.big_container);
        virtual_view->createAndSetScene(ui_main.big_container->size(), &(go_game->getBoard()));
        ui_main.big_container->setToolTip("virtual view");
        virtual_view->show();
    }
}

/**
 * @brief	SLOT QAction "MenuOpen"
 *			opens a filedialog that lets the user choose an sgf-file.
 * @todo	loading sgf file
 */
void GUI::slot_MenuOpen(){
    QString selfilter = tr("SGF (*.sgf)");
    QString fileName = QFileDialog::getOpenFileName(
        this,
        "open sgf-file",
        NULL,
        tr("SGF (*.sgf)" ),
        &selfilter
    );

    if (!fileName.isNull()){
        // TODO ask if user wants to save the current game!
        emit signal_openGame(fileName);
    }
}

/**
 * @brief	SLOT QAction "MenuSave"
 *			opens a filedialog that lets the user choose an sgf-file.
 */
void GUI::slot_MenuSave(){
    QString selfilter = tr("SGF (*.sgf)");
    QString fileName = QFileDialog::getSaveFileName(
        this,
        "save sgf-file",
        NULL,
        tr("SGF (*.sgf)" ),
        &selfilter
    );

    if (!fileName.isNull())
        emit signal_saveGame(fileName, ui_main.blackplayer_label->text(), ui_main.whiteplayer_label->text(), this->game_name);
}

/**
 * @brief	SLOT QAction "MenuInfo"
 *			opens a window with information about the application.
 */
void GUI::slot_MenuInfo(){
    // Appliction Info
    std::string output = "Augmented Go - Interactive Game of Go as Augmented Reality Application\n\n\n";

    // Build date and time
    output += "This build of Augmented Go was compiled at " __DATE__ ", " __TIME__ ".\n";

    // Copyright
    std::string year = __DATE__;
    year = year.substr(year.find_last_of(" "));	// deleting day and month
    output += "Copyright " + year + "\n";

    // Licence
    output += "\nThis software is released under the \"MIT License\".\n"
        "See the file LICENSE for full license and copying terms.\n";

    // Final InfoBox
    QMessageBox::about(this, "Info", output.c_str());
}

/**
 * @brief	overridden SLOT QCloseEvent "closeEvent"
 *			When trying to close the application a window appears and asks if user is sure.
 *			If answered "yes" the a signal to the backend thread is sent to stop it.
 *			If answered "no" the close event is ignored.
 * @param	QCloseEvent		close event that shall or shall not be executed afterwards.
 */
void GUI::closeEvent(QCloseEvent *event){

    // If at least one move was was done
    // TODO If game loaded -> move number greater than start number!
    int answer = 0;
    bool saveable = ui_main.movenumber_label->text().toInt() > 0;

    if (saveable)
        answer = QMessageBox::question(this, "Save?", "Do you want to save before quit?", "Save", "Don't Save", "Cancel");
    else
        answer = QMessageBox::question(this, "Quit?", "Do you really want to quit?", "Quit", "Cancel");

    if(answer == 0 && saveable){
        this->slot_MenuSave();
        emit stop_backend_thread();
        event->accept();
    }
    else if((answer == 1 && saveable)
        || (answer == 0 && !saveable)){
        emit stop_backend_thread();
        event->accept();
    }
    else
        event->ignore();
}

} // namespace Go_GUI<|endoftext|>