<commit_before>#include <mtp/metadata/Library.h>
#include <mtp/ptp/Session.h>
#include <mtp/log.h>
#include <unordered_map>

namespace mtp
{
	namespace
	{
		const std::string UknownArtist		("UknownArtist");
		const std::string UknownAlbum		("UknownAlbum");
		const std::string VariousArtists	("VariousArtists");
	}

	Library::NameToObjectIdMap Library::ListAssociations(ObjectId parentId)
	{
		NameToObjectIdMap list;
		auto folders = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId);
		list.reserve(folders.ObjectHandles.size());

		for(auto id : folders.ObjectHandles)
		{
			auto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
			list.insert(std::make_pair(name, id));
		}
		return list;
	}

	ObjectId Library::GetOrCreate(ObjectId parentId, const std::string &name)
	{
		auto objects = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId);
		for (auto id : objects.ObjectHandles)
		{
			auto oname = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
			if (name == oname)
				return id;
		}
		return _session->CreateDirectory(name, parentId, _storage).ObjectId;
	}

	Library::Library(const mtp::SessionPtr & session, ProgressReporter && reporter): _session(session)
	{
		auto storages = _session->GetStorageIDs();
		if (storages.StorageIDs.empty())
			throw std::runtime_error("no storages found");

		u64 progress = 0, total = 0;
		if (reporter)
			reporter(State::Initialising, progress, total);

		_artistSupported = _session->GetDeviceInfo().Supports(ObjectFormat::Artist);
		{
			auto propsSupported = _session->GetObjectPropertiesSupported(ObjectFormat::AbstractAudioAlbum);
			_albumDateAuthoredSupported = std::find(propsSupported.ObjectPropertyCodes.begin(), propsSupported.ObjectPropertyCodes.end(), ObjectProperty::DateAuthored) != propsSupported.ObjectPropertyCodes.end();
		}

		_storage = storages.StorageIDs[0]; //picking up first storage.
		//zune fails to create artist/album without storage id

		{
			msg::ObjectHandles rootFolders = _session->GetObjectHandles(Session::AllStorages, mtp::ObjectFormat::Association, Session::Root);
			for (auto id : rootFolders.ObjectHandles)
			{
				auto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
				if (name == "Artists")
					_artistsFolder = id;
				else if (name == "Albums")
					_albumsFolder = id;
				else if (name == "Music")
					_musicFolder = id;
			}
		}
		if (_artistSupported && _artistsFolder == ObjectId())
			_artistsFolder = _session->CreateDirectory("Artists", Session::Root, _storage).ObjectId;
		if (_albumsFolder == ObjectId())
			_albumsFolder = _session->CreateDirectory("Albums", Session::Root, _storage).ObjectId;
		if (_musicFolder == ObjectId())
			_musicFolder = _session->CreateDirectory("Music", Session::Root, _storage).ObjectId;

		debug("artists folder: ", _artistsFolder != ObjectId()? _artistsFolder.Id: 0);
		debug("albums folder: ", _albumsFolder.Id);
		debug("music folder: ", _musicFolder.Id);

		auto musicFolders = ListAssociations(_musicFolder);

		using namespace mtp;

		msg::ObjectHandles artists;
		if (_artistSupported)
		{
			debug("getting artists...");
			if (reporter)
				reporter(State::QueryingArtists, progress, total);
			artists = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::Artist, Session::Device);

			total += artists.ObjectHandles.size();
			if (reporter)
				reporter(State::LoadingArtists, progress, total);
		}

		if (_artistSupported)
		{
			for (auto id : artists.ObjectHandles)
			{
				auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);
				debug("artist: ", name, "\t", id.Id);
				auto artist = std::make_shared<Artist>();
				artist->Id = id;
				artist->Name = name;
				auto it = musicFolders.find(name);
				if (it != musicFolders.end())
					artist->MusicFolderId = it->second;
				else
					artist->MusicFolderId = _session->CreateDirectory(name, _musicFolder, _storage).ObjectId;

				_artists.insert(std::make_pair(name, artist));
				if (reporter)
					reporter(State::LoadingArtists, ++progress, total);
			}
		}

		std::unordered_map<ArtistPtr, NameToObjectIdMap> albumFolders;
		{
			debug("getting albums...");
			if (reporter)
				reporter(State::QueryingAlbums, progress, total);

			auto albums = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::AbstractAudioAlbum, Session::Device);
			total += albums.ObjectHandles.size();
			if (reporter)
				reporter(State::LoadingAlbums, progress, total);

			for (auto id : albums.ObjectHandles)
			{
				auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);
				auto artistName = _session->GetObjectStringProperty(id, ObjectProperty::Artist);
				std::string albumDate;

				if (_albumDateAuthoredSupported)
					albumDate = _session->GetObjectStringProperty(id, ObjectProperty::DateAuthored);

				auto artist = GetArtist(artistName);
				if (!artist)
					artist = CreateArtist(artistName);

				debug("album: ", artistName, " -- ", name, "\t", id.Id, "\t", albumDate);
				auto album = std::make_shared<Album>();
				album->Name = name;
				album->Artist = artist;
				album->Id = id;
				album->Year = !albumDate.empty()? ConvertDateTime(albumDate): 0;
				if (albumFolders.find(artist) == albumFolders.end()) {
					albumFolders[artist] = ListAssociations(artist->MusicFolderId);
				}
				auto it = albumFolders.find(artist);
				if (it == albumFolders.end())
					throw std::runtime_error("no iterator after insert, internal error");

				{
					auto refs = _session->GetObjectReferences(id).ObjectHandles;
					std::copy(refs.begin(), refs.end(), std::inserter(album->Refs, album->Refs.begin()));
					for(auto trackId : refs)
					{
						auto name = _session->GetObjectStringProperty(trackId, ObjectProperty::Name);
						auto index = _session->GetObjectIntegerProperty(trackId, ObjectProperty::Track);
						debug("[", index, "]: ", name);
						album->Tracks.insert(std::make_pair(name, index));
					}
				}

				const auto & albums = it->second;
				auto alit = albums.find(name);
				if (alit != albums.end())
					album->MusicFolderId = alit->second;
				else
					album->MusicFolderId = _session->CreateDirectory(name, artist->MusicFolderId, _storage).ObjectId;

				_albums.insert(std::make_pair(std::make_pair(artist, name), album));
				if (reporter)
					reporter(State::LoadingAlbums, ++progress, total);
			}
		}

		if (reporter)
			reporter(State::Loaded, progress, total);
	}

	Library::~Library()
	{ }

	Library::ArtistPtr Library::GetArtist(std::string name)
	{
		if (name.empty())
			name = UknownArtist;

		auto it = _artists.find(name);
		return it != _artists.end()? it->second: ArtistPtr();
	}

	Library::ArtistPtr Library::CreateArtist(std::string name)
	{
		if (name.empty())
			name = UknownArtist;

		auto artist = std::make_shared<Artist>();
		artist->Name = name;
		artist->MusicFolderId = GetOrCreate(_musicFolder, name);

		if (_artistSupported)
		{
			ByteArray propList;
			OutputStream os(propList);

			os.Write32(2); //number of props

			os.Write32(0); //object handle
			os.Write16(static_cast<u16>(ObjectProperty::Name));
			os.Write16(static_cast<u16>(DataTypeCode::String));
			os.WriteString(name);

			os.Write32(0); //object handle
			os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
			os.Write16(static_cast<u16>(DataTypeCode::String));
			os.WriteString(name + ".art");

			auto response = _session->SendObjectPropList(_storage, _artistsFolder, ObjectFormat::Artist, 0, propList);
			artist->Id = response.ObjectId;
		}

		_artists.insert(std::make_pair(name, artist));
		return artist;
	}

	Library::AlbumPtr Library::GetAlbum(const ArtistPtr & artist, std::string name)
	{
		if (name.empty())
			name = UknownAlbum;

		auto it = _albums.find(std::make_pair(artist, name));
		return it != _albums.end()? it->second: AlbumPtr();
	}

	Library::AlbumPtr Library::CreateAlbum(const ArtistPtr & artist, std::string name, int year)
	{
		if (!artist)
			throw std::runtime_error("artists is required");

		if (name.empty())
			name = UknownAlbum;

		ByteArray propList;
		OutputStream os(propList);
		bool sendYear = year != 0 && _albumDateAuthoredSupported;

		os.Write32(3 + (sendYear? 1: 0)); //number of props

		if (_artistSupported)
		{
			os.Write32(0); //object handle
			os.Write16(static_cast<u16>(ObjectProperty::ArtistId));
			os.Write16(static_cast<u16>(DataTypeCode::Uint32));
			os.Write32(artist->Id.Id);
		}
		else
		{
			os.Write32(0); //object handle
			os.Write16(static_cast<u16>(ObjectProperty::Artist));
			os.Write16(static_cast<u16>(DataTypeCode::String));
			os.WriteString(artist->Name);
		}

		os.Write32(0); //object handle
		os.Write16(static_cast<u16>(ObjectProperty::Name));
		os.Write16(static_cast<u16>(DataTypeCode::String));
		os.WriteString(name);

		os.Write32(0); //object handle
		os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
		os.Write16(static_cast<u16>(DataTypeCode::String));
		os.WriteString(artist->Name + "--" + name + ".alb");

		if (sendYear)
		{
			os.Write32(0); //object handle
			os.Write16(static_cast<u16>(ObjectProperty::DateAuthored));
			os.Write16(static_cast<u16>(DataTypeCode::String));
			os.WriteString(ConvertYear(year));
		}

		auto album = std::make_shared<Album>();
		album->Artist = artist;
		album->Name = name;
		album->Year = year;
		album->MusicFolderId = GetOrCreate(artist->MusicFolderId, name);

		auto response = _session->SendObjectPropList(_storage, _albumsFolder, ObjectFormat::AbstractAudioAlbum, 0, propList);
		album->Id = response.ObjectId;

		_albums.insert(std::make_pair(std::make_pair(artist, name), album));
		return album;
	}

	bool Library::HasTrack(const AlbumPtr & album, const std::string &name, int trackIndex)
	{
		if (!album)
			return false;

		auto & tracks = album->Tracks;
		auto range = tracks.equal_range(name);
		for(auto i = range.first; i != range.second; ++i)
		{
			if (i->second == trackIndex)
				return true;
		}

		return false;
	}

	Library::NewTrackInfo Library::CreateTrack(const ArtistPtr & artist,
		const AlbumPtr & album,
		ObjectFormat type,
		std::string name, const std::string & genre, int trackIndex,
		const std::string &filename, size_t size)
	{
		ByteArray propList;
		OutputStream os(propList);

		os.Write32(3 + (!genre.empty()? 1: 0) + (trackIndex? 1: 0)); //number of props

		if (_artistSupported)
		{
			os.Write32(0); //object handle
			os.Write16(static_cast<u16>(ObjectProperty::ArtistId));
			os.Write16(static_cast<u16>(DataTypeCode::Uint32));
			os.Write32(artist->Id.Id);
		}
		else
		{
			os.Write32(0); //object handle
			os.Write16(static_cast<u16>(ObjectProperty::Artist));
			os.Write16(static_cast<u16>(DataTypeCode::String));
			os.WriteString(artist->Name);
		}

		os.Write32(0); //object handle
		os.Write16(static_cast<u16>(ObjectProperty::Name));
		os.Write16(static_cast<u16>(DataTypeCode::String));
		os.WriteString(name);

		if (trackIndex)
		{
			os.Write32(0); //object handle
			os.Write16(static_cast<u16>(ObjectProperty::Track));
			os.Write16(static_cast<u16>(DataTypeCode::Uint16));
			os.Write16(trackIndex);
		}

		if (!genre.empty())
		{
			os.Write32(0); //object handle
			os.Write16(static_cast<u16>(ObjectProperty::Genre));
			os.Write16(static_cast<u16>(DataTypeCode::String));
			os.WriteString(genre);
		}

		os.Write32(0); //object handle
		os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
		os.Write16(static_cast<u16>(DataTypeCode::String));
		os.WriteString(filename);

		auto response = _session->SendObjectPropList(_storage, album->MusicFolderId, type, size, propList);
		NewTrackInfo ti;
		ti.Id = response.ObjectId;
		ti.Name = name;
		ti.Index = trackIndex;
		return ti;
	}

	void Library::AddTrack(AlbumPtr album, const NewTrackInfo & ti)
	{
		if (!album)
			return;

		auto & refs = album->Refs;
		auto & tracks = album->Tracks;

		msg::ObjectHandles handles;
		std::copy(refs.begin(), refs.end(), std::back_inserter(handles.ObjectHandles));
		handles.ObjectHandles.push_back(ti.Id);
		_session->SetObjectReferences(album->Id, handles);
		refs.insert(ti.Id);
		tracks.insert(std::make_pair(ti.Name, ti.Index));
	}

	bool Library::Supported(const mtp::SessionPtr & session)
	{
		auto & gdi = session->GetDeviceInfo();
		return
			gdi.Supports(OperationCode::SendObjectPropList) &&
			gdi.Supports(OperationCode::SetObjectReferences) &&
			gdi.Supports(ObjectFormat::AbstractAudioAlbum);
		;
	}

}
<commit_msg>load object refs at the beginning, providing consistent total<commit_after>#include <mtp/metadata/Library.h>
#include <mtp/ptp/Session.h>
#include <mtp/log.h>
#include <unordered_map>

