<commit_before>#include <string>
#include <iostream>
#include <vector>
#include "../stringtools.h"
#include "../urbackupcommon/os_functions.h"
#include <stdlib.h>
#ifndef _WIN32
#include <unistd.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pwd.h>
#endif

#define DEF_Server
#include "../Server.h"

const std::string btrfs_cmd="/sbin/btrfs";

CServer *Server;

#ifdef _WIN32
#include <Windows.h>

bool CopyFolder(std::wstring src, std::wstring dst)
{
	if(!os_create_dir(dst))
		return false;

	std::vector<SFile> curr_files=getFiles(src);
	for(size_t i=0;i<curr_files.size();++i)
	{
		if(curr_files[i].isdir)
		{
			bool b=CopyFolder(src+os_file_sep()+curr_files[i].name, dst+os_file_sep()+curr_files[i].name);
			if(!b)
				return false;
		}
		else
		{
			if(!os_create_hardlink(dst+os_file_sep()+curr_files[i].name, src+os_file_sep()+curr_files[i].name, false, NULL) )
			{
				BOOL b=CopyFileW( (src+os_file_sep()+curr_files[i].name).c_str(), (dst+os_file_sep()+curr_files[i].name).c_str(), FALSE);
				if(!b)
				{
					return false;
				}
			}
		}
	}

	return true;
}
#endif

std::string getBackupfolderPath(void)
{
	std::string fn;
#ifdef _WIN32
	fn=trim(getFile("backupfolder"));
#else
	fn=trim(getFile("/etc/urbackup/backupfolder"));
#endif
	if(fn.find("\n")!=std::string::npos)
		fn=getuntil("\n", fn);
	if(fn.find("\r")!=std::string::npos)
		fn=getuntil("\r", fn);

	return fn;
}

std::string handleFilename(std::string fn)
{
	fn=conv_filename(fn);
	if(fn=="..")
	{
		return "";
	}
	return fn;
}

#ifndef _WIN32
int exec_wait(const std::string& path, ...)
{
	va_list vl;
	va_start(vl, path);

	std::vector<char*> args;
	args.push_back(const_cast<char*>(path.c_str()));

	while(true)
	{
		const char* p = va_arg(vl, const char*);
		if(p==NULL) break;
		args.push_back(const_cast<char*>(p));
	}
	va_end(vl);

	args.push_back(NULL);

	pid_t child_pid = fork();

	if(child_pid==0)
	{
		int rc = execvpe(path.c_str(), args.data(), NULL);
		exit(rc);
	}
	else
	{
		int status;
		waitpid(child_pid, &status, 0);
		if(WIFEXITED(status))
		{
			return WEXITSTATUS(status);
		}
		else
		{
			return -1;
		}
	}
}

bool chown_dir(const std::string& dir)
{
	passwd* user_info = getpwnam("urbackup");
	if(user_info)
	{
		int rc = chown(dir.c_str(), user_info->pw_uid, user_info->pw_gid);
		return rc!=-1;
	}
	return false;
}
#endif

bool create_subvolume(std::string subvolume_folder)
{
#ifdef _WIN32
	return os_create_dir(subvolume_folder);
#else
	int rc=exec_wait(btrfs_cmd, "subvolume", "create", subvolume_folder.c_str(), NULL);
	chown_dir(subvolume_folder);
	return rc==0;
#endif
}

bool create_snapshot(std::string snapshot_src, std::string snapshot_dst)
{
#ifdef _WIN32
	return CopyFolder(widen(snapshot_src), widen(snapshot_dst));
#else
	int rc=exec_wait(btrfs_cmd, "subvolume", "snapshot", snapshot_src.c_str(), snapshot_dst.c_str(), NULL);
	chown_dir(snapshot_dst);
	return rc==0;
#endif
}

bool remove_subvolume(std::string subvolume_folder)
{
#ifdef _WIN32
	return os_remove_nonempty_dir(widen(subvolume_folder));
#else
	int rc=exec_wait(btrfs_cmd, "subvolume", "delete", subvolume_folder.c_str(), NULL);
	return rc==0;
#endif
}

bool is_subvolume(std::string subvolume_folder)
{
#ifdef _WIN32
	return true;
#else
	int rc=exec_wait(btrfs_cmd, "subvolume", "list", subvolume_folder.c_str(), NULL);
	return rc==0;
#endif
}

int main(int argc, char *argv[])
{
	if(argc<2)
	{
		std::cout << "Not enough parameters" << std::endl;
		return 1;
	}

	std::string cmd=argv[1];

	std::string backupfolder=getBackupfolderPath();

	if(backupfolder.empty())
	{
		std::cout << "Backupfolder not set" << std::endl;
		return 1;
	}

#ifndef _WIN32
	if(seteuid(0)!=0)
	{
		std::cout << "Cannot become root user" << std::endl;
		return 1;
	}
#endif

	if(cmd=="create")
	{
		if(argc<4)
		{
			std::cout << "Not enough parameters for create" << std::endl;
			return 1;
		}

		std::string clientname=handleFilename(argv[2]);
		std::string name=handleFilename(argv[3]);

		std::string subvolume_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+name;

		return create_subvolume(subvolume_folder)?0:1;
	}
	else if(cmd=="snapshot")
	{
		if(argc<5)
		{
			std::cout << "Not enough parameters for snapshot" << std::endl;
			return 1;
		}

		std::string clientname=handleFilename(argv[2]);
		std::string src_name=handleFilename(argv[3]);
		std::string dst_name=handleFilename(argv[4]);

		std::string subvolume_src_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+src_name;
		std::string subvolume_dst_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+dst_name;

		return create_snapshot(subvolume_src_folder, subvolume_dst_folder)?0:1;
	}
	else if(cmd=="remove")
	{
		if(argc<4)
		{
			std::cout << "Not enough parameters for remove" << std::endl;
			return 1;
		}

		std::string clientname=handleFilename(argv[2]);
		std::string name=handleFilename(argv[3]);

		std::string subvolume_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+name;

		return remove_subvolume(subvolume_folder)?0:1;
	}
	else if(cmd=="test")
	{
		std::string clientdir=backupfolder+os_file_sepn()+"testA54hj5luZtlorr494";

		bool create_dir_rc=os_create_dir(clientdir);
		if(!create_dir_rc)
		{
			remove_subvolume(clientdir+os_file_sepn()+"A");
			remove_subvolume(clientdir+os_file_sepn()+"B");
			os_remove_dir(clientdir);
		}
		create_dir_rc = create_dir_rc || os_create_dir(clientdir);
		if(create_dir_rc)
		{
			if(!create_subvolume(clientdir+os_file_sepn()+"A") )
			{
				std::cout << "TEST FAILED: Creating test subvolume failed" << std::endl;
				os_remove_dir(clientdir);
				return 1;
			}

			bool suc=true;

			if(!create_snapshot(clientdir+os_file_sepn()+"A", clientdir+os_file_sepn()+"B") )
			{
				std::cout << "TEST FAILED: Creating test snapshot failed" << std::endl;
				suc=false;
			}

			if(suc)
			{
				writestring("test", clientdir+os_file_sepn()+"A"+os_file_sepn()+"test");

				if(!os_create_hardlink(clientdir+os_file_sepn()+"B"+os_file_sepn()+"test", clientdir+os_file_sepn()+"A"+os_file_sepn()+"test", true, NULL))
				{
					std::cout << "TEST FAILED: Creating cross sub-volume reflink failed. Need Linux kernel >= 3.6." << std::endl;
					suc=false;
				}
				else
				{
					if(getFile(clientdir+os_file_sepn()+"B"+os_file_sepn()+"test")!="test")
					{
						std::cout << "TEST FAILED: Cannot read reflinked file" << std::endl;
						suc=false;
					}
				}
			}

			if(!remove_subvolume(clientdir+os_file_sepn()+"A") )
			{
				std::cout << "TEST FAILED: Removing subvolume A failed" << std::endl;
				suc=false;
			}

			if(!remove_subvolume(clientdir+os_file_sepn()+"B") )
			{
				std::cout << "TEST FAILED: Removing subvolume B failed" << std::endl;
				suc=false;
			}

			if(!os_remove_dir(clientdir))
			{
				std::cout << "TEST FAILED: Removing test clientdir failed" << std::endl;
				return 1;
			}

			if(!suc)
			{
				return 1;
			}
		}
		else
		{
			std::cout << "TEST FAILED: Creating test clientdir \"" << clientdir << "\" failed" << std::endl;
			return 1;
		}
		std::cout << "TEST OK" << std::endl;
		return 0;
	}
	else if(cmd=="issubvolume")
	{
		if(argc<4)
		{
			std::cout << "Not enough parameters for issubvolume" << std::endl;
			return 1;
		}

		std::string clientname=handleFilename(argv[2]);
		std::string name=handleFilename(argv[3]);

		std::string subvolume_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+name;

		return is_subvolume(subvolume_folder)?0:1;
	}
	else
	{
		std::cout << "Command not found" << std::endl;
		return 1;
	}
}

<commit_msg>Build fix for FreeBSD<commit_after>#include <string>
#include <iostream>
#include <vector>
#include "../stringtools.h"
#include "../urbackupcommon/os_functions.h"
#include <stdlib.h>
#ifndef _WIN32
#include <unistd.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pwd.h>
#endif

#ifdef __FreeBSD__
#define execvpe exect
#endif

#define DEF_Server
#include "../Server.h"

const std::string btrfs_cmd="/sbin/btrfs";

CServer *Server;

#ifdef _WIN32
#include <Windows.h>

bool CopyFolder(std::wstring src, std::wstring dst)
{
	if(!os_create_dir(dst))
		return false;

	std::vector<SFile> curr_files=getFiles(src);
	for(size_t i=0;i<curr_files.size();++i)
	{
		if(curr_files[i].isdir)
		{
			bool b=CopyFolder(src+os_file_sep()+curr_files[i].name, dst+os_file_sep()+curr_files[i].name);
			if(!b)
				return false;
		}
		else
		{
			if(!os_create_hardlink(dst+os_file_sep()+curr_files[i].name, src+os_file_sep()+curr_files[i].name, false, NULL) )
			{
				BOOL b=CopyFileW( (src+os_file_sep()+curr_files[i].name).c_str(), (dst+os_file_sep()+curr_files[i].name).c_str(), FALSE);
				if(!b)
				{
					return false;
				}
			}
		}
	}

	return true;
}
#endif

std::string getBackupfolderPath(void)
{
	std::string fn;
#ifdef _WIN32
	fn=trim(getFile("backupfolder"));
#else
	fn=trim(getFile("/etc/urbackup/backupfolder"));
#endif
	if(fn.find("\n")!=std::string::npos)
		fn=getuntil("\n", fn);
	if(fn.find("\r")!=std::string::npos)
		fn=getuntil("\r", fn);

	return fn;
}

std::string handleFilename(std::string fn)
{
	fn=conv_filename(fn);
	if(fn=="..")
	{
		return "";
	}
	return fn;
}

#ifndef _WIN32
int exec_wait(const std::string& path, ...)
{
	va_list vl;
	va_start(vl, path);

	std::vector<char*> args;
	args.push_back(const_cast<char*>(path.c_str()));

	while(true)
	{
		const char* p = va_arg(vl, const char*);
		if(p==NULL) break;
		args.push_back(const_cast<char*>(p));
	}
	va_end(vl);

	args.push_back(NULL);

	pid_t child_pid = fork();

	if(child_pid==0)
	{
		int rc = execvpe(path.c_str(), args.data(), NULL);
		exit(rc);
	}
	else
	{
		int status;
		waitpid(child_pid, &status, 0);
		if(WIFEXITED(status))
		{
			return WEXITSTATUS(status);
		}
		else
		{
			return -1;
		}
	}
}

bool chown_dir(const std::string& dir)
{
	passwd* user_info = getpwnam("urbackup");
	if(user_info)
	{
		int rc = chown(dir.c_str(), user_info->pw_uid, user_info->pw_gid);
		return rc!=-1;
	}
	return false;
}
#endif