namespace mtp
{
	namespace
	{
		const std::string UknownArtist		("UknownArtist");
		const std::string UknownAlbum		("UknownAlbum");
		const std::string VariousArtists	("VariousArtists");
	}

	Library::NameToObjectIdMap Library::ListAssociations(ObjectId parentId)
	{
		NameToObjectIdMap list;
		auto folders = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId);
		list.reserve(folders.ObjectHandles.size());

		for(auto id : folders.ObjectHandles)
		{
			auto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
			list.insert(std::make_pair(name, id));
		}
		return list;
	}

	ObjectId Library::GetOrCreate(ObjectId parentId, const std::string &name)
	{
		auto objects = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId);
		for (auto id : objects.ObjectHandles)
		{
			auto oname = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
			if (name == oname)
				return id;
		}
		return _session->CreateDirectory(name, parentId, _storage).ObjectId;
	}

	Library::Library(const mtp::SessionPtr & session, ProgressReporter && reporter): _session(session)
	{
		auto storages = _session->GetStorageIDs();
		if (storages.StorageIDs.empty())
			throw std::runtime_error("no storages found");

		u64 progress = 0, total = 0;
		if (reporter)
			reporter(State::Initialising, progress, total);

		_artistSupported = _session->GetDeviceInfo().Supports(ObjectFormat::Artist);
		{
			auto propsSupported = _session->GetObjectPropertiesSupported(ObjectFormat::AbstractAudioAlbum);
			_albumDateAuthoredSupported = std::find(propsSupported.ObjectPropertyCodes.begin(), propsSupported.ObjectPropertyCodes.end(), ObjectProperty::DateAuthored) != propsSupported.ObjectPropertyCodes.end();
		}

		_storage = storages.StorageIDs[0]; //picking up first storage.
		//zune fails to create artist/album without storage id

		{
			msg::ObjectHandles rootFolders = _session->GetObjectHandles(Session::AllStorages, mtp::ObjectFormat::Association, Session::Root);
			for (auto id : rootFolders.ObjectHandles)
			{
				auto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);
				if (name == "Artists")
					_artistsFolder = id;
				else if (name == "Albums")
					_albumsFolder = id;
				else if (name == "Music")
					_musicFolder = id;
			}
		}
		if (_artistSupported && _artistsFolder == ObjectId())
			_artistsFolder = _session->CreateDirectory("Artists", Session::Root, _storage).ObjectId;
		if (_albumsFolder == ObjectId())
			_albumsFolder = _session->CreateDirectory("Albums", Session::Root, _storage).ObjectId;
		if (_musicFolder == ObjectId())
			_musicFolder = _session->CreateDirectory("Music", Session::Root, _storage).ObjectId;

		debug("artists folder: ", _artistsFolder != ObjectId()? _artistsFolder.Id: 0);
		debug("albums folder: ", _albumsFolder.Id);
		debug("music folder: ", _musicFolder.Id);

		auto musicFolders = ListAssociations(_musicFolder);

		using namespace mtp;

		msg::ObjectHandles artists, albums;
		if (_artistSupported)
		{
			debug("getting artists...");
			if (reporter)
				reporter(State::QueryingArtists, progress, total);
			artists = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::Artist, Session::Device);

			total += artists.ObjectHandles.size();
			if (reporter)
				reporter(State::LoadingArtists, progress, total);
		}
		{
			debug("getting albums...");
			if (reporter)
				reporter(State::QueryingAlbums, progress, total);

			albums = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::AbstractAudioAlbum, Session::Device);
			total += albums.ObjectHandles.size();
			if (reporter)
				reporter(State::LoadingAlbums, progress, total);
		}

		if (_artistSupported)
		{
			for (auto id : artists.ObjectHandles)
			{
				auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);
				debug("artist: ", name, "\t", id.Id);
				auto artist = std::make_shared<Artist>();
				artist->Id = id;
				artist->Name = name;
				auto it = musicFolders.find(name);
				if (it != musicFolders.end())
					artist->MusicFolderId = it->second;
				else
					artist->MusicFolderId = _session->CreateDirectory(name, _musicFolder, _storage).ObjectId;

				_artists.insert(std::make_pair(name, artist));
				if (reporter)
					reporter(State::LoadingArtists, ++progress, total);
			}
		}

		std::unordered_map<ArtistPtr, NameToObjectIdMap> albumFolders;
		for (auto id : albums.ObjectHandles)
		{
			auto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);
			auto artistName = _session->GetObjectStringProperty(id, ObjectProperty::Artist);
			std::string albumDate;

			if (_albumDateAuthoredSupported)
				albumDate = _session->GetObjectStringProperty(id, ObjectProperty::DateAuthored);

			auto artist = GetArtist(artistName);
			if (!artist)
				artist = CreateArtist(artistName);

			debug("album: ", artistName, " -- ", name, "\t", id.Id, "\t", albumDate);
			auto album = std::make_shared<Album>();
			album->Name = name;
			album->Artist = artist;
			album->Id = id;
			album->Year = !albumDate.empty()? ConvertDateTime(albumDate): 0;
			if (albumFolders.find(artist) == albumFolders.end()) {
				albumFolders[artist] = ListAssociations(artist->MusicFolderId);
			}
			auto it = albumFolders.find(artist);
			if (it == albumFolders.end())
				throw std::runtime_error("no iterator after insert, internal error");

			{
				auto refs = _session->GetObjectReferences(id).ObjectHandles;
				std::copy(refs.begin(), refs.end(), std::inserter(album->Refs, album->Refs.begin()));
				for(auto trackId : refs)
				{
					auto name = _session->GetObjectStringProperty(trackId, ObjectProperty::Name);
					auto index = _session->GetObjectIntegerProperty(trackId, ObjectProperty::Track);
					debug("[", index, "]: ", name);
					album->Tracks.insert(std::make_pair(name, index));
				}
			}

			const auto & albums = it->second;
			auto alit = albums.find(name);
			if (alit != albums.end())
				album->MusicFolderId = alit->second;
			else
				album->MusicFolderId = _session->CreateDirectory(name, artist->MusicFolderId, _storage).ObjectId;

			_albums.insert(std::make_pair(std::make_pair(artist, name), album));
			if (reporter)
				reporter(State::LoadingAlbums, ++progress, total);
		}

		if (reporter)
			reporter(State::Loaded, progress, total);
	}

	Library::~Library()
	{ }

	Library::ArtistPtr Library::GetArtist(std::string name)
	{
		if (name.empty())
			name = UknownArtist;

		auto it = _artists.find(name);
		return it != _artists.end()? it->second: ArtistPtr();
	}

	Library::ArtistPtr Library::CreateArtist(std::string name)
	{
		if (name.empty())
			name = UknownArtist;

		auto artist = std::make_shared<Artist>();
		artist->Name = name;
		artist->MusicFolderId = GetOrCreate(_musicFolder, name);

		if (_artistSupported)
		{
			ByteArray propList;
			OutputStream os(propList);

			os.Write32(2); //number of props

			os.Write32(0); //object handle
			os.Write16(static_cast<u16>(ObjectProperty::Name));
			os.Write16(static_cast<u16>(DataTypeCode::String));
			os.WriteString(name);

			os.Write32(0); //object handle
			os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
			os.Write16(static_cast<u16>(DataTypeCode::String));
			os.WriteString(name + ".art");

			auto response = _session->SendObjectPropList(_storage, _artistsFolder, ObjectFormat::Artist, 0, propList);
			artist->Id = response.ObjectId;
		}

		_artists.insert(std::make_pair(name, artist));
		return artist;
	}

	Library::AlbumPtr Library::GetAlbum(const ArtistPtr & artist, std::string name)
	{
		if (name.empty())
			name = UknownAlbum;

		auto it = _albums.find(std::make_pair(artist, name));
		return it != _albums.end()? it->second: AlbumPtr();
	}

	Library::AlbumPtr Library::CreateAlbum(const ArtistPtr & artist, std::string name, int year)
	{
		if (!artist)
			throw std::runtime_error("artists is required");

		if (name.empty())
			name = UknownAlbum;

		ByteArray propList;
		OutputStream os(propList);
		bool sendYear = year != 0 && _albumDateAuthoredSupported;

		os.Write32(3 + (sendYear? 1: 0)); //number of props

		if (_artistSupported)
		{
			os.Write32(0); //object handle
			os.Write16(static_cast<u16>(ObjectProperty::ArtistId));
			os.Write16(static_cast<u16>(DataTypeCode::Uint32));
			os.Write32(artist->Id.Id);
		}
		else
		{
			os.Write32(0); //object handle
			os.Write16(static_cast<u16>(ObjectProperty::Artist));
			os.Write16(static_cast<u16>(DataTypeCode::String));
			os.WriteString(artist->Name);
		}

		os.Write32(0); //object handle
		os.Write16(static_cast<u16>(ObjectProperty::Name));
		os.Write16(static_cast<u16>(DataTypeCode::String));
		os.WriteString(name);

		os.Write32(0); //object handle
		os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
		os.Write16(static_cast<u16>(DataTypeCode::String));
		os.WriteString(artist->Name + "--" + name + ".alb");

		if (sendYear)
		{
			os.Write32(0); //object handle
			os.Write16(static_cast<u16>(ObjectProperty::DateAuthored));
			os.Write16(static_cast<u16>(DataTypeCode::String));
			os.WriteString(ConvertYear(year));
		}

		auto album = std::make_shared<Album>();
		album->Artist = artist;
		album->Name = name;
		album->Year = year;
		album->MusicFolderId = GetOrCreate(artist->MusicFolderId, name);

		auto response = _session->SendObjectPropList(_storage, _albumsFolder, ObjectFormat::AbstractAudioAlbum, 0, propList);
		album->Id = response.ObjectId;

		_albums.insert(std::make_pair(std::make_pair(artist, name), album));
		return album;
	}

	bool Library::HasTrack(const AlbumPtr & album, const std::string &name, int trackIndex)
	{
		if (!album)
			return false;

		auto & tracks = album->Tracks;
		auto range = tracks.equal_range(name);
		for(auto i = range.first; i != range.second; ++i)
		{
			if (i->second == trackIndex)
				return true;
		}

		return false;
	}

	Library::NewTrackInfo Library::CreateTrack(const ArtistPtr & artist,
		const AlbumPtr & album,
		ObjectFormat type,
		std::string name, const std::string & genre, int trackIndex,
		const std::string &filename, size_t size)
	{
		ByteArray propList;
		OutputStream os(propList);

		os.Write32(3 + (!genre.empty()? 1: 0) + (trackIndex? 1: 0)); //number of props

		if (_artistSupported)
		{
			os.Write32(0); //object handle
			os.Write16(static_cast<u16>(ObjectProperty::ArtistId));
			os.Write16(static_cast<u16>(DataTypeCode::Uint32));
			os.Write32(artist->Id.Id);
		}
		else
		{
			os.Write32(0); //object handle
			os.Write16(static_cast<u16>(ObjectProperty::Artist));
			os.Write16(static_cast<u16>(DataTypeCode::String));
			os.WriteString(artist->Name);
		}

		os.Write32(0); //object handle
		os.Write16(static_cast<u16>(ObjectProperty::Name));
		os.Write16(static_cast<u16>(DataTypeCode::String));
		os.WriteString(name);

		if (trackIndex)
		{
			os.Write32(0); //object handle
			os.Write16(static_cast<u16>(ObjectProperty::Track));
			os.Write16(static_cast<u16>(DataTypeCode::Uint16));
			os.Write16(trackIndex);
		}

		if (!genre.empty())
		{
			os.Write32(0); //object handle
			os.Write16(static_cast<u16>(ObjectProperty::Genre));
			os.Write16(static_cast<u16>(DataTypeCode::String));
			os.WriteString(genre);
		}

		os.Write32(0); //object handle
		os.Write16(static_cast<u16>(ObjectProperty::ObjectFilename));
		os.Write16(static_cast<u16>(DataTypeCode::String));
		os.WriteString(filename);

		auto response = _session->SendObjectPropList(_storage, album->MusicFolderId, type, size, propList);
		NewTrackInfo ti;
		ti.Id = response.ObjectId;
		ti.Name = name;
		ti.Index = trackIndex;
		return ti;
	}

	void Library::AddTrack(AlbumPtr album, const NewTrackInfo & ti)
	{
		if (!album)
			return;

		auto & refs = album->Refs;
		auto & tracks = album->Tracks;

		msg::ObjectHandles handles;
		std::copy(refs.begin(), refs.end(), std::back_inserter(handles.ObjectHandles));
		handles.ObjectHandles.push_back(ti.Id);
		_session->SetObjectReferences(album->Id, handles);
		refs.insert(ti.Id);
		tracks.insert(std::make_pair(ti.Name, ti.Index));
	}

	bool Library::Supported(const mtp::SessionPtr & session)
	{
		auto & gdi = session->GetDeviceInfo();
		return
			gdi.Supports(OperationCode::SendObjectPropList) &&
			gdi.Supports(OperationCode::SetObjectReferences) &&
			gdi.Supports(ObjectFormat::AbstractAudioAlbum);
		;
	}

}
<|endoftext|>


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