bool create_subvolume(std::string subvolume_folder)
{
#ifdef _WIN32
	return os_create_dir(subvolume_folder);
#else
	int rc=exec_wait(btrfs_cmd, "subvolume", "create", subvolume_folder.c_str(), NULL);
	chown_dir(subvolume_folder);
	return rc==0;
#endif
}

bool create_snapshot(std::string snapshot_src, std::string snapshot_dst)
{
#ifdef _WIN32
	return CopyFolder(widen(snapshot_src), widen(snapshot_dst));
#else
	int rc=exec_wait(btrfs_cmd, "subvolume", "snapshot", snapshot_src.c_str(), snapshot_dst.c_str(), NULL);
	chown_dir(snapshot_dst);
	return rc==0;
#endif
}

bool remove_subvolume(std::string subvolume_folder)
{
#ifdef _WIN32
	return os_remove_nonempty_dir(widen(subvolume_folder));
#else
	int rc=exec_wait(btrfs_cmd, "subvolume", "delete", subvolume_folder.c_str(), NULL);
	return rc==0;
#endif
}

bool is_subvolume(std::string subvolume_folder)
{
#ifdef _WIN32
	return true;
#else
	int rc=exec_wait(btrfs_cmd, "subvolume", "list", subvolume_folder.c_str(), NULL);
	return rc==0;
#endif
}

int main(int argc, char *argv[])
{
	if(argc<2)
	{
		std::cout << "Not enough parameters" << std::endl;
		return 1;
	}

	std::string cmd=argv[1];

	std::string backupfolder=getBackupfolderPath();

	if(backupfolder.empty())
	{
		std::cout << "Backupfolder not set" << std::endl;
		return 1;
	}

#ifndef _WIN32
	if(seteuid(0)!=0)
	{
		std::cout << "Cannot become root user" << std::endl;
		return 1;
	}
#endif

	if(cmd=="create")
	{
		if(argc<4)
		{
			std::cout << "Not enough parameters for create" << std::endl;
			return 1;
		}

		std::string clientname=handleFilename(argv[2]);
		std::string name=handleFilename(argv[3]);

		std::string subvolume_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+name;

		return create_subvolume(subvolume_folder)?0:1;
	}
	else if(cmd=="snapshot")
	{
		if(argc<5)
		{
			std::cout << "Not enough parameters for snapshot" << std::endl;
			return 1;
		}

		std::string clientname=handleFilename(argv[2]);
		std::string src_name=handleFilename(argv[3]);
		std::string dst_name=handleFilename(argv[4]);

		std::string subvolume_src_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+src_name;
		std::string subvolume_dst_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+dst_name;

		return create_snapshot(subvolume_src_folder, subvolume_dst_folder)?0:1;
	}
	else if(cmd=="remove")
	{
		if(argc<4)
		{
			std::cout << "Not enough parameters for remove" << std::endl;
			return 1;
		}

		std::string clientname=handleFilename(argv[2]);
		std::string name=handleFilename(argv[3]);

		std::string subvolume_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+name;

		return remove_subvolume(subvolume_folder)?0:1;
	}
	else if(cmd=="test")
	{
		std::string clientdir=backupfolder+os_file_sepn()+"testA54hj5luZtlorr494";

		bool create_dir_rc=os_create_dir(clientdir);
		if(!create_dir_rc)
		{
			remove_subvolume(clientdir+os_file_sepn()+"A");
			remove_subvolume(clientdir+os_file_sepn()+"B");
			os_remove_dir(clientdir);
		}
		create_dir_rc = create_dir_rc || os_create_dir(clientdir);
		if(create_dir_rc)
		{
			if(!create_subvolume(clientdir+os_file_sepn()+"A") )
			{
				std::cout << "TEST FAILED: Creating test subvolume failed" << std::endl;
				os_remove_dir(clientdir);
				return 1;
			}

			bool suc=true;

			if(!create_snapshot(clientdir+os_file_sepn()+"A", clientdir+os_file_sepn()+"B") )
			{
				std::cout << "TEST FAILED: Creating test snapshot failed" << std::endl;
				suc=false;
			}

			if(suc)
			{
				writestring("test", clientdir+os_file_sepn()+"A"+os_file_sepn()+"test");

				if(!os_create_hardlink(clientdir+os_file_sepn()+"B"+os_file_sepn()+"test", clientdir+os_file_sepn()+"A"+os_file_sepn()+"test", true, NULL))
				{
					std::cout << "TEST FAILED: Creating cross sub-volume reflink failed. Need Linux kernel >= 3.6." << std::endl;
					suc=false;
				}
				else
				{
					if(getFile(clientdir+os_file_sepn()+"B"+os_file_sepn()+"test")!="test")
					{
						std::cout << "TEST FAILED: Cannot read reflinked file" << std::endl;
						suc=false;
					}
				}
			}

			if(!remove_subvolume(clientdir+os_file_sepn()+"A") )
			{
				std::cout << "TEST FAILED: Removing subvolume A failed" << std::endl;
				suc=false;
			}

			if(!remove_subvolume(clientdir+os_file_sepn()+"B") )
			{
				std::cout << "TEST FAILED: Removing subvolume B failed" << std::endl;
				suc=false;
			}

			if(!os_remove_dir(clientdir))
			{
				std::cout << "TEST FAILED: Removing test clientdir failed" << std::endl;
				return 1;
			}

			if(!suc)
			{
				return 1;
			}
		}
		else
		{
			std::cout << "TEST FAILED: Creating test clientdir \"" << clientdir << "\" failed" << std::endl;
			return 1;
		}
		std::cout << "TEST OK" << std::endl;
		return 0;
	}
	else if(cmd=="issubvolume")
	{
		if(argc<4)
		{
			std::cout << "Not enough parameters for issubvolume" << std::endl;
			return 1;
		}

		std::string clientname=handleFilename(argv[2]);
		std::string name=handleFilename(argv[3]);

		std::string subvolume_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+name;

		return is_subvolume(subvolume_folder)?0:1;
	}
	else
	{
		std::cout << "Command not found" << std::endl;
		return 1;
	}
}

<|endoftext|>


<commit_before><commit_msg>bUseTarget is never read<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tplpitem.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 18:34:36 $
 *
 *  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
 *
 ************************************************************************/

// INCLUDE ---------------------------------------------------------------

#ifndef GCC
#pragma hdrstop
#endif

#include "tplpitem.hxx"

#ifndef _COM_SUN_STAR_FRAME_STATUS_TEMPLATE_HPP_
#include <com/sun/star/frame/status/Template.hpp>
#endif

// STATIC DATA -----------------------------------------------------------

TYPEINIT1_AUTOFACTORY(SfxTemplateItem, SfxFlagItem);

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

SfxTemplateItem::SfxTemplateItem() :
    SfxFlagItem()
{
}

SfxTemplateItem::SfxTemplateItem
(
    USHORT nWhich,          // Slot-ID
    const String& rStyle,   // Name des aktuellen Styles
    USHORT nValue           // Flags f"ur das Filtern bei automatischer Anzeige
) :

    SfxFlagItem( nWhich, nValue ),

    aStyle( rStyle )

{
}

//-------------------------------------------------------------------------

// copy ctor
SfxTemplateItem::SfxTemplateItem( const SfxTemplateItem& rCopy ) :

    SfxFlagItem( rCopy ),

    aStyle( rCopy.aStyle )
{
}

//-------------------------------------------------------------------------

// op ==

int SfxTemplateItem::operator==( const SfxPoolItem& rCmp ) const
{
    return ( SfxFlagItem::operator==( rCmp ) &&
             aStyle == ( (const SfxTemplateItem&)rCmp ).aStyle );
}

//-------------------------------------------------------------------------

SfxPoolItem* SfxTemplateItem::Clone( SfxItemPool *) const
{
    return new SfxTemplateItem(*this);
}

//-------------------------------------------------------------------------
sal_Bool SfxTemplateItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const
{
    ::com::sun::star::frame::status::Template aTemplate;

    aTemplate.Value = GetValue();
    aTemplate.StyleName = aStyle;
    rVal <<= aTemplate;

    return sal_True;
}

//-------------------------------------------------------------------------
sal_Bool SfxTemplateItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId )
{
    ::com::sun::star::frame::status::Template aTemplate;

    if ( rVal >>= aTemplate )
    {
        SetValue( aTemplate.Value );
        aStyle = aTemplate.StyleName;
        return sal_True;
    }

    return sal_False;
}

//-------------------------------------------------------------------------

BYTE SfxTemplateItem::GetFlagCount() const
{
    return sizeof(USHORT) * 8;
}

<commit_msg>INTEGRATION: CWS warnings01 (1.7.64); FILE MERGED 2005/11/28 16:16:12 cd 1.7.64.1: #i55991# Remove warnings<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tplpitem.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 22:25:26 $
 *
 *  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
 *
 ************************************************************************/

// INCLUDE ---------------------------------------------------------------

#ifndef GCC
#pragma hdrstop
#endif

#include "tplpitem.hxx"

#ifndef _COM_SUN_STAR_FRAME_STATUS_TEMPLATE_HPP_
#include <com/sun/star/frame/status/Template.hpp>
#endif

// STATIC DATA -----------------------------------------------------------

TYPEINIT1_AUTOFACTORY(SfxTemplateItem, SfxFlagItem);

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

SfxTemplateItem::SfxTemplateItem() :
    SfxFlagItem()
{
}

SfxTemplateItem::SfxTemplateItem
(
    USHORT nWhichId,      // Slot-ID
    const String& rStyle, // Name des aktuellen Styles
    USHORT nValue         // Flags f"ur das Filtern bei automatischer Anzeige
) : SfxFlagItem( nWhichId, nValue ),
    aStyle( rStyle )
{
}

//-------------------------------------------------------------------------

// copy ctor
SfxTemplateItem::SfxTemplateItem( const SfxTemplateItem& rCopy ) :

    SfxFlagItem( rCopy ),

    aStyle( rCopy.aStyle )
{
}

//-------------------------------------------------------------------------

// op ==

int SfxTemplateItem::operator==( const SfxPoolItem& rCmp ) const
{
    return ( SfxFlagItem::operator==( rCmp ) &&
             aStyle == ( (const SfxTemplateItem&)rCmp ).aStyle );
}

//-------------------------------------------------------------------------

SfxPoolItem* SfxTemplateItem::Clone( SfxItemPool *) const
{
    return new SfxTemplateItem(*this);
}

//-------------------------------------------------------------------------
sal_Bool SfxTemplateItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE /*nMemberId*/ ) const
{
    ::com::sun::star::frame::status::Template aTemplate;

    aTemplate.Value = GetValue();
    aTemplate.StyleName = aStyle;
    rVal <<= aTemplate;

    return sal_True;
}

//-------------------------------------------------------------------------
sal_Bool SfxTemplateItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE /*nMemberId*/ )
{
    ::com::sun::star::frame::status::Template aTemplate;

    if ( rVal >>= aTemplate )
    {
        SetValue( aTemplate.Value );
        aStyle = aTemplate.StyleName;
        return sal_True;
    }

    return sal_False;
}

//-------------------------------------------------------------------------

BYTE SfxTemplateItem::GetFlagCount() const
{
    return sizeof(USHORT) * 8;
}

<|endoftext|>


<commit_before><commit_msg>Open remote templates when double clicking in the thumbnail.<commit_after><|endoftext|>


<commit_before>#include "RC.h"

#define ENDPOINT_BUFFER_SIZE 50

//#define DEBUG(s) Serial.print(s)
//#define DEBUGLN(s) Serial.println(s)
#define DEBUG(s)
#define DEBUGLN(s)

APIClient::APIClient(Client& c, String publicKey, String privateKey) : client(c) {
  this->publicKey = publicKey;
  this->privateKey = privateKey;
}

APIClient::~APIClient() {

}

boolean APIClient::user(int id, User& user) {
  char endpoint[ENDPOINT_BUFFER_SIZE];
  sprintf(endpoint, "users/%u/", id);

  if(!get(endpoint)) {
    return false;
  }

  if(!readHeaders()) {
    client.stop();
    return false;
  }

  while(client.connected() || client.available()) {
    while(client.available()) {
      String buffer = client.readStringUntil(',');

     if(readKey(buffer, "\"id\"", user.id)) {
        continue;
      }
      if(readKey(buffer, "\"username\"", user.username)) {
        continue;
      }
      if(readKey(buffer, "\"first_name\"", user.first_name)) {
        continue;
      }
      if(readKey(buffer, "\"last_name\"", user.last_name)) {
        continue;
      }
      if(readKey(buffer, "\"magnetic\"", user.magnetic)) {
        continue;
      }
      if(readKey(buffer, "\"rfid\"", user.rfid)) {
        continue;
      }
      if(readKey(buffer, "\"balance\"", user.balance)) {
        continue;
      }
    }
  }

  client.stop();

  return true;
}

boolean APIClient::channel(int id, Channel& channel) {
  DEBUGLN("Called channel");

  char endpoint[ENDPOINT_BUFFER_SIZE];
  sprintf(endpoint, "channels/%u/?exclude=description,created", id);

  DEBUGLN(endpoint);

  if(!get(endpoint)) {
    return false;
  }

  DEBUGLN("Get good");

  if(!readHeaders() || responseCode != 200) {
    client.stop();
    return false;
  }

  DEBUGLN("Headers and responseCode okay");

  while(client.connected() || client.available()) {
    while(client.available()) {
      String buffer = client.readStringUntil(',');

     if(readKey(buffer, "\"id\"", channel.id)) {
       DEBUGLN("FOUND ID");
       DEBUGLN(channel.id);
        continue;
      }
      if(readKey(buffer, "\"name\"", channel.name)) {
        DEBUGLN("FOUND NAME");
        DEBUGLN(channel.name);
        continue;
      }
      if(readKey(buffer, "\"value\"", channel.value)) {
        //while(client.available()) {
        //  client.read();
        //}

        DEBUGLN("FOUND VALUE");
        DEBUGLN(channel.value);

        continue;
      }
      if(readKey(buffer, "\"updated\"", channel.updated)) {
        DEBUGLN("FOUND UPDATED");
        DEBUGLN(channel.updated);
        continue;
      }
    }
  }

  DEBUGLN("Stopping client");

  client.stop();

  return true;
}

boolean APIClient::magnetic(String magneticID, String meta, UserLookup& userLookup) {
  String body = "{\"magnetic\":\"";
  body += magneticID;
  body += "\",\"meta\":\"";
  body += meta;
  body += "\"}";

  DEBUGLN(body);

  if(!post("magnetic/", body)) {
    return false;
  }

  if(!readHeaders() || responseCode != 200) {
    client.stop();
    return false;
  }

  while(client.connected() || client.available()) {
    while(client.available()) {
      String buffer = client.readStringUntil(',');

      DEBUGLN(buffer);

      if(readKey(buffer, "\"found\"", userLookup.found)) {
        DEBUGLN("FOUND found");
        continue;
      }
      if(readKey(buffer, "\"user\"", userLookup.user_id)) {
        DEBUGLN("FOUND user");
        continue;
      }
      if(readKey(buffer, "\"api_request\"", userLookup.api_request_id)) {
        DEBUGLN("FOUND api_request");
        continue;
      }
    }
  }

  client.stop();

  return true;
}

boolean APIClient::rfid(String rfid, String meta, UserLookup& userLookup) {
  String body = "{\"rfid\":\"";
  body += rfid;
  body += "\",\"meta\":\"";
  body += meta;
  body += "\"}";

  DEBUG("rfid body: ");
  DEBUGLN(body);

  if(!post("rfid/", body)) {
    return false;
  }

  if(!readHeaders() || responseCode != 200) {
    DEBUG("Bad response code: ");
    DEBUGLN(responseCode);
    client.stop();

    return false;
  }

  while(client.connected() || client.available()) {
    while(client.available()) {
      String buffer = client.readStringUntil(',');

      DEBUGLN(buffer);

      if(readKey(buffer, "\"found\"", userLookup.found)) {
        DEBUGLN("FOUND found");
        continue;
      }
      if(readKey(buffer, "\"user\"", userLookup.user_id)) {
        DEBUGLN("FOUND user");
        continue;
      }
      if(readKey(buffer, "\"api_request\"", userLookup.api_request_id)) {
        DEBUGLN("FOUND api_request");
        continue;
      }
    }
  }

  client.stop();

  return true;
}

boolean APIClient::userRFID(int id, String rfid, String meta, int& apiRequestID) {
  char endpoint[ENDPOINT_BUFFER_SIZE];
  sprintf(endpoint, "users/%u/rfid/", id);

  String body = "{\"rfid\":\"";
  body += rfid;
  body += "\",\"meta\":\"";
  body += meta;
  body += "\"}";

  if(!post(endpoint, body)) {
    return false;
  }

  if(!readHeaders() || responseCode != 200) {
    client.stop();
    return false;
  }

  while(client.connected() || client.available()) {
    while(client.available()) {
      String buffer = client.readStringUntil(',');

      if(readKey(buffer, "\"api_request\"", apiRequestID)) {
        DEBUGLN("FOUND api_request");
        continue;
      }
    }
  }

  client.stop();

  return true;
}

boolean APIClient::channelWriteValue(int id, String value) {
  char endpoint[ENDPOINT_BUFFER_SIZE];
  sprintf(endpoint, "channels/%u/", id);

  String message = "{\"value\": \"" + value + "\"}";

  if(!put(endpoint, message)) {
    return false;
  }

  if(!readHeaders() || responseCode != 200) {
    client.stop();
    return false;
  }

  while(client.connected() || client.available()) {
    while(client.available()) {
      // Need to clear out buffer
      client.read();
    }
  }

  client.stop();

  return true;
}

boolean APIClient::datetime(String form, String& datetime){
  DEBUGLN("Called datetime");

  // url encode query parameter
  form.replace(" ", "%20");

  char temp[form.length() + 2];
  form.toCharArray(temp, form.length() + 1);

  char endpoint[ENDPOINT_BUFFER_SIZE];
  sprintf(endpoint, "datetime/?form=%s", temp);

  DEBUGLN(endpoint);

  if(!get(endpoint)) {
    return false;
  }

  DEBUGLN("Get good");

  if(!readHeaders() || responseCode != 200) {
    client.stop();
    return false;
  }

  DEBUGLN("Headers and responseCode okay");

  while(client.connected() || client.available()) {
    while(client.available()) {
      String buffer = client.readStringUntil('}');

      if(readKey(buffer, "\"datetime\"", datetime)) {
        DEBUGLN("FOUND datetime");
        continue;
      }
    }
  }

  DEBUGLN("Stopping client");

  client.stop();

  return true;
}

int APIClient::lastResponseCode() {
  return responseCode;
}

// TODO: make inline

boolean APIClient::get(char* endpoint) {
  return request(endpoint, "", false);
}

boolean APIClient::post(char* endpoint, String body) {
  return request(endpoint, body, false);
}

boolean APIClient::put(char* endpoint, String body) {
  return request(endpoint, body, true);
}

boolean APIClient::request(char* endpoint, String buffer, boolean put) {
  DEBUGLN("Before connect");

  boolean c = client.connect("www.roboticsclub.org", 80);

  DEBUG("Connected: ");
  DEBUGLN(c);

  if(!c) {
    return false;
  }

  if(buffer.length()) {
    if(put) {
      client.print(F("PATCH"));
    } else {
      client.print(F("POST"));
    }
  } else {
    client.print(F("GET"));
  }

  client.print(F(" /api/"));
  client.print(endpoint);
  client.println(F(" HTTP/1.1"));

  client.println(F("Host: roboticsclub.org"));

  client.print(F("PUBLIC_KEY: "));
  client.println(publicKey);

  client.print(F("PRIVATE_KEY: "));
  client.println(privateKey);

  client.print(F("API_CLIENT: "));
  client.println(F("ArduinoRC 1.0"));

  client.println(F("Accept: application/json"));

  client.println(F("Connection: close"));

  if(buffer.length()) {
    client.println(F("Content-Type: application/json"));

    client.print(F("Content-Length: "));
    client.println(buffer.length());
  }

  client.println();

  if(buffer.length()) {
    client.println(buffer);
  }

  DEBUGLN("End of request");

  return true;
}

boolean APIClient::readHeaders() {
  // Seen status code
  boolean seen_code = false;

  //DEBUG("Client connected: ");
  //DEBUGLN(client.connected());

  //DEBUG("Client available: ");
  //DEBUGLN(client.available());

  while(client.connected() || client.available()) {
    while(client.available()) {
      String b = client.readStringUntil('\n');

      //DEBUG("readHeaders buffer: ");
      //DEBUGLN(b);

      if(!seen_code) {
        responseCode = b.substring(b.indexOf(' '), b.lastIndexOf(' ')).toInt();
        seen_code = true;
      }

      // If not just a newline, not
      // the response expected and should
      // error after done reading
      if(b.length() == 1) {
        return true;
      }
    }
  }

  return false;
}

boolean APIClient::readKey(String buffer, char* key, String& value) {
  int index = buffer.indexOf(key);

  if(index < 0) {
    return false;
  } else {
    // +1 ':'
    value = buffer.substring(index + strlen(key) + 1);

    value.replace("\"", "");

    //TODO: uncomment this
    //value.replace("}", "");

    return true;
  }
}

boolean APIClient::readKey(String buffer, char* key, int& value) {
  String v;
  boolean r = readKey(buffer, key, v);

  if(!r) {
    return false;
  }

  value = v.toInt();

  return true;
}

boolean APIClient::readKey(String buffer, char* key, double& value) {
  String v;
  boolean r = readKey(buffer, key, v);

  if(!r) {
    return false;
  }

  char charBuffer[v.length()+1];
  v.toCharArray(charBuffer, v.length()+1);

  value = atof(charBuffer);

  return true;
}

bool contains(String s, String search)
{
  int max = s.length() - search.length(); // the searchstring has to fit in the other one

  for (int i=0; i<= max; i++)
  {
    if (s.substring(i, i + search.length()) == search) {
      return true;
    }
  }

  return false;  //or -1
}

boolean APIClient::readKey(String buffer, char* key, boolean& value) {
  String v;
  boolean r = readKey(buffer, key, v);

  if(!r) {
    return false;
  }

  //value = (v == "true") ? true : false;
  value = contains(v, "true");

  return true;
}

<commit_msg>Added  '-' version of headers.<commit_after>#include "RC.h"

#define ENDPOINT_BUFFER_SIZE 50

//#define DEBUG(s) Serial.print(s)
//#define DEBUGLN(s) Serial.println(s)
#define DEBUG(s)
#define DEBUGLN(s)

APIClient::APIClient(Client& c, String publicKey, String privateKey) : client(c) {
  this->publicKey = publicKey;
  this->privateKey = privateKey;
}

APIClient::~APIClient() {

}

boolean APIClient::user(int id, User& user) {
  char endpoint[ENDPOINT_BUFFER_SIZE];
  sprintf(endpoint, "users/%u/", id);

  if(!get(endpoint)) {
    return false;
  }

  if(!readHeaders()) {
    client.stop();
    return false;
  }

  while(client.connected() || client.available()) {
    while(client.available()) {
      String buffer = client.readStringUntil(',');

     if(readKey(buffer, "\"id\"", user.id)) {
        continue;
      }
      if(readKey(buffer, "\"username\"", user.username)) {
        continue;
      }
      if(readKey(buffer, "\"first_name\"", user.first_name)) {
        continue;
      }
      if(readKey(buffer, "\"last_name\"", user.last_name)) {
        continue;
      }
      if(readKey(buffer, "\"magnetic\"", user.magnetic)) {
        continue;
      }
      if(readKey(buffer, "\"rfid\"", user.rfid)) {
        continue;
      }
      if(readKey(buffer, "\"balance\"", user.balance)) {
        continue;
      }
    }
  }

  client.stop();

  return true;
}