#ifndef INCLUDED_OOXML_DOCUMENT_HXX
#include <ooxml/OOXMLDocument.hxx>
#endif

#ifndef _COMPHELPER_STORAGEHELPER_HXX
#include <comphelper/storagehelper.hxx>
#endif

#ifndef _COM_SUN_STAR_EMBED_XRELATIONSHIPACCESS_HPP_
#include <com/sun/star/embed/XRelationshipAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_
#include <com/sun/star/io/XStream.hpp>
#endif

namespace writerfilter {
namespace ooxml
{

using namespace com::sun::star;

class OOXMLStreamImpl : public OOXMLStream
{
    void init();

    uno::Reference<uno::XComponentContext> mxContext;
    uno::Reference<embed::XStorage> mxStorage;
    uno::Reference<io::XInputStream> mxInputStream;
    uno::Reference<embed::XRelationshipAccess> mxRelationshipAccess;
    uno::Reference<io::XStream> mxDocumentStream;
    uno::Reference<xml::sax::XFastParser> mxFastParser;
    uno::Reference<xml::sax::XFastTokenHandler> mxFastTokenHandler;

    StreamType_t mnStreamType;

    rtl::OUString msId;
    rtl::OUString msPath;

    bool getTarget(uno::Reference<embed::XRelationshipAccess>
                   xRelationshipAccess,
                   StreamType_t nStreamType,
                   const ::rtl::OUString & rId,
                   ::rtl::OUString & rDocumentTarget);
public:
    typedef boost::shared_ptr<OOXMLStreamImpl> Pointer_t;

    OOXMLStreamImpl
    (OOXMLStreamImpl & rStream, StreamType_t nType);
    OOXMLStreamImpl
    (uno::Reference<uno::XComponentContext> xContext,
     uno::Reference<embed::XStorage> xStorage,
     StreamType_t nType);
    OOXMLStreamImpl(OOXMLStreamImpl & rStream, const rtl::OUString & rId);
    OOXMLStreamImpl
    (uno::Reference<uno::XComponentContext> xContext,
     uno::Reference<embed::XStorage> xStorage,
     const rtl::OUString & rId);

    virtual ~OOXMLStreamImpl();

    virtual uno::Reference<xml::sax::XParser> getParser();
    virtual uno::Reference<xml::sax::XFastParser> getFastParser();
    virtual uno::Reference<io::XInputStream> getDocumentStream();
    virtual uno::Reference<io::XInputStream> getInputStream();
    virtual uno::Reference<uno::XComponentContext> getContext();
    ::rtl::OUString getTargetForId(const ::rtl::OUString & rId);
    virtual uno::Reference<xml::sax::XFastTokenHandler>
    getFastTokenHandler(uno::Reference<uno::XComponentContext> rContext);

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

#include <ooxml/OOXMLDocument.hxx>
#include <comphelper/storagehelper.hxx>
#include <com/sun/star/embed/XRelationshipAccess.hpp>
#include <com/sun/star/io/XStream.hpp>

namespace writerfilter {
namespace ooxml
{

using namespace com::sun::star;

class OOXMLStreamImpl : public OOXMLStream
{
    void init();