boolean APIClient::channel(int id, Channel& channel) {
  DEBUGLN("Called channel");

  char endpoint[ENDPOINT_BUFFER_SIZE];
  sprintf(endpoint, "channels/%u/?exclude=description,created", id);

  DEBUGLN(endpoint);

  if(!get(endpoint)) {
    return false;
  }

  DEBUGLN("Get good");

  if(!readHeaders() || responseCode != 200) {
    client.stop();
    return false;
  }

  DEBUGLN("Headers and responseCode okay");

  while(client.connected() || client.available()) {
    while(client.available()) {
      String buffer = client.readStringUntil(',');

     if(readKey(buffer, "\"id\"", channel.id)) {
       DEBUGLN("FOUND ID");
       DEBUGLN(channel.id);
        continue;
      }
      if(readKey(buffer, "\"name\"", channel.name)) {
        DEBUGLN("FOUND NAME");
        DEBUGLN(channel.name);
        continue;
      }
      if(readKey(buffer, "\"value\"", channel.value)) {
        //while(client.available()) {
        //  client.read();
        //}

        DEBUGLN("FOUND VALUE");
        DEBUGLN(channel.value);

        continue;
      }
      if(readKey(buffer, "\"updated\"", channel.updated)) {
        DEBUGLN("FOUND UPDATED");
        DEBUGLN(channel.updated);
        continue;
      }
    }
  }

  DEBUGLN("Stopping client");

  client.stop();

  return true;
}

boolean APIClient::magnetic(String magneticID, String meta, UserLookup& userLookup) {
  String body = "{\"magnetic\":\"";
  body += magneticID;
  body += "\",\"meta\":\"";
  body += meta;
  body += "\"}";

  DEBUGLN(body);

  if(!post("magnetic/", body)) {
    return false;
  }

  if(!readHeaders() || responseCode != 200) {
    client.stop();
    return false;
  }

  while(client.connected() || client.available()) {
    while(client.available()) {
      String buffer = client.readStringUntil(',');

      DEBUGLN(buffer);

      if(readKey(buffer, "\"found\"", userLookup.found)) {
        DEBUGLN("FOUND found");
        continue;
      }
      if(readKey(buffer, "\"user\"", userLookup.user_id)) {
        DEBUGLN("FOUND user");
        continue;
      }
      if(readKey(buffer, "\"api_request\"", userLookup.api_request_id)) {
        DEBUGLN("FOUND api_request");
        continue;
      }
    }
  }

  client.stop();

  return true;
}

boolean APIClient::rfid(String rfid, String meta, UserLookup& userLookup) {
  String body = "{\"rfid\":\"";
  body += rfid;
  body += "\",\"meta\":\"";
  body += meta;
  body += "\"}";

  DEBUG("rfid body: ");
  DEBUGLN(body);

  if(!post("rfid/", body)) {
    return false;
  }

  if(!readHeaders() || responseCode != 200) {
    DEBUG("Bad response code: ");
    DEBUGLN(responseCode);
    client.stop();

    return false;
  }

  while(client.connected() || client.available()) {
    while(client.available()) {
      String buffer = client.readStringUntil(',');

      DEBUGLN(buffer);

      if(readKey(buffer, "\"found\"", userLookup.found)) {
        DEBUGLN("FOUND found");
        continue;
      }
      if(readKey(buffer, "\"user\"", userLookup.user_id)) {
        DEBUGLN("FOUND user");
        continue;
      }
      if(readKey(buffer, "\"api_request\"", userLookup.api_request_id)) {
        DEBUGLN("FOUND api_request");
        continue;
      }
    }
  }

  client.stop();

  return true;
}

boolean APIClient::userRFID(int id, String rfid, String meta, int& apiRequestID) {
  char endpoint[ENDPOINT_BUFFER_SIZE];
  sprintf(endpoint, "users/%u/rfid/", id);

  String body = "{\"rfid\":\"";
  body += rfid;
  body += "\",\"meta\":\"";
  body += meta;
  body += "\"}";

  if(!post(endpoint, body)) {
    return false;
  }

  if(!readHeaders() || responseCode != 200) {
    client.stop();
    return false;
  }

  while(client.connected() || client.available()) {
    while(client.available()) {
      String buffer = client.readStringUntil(',');

      if(readKey(buffer, "\"api_request\"", apiRequestID)) {
        DEBUGLN("FOUND api_request");
        continue;
      }
    }
  }

  client.stop();

  return true;
}

boolean APIClient::channelWriteValue(int id, String value) {
  char endpoint[ENDPOINT_BUFFER_SIZE];
  sprintf(endpoint, "channels/%u/", id);

  String message = "{\"value\": \"" + value + "\"}";

  if(!put(endpoint, message)) {
    return false;
  }

  if(!readHeaders() || responseCode != 200) {
    client.stop();
    return false;
  }

  while(client.connected() || client.available()) {
    while(client.available()) {
      // Need to clear out buffer
      client.read();
    }
  }

  client.stop();

  return true;
}

boolean APIClient::datetime(String form, String& datetime){
  DEBUGLN("Called datetime");

  // url encode query parameter
  form.replace(" ", "%20");

  char temp[form.length() + 2];
  form.toCharArray(temp, form.length() + 1);

  char endpoint[ENDPOINT_BUFFER_SIZE];
  sprintf(endpoint, "datetime/?form=%s", temp);

  DEBUGLN(endpoint);

  if(!get(endpoint)) {
    return false;
  }

  DEBUGLN("Get good");

  if(!readHeaders() || responseCode != 200) {
    client.stop();
    return false;
  }

  DEBUGLN("Headers and responseCode okay");

  while(client.connected() || client.available()) {
    while(client.available()) {
      String buffer = client.readStringUntil('}');

      if(readKey(buffer, "\"datetime\"", datetime)) {
        DEBUGLN("FOUND datetime");
        continue;
      }
    }
  }

  DEBUGLN("Stopping client");

  client.stop();

  return true;
}

int APIClient::lastResponseCode() {
  return responseCode;
}

// TODO: make inline

boolean APIClient::get(char* endpoint) {
  return request(endpoint, "", false);
}

boolean APIClient::post(char* endpoint, String body) {
  return request(endpoint, body, false);
}

boolean APIClient::put(char* endpoint, String body) {
  return request(endpoint, body, true);
}

boolean APIClient::request(char* endpoint, String buffer, boolean put) {
  DEBUGLN("Before connect");

  boolean c = client.connect("www.roboticsclub.org", 80);

  DEBUG("Connected: ");
  DEBUGLN(c);

  if(!c) {
    return false;
  }

  if(buffer.length()) {
    if(put) {
      client.print(F("PATCH"));
    } else {
      client.print(F("POST"));
    }
  } else {
    client.print(F("GET"));
  }

  client.print(F(" /api/"));
  client.print(endpoint);
  client.println(F(" HTTP/1.1"));

  client.println(F("Host: roboticsclub.org"));

  client.print(F("PUBLIC_KEY: "));
  client.println(publicKey);

  client.print(F("PRIVATE_KEY: "));
  client.println(privateKey);

  client.print(F("API_CLIENT: "));
  client.println(F("ArduinoRC 1.0"));

  client.print(F("PUBLIC-KEY: "));
  client.println(publicKey);

  client.print(F("PRIVATE-KEY: "));
  client.println(privateKey);

  client.print(F("API-CLIENT: "));
  client.println(F("ArduinoRC 1.0"));

  client.println(F("Accept: application/json"));

  client.println(F("Connection: close"));

  if(buffer.length()) {
    client.println(F("Content-Type: application/json"));

    client.print(F("Content-Length: "));
    client.println(buffer.length());
  }

  client.println();

  if(buffer.length()) {
    client.println(buffer);
  }

  DEBUGLN("End of request");

  return true;
}

boolean APIClient::readHeaders() {
  // Seen status code
  boolean seen_code = false;

  //DEBUG("Client connected: ");
  //DEBUGLN(client.connected());

  //DEBUG("Client available: ");
  //DEBUGLN(client.available());

  while(client.connected() || client.available()) {
    while(client.available()) {
      String b = client.readStringUntil('\n');

      //DEBUG("readHeaders buffer: ");
      //DEBUGLN(b);

      if(!seen_code) {
        responseCode = b.substring(b.indexOf(' '), b.lastIndexOf(' ')).toInt();
        seen_code = true;
      }

      // If not just a newline, not
      // the response expected and should
      // error after done reading
      if(b.length() == 1) {
        return true;
      }
    }
  }

  return false;
}

boolean APIClient::readKey(String buffer, char* key, String& value) {
  int index = buffer.indexOf(key);

  if(index < 0) {
    return false;
  } else {
    // +1 ':'
    value = buffer.substring(index + strlen(key) + 1);

    value.replace("\"", "");

    //TODO: uncomment this
    //value.replace("}", "");

    return true;
  }
}

boolean APIClient::readKey(String buffer, char* key, int& value) {
  String v;
  boolean r = readKey(buffer, key, v);

  if(!r) {
    return false;
  }

  value = v.toInt();

  return true;
}

boolean APIClient::readKey(String buffer, char* key, double& value) {
  String v;
  boolean r = readKey(buffer, key, v);

  if(!r) {
    return false;
  }

  char charBuffer[v.length()+1];
  v.toCharArray(charBuffer, v.length()+1);

  value = atof(charBuffer);

  return true;
}

bool contains(String s, String search)
{
  int max = s.length() - search.length(); // the searchstring has to fit in the other one

  for (int i=0; i<= max; i++)
  {
    if (s.substring(i, i + search.length()) == search) {
      return true;
    }
  }

  return false;  //or -1
}

boolean APIClient::readKey(String buffer, char* key, boolean& value) {
  String v;
  boolean r = readKey(buffer, key, v);

  if(!r) {
    return false;
  }

  //value = (v == "true") ? true : false;
  value = contains(v, "true");

  return true;
}

<|endoftext|>


<commit_before>/*
 *
 * Copyright 2019 Asylo authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "asylo/identity/sgx/pce_util.h"

#include <openssl/base.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>

#include <cstdint>
#include <utility>
#include <vector>

#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/base/macros.h"
#include "absl/container/flat_hash_map.h"
#include "absl/strings/escaping.h"
#include "absl/types/optional.h"
#include "asylo/crypto/algorithms.pb.h"
#include "asylo/crypto/util/bssl_util.h"
#include "asylo/test/util/status_matchers.h"
#include "QuoteGeneration/psw/pce_wrapper/inc/sgx_pce.h"

namespace asylo {
namespace sgx {
namespace {

constexpr char kSecretMessage[] = "secret message";

// Hex-encoded RSA_F4 in big-endian format.
constexpr char kExponentBigEndianHex[] = "00010001";

// A hex-encoded RSA-3072 key modulus in big-endian format.
constexpr char kModulusBigEndianHex[] =
    "ecb62879f45c3880514bd2ee7bf1c2373c0de9184a641c250bfe59a3702e0a6632cc5e9e96"
    "ef16c04ca2844b1fa14ca0cdda7fa953fd69e5cb3f2368cab778fcf3e42db4c3b57f6b8a17"
    "c1fa58bc9fb99486668bdb4ddde725762c9f06d488463ece26aa5b57de5200785622d9b485"
    "95ef9523de581c50d98dc40e2605d907f057a66a13b6725b07b60f344cabf6255568a73267"
    "8d2fa9a8ed2c482e23aedf47d4ce2c77a73b622c2712176386cd6ecddff1dc200ede191918"
    "c63a74197d505f264349fdafbc44595e22b3cca2b428b5098c53e360cff8fd0d7053d3a868"
    "855c17dc9e7bf376b077ee4abcea326e46799d983962939a0bd51a6291cf494d8cb61f402f"
    "cfcec220f43ac2df50923e242f7ee0d2a91d2511cd5aa4cfa83d5e651d397f77806fb93ef3"
    "f9d04103097079a2b65d6041f339cf589bd8452dfc7683d7c1d5f7bfacc0039dd263f4a447"
    "af1909db1c1f6f0196218754dfeb2cd9b63f5268c6b51f39124765aed40af4e5dd78626aed"
    "43b51ae86688da36864bb063cab5";

using ::testing::Eq;
using ::testing::Optional;

// All encryption schemes supported by the PCE.
constexpr AsymmetricEncryptionScheme kSupportedEncryptionSchemes[] = {
    RSA3072_OAEP};

// The crypto suite corresponding to each scheme in kSupportedEncryptionSchemes.
constexpr uint8_t kTranslatedEncryptionSchemes[] = {PCE_ALG_RSA_OAEP_3072};

// All signature schemes supported by the PCE.
constexpr SignatureScheme kSupportedSignatureSchemes[] = {ECDSA_P256_SHA256};

// The signature scheme corresponding to each scheme in
// kSupportedSignatureSchemes.
constexpr uint8_t kTranslatedSignatureSchemes[] = {PCE_NIST_P256_ECDSA_SHA256};

class PceUtilTest : public ::testing::Test {
 public:
  void SetUp() override {
    supported_encryption_schemes_.reserve(
        ABSL_ARRAYSIZE(kSupportedEncryptionSchemes));
    for (int i = 0; i < ABSL_ARRAYSIZE(kSupportedEncryptionSchemes); ++i) {
      ASSERT_TRUE(supported_encryption_schemes_
                      .emplace(kSupportedEncryptionSchemes[i],
                               kTranslatedEncryptionSchemes[i])
                      .second);
    }
    for (int i = 0; i < AsymmetricEncryptionScheme_ARRAYSIZE; ++i) {
      if (AsymmetricEncryptionScheme_IsValid(i)) {
        AsymmetricEncryptionScheme scheme =
            static_cast<AsymmetricEncryptionScheme>(i);
        if (!supported_encryption_schemes_.contains(scheme)) {
          unsupported_encryption_schemes_.push_back(scheme);
        }
      }
    }

    supported_signature_schemes_.reserve(
        ABSL_ARRAYSIZE(kSupportedSignatureSchemes));
    for (int i = 0; i < ABSL_ARRAYSIZE(kSupportedSignatureSchemes); ++i) {
      ASSERT_TRUE(supported_signature_schemes_
                      .emplace(kSupportedSignatureSchemes[i],
                               kTranslatedSignatureSchemes[i])
                      .second);
    }
    for (int i = 0; i < SignatureScheme_ARRAYSIZE; ++i) {
      if (SignatureScheme_IsValid(i)) {
        SignatureScheme scheme = static_cast<SignatureScheme>(i);
        if (!supported_signature_schemes_.contains(scheme)) {
          unsupported_signature_schemes_.push_back(scheme);
        }
      }
    }

    plaintext_ =
        std::vector<uint8_t>(reinterpret_cast<const uint8_t *>(kSecretMessage),
                             reinterpret_cast<const uint8_t *>(kSecretMessage) +
                                 sizeof(kSecretMessage));
  }

  absl::flat_hash_map<AsymmetricEncryptionScheme, uint8_t>
      supported_encryption_schemes_;
  absl::flat_hash_map<SignatureScheme, uint8_t> supported_signature_schemes_;

  std::vector<AsymmetricEncryptionScheme> unsupported_encryption_schemes_;
  std::vector<SignatureScheme> unsupported_signature_schemes_;

  std::vector<uint8_t> plaintext_;
};

TEST_F(PceUtilTest, AsymmetricEncryptionSchemeToPceCryptoSuiteSupported) {
  for (const auto &pair : supported_encryption_schemes_) {
    EXPECT_THAT(AsymmetricEncryptionSchemeToPceCryptoSuite(pair.first),
                Optional(pair.second));
  }
}

TEST_F(PceUtilTest, AsymmetricEncryptionSchemeToPceCryptoSuiteUnsupported) {
  for (AsymmetricEncryptionScheme scheme : unsupported_encryption_schemes_) {
    EXPECT_THAT(AsymmetricEncryptionSchemeToPceCryptoSuite(scheme),
                Eq(absl::nullopt));
  }
}

TEST_F(PceUtilTest, SignatureSchemeToPceSignatureSchemeSupported) {
  for (const auto &pair : supported_signature_schemes_) {
    EXPECT_THAT(SignatureSchemeToPceSignatureScheme(pair.first),
                Optional(pair.second));
  }
}

TEST_F(PceUtilTest, SignatureSchemeToPceSignatureSchemeUnsupported) {
  for (SignatureScheme scheme : unsupported_signature_schemes_) {
    EXPECT_THAT(SignatureSchemeToPceSignatureScheme(scheme), Eq(absl::nullopt));
  }
}

TEST_F(PceUtilTest, ParseRsa3072PublicKeyInvalidSize) {
  std::vector<uint8_t> public_key(0);
  ASSERT_THAT(ParseRsa3072PublicKey(absl::MakeSpan(public_key)).status(),
              StatusIs(error::INVALID_ARGUMENT));
}

// Verify that an RSA public key serialized according to what is expected by the
// PCE can be parsed and restored to an RSA key, and that its exponent and
// modulus are as expected.
TEST_F(PceUtilTest, ParseRsa3072PublicKeySuccess) {
  std::string modulus = absl::HexStringToBytes(kModulusBigEndianHex);
  std::string exponent = absl::HexStringToBytes(kExponentBigEndianHex);

  std::vector<uint8_t> public_key;
  public_key.insert(public_key.end(), modulus.cbegin(), modulus.cend());
  public_key.insert(public_key.end(), exponent.cbegin(), exponent.cend());

  auto result = ParseRsa3072PublicKey(absl::MakeSpan(public_key));
  ASYLO_ASSERT_OK(result.status());

  bssl::UniquePtr<RSA> rsa = std::move(result).ValueOrDie();

  EXPECT_THAT(RSA_size(rsa.get()), modulus.size());

  const BIGNUM *n;
  const BIGNUM *e;

  // The private exponent, d, is not set for a public key.
  RSA_get0_key(rsa.get(), &n, &e, /*out_d=*/nullptr);

  // Compare against expected public exponent.
  EXPECT_EQ(BN_is_word(e, RSA_F4), 1);

  bssl::UniquePtr<BIGNUM> expected_n(BN_new());
  BN_bin2bn(reinterpret_cast<const uint8_t *>(modulus.data()), modulus.size(),
            expected_n.get());

  // Compare against expected modulus.
  EXPECT_EQ(BN_cmp(n, expected_n.get()), 0);
}

TEST_F(PceUtilTest, DISABLED_ParseRsa3072PublicKeyRestoreFromSerializedKey) {
  bssl::UniquePtr<RSA> rsa1(RSA_new());
  bssl::UniquePtr<BIGNUM> e(BN_new());

  ASSERT_EQ(BN_set_word(e.get(), RSA_F4), 1) << BsslLastErrorString();
  ASSERT_EQ(
      RSA_generate_key_ex(rsa1.get(), /*bits=*/3072, e.get(), /*cb=*/nullptr),
      1)
      << BsslLastErrorString();

  auto result1 = SerializeRsa3072PublicKey(rsa1.get());
  ASYLO_ASSERT_OK(result1);

  std::vector<uint8_t> serialized_key = std::move(result1).ValueOrDie();

  auto result2 = ParseRsa3072PublicKey(absl::MakeSpan(serialized_key));
  ASYLO_ASSERT_OK(result2);

  bssl::UniquePtr<RSA> rsa2(std::move(result2).ValueOrDie());

  // Verify that both keys have the same modulus size.
  EXPECT_THAT(RSA_size(rsa2.get()), Eq(RSA_size(rsa1.get())));

  // Verify that the restored key can decrypt a message encrypted by the
  // original key.
  std::vector<uint8_t> ciphertext(RSA_size(rsa1.get()));
  size_t out_len;
  ASSERT_EQ(
      RSA_encrypt(rsa1.get(), &out_len, ciphertext.data(), ciphertext.size(),
                  plaintext_.data(), plaintext_.size(), RSA_PKCS1_OAEP_PADDING),
      1)
      << BsslLastErrorString();
  ciphertext.resize(out_len);

  std::vector<uint8_t> decrypted(RSA_size(rsa2.get()));
  ASSERT_EQ(
      RSA_decrypt(rsa2.get(), &out_len, decrypted.data(), decrypted.size(),
                  ciphertext.data(), ciphertext.size(), RSA_PKCS1_OAEP_PADDING),
      1)
      << BsslLastErrorString();
  decrypted.resize(out_len);

  EXPECT_THAT(decrypted, Eq(plaintext_));
}

}  // namespace
}  // namespace sgx
}  // namespace asylo
<commit_msg>Fix bug in pce_util_test<commit_after>/*
 *
 * Copyright 2019 Asylo authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "asylo/identity/sgx/pce_util.h"

#include <openssl/base.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>

#include <cstdint>
#include <utility>
#include <vector>

#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/base/macros.h"
#include "absl/container/flat_hash_map.h"
#include "absl/strings/escaping.h"
#include "absl/types/optional.h"
#include "asylo/crypto/algorithms.pb.h"
#include "asylo/crypto/util/bssl_util.h"
#include "asylo/test/util/status_matchers.h"
#include "QuoteGeneration/psw/pce_wrapper/inc/sgx_pce.h"

namespace asylo {
namespace sgx {
namespace {

constexpr char kSecretMessage[] = "secret message";

// Hex-encoded RSA_F4 in big-endian format.
constexpr char kExponentBigEndianHex[] = "00010001";

// A hex-encoded RSA-3072 key modulus in big-endian format.
constexpr char kModulusBigEndianHex[] =
    "ecb62879f45c3880514bd2ee7bf1c2373c0de9184a641c250bfe59a3702e0a6632cc5e9e96"
    "ef16c04ca2844b1fa14ca0cdda7fa953fd69e5cb3f2368cab778fcf3e42db4c3b57f6b8a17"
    "c1fa58bc9fb99486668bdb4ddde725762c9f06d488463ece26aa5b57de5200785622d9b485"
    "95ef9523de581c50d98dc40e2605d907f057a66a13b6725b07b60f344cabf6255568a73267"
    "8d2fa9a8ed2c482e23aedf47d4ce2c77a73b622c2712176386cd6ecddff1dc200ede191918"
    "c63a74197d505f264349fdafbc44595e22b3cca2b428b5098c53e360cff8fd0d7053d3a868"
    "855c17dc9e7bf376b077ee4abcea326e46799d983962939a0bd51a6291cf494d8cb61f402f"
    "cfcec220f43ac2df50923e242f7ee0d2a91d2511cd5aa4cfa83d5e651d397f77806fb93ef3"
    "f9d04103097079a2b65d6041f339cf589bd8452dfc7683d7c1d5f7bfacc0039dd263f4a447"
    "af1909db1c1f6f0196218754dfeb2cd9b63f5268c6b51f39124765aed40af4e5dd78626aed"
    "43b51ae86688da36864bb063cab5";

using ::testing::Eq;
using ::testing::Optional;

// All encryption schemes supported by the PCE.
constexpr AsymmetricEncryptionScheme kSupportedEncryptionSchemes[] = {
    RSA3072_OAEP};

// The crypto suite corresponding to each scheme in kSupportedEncryptionSchemes.
constexpr uint8_t kTranslatedEncryptionSchemes[] = {PCE_ALG_RSA_OAEP_3072};

// All signature schemes supported by the PCE.
constexpr SignatureScheme kSupportedSignatureSchemes[] = {ECDSA_P256_SHA256};

// The signature scheme corresponding to each scheme in
// kSupportedSignatureSchemes.
constexpr uint8_t kTranslatedSignatureSchemes[] = {PCE_NIST_P256_ECDSA_SHA256};

class PceUtilTest : public ::testing::Test {
 public:
  void SetUp() override {
    supported_encryption_schemes_.reserve(
        ABSL_ARRAYSIZE(kSupportedEncryptionSchemes));
    for (int i = 0; i < ABSL_ARRAYSIZE(kSupportedEncryptionSchemes); ++i) {
      ASSERT_TRUE(supported_encryption_schemes_
                      .emplace(kSupportedEncryptionSchemes[i],
                               kTranslatedEncryptionSchemes[i])
                      .second);
    }
    for (int i = 0; i < AsymmetricEncryptionScheme_ARRAYSIZE; ++i) {
      if (AsymmetricEncryptionScheme_IsValid(i)) {
        AsymmetricEncryptionScheme scheme =
            static_cast<AsymmetricEncryptionScheme>(i);
        if (!supported_encryption_schemes_.contains(scheme)) {
          unsupported_encryption_schemes_.push_back(scheme);
        }
      }
    }

    supported_signature_schemes_.reserve(
        ABSL_ARRAYSIZE(kSupportedSignatureSchemes));
    for (int i = 0; i < ABSL_ARRAYSIZE(kSupportedSignatureSchemes); ++i) {
      ASSERT_TRUE(supported_signature_schemes_
                      .emplace(kSupportedSignatureSchemes[i],
                               kTranslatedSignatureSchemes[i])
                      .second);
    }
    for (int i = 0; i < SignatureScheme_ARRAYSIZE; ++i) {
      if (SignatureScheme_IsValid(i)) {
        SignatureScheme scheme = static_cast<SignatureScheme>(i);
        if (!supported_signature_schemes_.contains(scheme)) {
          unsupported_signature_schemes_.push_back(scheme);
        }
      }
    }

    plaintext_ =
        std::vector<uint8_t>(reinterpret_cast<const uint8_t *>(kSecretMessage),
                             reinterpret_cast<const uint8_t *>(kSecretMessage) +
                                 sizeof(kSecretMessage));
  }

  absl::flat_hash_map<AsymmetricEncryptionScheme, uint8_t>
      supported_encryption_schemes_;
  absl::flat_hash_map<SignatureScheme, uint8_t> supported_signature_schemes_;

  std::vector<AsymmetricEncryptionScheme> unsupported_encryption_schemes_;
  std::vector<SignatureScheme> unsupported_signature_schemes_;

  std::vector<uint8_t> plaintext_;
};

TEST_F(PceUtilTest, AsymmetricEncryptionSchemeToPceCryptoSuiteSupported) {
  for (const auto &pair : supported_encryption_schemes_) {
    EXPECT_THAT(AsymmetricEncryptionSchemeToPceCryptoSuite(pair.first),
                Optional(pair.second));
  }
}

TEST_F(PceUtilTest, AsymmetricEncryptionSchemeToPceCryptoSuiteUnsupported) {
  for (AsymmetricEncryptionScheme scheme : unsupported_encryption_schemes_) {
    EXPECT_THAT(AsymmetricEncryptionSchemeToPceCryptoSuite(scheme),
                Eq(absl::nullopt));
  }
}

TEST_F(PceUtilTest, SignatureSchemeToPceSignatureSchemeSupported) {
  for (const auto &pair : supported_signature_schemes_) {
    EXPECT_THAT(SignatureSchemeToPceSignatureScheme(pair.first),
                Optional(pair.second));
  }
}

TEST_F(PceUtilTest, SignatureSchemeToPceSignatureSchemeUnsupported) {
  for (SignatureScheme scheme : unsupported_signature_schemes_) {
    EXPECT_THAT(SignatureSchemeToPceSignatureScheme(scheme), Eq(absl::nullopt));
  }
}

TEST_F(PceUtilTest, ParseRsa3072PublicKeyInvalidSize) {
  std::vector<uint8_t> public_key(0);
  ASSERT_THAT(ParseRsa3072PublicKey(absl::MakeSpan(public_key)).status(),
              StatusIs(error::INVALID_ARGUMENT));
}

// Verify that an RSA public key serialized according to what is expected by the
// PCE can be parsed and restored to an RSA key, and that its exponent and
// modulus are as expected.
TEST_F(PceUtilTest, ParseRsa3072PublicKeySuccess) {
  std::string modulus = absl::HexStringToBytes(kModulusBigEndianHex);
  std::string exponent = absl::HexStringToBytes(kExponentBigEndianHex);

  std::vector<uint8_t> public_key;
  public_key.insert(public_key.end(), modulus.cbegin(), modulus.cend());
  public_key.insert(public_key.end(), exponent.cbegin(), exponent.cend());

  auto result = ParseRsa3072PublicKey(absl::MakeSpan(public_key));
  ASYLO_ASSERT_OK(result.status());

  bssl::UniquePtr<RSA> rsa = std::move(result).ValueOrDie();

  EXPECT_THAT(RSA_size(rsa.get()), modulus.size());

  const BIGNUM *n;
  const BIGNUM *e;

  // The private exponent, d, is not set for a public key.
  RSA_get0_key(rsa.get(), &n, &e, /*out_d=*/nullptr);

  // Compare against expected public exponent.
  EXPECT_EQ(BN_is_word(e, RSA_F4), 1);

  bssl::UniquePtr<BIGNUM> expected_n(BN_new());
  BN_bin2bn(reinterpret_cast<const uint8_t *>(modulus.data()), modulus.size(),
            expected_n.get());

  // Compare against expected modulus.
  EXPECT_EQ(BN_cmp(n, expected_n.get()), 0);
}