    uno::Reference<uno::XComponentContext> mxContext;
    uno::Reference<embed::XStorage> mxStorage;
    uno::Reference<io::XInputStream> mxInputStream;
    uno::Reference<embed::XRelationshipAccess> mxRelationshipAccess;
    uno::Reference<io::XStream> mxDocumentStream;
    uno::Reference<xml::sax::XFastParser> mxFastParser;
    uno::Reference<xml::sax::XFastTokenHandler> mxFastTokenHandler;

    StreamType_t mnStreamType;

    rtl::OUString msId;
    rtl::OUString msPath;

    bool getTarget(uno::Reference<embed::XRelationshipAccess>
                   xRelationshipAccess,
                   StreamType_t nStreamType,
                   const ::rtl::OUString & rId,
                   ::rtl::OUString & rDocumentTarget);
public:
    typedef boost::shared_ptr<OOXMLStreamImpl> Pointer_t;

    OOXMLStreamImpl
    (OOXMLStreamImpl & rStream, StreamType_t nType);
    OOXMLStreamImpl
    (uno::Reference<uno::XComponentContext> xContext,
     uno::Reference<embed::XStorage> xStorage,
     StreamType_t nType);
    OOXMLStreamImpl(OOXMLStreamImpl & rStream, const rtl::OUString & rId);
    OOXMLStreamImpl
    (uno::Reference<uno::XComponentContext> xContext,
     uno::Reference<embed::XStorage> xStorage,
     const rtl::OUString & rId);

    virtual ~OOXMLStreamImpl();

    virtual uno::Reference<xml::sax::XParser> getParser();
    virtual uno::Reference<xml::sax::XFastParser> getFastParser();
    virtual uno::Reference<io::XInputStream> getDocumentStream();
    virtual uno::Reference<io::XInputStream> getInputStream();
    virtual uno::Reference<uno::XComponentContext> getContext();
    ::rtl::OUString getTargetForId(const ::rtl::OUString & rId);
    virtual uno::Reference<xml::sax::XFastTokenHandler>
    getFastTokenHandler(uno::Reference<uno::XComponentContext> rContext);