TEST_F(PceUtilTest, DISABLED_ParseRsa3072PublicKeyRestoreFromSerializedKey) {
  bssl::UniquePtr<RSA> rsa1(RSA_new());
  bssl::UniquePtr<BIGNUM> e(BN_new());

  ASSERT_EQ(BN_set_word(e.get(), RSA_F4), 1) << BsslLastErrorString();
  ASSERT_EQ(
      RSA_generate_key_ex(rsa1.get(), /*bits=*/3072, e.get(), /*cb=*/nullptr),
      1)
      << BsslLastErrorString();

  auto result1 = SerializeRsa3072PublicKey(rsa1.get());
  ASYLO_ASSERT_OK(result1);

  std::vector<uint8_t> serialized_key = std::move(result1).ValueOrDie();

  auto result2 = ParseRsa3072PublicKey(absl::MakeSpan(serialized_key));
  ASYLO_ASSERT_OK(result2);

  bssl::UniquePtr<RSA> rsa2(std::move(result2).ValueOrDie());

  // Verify that both keys have the same modulus size.
  EXPECT_THAT(RSA_size(rsa2.get()), Eq(RSA_size(rsa1.get())));

  // Verify that the original key can decrypt a message encrypted by the
  // restored key.
  std::vector<uint8_t> ciphertext(RSA_size(rsa1.get()));
  size_t out_len;
  ASSERT_EQ(
      RSA_encrypt(rsa2.get(), &out_len, ciphertext.data(), ciphertext.size(),
                  plaintext_.data(), plaintext_.size(), RSA_PKCS1_OAEP_PADDING),
      1)
      << BsslLastErrorString();
  ciphertext.resize(out_len);

  std::vector<uint8_t> decrypted(RSA_size(rsa2.get()));
  ASSERT_EQ(
      RSA_decrypt(rsa1.get(), &out_len, decrypted.data(), decrypted.size(),
                  ciphertext.data(), ciphertext.size(), RSA_PKCS1_OAEP_PADDING),
      1)
      << BsslLastErrorString();
  decrypted.resize(out_len);

  EXPECT_THAT(decrypted, Eq(plaintext_));
}

}  // namespace
}  // namespace sgx
}  // namespace asylo
<|endoftext|>


<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include <string>
#include <utility>
#include <vector>

#include "atom/browser/api/atom_api_window.h"
#include "atom/browser/native_window.h"
#include "atom/browser/ui/certificate_trust.h"
#include "atom/browser/ui/file_dialog.h"
#include "atom/browser/ui/message_box.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "native_mate/dictionary.h"

#include "atom/common/node_includes.h"

namespace mate {

template<>
struct Converter<file_dialog::Filter> {
  static bool FromV8(v8::Isolate* isolate,
                     v8::Local<v8::Value> val,
                     file_dialog::Filter* out) {
    mate::Dictionary dict;
    if (!ConvertFromV8(isolate, val, &dict))
      return false;
    if (!dict.Get("name", &(out->first)))
      return false;
    if (!dict.Get("extensions", &(out->second)))
      return false;
    return true;
  }
};

template<>
struct Converter<file_dialog::DialogSettings> {
  static bool FromV8(v8::Isolate* isolate,
                     v8::Local<v8::Value> val,
                     file_dialog::DialogSettings* out) {
    mate::Dictionary dict;
    if (!ConvertFromV8(isolate, val, &dict))
      return false;
    dict.Get("window", &(out->parent_window));
    dict.Get("title", &(out->title));
    dict.Get("message", &(out->message));
    dict.Get("buttonLabel", &(out->button_label));
    dict.Get("nameFieldLabel", &(out->name_field_label));
    dict.Get("defaultPath", &(out->default_path));
    dict.Get("filters", &(out->filters));
    dict.Get("properties", &(out->properties));
    dict.Get("showsTagField", &(out->shows_tag_field));
    return true;
  }
};

}  // namespace mate

namespace {

void ShowMessageBox(int type,
                    const std::vector<std::string>& buttons,
                    int default_id,
                    int cancel_id,
                    int options,
                    const std::string& title,
                    const std::string& message,
                    const std::string& detail,
                    const std::string& checkbox_label,
                    bool checkbox_checked,
                    const gfx::ImageSkia& icon,
                    atom::NativeWindow* window,
                    mate::Arguments* args) {
  v8::Local<v8::Value> peek = args->PeekNext();
  atom::MessageBoxCallback callback;
  if (mate::Converter<atom::MessageBoxCallback>::FromV8(args->isolate(),
                                                        peek,
                                                        &callback)) {
    atom::ShowMessageBox(window, (atom::MessageBoxType)type, buttons,
                         default_id, cancel_id, options, title, message, detail,
                         checkbox_label, checkbox_checked, icon, callback);
  } else {
    int chosen = atom::ShowMessageBox(window, (atom::MessageBoxType)type,
                                      buttons, default_id, cancel_id,
                                      options, title, message, detail, icon);
    args->Return(chosen);
  }
}

void ShowOpenDialog(const file_dialog::DialogSettings& settings,
                    mate::Arguments* args) {
  v8::Local<v8::Value> peek = args->PeekNext();
  file_dialog::OpenDialogCallback callback;
  if (mate::Converter<file_dialog::OpenDialogCallback>::FromV8(args->isolate(),
                                                               peek,
                                                               &callback)) {
    file_dialog::ShowOpenDialog(settings, callback);
  } else {
    std::vector<base::FilePath> paths;
    if (file_dialog::ShowOpenDialog(settings, &paths))
      args->Return(paths);
  }
}

void ShowSaveDialog(const file_dialog::DialogSettings& settings,
                    mate::Arguments* args) {
  v8::Local<v8::Value> peek = args->PeekNext();
  file_dialog::SaveDialogCallback callback;
  if (mate::Converter<file_dialog::SaveDialogCallback>::FromV8(args->isolate(),
                                                               peek,
                                                               &callback)) {
    file_dialog::ShowSaveDialog(settings, callback);
  } else {
    base::FilePath path;
    if (file_dialog::ShowSaveDialog(settings, &path))
      args->Return(path);
  }
}

// #if defined(OS_MACOSX)
void ShowCertificateTrust(atom::NativeWindow* parent_window,
                               const scoped_refptr<net::X509Certificate>& cert,
                               std::string message,
                               const certificate_trust::ShowTrustCallback& callback,
                               mate::Arguments* args) {
  certificate_trust::ShowCertificateTrust(parent_window, cert, message, callback);
}
// #endif

void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
                v8::Local<v8::Context> context, void* priv) {
  mate::Dictionary dict(context->GetIsolate(), exports);
  dict.SetMethod("showMessageBox", &ShowMessageBox);
  dict.SetMethod("showErrorBox", &atom::ShowErrorBox);
  dict.SetMethod("showOpenDialog", &ShowOpenDialog);
  dict.SetMethod("showSaveDialog", &ShowSaveDialog);
// #if defined(OS_MACOSX)
  dict.SetMethod("showCertificateTrustDialog", &ShowCertificateTrust);
// #endif
}

}  // namespace

NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_dialog, Initialize)
<commit_msg>Fix indentation<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include <string>
#include <utility>
#include <vector>

#include "atom/browser/api/atom_api_window.h"
#include "atom/browser/native_window.h"
#include "atom/browser/ui/certificate_trust.h"
#include "atom/browser/ui/file_dialog.h"
#include "atom/browser/ui/message_box.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "native_mate/dictionary.h"

#include "atom/common/node_includes.h"