    void setInputStream(uno::Reference<io::XInputStream> rxInputStream);
};
}}
#endif // INCLUDED_OOXML_STREAM_IMPL_HXX
<|endoftext|>


<commit_before><commit_msg>Create 1542 - Reading Books.cpp<commit_after><|endoftext|>


<commit_before>/**
 * This file is part of the CernVM File System.
 */

#include "history_sql.h"

namespace history {

const float HistoryDatabase::kLatestSchema = 1.0;
const float HistoryDatabase::kLatestSupportedSchema = 1.0;
const unsigned HistoryDatabase::kLatestSchemaRevision = 1;

const std::string HistoryDatabase::kFqrnKey = "fqrn";

/**
 * This method creates a new database file and initializes the database schema.
 */
bool HistoryDatabase::CreateEmptyDatabase() {
  assert (read_write());
  return sqlite::Sql(sqlite_db(),
    "CREATE TABLE tags (name TEXT, hash TEXT, revision INTEGER, "
    "  timestamp INTEGER, channel INTEGER, description TEXT, size INTEGER, "
    "  CONSTRAINT pk_tags PRIMARY KEY (name))").Execute();
}

bool HistoryDatabase::InsertInitialValues(const std::string &repository_name) {
  assert (read_write());
  return this->SetProperty(kFqrnKey, repository_name);
}

bool HistoryDatabase::CheckSchemaCompatibility() {
  return ! ((schema_version() < kLatestSupportedSchema - kSchemaEpsilon) ||
            (schema_version() > kLatestSchema          + kSchemaEpsilon));
}

bool HistoryDatabase::LiveSchemaUpgradeIfNecessary() {
  assert (read_write());

  if (schema_revision() == 0) {
    LogCvmfs(kLogHistory, kLogDebug, "upgrading schema revision");

    sqlite::Sql sql_upgrade(sqlite_db(), "ALTER TABLE tags ADD size INTEGER;");
    if (!sql_upgrade.Execute()) {
      LogCvmfs(kLogHistory, kLogDebug, "failed to upgrade tags table");
      return false;
    }

    set_schema_revision(1);
    if (! StoreSchemaRevision()) {
      LogCvmfs(kLogHistory, kLogDebug, "failed tp upgrade schema revision");
      return false;
    }
  }

  return true;
}

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

const std::string SqlRetrieveTag::tag_database_fields =
  "name, hash, revision, timestamp, channel, description, size";

const std::string& SqlRetrieveTag::GetDatabaseFields() const {
  return SqlRetrieveTag::tag_database_fields;
}

History::Tag SqlRetrieveTag::RetrieveTag() const {
  History::Tag result;
  result.name        = RetrieveString(0);
  result.root_hash   = shash::MkFromHexPtr(shash::HexPtr(RetrieveString(1)));
  result.revision    = RetrieveInt64(2);
  result.timestamp   = RetrieveInt64(3);
  result.channel     = static_cast<History::UpdateChannel>(RetrieveInt64(4));
  result.description = RetrieveString(5);
  result.size        = RetrieveInt64(6);
  return result;
}

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

SqlInsertTag::SqlInsertTag(const HistoryDatabase *database) {
  const std::string stmt =
    "INSERT INTO tags (" + GetDatabaseFields() + ")"
    "VALUES (" + GetDatabasePlaceholders() + ");";
  Init(database->sqlite_db(), stmt);
}

const std::string SqlInsertTag::tag_database_placeholders =
  ":name, :hash, :revision, :timestamp, :channel, :description, :size";

const std::string& SqlInsertTag::GetDatabasePlaceholders() const {
  return SqlInsertTag::tag_database_placeholders;
}

bool SqlInsertTag::BindTag(const History::Tag &tag) {
  return (
    BindText         (1, tag.name)                 &&
    BindTextTransient(2, tag.root_hash.ToString()) && // temporary from ToString
    BindInt64        (3, tag.revision)             &&
    BindInt64        (4, tag.timestamp)            &&
    BindInt64        (5, tag.channel)              &&
    BindText         (6, tag.description)          &&
    BindInt64        (7, tag.size)
  );
}

SqlRemoveTag::SqlRemoveTag(const HistoryDatabase *database) {
  const std::string stmt = "DELETE FROM tags WHERE name = :name;";
  const bool success = Init(database->sqlite_db(), stmt);
  assert (success);
}

bool SqlRemoveTag::BindName(const std::string &name) {
  return BindText(1, name);
}

SqlFindTag::SqlFindTag(const HistoryDatabase *database) {
  const std::string stmt =
    "SELECT " + GetDatabaseFields() + " FROM tags "
    "WHERE name = :name LIMIT 1;";
  Init(database->sqlite_db(), stmt);
}

bool SqlFindTag::BindName(const std::string &name) {
  return BindText(1, name);
}

SqlCountTags::SqlCountTags(const HistoryDatabase *database) {
  Init(database->sqlite_db(), "SELECT count(*) FROM tags;");
}

int SqlCountTags::RetrieveCount() const {
  return RetrieveInt64(0);
}

SqlListTags::SqlListTags(const HistoryDatabase *database) {
  Init(database->sqlite_db(), "SELECT " + GetDatabaseFields() + " FROM tags "
                              "ORDER BY revision DESC;");
}

bool SqlTag::BindTag(const History::Tag &tag) {
  return (
    BindText(1, tag.name) &&
    BindTextTransient(2, tag.root_hash.ToString()) && // temporary from ToString
    BindInt64(3, tag.revision) &&
    BindInt64(4, tag.timestamp) &&
    BindInt64(5, tag.channel) &&
    BindText(6, tag.description) &&
    BindInt64(7, tag.size)
  );
}

History::Tag SqlTag::RetrieveTag() {
  History::Tag result;
  result.name = std::string(reinterpret_cast<const char *>(RetrieveText(0)));
  const std::string hash_str(reinterpret_cast<const char *>(RetrieveText(1)));
  result.root_hash = shash::MkFromHexPtr(shash::HexPtr(hash_str));
  result.revision = RetrieveInt64(2);
  result.timestamp = RetrieveInt64(3);
  result.channel = static_cast<History::UpdateChannel>(RetrieveInt64(4));
  result.description = std::string(reinterpret_cast<const char *>(RetrieveText(5)));
  result.size = RetrieveInt64(6);
  return result;
}

}; /* namespace history */
<commit_msg>assert success of `Sql::Init()`<commit_after>/**
 * This file is part of the CernVM File System.
 */

#include "history_sql.h"

namespace history {

const float HistoryDatabase::kLatestSchema = 1.0;
const float HistoryDatabase::kLatestSupportedSchema = 1.0;
const unsigned HistoryDatabase::kLatestSchemaRevision = 1;

const std::string HistoryDatabase::kFqrnKey = "fqrn";

/**
 * This method creates a new database file and initializes the database schema.
 */
bool HistoryDatabase::CreateEmptyDatabase() {
  assert (read_write());
  return sqlite::Sql(sqlite_db(),
    "CREATE TABLE tags (name TEXT, hash TEXT, revision INTEGER, "
    "  timestamp INTEGER, channel INTEGER, description TEXT, size INTEGER, "
    "  CONSTRAINT pk_tags PRIMARY KEY (name))").Execute();
}

bool HistoryDatabase::InsertInitialValues(const std::string &repository_name) {
  assert (read_write());
  return this->SetProperty(kFqrnKey, repository_name);
}

bool HistoryDatabase::CheckSchemaCompatibility() {
  return ! ((schema_version() < kLatestSupportedSchema - kSchemaEpsilon) ||
            (schema_version() > kLatestSchema          + kSchemaEpsilon));
}

bool HistoryDatabase::LiveSchemaUpgradeIfNecessary() {
  assert (read_write());

  if (schema_revision() == 0) {
    LogCvmfs(kLogHistory, kLogDebug, "upgrading schema revision");

    sqlite::Sql sql_upgrade(sqlite_db(), "ALTER TABLE tags ADD size INTEGER;");
    if (!sql_upgrade.Execute()) {
      LogCvmfs(kLogHistory, kLogDebug, "failed to upgrade tags table");
      return false;
    }

    set_schema_revision(1);
    if (! StoreSchemaRevision()) {
      LogCvmfs(kLogHistory, kLogDebug, "failed tp upgrade schema revision");
      return false;
    }
  }

  return true;
}

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

const std::string SqlRetrieveTag::tag_database_fields =
  "name, hash, revision, timestamp, channel, description, size";

const std::string& SqlRetrieveTag::GetDatabaseFields() const {
  return SqlRetrieveTag::tag_database_fields;
}

History::Tag SqlRetrieveTag::RetrieveTag() const {
  History::Tag result;
  result.name        = RetrieveString(0);
  result.root_hash   = shash::MkFromHexPtr(shash::HexPtr(RetrieveString(1)));
  result.revision    = RetrieveInt64(2);
  result.timestamp   = RetrieveInt64(3);
  result.channel     = static_cast<History::UpdateChannel>(RetrieveInt64(4));
  result.description = RetrieveString(5);
  result.size        = RetrieveInt64(6);
  return result;
}

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

SqlInsertTag::SqlInsertTag(const HistoryDatabase *database) {
  const std::string stmt =
    "INSERT INTO tags (" + GetDatabaseFields() + ")"
    "VALUES (" + GetDatabasePlaceholders() + ");";
  const bool success = Init(database->sqlite_db(), stmt);
  assert (success);
}

const std::string SqlInsertTag::tag_database_placeholders =
  ":name, :hash, :revision, :timestamp, :channel, :description, :size";

const std::string& SqlInsertTag::GetDatabasePlaceholders() const {
  return SqlInsertTag::tag_database_placeholders;
}

bool SqlInsertTag::BindTag(const History::Tag &tag) {
  return (
    BindText         (1, tag.name)                 &&
    BindTextTransient(2, tag.root_hash.ToString()) && // temporary from ToString
    BindInt64        (3, tag.revision)             &&
    BindInt64        (4, tag.timestamp)            &&
    BindInt64        (5, tag.channel)              &&
    BindText         (6, tag.description)          &&
    BindInt64        (7, tag.size)
  );
}

SqlRemoveTag::SqlRemoveTag(const HistoryDatabase *database) {
  const std::string stmt = "DELETE FROM tags WHERE name = :name;";
  const bool success = Init(database->sqlite_db(), stmt);
  assert (success);
}

bool SqlRemoveTag::BindName(const std::string &name) {
  return BindText(1, name);
}

SqlFindTag::SqlFindTag(const HistoryDatabase *database) {
  const std::string stmt =
    "SELECT " + GetDatabaseFields() + " FROM tags "
    "WHERE name = :name LIMIT 1;";
  const bool success = Init(database->sqlite_db(), stmt);
  assert (success);
}

bool SqlFindTag::BindName(const std::string &name) {
  return BindText(1, name);
}

SqlCountTags::SqlCountTags(const HistoryDatabase *database) {
  const bool success = Init(database->sqlite_db(),
                            "SELECT count(*) FROM tags;");
  assert (success);
}

int SqlCountTags::RetrieveCount() const {
  return RetrieveInt64(0);
}

SqlListTags::SqlListTags(const HistoryDatabase *database) {
  const bool success = Init(database->sqlite_db(),
                            "SELECT " + GetDatabaseFields() + " FROM tags "
                            "ORDER BY revision DESC;");
  assert (success);
}

bool SqlTag::BindTag(const History::Tag &tag) {
  return (
    BindText(1, tag.name) &&
    BindTextTransient(2, tag.root_hash.ToString()) && // temporary from ToString
    BindInt64(3, tag.revision) &&
    BindInt64(4, tag.timestamp) &&
    BindInt64(5, tag.channel) &&
    BindText(6, tag.description) &&
    BindInt64(7, tag.size)
  );
}

History::Tag SqlTag::RetrieveTag() {
  History::Tag result;
  result.name = std::string(reinterpret_cast<const char *>(RetrieveText(0)));
  const std::string hash_str(reinterpret_cast<const char *>(RetrieveText(1)));
  result.root_hash = shash::MkFromHexPtr(shash::HexPtr(hash_str));
  result.revision = RetrieveInt64(2);
  result.timestamp = RetrieveInt64(3);
  result.channel = static_cast<History::UpdateChannel>(RetrieveInt64(4));
  result.description = std::string(reinterpret_cast<const char *>(RetrieveText(5)));
  result.size = RetrieveInt64(6);
  return result;
}

}; /* namespace history */
<|endoftext|>


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

#ifndef ACCESSIBILITY_STANDARD_ACCESSIBLEMENUBASECOMPONENT_HXX
#define ACCESSIBILITY_STANDARD_ACCESSIBLEMENUBASECOMPONENT_HXX

#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <com/sun/star/accessibility/XAccessible.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_POINT_HPP_
#include <com/sun/star/awt/Point.hpp>
#endif

#ifndef COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
#include <comphelper/accessiblecomponenthelper.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX
#include <cppuhelper/implbase2.hxx>
#endif

#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif

#include <vector>

class Menu;
class VclSimpleEvent;
class VclMenuEvent;
class VCLExternalSolarLock;

namespace utl {
class AccessibleStateSetHelper;
}

//  ----------------------------------------------------
//  class OAccessibleMenuBaseComponent
//  ----------------------------------------------------

typedef ::comphelper::OAccessibleExtendedComponentHelper    AccessibleExtendedComponentHelper_BASE;

typedef ::cppu::ImplHelper2<
    ::com::sun::star::accessibility::XAccessible,
    ::com::sun::star::lang::XServiceInfo > OAccessibleMenuBaseComponent_BASE;

class OAccessibleMenuBaseComponent : public AccessibleExtendedComponentHelper_BASE,
                                     public OAccessibleMenuBaseComponent_BASE
{
    friend class OAccessibleMenuItemComponent;
    friend class VCLXAccessibleMenuItem;
    friend class VCLXAccessibleMenu;

private:
    VCLExternalSolarLock*   m_pExternalLock;

protected:
    typedef ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > > AccessibleChildren;

    AccessibleChildren      m_aAccessibleChildren;
    Menu*                   m_pMenu;

    sal_Bool                m_bEnabled;
    sal_Bool                m_bFocused;
    sal_Bool                m_bVisible;
    sal_Bool                m_bSelected;
    sal_Bool                m_bChecked;

    Menu*                   GetMenu() { return m_pMenu; }

    virtual sal_Bool        IsEnabled();
    virtual sal_Bool        IsFocused();
    virtual sal_Bool        IsVisible();
    virtual sal_Bool        IsSelected();
    virtual sal_Bool        IsChecked();

    void                    SetEnabled( sal_Bool bEnabled );
    void                    SetFocused( sal_Bool bFocused );
    void                    SetVisible( sal_Bool bVisible );
    void                    SetSelected( sal_Bool bSelected );
    void                    SetChecked( sal_Bool bChecked );

    void                    UpdateEnabled( sal_Int32 i, sal_Bool bEnabled );
    void                    UpdateFocused( sal_Int32 i, sal_Bool bFocused );
    void                    UpdateVisible();
    void                    UpdateSelected( sal_Int32 i, sal_Bool bSelected );
    void                    UpdateChecked( sal_Int32 i, sal_Bool bChecked );
    void                    UpdateAccessibleName( sal_Int32 i );
    void                    UpdateItemText( sal_Int32 i );

    sal_Int32               GetChildCount();

    ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > GetChild( sal_Int32 i );
    ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > GetChildAt( const ::com::sun::star::awt::Point& rPoint );

    void                    InsertChild( sal_Int32 i );
    void                    RemoveChild( sal_Int32 i );

    virtual sal_Bool        IsHighlighted();
    sal_Bool                IsChildHighlighted();

    void                    SelectChild( sal_Int32 i );
    void                    DeSelectAll();
    sal_Bool                IsChildSelected( sal_Int32 i );

    virtual void            Select();
    virtual void            DeSelect();
    virtual void            Click();
    virtual sal_Bool        IsPopupMenuOpen();

    DECL_LINK( MenuEventListener, VclSimpleEvent* );

    virtual void            ProcessMenuEvent( const VclMenuEvent& rVclMenuEvent );

    virtual void            FillAccessibleStateSet( utl::AccessibleStateSetHelper& rStateSet ) = 0;

    // XComponent
    virtual void SAL_CALL   disposing();

public:
    OAccessibleMenuBaseComponent( Menu* pMenu );
    virtual ~OAccessibleMenuBaseComponent();

    void                    SetStates();

    // XInterface
    DECLARE_XINTERFACE()

    // XTypeProvider
    DECLARE_XTYPEPROVIDER()

    // XServiceInfo
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName ) throw (::com::sun::star::uno::RuntimeException);

    // XAccessible
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext(  ) throw (::com::sun::star::uno::RuntimeException);

    // XAccessibleContext
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet(  ) throw (::com::sun::star::uno::RuntimeException);
};

#endif // ACCESSIBILITY_STANDARD_ACCESSIBLEMENUBASECOMPONENT_HXX

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

#ifndef ACCESSIBILITY_STANDARD_ACCESSIBLEMENUBASECOMPONENT_HXX
#define ACCESSIBILITY_STANDARD_ACCESSIBLEMENUBASECOMPONENT_HXX

#include <com/sun/star/accessibility/XAccessible.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/awt/Point.hpp>
#include <comphelper/accessiblecomponenthelper.hxx>
#ifndef _CPPUHELPER_IMPLBASE2_HXX
#include <cppuhelper/implbase2.hxx>
#endif
#include <tools/link.hxx>

#include <vector>

class Menu;
class VclSimpleEvent;
class VclMenuEvent;
class VCLExternalSolarLock;

namespace utl {
class AccessibleStateSetHelper;
}

//  ----------------------------------------------------
//  class OAccessibleMenuBaseComponent
//  ----------------------------------------------------

typedef ::comphelper::OAccessibleExtendedComponentHelper    AccessibleExtendedComponentHelper_BASE;

typedef ::cppu::ImplHelper2<
    ::com::sun::star::accessibility::XAccessible,
    ::com::sun::star::lang::XServiceInfo > OAccessibleMenuBaseComponent_BASE;

class OAccessibleMenuBaseComponent : public AccessibleExtendedComponentHelper_BASE,
                                     public OAccessibleMenuBaseComponent_BASE
{
    friend class OAccessibleMenuItemComponent;
    friend class VCLXAccessibleMenuItem;
    friend class VCLXAccessibleMenu;

private:
    VCLExternalSolarLock*   m_pExternalLock;

protected:
    typedef ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > > AccessibleChildren;

    AccessibleChildren      m_aAccessibleChildren;
    Menu*                   m_pMenu;

    sal_Bool                m_bEnabled;
    sal_Bool                m_bFocused;
    sal_Bool                m_bVisible;
    sal_Bool                m_bSelected;
    sal_Bool                m_bChecked;

    Menu*                   GetMenu() { return m_pMenu; }

    virtual sal_Bool        IsEnabled();
    virtual sal_Bool        IsFocused();
    virtual sal_Bool        IsVisible();
    virtual sal_Bool        IsSelected();
    virtual sal_Bool        IsChecked();

    void                    SetEnabled( sal_Bool bEnabled );
    void                    SetFocused( sal_Bool bFocused );
    void                    SetVisible( sal_Bool bVisible );
    void                    SetSelected( sal_Bool bSelected );
    void                    SetChecked( sal_Bool bChecked );

    void                    UpdateEnabled( sal_Int32 i, sal_Bool bEnabled );
    void                    UpdateFocused( sal_Int32 i, sal_Bool bFocused );
    void                    UpdateVisible();
    void                    UpdateSelected( sal_Int32 i, sal_Bool bSelected );
    void                    UpdateChecked( sal_Int32 i, sal_Bool bChecked );
    void                    UpdateAccessibleName( sal_Int32 i );
    void                    UpdateItemText( sal_Int32 i );

    sal_Int32               GetChildCount();

    ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > GetChild( sal_Int32 i );
    ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > GetChildAt( const ::com::sun::star::awt::Point& rPoint );

    void                    InsertChild( sal_Int32 i );
    void                    RemoveChild( sal_Int32 i );

    virtual sal_Bool        IsHighlighted();
    sal_Bool                IsChildHighlighted();

    void                    SelectChild( sal_Int32 i );
    void                    DeSelectAll();
    sal_Bool                IsChildSelected( sal_Int32 i );

    virtual void            Select();
    virtual void            DeSelect();
    virtual void            Click();
    virtual sal_Bool        IsPopupMenuOpen();

    DECL_LINK( MenuEventListener, VclSimpleEvent* );

    virtual void            ProcessMenuEvent( const VclMenuEvent& rVclMenuEvent );

    virtual void            FillAccessibleStateSet( utl::AccessibleStateSetHelper& rStateSet ) = 0;

    // XComponent
    virtual void SAL_CALL   disposing();

public:
    OAccessibleMenuBaseComponent( Menu* pMenu );
    virtual ~OAccessibleMenuBaseComponent();

    void                    SetStates();

    // XInterface
    DECLARE_XINTERFACE()

    // XTypeProvider
    DECLARE_XTYPEPROVIDER()

    // XServiceInfo
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName ) throw (::com::sun::star::uno::RuntimeException);

    // XAccessible
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext(  ) throw (::com::sun::star::uno::RuntimeException);