namespace mate {

template<>
struct Converter<file_dialog::Filter> {
  static bool FromV8(v8::Isolate* isolate,
                     v8::Local<v8::Value> val,
                     file_dialog::Filter* out) {
    mate::Dictionary dict;
    if (!ConvertFromV8(isolate, val, &dict))
      return false;
    if (!dict.Get("name", &(out->first)))
      return false;
    if (!dict.Get("extensions", &(out->second)))
      return false;
    return true;
  }
};

template<>
struct Converter<file_dialog::DialogSettings> {
  static bool FromV8(v8::Isolate* isolate,
                     v8::Local<v8::Value> val,
                     file_dialog::DialogSettings* out) {
    mate::Dictionary dict;
    if (!ConvertFromV8(isolate, val, &dict))
      return false;
    dict.Get("window", &(out->parent_window));
    dict.Get("title", &(out->title));
    dict.Get("message", &(out->message));
    dict.Get("buttonLabel", &(out->button_label));
    dict.Get("nameFieldLabel", &(out->name_field_label));
    dict.Get("defaultPath", &(out->default_path));
    dict.Get("filters", &(out->filters));
    dict.Get("properties", &(out->properties));
    dict.Get("showsTagField", &(out->shows_tag_field));
    return true;
  }
};

}  // namespace mate

namespace {

void ShowMessageBox(int type,
                    const std::vector<std::string>& buttons,
                    int default_id,
                    int cancel_id,
                    int options,
                    const std::string& title,
                    const std::string& message,
                    const std::string& detail,
                    const std::string& checkbox_label,
                    bool checkbox_checked,
                    const gfx::ImageSkia& icon,
                    atom::NativeWindow* window,
                    mate::Arguments* args) {
  v8::Local<v8::Value> peek = args->PeekNext();
  atom::MessageBoxCallback callback;
  if (mate::Converter<atom::MessageBoxCallback>::FromV8(args->isolate(),
                                                        peek,
                                                        &callback)) {
    atom::ShowMessageBox(window, (atom::MessageBoxType)type, buttons,
                         default_id, cancel_id, options, title, message, detail,
                         checkbox_label, checkbox_checked, icon, callback);
  } else {
    int chosen = atom::ShowMessageBox(window, (atom::MessageBoxType)type,
                                      buttons, default_id, cancel_id,
                                      options, title, message, detail, icon);
    args->Return(chosen);
  }
}

void ShowOpenDialog(const file_dialog::DialogSettings& settings,
                    mate::Arguments* args) {
  v8::Local<v8::Value> peek = args->PeekNext();
  file_dialog::OpenDialogCallback callback;
  if (mate::Converter<file_dialog::OpenDialogCallback>::FromV8(args->isolate(),
                                                               peek,
                                                               &callback)) {
    file_dialog::ShowOpenDialog(settings, callback);
  } else {
    std::vector<base::FilePath> paths;
    if (file_dialog::ShowOpenDialog(settings, &paths))
      args->Return(paths);
  }
}

void ShowSaveDialog(const file_dialog::DialogSettings& settings,
                    mate::Arguments* args) {
  v8::Local<v8::Value> peek = args->PeekNext();
  file_dialog::SaveDialogCallback callback;
  if (mate::Converter<file_dialog::SaveDialogCallback>::FromV8(args->isolate(),
                                                               peek,
                                                               &callback)) {
    file_dialog::ShowSaveDialog(settings, callback);
  } else {
    base::FilePath path;
    if (file_dialog::ShowSaveDialog(settings, &path))
      args->Return(path);
  }
}

// #if defined(OS_MACOSX)
void ShowCertificateTrust(atom::NativeWindow* parent_window,
                          const scoped_refptr<net::X509Certificate>& cert,
                          std::string message,
                          const certificate_trust::ShowTrustCallback& callback,
                          mate::Arguments* args) {
  certificate_trust::ShowCertificateTrust(parent_window, cert, message, callback);
}
// #endif

void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
                v8::Local<v8::Context> context, void* priv) {
  mate::Dictionary dict(context->GetIsolate(), exports);
  dict.SetMethod("showMessageBox", &ShowMessageBox);
  dict.SetMethod("showErrorBox", &atom::ShowErrorBox);
  dict.SetMethod("showOpenDialog", &ShowOpenDialog);
  dict.SetMethod("showSaveDialog", &ShowSaveDialog);
// #if defined(OS_MACOSX)
  dict.SetMethod("showCertificateTrustDialog", &ShowCertificateTrust);
// #endif
}

}  // namespace

NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_dialog, Initialize)
<|endoftext|>


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

#include "atom/common/api/object_life_monitor.h"

#include "atom/common/v8/native_type_conversions.h"
#include "v8/include/v8-profiler.h"

#include "atom/common/v8/node_common.h"

namespace atom {

namespace api {

namespace {

void CreateObjectWithName(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
  t->SetClassName(args[0]->ToString());
  args.GetReturnValue().Set(t->GetFunction()->NewInstance());
}

void GetHiddenValue(const v8::FunctionCallbackInfo<v8::Value>& args) {
  args.GetReturnValue().Set(
      args[0]->ToObject()->GetHiddenValue(args[1]->ToString()));
}

void SetHiddenValue(const v8::FunctionCallbackInfo<v8::Value>& args) {
  args[0]->ToObject()->SetHiddenValue(args[1]->ToString(), args[2]);
}

void GetObjectHash(const v8::FunctionCallbackInfo<v8::Value>& args) {
  args.GetReturnValue().Set(args[0]->ToObject()->GetIdentityHash());
}

void SetDestructor(const v8::FunctionCallbackInfo<v8::Value>& args) {
  ObjectLifeMonitor::BindTo(args[0]->ToObject(), args[1]);
}

void TakeHeapSnapshot(const v8::FunctionCallbackInfo<v8::Value>& args) {
  node::node_isolate->GetHeapProfiler()->TakeHeapSnapshot(
      v8::String::New("test"));
}

}  // namespace

void InitializeV8Util(v8::Handle<v8::Object> target) {
  NODE_SET_METHOD(target, "createObjectWithName", CreateObjectWithName);
  NODE_SET_METHOD(target, "getHiddenValue", GetHiddenValue);
  NODE_SET_METHOD(target, "setHiddenValue", SetHiddenValue);
  NODE_SET_METHOD(target, "getObjectHash", GetObjectHash);
  NODE_SET_METHOD(target, "setDestructor", SetDestructor);
  NODE_SET_METHOD(target, "takeHeapSnapshot", TakeHeapSnapshot);
}

}  // namespace api

}  // namespace atom

NODE_MODULE(atom_common_v8_util, atom::api::InitializeV8Util)
<commit_msg>Remove unneeded include.<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "atom/common/api/object_life_monitor.h"
#include "v8/include/v8-profiler.h"

#include "atom/common/v8/node_common.h"

namespace atom {

namespace api {

namespace {

void CreateObjectWithName(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
  t->SetClassName(args[0]->ToString());
  args.GetReturnValue().Set(t->GetFunction()->NewInstance());
}

void GetHiddenValue(const v8::FunctionCallbackInfo<v8::Value>& args) {
  args.GetReturnValue().Set(
      args[0]->ToObject()->GetHiddenValue(args[1]->ToString()));
}

void SetHiddenValue(const v8::FunctionCallbackInfo<v8::Value>& args) {
  args[0]->ToObject()->SetHiddenValue(args[1]->ToString(), args[2]);
}

void GetObjectHash(const v8::FunctionCallbackInfo<v8::Value>& args) {
  args.GetReturnValue().Set(args[0]->ToObject()->GetIdentityHash());
}

void SetDestructor(const v8::FunctionCallbackInfo<v8::Value>& args) {
  ObjectLifeMonitor::BindTo(args[0]->ToObject(), args[1]);
}

void TakeHeapSnapshot(const v8::FunctionCallbackInfo<v8::Value>& args) {
  node::node_isolate->GetHeapProfiler()->TakeHeapSnapshot(
      v8::String::New("test"));
}

}  // namespace

void InitializeV8Util(v8::Handle<v8::Object> target) {
  NODE_SET_METHOD(target, "createObjectWithName", CreateObjectWithName);
  NODE_SET_METHOD(target, "getHiddenValue", GetHiddenValue);
  NODE_SET_METHOD(target, "setHiddenValue", SetHiddenValue);
  NODE_SET_METHOD(target, "getObjectHash", GetObjectHash);
  NODE_SET_METHOD(target, "setDestructor", SetDestructor);
  NODE_SET_METHOD(target, "takeHeapSnapshot", TakeHeapSnapshot);
}

}  // namespace api

}  // namespace atom

NODE_MODULE(atom_common_v8_util, atom::api::InitializeV8Util)
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008-2009 Manjeet Dahiya
 *
 * Author:
 *	Manjeet Dahiya
 *
 * Source:
 *	http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 */

#include "QXmppPresence.h"
#include "QXmppUtils.h"
#include <QtDebug>
#include <QDomElement>
#include <QXmlStreamWriter>

QXmppPresence::QXmppPresence(QXmppPresence::Type type,
                             const QXmppPresence::Status& status)
    : QXmppStanza(), m_type(type), m_status(status)
{

}

QXmppPresence::~QXmppPresence()
{

}

QXmppPresence::Type QXmppPresence::type() const
{
    return m_type;
}

void QXmppPresence::setType(QXmppPresence::Type type)
{
    m_type = type;
}

const QXmppPresence::Status& QXmppPresence::status() const
{
    return m_status;
}

QXmppPresence::Status& QXmppPresence::status()
{
    return m_status;
}

void QXmppPresence::setStatus(const QXmppPresence::Status& status)
{
    m_status = status;
}

void QXmppPresence::parse(const QDomElement &element)
{
    QXmppStanza::parse(element);

    setTypeFromStr(element.attribute("type"));
    m_status.parse(element);

    QDomElement xElement = element.firstChildElement("x");
    if(!xElement.isNull())
        setExtensions(QXmppElement(xElement));
}

void QXmppPresence::toXml(QXmlStreamWriter *xmlWriter) const
{
    xmlWriter->writeStartElement("presence");
    helperToXmlAddAttribute(xmlWriter,"xml:lang", lang());
    helperToXmlAddAttribute(xmlWriter,"id", id());
    helperToXmlAddAttribute(xmlWriter,"to", to());
    helperToXmlAddAttribute(xmlWriter,"from", from());
    helperToXmlAddAttribute(xmlWriter,"type", getTypeStr());
    m_status.toXml(xmlWriter);

    error().toXml(xmlWriter);
    foreach (const QXmppElement &extension, extensions())
        extension.toXml(xmlWriter);

    xmlWriter->writeEndElement();
}

QString QXmppPresence::getTypeStr() const
{
    QString text;
    switch(m_type)
    {
    case QXmppPresence::Error:
        text = "error";
        break;
    case QXmppPresence::Available:
        // no type-attribute if available
        text = "";
        break;
    case QXmppPresence::Unavailable:
        text = "unavailable";
        break;
    case QXmppPresence::Subscribe:
        text = "subscribe";
        break;
    case QXmppPresence::Subscribed:
        text = "subscribed";
        break;
    case QXmppPresence::Unsubscribe:
        text = "unsubscribe";
        break;
    case QXmppPresence::Unsubscribed:
        text = "unsubscribed";
        break;
    case QXmppPresence::Probe:
        text = "probe";
        break;
    default:
        qWarning("QXmppPresence::getTypeStr() invalid type %d", (int)m_type);
        break;
    }
    return text;
}

void QXmppPresence::setTypeFromStr(const QString& str)
{
    QXmppPresence::Type type;
    if(str == "error")
    {
        type = QXmppPresence::Error;
        setType(type);
        return;
    }
    else if(str == "unavailable")
    {
        type = QXmppPresence::Unavailable;
        setType(type);
        return;
    }
    else if(str == "subscribe")
    {
        type = QXmppPresence::Subscribe;
        setType(type);
        return;
    }
    else if(str == "subscribed")
    {
        type = QXmppPresence::Subscribed;
        setType(type);
        return;
    }
    else if(str == "unsubscribe")
    {
        type = QXmppPresence::Unsubscribe;
        setType(type);
        return;
    }
    else if(str == "unsubscribed")
    {
        type = QXmppPresence::Unsubscribed;
        setType(type);
        return;
    }
    else if(str == "probe")
    {
        type = QXmppPresence::Probe;
        setType(type);
        return;
    }
    else if(str == "")
    {
        type = QXmppPresence::Available;
        setType(type);
        return;
    }
    else
    {
        type = static_cast<QXmppPresence::Type>(-1);
        qWarning("QXmppPresence::setTypeFromStr() invalid input string type: %s",
                 qPrintable(str));
        setType(type);
        return;
    }
}

QXmppPresence::Status::Status(QXmppPresence::Status::Type type,
                             const QString statusText, int priority) :
                                m_type(type),
                                m_statusText(statusText), m_priority(priority)
{
}

QXmppPresence::Status::Type QXmppPresence::Status::type() const
{
    return m_type;
}

void QXmppPresence::Status::setType(QXmppPresence::Status::Type type)
{
    m_type = type;
}

void QXmppPresence::Status::setTypeFromStr(const QString& str)
{
    // there is no keyword for Offline

    QXmppPresence::Status::Type type;
    if(str == "")   // not type-attribute means online
    {
        type = QXmppPresence::Status::Online;
        setType(type);
        return;
    }
    else if(str == "away")
    {
        type = QXmppPresence::Status::Away;
        setType(type);
        return;
    }
    else if(str == "xa")
    {
        type = QXmppPresence::Status::XA;
        setType(type);
        return;
    }
    else if(str == "dnd")
    {
        type = QXmppPresence::Status::DND;
        setType(type);
        return;
    }
    else if(str == "chat")
    {
        type = QXmppPresence::Status::Chat;
        setType(type);
        return;
    }
    else
    {
        type = static_cast<QXmppPresence::Status::Type>(-1);
        qWarning("QXmppPresence::Status::setTypeFromStr() invalid input string type %s",
            qPrintable(str));
        setType(type);
    }
}

QString QXmppPresence::Status::getTypeStr() const
{
    QString text;
    switch(m_type)
    {
    case QXmppPresence::Status::Online:
        // no type-attribute if available
        text = "";
        break;
    case QXmppPresence::Status::Offline:
        text = "";
        break;
    case QXmppPresence::Status::Away:
        text = "away";
        break;
    case QXmppPresence::Status::XA:
        text = "xa";
        break;
    case QXmppPresence::Status::DND:
        text = "dnd";
        break;
    case QXmppPresence::Status::Chat:
        text = "chat";
        break;
    default:
        qWarning("QXmppPresence::Status::getTypeStr() invalid type %d",
                 (int)m_type);
        break;
    }
    return text;
}

QString QXmppPresence::Status::statusText() const
{
    return m_statusText;
}

void QXmppPresence::Status::setStatusText(const QString& str)
{
    m_statusText = str;
}

int QXmppPresence::Status::priority() const
{
    return m_priority;
}

void QXmppPresence::Status::setPriority(int priority)
{
    m_priority = priority;
}

void QXmppPresence::Status::parse(const QDomElement &element)
{
    setTypeFromStr(element.firstChildElement("show").text());
    m_statusText = element.firstChildElement("status").text();
    m_priority = element.firstChildElement("priority").text().toInt();
}

void QXmppPresence::Status::toXml(QXmlStreamWriter *xmlWriter) const
{
    helperToXmlAddTextElement(xmlWriter, "show", getTypeStr());
    helperToXmlAddTextElement(xmlWriter, "status", m_statusText);
    if (m_priority != 0)
        helperToXmlAddNumberElement(xmlWriter, "priority", m_priority);
}

// obsolete start

QXmppPresence::Type QXmppPresence::getType() const
{
    return m_type;
}

const QXmppPresence::Status& QXmppPresence::getStatus() const
{
    return m_status;
}

QXmppPresence::Status& QXmppPresence::getStatus()
{
    return m_status;
}

QXmppPresence::Status::Type QXmppPresence::Status::getType() const
{
    return m_type;
}

QString QXmppPresence::Status::getStatusText() const
{
    return m_statusText;
}

int QXmppPresence::Status::getPriority() const
{
    return m_priority;
}

// obsolete end
<commit_msg>don't add "show" and "status" to presence if empty<commit_after>/*
 * Copyright (C) 2008-2009 Manjeet Dahiya
 *
 * Author:
 *	Manjeet Dahiya
 *
 * Source:
 *	http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 */

#include "QXmppPresence.h"
#include "QXmppUtils.h"
#include <QtDebug>
#include <QDomElement>
#include <QXmlStreamWriter>

QXmppPresence::QXmppPresence(QXmppPresence::Type type,
                             const QXmppPresence::Status& status)
    : QXmppStanza(), m_type(type), m_status(status)
{

}

QXmppPresence::~QXmppPresence()
{

}

QXmppPresence::Type QXmppPresence::type() const
{
    return m_type;
}

void QXmppPresence::setType(QXmppPresence::Type type)
{
    m_type = type;
}

const QXmppPresence::Status& QXmppPresence::status() const
{
    return m_status;
}

QXmppPresence::Status& QXmppPresence::status()
{
    return m_status;
}

void QXmppPresence::setStatus(const QXmppPresence::Status& status)
{
    m_status = status;
}

void QXmppPresence::parse(const QDomElement &element)
{
    QXmppStanza::parse(element);

    setTypeFromStr(element.attribute("type"));
    m_status.parse(element);

    QDomElement xElement = element.firstChildElement("x");
    if(!xElement.isNull())
        setExtensions(QXmppElement(xElement));
}

void QXmppPresence::toXml(QXmlStreamWriter *xmlWriter) const
{
    xmlWriter->writeStartElement("presence");
    helperToXmlAddAttribute(xmlWriter,"xml:lang", lang());
    helperToXmlAddAttribute(xmlWriter,"id", id());
    helperToXmlAddAttribute(xmlWriter,"to", to());
    helperToXmlAddAttribute(xmlWriter,"from", from());
    helperToXmlAddAttribute(xmlWriter,"type", getTypeStr());
    m_status.toXml(xmlWriter);

    error().toXml(xmlWriter);
    foreach (const QXmppElement &extension, extensions())
        extension.toXml(xmlWriter);

    xmlWriter->writeEndElement();
}

QString QXmppPresence::getTypeStr() const
{
    QString text;
    switch(m_type)
    {
    case QXmppPresence::Error:
        text = "error";
        break;
    case QXmppPresence::Available:
        // no type-attribute if available
        text = "";
        break;
    case QXmppPresence::Unavailable:
        text = "unavailable";
        break;
    case QXmppPresence::Subscribe:
        text = "subscribe";
        break;
    case QXmppPresence::Subscribed:
        text = "subscribed";
        break;
    case QXmppPresence::Unsubscribe:
        text = "unsubscribe";
        break;
    case QXmppPresence::Unsubscribed:
        text = "unsubscribed";
        break;
    case QXmppPresence::Probe:
        text = "probe";
        break;
    default:
        qWarning("QXmppPresence::getTypeStr() invalid type %d", (int)m_type);
        break;
    }
    return text;
}

void QXmppPresence::setTypeFromStr(const QString& str)
{
    QXmppPresence::Type type;
    if(str == "error")
    {
        type = QXmppPresence::Error;
        setType(type);
        return;
    }
    else if(str == "unavailable")
    {
        type = QXmppPresence::Unavailable;
        setType(type);
        return;
    }
    else if(str == "subscribe")
    {
        type = QXmppPresence::Subscribe;
        setType(type);
        return;
    }
    else if(str == "subscribed")
    {
        type = QXmppPresence::Subscribed;
        setType(type);
        return;
    }
    else if(str == "unsubscribe")
    {
        type = QXmppPresence::Unsubscribe;
        setType(type);
        return;
    }
    else if(str == "unsubscribed")
    {
        type = QXmppPresence::Unsubscribed;
        setType(type);
        return;
    }
    else if(str == "probe")
    {
        type = QXmppPresence::Probe;
        setType(type);
        return;
    }
    else if(str == "")
    {
        type = QXmppPresence::Available;
        setType(type);
        return;
    }
    else
    {
        type = static_cast<QXmppPresence::Type>(-1);
        qWarning("QXmppPresence::setTypeFromStr() invalid input string type: %s",
                 qPrintable(str));
        setType(type);
        return;
    }
}

QXmppPresence::Status::Status(QXmppPresence::Status::Type type,
                             const QString statusText, int priority) :
                                m_type(type),
                                m_statusText(statusText), m_priority(priority)
{
}

QXmppPresence::Status::Type QXmppPresence::Status::type() const
{
    return m_type;
}

void QXmppPresence::Status::setType(QXmppPresence::Status::Type type)
{
    m_type = type;
}

void QXmppPresence::Status::setTypeFromStr(const QString& str)
{
    // there is no keyword for Offline

    QXmppPresence::Status::Type type;
    if(str == "")   // not type-attribute means online
    {
        type = QXmppPresence::Status::Online;
        setType(type);
        return;
    }
    else if(str == "away")
    {
        type = QXmppPresence::Status::Away;
        setType(type);
        return;
    }
    else if(str == "xa")
    {
        type = QXmppPresence::Status::XA;
        setType(type);
        return;
    }
    else if(str == "dnd")
    {
        type = QXmppPresence::Status::DND;
        setType(type);
        return;
    }
    else if(str == "chat")
    {
        type = QXmppPresence::Status::Chat;
        setType(type);
        return;
    }
    else
    {
        type = static_cast<QXmppPresence::Status::Type>(-1);
        qWarning("QXmppPresence::Status::setTypeFromStr() invalid input string type %s",
            qPrintable(str));
        setType(type);
    }
}

QString QXmppPresence::Status::getTypeStr() const
{
    QString text;
    switch(m_type)
    {
    case QXmppPresence::Status::Online:
        // no type-attribute if available
        text = "";
        break;
    case QXmppPresence::Status::Offline:
        text = "";
        break;
    case QXmppPresence::Status::Away:
        text = "away";
        break;
    case QXmppPresence::Status::XA:
        text = "xa";
        break;
    case QXmppPresence::Status::DND:
        text = "dnd";
        break;
    case QXmppPresence::Status::Chat:
        text = "chat";
        break;
    default:
        qWarning("QXmppPresence::Status::getTypeStr() invalid type %d",
                 (int)m_type);
        break;
    }
    return text;
}

QString QXmppPresence::Status::statusText() const
{
    return m_statusText;
}

void QXmppPresence::Status::setStatusText(const QString& str)
{
    m_statusText = str;
}

int QXmppPresence::Status::priority() const
{
    return m_priority;
}

void QXmppPresence::Status::setPriority(int priority)
{
    m_priority = priority;
}

void QXmppPresence::Status::parse(const QDomElement &element)
{
    setTypeFromStr(element.firstChildElement("show").text());
    m_statusText = element.firstChildElement("status").text();
    m_priority = element.firstChildElement("priority").text().toInt();
}

void QXmppPresence::Status::toXml(QXmlStreamWriter *xmlWriter) const
{
    const QString show = getTypeStr();
    if (!show.isEmpty())
        helperToXmlAddTextElement(xmlWriter, "show", getTypeStr());
    if (!m_statusText.isEmpty())
        helperToXmlAddTextElement(xmlWriter, "status", m_statusText);
    if (m_priority != 0)
        helperToXmlAddNumberElement(xmlWriter, "priority", m_priority);
}

// obsolete start

QXmppPresence::Type QXmppPresence::getType() const
{
    return m_type;
}

const QXmppPresence::Status& QXmppPresence::getStatus() const
{
    return m_status;
}

QXmppPresence::Status& QXmppPresence::getStatus()
{
    return m_status;
}

QXmppPresence::Status::Type QXmppPresence::Status::getType() const
{
    return m_type;
}

QString QXmppPresence::Status::getStatusText() const
{
    return m_statusText;
}

int QXmppPresence::Status::getPriority() const
{
    return m_priority;
}

// obsolete end
<|endoftext|>