    // XAccessibleContext
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet(  ) throw (::com::sun::star::uno::RuntimeException);
};

#endif // ACCESSIBILITY_STANDARD_ACCESSIBLEMENUBASECOMPONENT_HXX

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tdoc_services.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 05:32:19 $
 *
 *  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 "com/sun/star/lang/XMultiServiceFactory.hpp"
#include "com/sun/star/lang/XSingleServiceFactory.hpp"
#include "com/sun/star/registry/XRegistryKey.hpp"

#include "tdoc_provider.hxx"
#include "tdoc_documentcontentfactory.hxx"

using namespace com::sun::star;
using namespace tdoc_ucp;

//=========================================================================
static sal_Bool writeInfo( void * pRegistryKey,
                           const rtl::OUString & rImplementationName,
                           uno::Sequence< rtl::OUString > const & rServiceNames )
{
    rtl::OUString aKeyName( rtl::OUString::createFromAscii( "/" ) );
    aKeyName += rImplementationName;
    aKeyName += rtl::OUString::createFromAscii( "/UNO/SERVICES" );

    uno::Reference< registry::XRegistryKey > xKey;
    try
    {
        xKey = static_cast< registry::XRegistryKey * >(
                                    pRegistryKey )->createKey( aKeyName );
    }
    catch ( registry::InvalidRegistryException const & )
    {
    }

    if ( !xKey.is() )
        return sal_False;

    sal_Bool bSuccess = sal_True;

    for ( sal_Int32 n = 0; n < rServiceNames.getLength(); ++n )
    {
        try
        {
            xKey->createKey( rServiceNames[ n ] );
        }
        catch ( registry::InvalidRegistryException const & )
        {
            bSuccess = sal_False;
            break;
        }
    }
    return bSuccess;
}

//=========================================================================
extern "C" void SAL_CALL component_getImplementationEnvironment(
    const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

//=========================================================================
extern "C" sal_Bool SAL_CALL component_writeInfo(
    void * /*pServiceManager*/, void * pRegistryKey )
{
    return pRegistryKey &&

    //////////////////////////////////////////////////////////////////////
    // Transient Documents Content Provider.
    //////////////////////////////////////////////////////////////////////

    writeInfo( pRegistryKey,
               ContentProvider::getImplementationName_Static(),
               ContentProvider::getSupportedServiceNames_Static() ) &&

    //////////////////////////////////////////////////////////////////////
    // Transient Documents Document Content Factory.
    //////////////////////////////////////////////////////////////////////

    writeInfo( pRegistryKey,
               DocumentContentFactory::getImplementationName_Static(),
               DocumentContentFactory::getSupportedServiceNames_Static() );
}

//=========================================================================
extern "C" void * SAL_CALL component_getFactory(
    const sal_Char * pImplName, void * pServiceManager, void * /*pRegistryKey*/ )
{
    void * pRet = 0;

    uno::Reference< lang::XMultiServiceFactory > xSMgr(
            reinterpret_cast< lang::XMultiServiceFactory * >(
                pServiceManager ) );
    uno::Reference< lang::XSingleServiceFactory > xFactory;

    //////////////////////////////////////////////////////////////////////
    // Transient Documents Content Provider.
    //////////////////////////////////////////////////////////////////////

    if ( ContentProvider::getImplementationName_Static().
                compareToAscii( pImplName ) == 0 )
    {
        xFactory = ContentProvider::createServiceFactory( xSMgr );
    }

    //////////////////////////////////////////////////////////////////////
    // Transient Documents Document Content Factory.
    //////////////////////////////////////////////////////////////////////

    else if ( DocumentContentFactory::getImplementationName_Static().
                compareToAscii( pImplName ) == 0 )
    {
        xFactory = DocumentContentFactory::createServiceFactory( xSMgr );
    }

    //////////////////////////////////////////////////////////////////////

    if ( xFactory.is() )
    {
        xFactory->acquire();
        pRet = xFactory.get();
    }

    return pRet;
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.4.20); FILE MERGED 2006/09/01 17:55:52 kaib 1.4.20.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tdoc_services.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 14:03:00 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucb.hxx"

#include "com/sun/star/lang/XMultiServiceFactory.hpp"
#include "com/sun/star/lang/XSingleServiceFactory.hpp"
#include "com/sun/star/registry/XRegistryKey.hpp"

#include "tdoc_provider.hxx"
#include "tdoc_documentcontentfactory.hxx"

using namespace com::sun::star;
using namespace tdoc_ucp;

//=========================================================================
static sal_Bool writeInfo( void * pRegistryKey,
                           const rtl::OUString & rImplementationName,
                           uno::Sequence< rtl::OUString > const & rServiceNames )
{
    rtl::OUString aKeyName( rtl::OUString::createFromAscii( "/" ) );
    aKeyName += rImplementationName;
    aKeyName += rtl::OUString::createFromAscii( "/UNO/SERVICES" );

    uno::Reference< registry::XRegistryKey > xKey;
    try
    {
        xKey = static_cast< registry::XRegistryKey * >(
                                    pRegistryKey )->createKey( aKeyName );
    }
    catch ( registry::InvalidRegistryException const & )
    {
    }

    if ( !xKey.is() )
        return sal_False;

    sal_Bool bSuccess = sal_True;

    for ( sal_Int32 n = 0; n < rServiceNames.getLength(); ++n )
    {
        try
        {
            xKey->createKey( rServiceNames[ n ] );
        }
        catch ( registry::InvalidRegistryException const & )
        {
            bSuccess = sal_False;
            break;
        }
    }
    return bSuccess;
}

//=========================================================================
extern "C" void SAL_CALL component_getImplementationEnvironment(
    const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

//=========================================================================
extern "C" sal_Bool SAL_CALL component_writeInfo(
    void * /*pServiceManager*/, void * pRegistryKey )
{
    return pRegistryKey &&

    //////////////////////////////////////////////////////////////////////
    // Transient Documents Content Provider.
    //////////////////////////////////////////////////////////////////////

    writeInfo( pRegistryKey,
               ContentProvider::getImplementationName_Static(),
               ContentProvider::getSupportedServiceNames_Static() ) &&

    //////////////////////////////////////////////////////////////////////
    // Transient Documents Document Content Factory.
    //////////////////////////////////////////////////////////////////////

    writeInfo( pRegistryKey,
               DocumentContentFactory::getImplementationName_Static(),
               DocumentContentFactory::getSupportedServiceNames_Static() );
}

//=========================================================================
extern "C" void * SAL_CALL component_getFactory(
    const sal_Char * pImplName, void * pServiceManager, void * /*pRegistryKey*/ )
{
    void * pRet = 0;

    uno::Reference< lang::XMultiServiceFactory > xSMgr(
            reinterpret_cast< lang::XMultiServiceFactory * >(
                pServiceManager ) );
    uno::Reference< lang::XSingleServiceFactory > xFactory;

    //////////////////////////////////////////////////////////////////////
    // Transient Documents Content Provider.
    //////////////////////////////////////////////////////////////////////

    if ( ContentProvider::getImplementationName_Static().
                compareToAscii( pImplName ) == 0 )
    {
        xFactory = ContentProvider::createServiceFactory( xSMgr );
    }

    //////////////////////////////////////////////////////////////////////
    // Transient Documents Document Content Factory.
    //////////////////////////////////////////////////////////////////////

    else if ( DocumentContentFactory::getImplementationName_Static().
                compareToAscii( pImplName ) == 0 )
    {
        xFactory = DocumentContentFactory::createServiceFactory( xSMgr );
    }

    //////////////////////////////////////////////////////////////////////

    if ( xFactory.is() )
    {
        xFactory->acquire();
        pRet = xFactory.get();
    }

    return pRet;
}

<|endoftext|>


<commit_before>#include <Python.h>

#include <fstream>

#include <boost/python/tuple.hpp>
#include <boost/test/unit_test.hpp>

#include <ackward/logging/LogRecord.hpp>

using namespace ackward::logging;

BOOST_AUTO_TEST_SUITE( logging )
BOOST_AUTO_TEST_SUITE( logRecord )

BOOST_AUTO_TEST_CASE( constructor )
{
    LogRecord(L"foo",
              DEBUG(),
              L"/some/path/name",
              101,
              L"Message",
              boost::python::tuple());

    LogRecord(L"foo",
              DEBUG(),
              L"/some/path/name",
              101,
              L"Message",
              boost::python::tuple(),
              boost::python::make_tuple(
                  boost::python::object(),
                  boost::python::object(),
                  boost::python::object()));
}

BOOST_AUTO_TEST_CASE( getMessage )
{
    LogRecord r(L"foo",
                DEBUG(),
                L"/some/path/name",
                101,
                L"Message",
                boost::python::tuple());
    BOOST_CHECK(r.getMessage() == L"Message");
}

BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>disabled tests that don't work right now.<commit_after>#include <Python.h>

#include <fstream>

#include <boost/python/tuple.hpp>
#include <boost/test/unit_test.hpp>

#include <ackward/logging/LogRecord.hpp>

using namespace ackward::logging;

namespace
{

struct Fixture
{
    Fixture() :
        rec (L"foo",
             DEBUG(),
             L"/some/path/name",
             101,
             L"Message",
             boost::python::tuple())
        {}

    LogRecord rec;
};

}

BOOST_AUTO_TEST_SUITE( logging )
BOOST_FIXTURE_TEST_SUITE( logRecord, Fixture )

BOOST_AUTO_TEST_CASE( constructor )
{
    LogRecord(L"foo",
              DEBUG(),
              L"/some/path/name",
              101,
              L"Message",
              boost::python::tuple(),
              boost::python::make_tuple(
                  boost::python::object(),
                  boost::python::object(),
                  boost::python::object()));
}

BOOST_AUTO_TEST_CASE( getMessage )
{
    BOOST_CHECK(rec.getMessage() == L"Message");
}

BOOST_AUTO_TEST_CASE( args )
{
    boost::python::tuple args = rec.args;
}

// BOOST_AUTO_TEST_CASE( asctime )
// {
//     std::wstring at = rec.asctime;
// }

BOOST_AUTO_TEST_CASE( created )
{
    float c = rec.created;
}

// BOOST_AUTO_TEST_CASE( exc_info )
// {
//     boost::python::tuple ei = rec.exc_info;
// }

BOOST_AUTO_TEST_CASE( filename )
{
    std::wstring fn = rec.filename;
}

// BOOST_AUTO_TEST_CASE( funcName )
// {
//     std::wstring fn = rec.funcName;
// }

BOOST_AUTO_TEST_CASE( levelname )
{
    std::wstring ln = rec.levelname;
}

BOOST_AUTO_TEST_CASE( levelno )
{
    int ln = rec.levelno;
}

BOOST_AUTO_TEST_CASE( lineno )
{
    int ln = rec.lineno;
}

BOOST_AUTO_TEST_CASE( module )
{
    std::wstring m = rec.module;
}

BOOST_AUTO_TEST_CASE( msecs )
{
    float ms = rec.msecs;
}

// BOOST_AUTO_TEST_CASE( message )
// {
//     std::wstring m = rec.message;
// }

BOOST_AUTO_TEST_CASE( msg )
{
    std::wstring m = rec.msg;
}

BOOST_AUTO_TEST_CASE( name )
{
    std::wstring n = rec.name;
}

BOOST_AUTO_TEST_CASE( pathname )
{
    std::wstring pn = rec.pathname;
}

BOOST_AUTO_TEST_CASE( process )
{
    int p  = rec.process;
}

BOOST_AUTO_TEST_CASE( processName )
{
    std::wstring pn = rec.processName;
}

BOOST_AUTO_TEST_CASE( relateveCreated )
{
    float rc = rec.relativeCreated;
}

BOOST_AUTO_TEST_CASE( stack_info )
{
    boost::python::object si = rec.stack_info;
}

BOOST_AUTO_TEST_CASE( thread )
{
    unsigned long t = rec.thread;
}

BOOST_AUTO_TEST_CASE( threadName )
{
    std::wstring tn = rec.threadName;
}

BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>// @(#)root/meta:$Id: TGWin32InterpreterProxy.cxx 38517 2011-03-18 20:20:16Z pcanal $
// Author: Valeriy Onuchin  15/11/2003

/*************************************************************************
 * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TGWin32InterpreterProxy                                              //
//                                                                      //
// This class defines thread-safe interface to a command line           //
// interpreter (CINT).                                                  //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TGWin32ProxyDefs.h"
#include "TGWin32InterpreterProxy.h"
#include "TROOT.h"
#include "TGWin32.h"

////////////////////////////////////////////////////////////////////////////////
//______________________________________________________________________________
TInterpreter *TGWin32InterpreterProxy::RealObject()
{
   // returns TCint object

   return gROOT->GetInterpreter();
}

RETURN_PROXY_OBJECT(Interpreter)
VOID_METHOD_ARG1(Interpreter,AddIncludePath,const char*,path,1)
RETURN_METHOD_ARG1(Interpreter,Int_t,AutoLoad,const char *,classname)
VOID_METHOD_ARG0(Interpreter,ClearFileBusy,1)
VOID_METHOD_ARG0(Interpreter,ClearStack,1)
VOID_METHOD_ARG0(Interpreter,EndOfLineAction,1)
VOID_METHOD_ARG0(Interpreter,EnableAutoLoading,1)
RETURN_METHOD_ARG0(Interpreter,Int_t,InitializeDictionaries)
RETURN_METHOD_ARG3(Interpreter,Int_t,GenerateDictionary,const char*,classes,const char*,headers,const char*,options);
RETURN_METHOD_ARG0(Interpreter,char*,GetPrompt)
RETURN_METHOD_ARG0(Interpreter,const char*,GetSharedLibs)
RETURN_METHOD_ARG0(Interpreter,const char*,GetIncludePath)
RETURN_METHOD_ARG2(Interpreter,Int_t,Load,const char*,filenam,Bool_t,system)
RETURN_METHOD_ARG1(Interpreter,Int_t,LoadLibraryMap,const char*,rootmapfile)
RETURN_METHOD_ARG0(Interpreter,Int_t,RescanLibraryMap)
RETURN_METHOD_ARG0(Interpreter,Int_t,ReloadAllSharedLibraryMaps)
RETURN_METHOD_ARG0(Interpreter,Int_t,UnloadAllSharedLibraryMaps)
RETURN_METHOD_ARG1(Interpreter,Int_t,UnloadLibraryMap,const char*,library)
VOID_METHOD_ARG2(Interpreter,LoadMacro,const char*,filename,TInterpreter::EErrorCode*,error,1)
RETURN_METHOD_ARG2(Interpreter,Long_t,ProcessLine,const char*,line,TInterpreter::EErrorCode*,error)
RETURN_METHOD_ARG2(Interpreter,Long_t,ProcessLineSynch,const char*,line,TInterpreter::EErrorCode*,error)
VOID_METHOD_ARG0(Interpreter,PrintIntro,1)
typedef char* (*GetlineFunc_t)(const char* prompt);
typedef void (*HistaddFunc_t)(char* line);
VOID_METHOD_ARG2(Interpreter,SetGetline,GetlineFunc_t, getlineFunc,\
		 HistaddFunc_t, histaddFunc, 1)
VOID_METHOD_ARG0(Interpreter,Reset,1)
VOID_METHOD_ARG0(Interpreter,ResetAll,1)
VOID_METHOD_ARG0(Interpreter,ResetGlobals,1)
VOID_METHOD_ARG1(Interpreter,ResetGlobalVar,void*,obj)
VOID_METHOD_ARG0(Interpreter,RewindDictionary,1)
RETURN_METHOD_ARG1(Interpreter,Int_t,DeleteGlobal,void*,obj)
VOID_METHOD_ARG0(Interpreter,SaveContext,1)
VOID_METHOD_ARG0(Interpreter,SaveGlobalsContext,1)
VOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfGlobals)
VOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfGlobalFunctions)
VOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfTypes)
VOID_METHOD_ARG2_LOCK(Interpreter,SetClassInfo,TClass*,cl,Bool_t,reload)
RETURN_METHOD_ARG2(Interpreter,Bool_t,CheckClassInfo,const char*,name,Bool_t,autoload)
RETURN_METHOD_ARG2(Interpreter,Long_t,Calc,const char*,line,TInterpreter::EErrorCode*,error)
VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfBaseClasses,TClass*,cl)
VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfDataMembers,TClass*,cl)
VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethods,TClass*,cl)
VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethodArgs,TFunction*,m)
VOID_METHOD_ARG1_LOCK(Interpreter,UpdateListOfMethods,TClass*,cl)
RETURN_METHOD_ARG3(Interpreter,TString,GetMangledName,TClass*,cl,const char*,method,const char*,params)
RETURN_METHOD_ARG3(Interpreter,TString,GetMangledNameWithPrototype,TClass*,cl,const char*,method,const char*,proto)
RETURN_METHOD_ARG3(Interpreter,void*,GetInterfaceMethod,TClass*,cl,const char*,method,const char*,params)
RETURN_METHOD_ARG3(Interpreter,void*,GetInterfaceMethodWithPrototype,TClass*,cl,const char*,method,const char*,proto)
RETURN_METHOD_ARG1(Interpreter,const char*,GetClassSharedLibs,const char*,s)
RETURN_METHOD_ARG1(Interpreter,const char*,GetSharedLibDeps,const char*,s)
RETURN_METHOD_ARG2(Interpreter,const char*,GetInterpreterTypeName,const char*,s,Bool_t,full)
VOID_METHOD_ARG3(Interpreter,Execute,const char*,function,const char*,params,int*,error,1)
VOID_METHOD_ARG5(Interpreter,Execute,TObject*,obj,TClass*,cl,const char*,method,const char*,params,int*,error,1)
VOID_METHOD_ARG5(Interpreter,Execute,TObject*,object,TClass*,cl,TMethod*,method,TObjArray*,params,int*,error,1)
RETURN_METHOD_ARG2(Interpreter,Long_t,ExecuteMacro,const char*,filename,TInterpreter::EErrorCode*,error)
RETURN_METHOD_ARG1(Interpreter,Bool_t,SetErrorMessages,Bool_t,enable)
VOID_METHOD_ARG1(Interpreter,SetProcessLineLock,Bool_t,lock,1)
RETURN_METHOD_ARG1(Interpreter,const char*,TypeName,const char*,s)
//Bool_t TGWin32InterpreterProxy::CheckClassInfo(const char* name) { return RealObject()->CheckClassInfo(name); }
<commit_msg>Add missing parameter<commit_after>// @(#)root/meta:$Id: TGWin32InterpreterProxy.cxx 38517 2011-03-18 20:20:16Z pcanal $
// Author: Valeriy Onuchin  15/11/2003

/*************************************************************************
 * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TGWin32InterpreterProxy                                              //
//                                                                      //
// This class defines thread-safe interface to a command line           //
// interpreter (CINT).                                                  //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TGWin32ProxyDefs.h"
#include "TGWin32InterpreterProxy.h"
#include "TROOT.h"
#include "TGWin32.h"

////////////////////////////////////////////////////////////////////////////////
//______________________________________________________________________________
TInterpreter *TGWin32InterpreterProxy::RealObject()
{
   // returns TCint object

   return gROOT->GetInterpreter();
}

RETURN_PROXY_OBJECT(Interpreter)
VOID_METHOD_ARG1(Interpreter,AddIncludePath,const char*,path,1)
RETURN_METHOD_ARG1(Interpreter,Int_t,AutoLoad,const char *,classname)
VOID_METHOD_ARG0(Interpreter,ClearFileBusy,1)
VOID_METHOD_ARG0(Interpreter,ClearStack,1)
VOID_METHOD_ARG0(Interpreter,EndOfLineAction,1)
VOID_METHOD_ARG0(Interpreter,EnableAutoLoading,1)
RETURN_METHOD_ARG0(Interpreter,Int_t,InitializeDictionaries)
RETURN_METHOD_ARG3(Interpreter,Int_t,GenerateDictionary,const char*,classes,const char*,headers,const char*,options);
RETURN_METHOD_ARG0(Interpreter,char*,GetPrompt)
RETURN_METHOD_ARG0(Interpreter,const char*,GetSharedLibs)
RETURN_METHOD_ARG0(Interpreter,const char*,GetIncludePath)
RETURN_METHOD_ARG2(Interpreter,Int_t,Load,const char*,filenam,Bool_t,system)
RETURN_METHOD_ARG1(Interpreter,Int_t,LoadLibraryMap,const char*,rootmapfile)
RETURN_METHOD_ARG0(Interpreter,Int_t,RescanLibraryMap)
RETURN_METHOD_ARG0(Interpreter,Int_t,ReloadAllSharedLibraryMaps)
RETURN_METHOD_ARG0(Interpreter,Int_t,UnloadAllSharedLibraryMaps)
RETURN_METHOD_ARG1(Interpreter,Int_t,UnloadLibraryMap,const char*,library)
VOID_METHOD_ARG2(Interpreter,LoadMacro,const char*,filename,TInterpreter::EErrorCode*,error,1)
RETURN_METHOD_ARG2(Interpreter,Long_t,ProcessLine,const char*,line,TInterpreter::EErrorCode*,error)
RETURN_METHOD_ARG2(Interpreter,Long_t,ProcessLineSynch,const char*,line,TInterpreter::EErrorCode*,error)
VOID_METHOD_ARG0(Interpreter,PrintIntro,1)
typedef char* (*GetlineFunc_t)(const char* prompt);
typedef void (*HistaddFunc_t)(char* line);
VOID_METHOD_ARG2(Interpreter,SetGetline,GetlineFunc_t, getlineFunc,\
		 HistaddFunc_t, histaddFunc, 1)
VOID_METHOD_ARG0(Interpreter,Reset,1)
VOID_METHOD_ARG0(Interpreter,ResetAll,1)
VOID_METHOD_ARG0(Interpreter,ResetGlobals,1)
VOID_METHOD_ARG1(Interpreter,ResetGlobalVar,void*,obj,1)
VOID_METHOD_ARG0(Interpreter,RewindDictionary,1)
RETURN_METHOD_ARG1(Interpreter,Int_t,DeleteGlobal,void*,obj)
VOID_METHOD_ARG0(Interpreter,SaveContext,1)
VOID_METHOD_ARG0(Interpreter,SaveGlobalsContext,1)
VOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfGlobals)
VOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfGlobalFunctions)
VOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfTypes)
VOID_METHOD_ARG2_LOCK(Interpreter,SetClassInfo,TClass*,cl,Bool_t,reload)
RETURN_METHOD_ARG2(Interpreter,Bool_t,CheckClassInfo,const char*,name,Bool_t,autoload)
RETURN_METHOD_ARG2(Interpreter,Long_t,Calc,const char*,line,TInterpreter::EErrorCode*,error)
VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfBaseClasses,TClass*,cl)
VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfDataMembers,TClass*,cl)
VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethods,TClass*,cl)
VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethodArgs,TFunction*,m)
VOID_METHOD_ARG1_LOCK(Interpreter,UpdateListOfMethods,TClass*,cl)
RETURN_METHOD_ARG3(Interpreter,TString,GetMangledName,TClass*,cl,const char*,method,const char*,params)
RETURN_METHOD_ARG3(Interpreter,TString,GetMangledNameWithPrototype,TClass*,cl,const char*,method,const char*,proto)
RETURN_METHOD_ARG3(Interpreter,void*,GetInterfaceMethod,TClass*,cl,const char*,method,const char*,params)
RETURN_METHOD_ARG3(Interpreter,void*,GetInterfaceMethodWithPrototype,TClass*,cl,const char*,method,const char*,proto)
RETURN_METHOD_ARG1(Interpreter,const char*,GetClassSharedLibs,const char*,s)
RETURN_METHOD_ARG1(Interpreter,const char*,GetSharedLibDeps,const char*,s)
RETURN_METHOD_ARG2(Interpreter,const char*,GetInterpreterTypeName,const char*,s,Bool_t,full)
VOID_METHOD_ARG3(Interpreter,Execute,const char*,function,const char*,params,int*,error,1)
VOID_METHOD_ARG5(Interpreter,Execute,TObject*,obj,TClass*,cl,const char*,method,const char*,params,int*,error,1)
VOID_METHOD_ARG5(Interpreter,Execute,TObject*,object,TClass*,cl,TMethod*,method,TObjArray*,params,int*,error,1)
RETURN_METHOD_ARG2(Interpreter,Long_t,ExecuteMacro,const char*,filename,TInterpreter::EErrorCode*,error)
RETURN_METHOD_ARG1(Interpreter,Bool_t,SetErrorMessages,Bool_t,enable)
VOID_METHOD_ARG1(Interpreter,SetProcessLineLock,Bool_t,lock,1)
RETURN_METHOD_ARG1(Interpreter,const char*,TypeName,const char*,s)
//Bool_t TGWin32InterpreterProxy::CheckClassInfo(const char* name) { return RealObject()->CheckClassInfo(name); }
<|endoftext|>