<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#ifndef __MITK_NRRD_DIFFUSION_VOULMES_IO_FACTORY_CPP__
#define __MITK_NRRD_DIFFUSION_VOULMES_IO_FACTORY_CPP__

#include "mitkDiffusionImageSource.h"
#include "mitkDiffusionImage.h"

template<typename TPixelType>
mitk::DiffusionImageSource<TPixelType>::DiffusionImageSource()
{
  // Create the output. We use static_cast<> here because we know the default
  // output must be of type DiffusionImage
  typename mitk::DiffusionImage<TPixelType>::Pointer output
    = static_cast<typename mitk::DiffusionImage<TPixelType>*>(this->MakeOutput(0).GetPointer());

  Superclass::SetNumberOfRequiredOutputs(1);
  Superclass::SetNthOutput(0, output.GetPointer());
}

template<typename TPixelType>
mitk::DiffusionImageSource<TPixelType>::~DiffusionImageSource()
{
}

template<typename TPixelType>
itk::DataObject::Pointer mitk::DiffusionImageSource<TPixelType>::MakeOutput ( DataObjectPointerArraySizeType /*idx*/ )
{
    return OutputType::New().GetPointer();
}

template<typename TPixelType>
itk::DataObject::Pointer mitk::DiffusionImageSource<TPixelType>::MakeOutput( const DataObjectIdentifierType & name )
{
  itkDebugMacro("MakeOutput(" << name << ")");
  if( this->IsIndexedOutputName(name) )
    {
    return this->MakeOutput( this->MakeIndexFromOutputName(name) );
    }
  return static_cast<itk::DataObject *>(OutputType::New().GetPointer());
}

template<typename TPixelType>
typename mitk::DiffusionImageSource<TPixelType>::OutputType*
mitk::DiffusionImageSource<TPixelType>::GetOutput(void)
{
  return itkDynamicCastInDebugMode<OutputType*>( this->GetPrimaryOutput() );
}

template<typename TPixelType>
const typename mitk::DiffusionImageSource<TPixelType>::OutputType*
mitk::DiffusionImageSource<TPixelType>::GetOutput(void) const
{
  return itkDynamicCastInDebugMode<const OutputType*>( this->GetPrimaryOutput() );
}

template<typename TPixelType>
typename mitk::DiffusionImageSource<TPixelType>::OutputType*
mitk::DiffusionImageSource<TPixelType>::GetOutput(DataObjectPointerArraySizeType idx)
{
  OutputType* out = dynamic_cast<OutputType*>( this->ProcessObject::GetOutput(idx) );
  if ( out == NULL && this->ProcessObject::GetOutput(idx) != NULL )
  {
    itkWarningMacro (<< "Unable to convert output number " << idx << " to type " <<  typeid( OutputType ).name () );
  }
  return out;
}

template<typename TPixelType>
const typename mitk::DiffusionImageSource<TPixelType>::OutputType*
mitk::DiffusionImageSource<TPixelType>::GetOutput(DataObjectPointerArraySizeType idx) const
{
  const OutputType* out = dynamic_cast<const OutputType*>( this->ProcessObject::GetOutput(idx) );
  if ( out == NULL && this->ProcessObject::GetOutput(idx) != NULL )
  {
    itkWarningMacro (<< "Unable to convert output number " << idx << " to type " <<  typeid( OutputType ).name () );
  }
  return out;
}

#endif //__MITK_NRRD_DIFFUSION_VOULMES_IO_FACTORY_CPP__
<commit_msg>Fixed pre-processor macro name<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#ifndef __MITK_DIFFUSIONIMAGE_SOURCE_CPP__
#define __MITK_DIFFUSIONIMAGE_SOURCE_CPP__

#include "mitkDiffusionImageSource.h"
#include "mitkDiffusionImage.h"

template<typename TPixelType>
mitk::DiffusionImageSource<TPixelType>::DiffusionImageSource()
{
  // Create the output. We use static_cast<> here because we know the default
  // output must be of type DiffusionImage
  typename mitk::DiffusionImage<TPixelType>::Pointer output
    = static_cast<typename mitk::DiffusionImage<TPixelType>*>(this->MakeOutput(0).GetPointer());

  Superclass::SetNumberOfRequiredOutputs(1);
  Superclass::SetNthOutput(0, output.GetPointer());
}

template<typename TPixelType>
mitk::DiffusionImageSource<TPixelType>::~DiffusionImageSource()
{
}

template<typename TPixelType>
itk::DataObject::Pointer mitk::DiffusionImageSource<TPixelType>::MakeOutput ( DataObjectPointerArraySizeType /*idx*/ )
{
    return OutputType::New().GetPointer();
}

template<typename TPixelType>
itk::DataObject::Pointer mitk::DiffusionImageSource<TPixelType>::MakeOutput( const DataObjectIdentifierType & name )
{
  itkDebugMacro("MakeOutput(" << name << ")");
  if( this->IsIndexedOutputName(name) )
    {
    return this->MakeOutput( this->MakeIndexFromOutputName(name) );
    }
  return static_cast<itk::DataObject *>(OutputType::New().GetPointer());
}

template<typename TPixelType>
typename mitk::DiffusionImageSource<TPixelType>::OutputType*
mitk::DiffusionImageSource<TPixelType>::GetOutput(void)
{
  return itkDynamicCastInDebugMode<OutputType*>( this->GetPrimaryOutput() );
}

template<typename TPixelType>
const typename mitk::DiffusionImageSource<TPixelType>::OutputType*
mitk::DiffusionImageSource<TPixelType>::GetOutput(void) const
{
  return itkDynamicCastInDebugMode<const OutputType*>( this->GetPrimaryOutput() );
}

template<typename TPixelType>
typename mitk::DiffusionImageSource<TPixelType>::OutputType*
mitk::DiffusionImageSource<TPixelType>::GetOutput(DataObjectPointerArraySizeType idx)
{
  OutputType* out = dynamic_cast<OutputType*>( this->ProcessObject::GetOutput(idx) );
  if ( out == NULL && this->ProcessObject::GetOutput(idx) != NULL )
  {
    itkWarningMacro (<< "Unable to convert output number " << idx << " to type " <<  typeid( OutputType ).name () );
  }
  return out;
}

template<typename TPixelType>
const typename mitk::DiffusionImageSource<TPixelType>::OutputType*
mitk::DiffusionImageSource<TPixelType>::GetOutput(DataObjectPointerArraySizeType idx) const
{
  const OutputType* out = dynamic_cast<const OutputType*>( this->ProcessObject::GetOutput(idx) );
  if ( out == NULL && this->ProcessObject::GetOutput(idx) != NULL )
  {
    itkWarningMacro (<< "Unable to convert output number " << idx << " to type " <<  typeid( OutputType ).name () );
  }
  return out;
}

#endif //__MITK_DIFFUSIONIMAGE_SOURCE_CPP__
<|endoftext|>


<commit_before>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013, 2014, 2015
              Vladimír Vondruš <mosra@centrum.cz>

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

#include "Magnum/Context.h"
#include "Magnum/Extensions.h"
#include "Magnum/Test/AbstractOpenGLTester.h"

namespace Magnum { namespace Test {

struct ContextGLTest: AbstractOpenGLTester {
    explicit ContextGLTest();

    void constructCopyMove();

    void isVersionSupported();
    void supportedVersion();
    void isExtensionSupported();
    void isExtensionDisabled();
};

ContextGLTest::ContextGLTest() {
    addTests({&ContextGLTest::constructCopyMove,

              &ContextGLTest::isVersionSupported,
              &ContextGLTest::supportedVersion,
              &ContextGLTest::isExtensionSupported,
              &ContextGLTest::isExtensionDisabled});
}

void ContextGLTest::constructCopyMove() {
    /* Only move-construction allowed */
    CORRADE_VERIFY(!(std::is_constructible<Context, const Context&>{}));
    CORRADE_VERIFY((std::is_constructible<Context, Context&&>{}));
    CORRADE_VERIFY(!(std::is_assignable<Context, const Context&>{}));
    CORRADE_VERIFY(!(std::is_assignable<Context, Context&&>{}));
}

void ContextGLTest::isVersionSupported() {
    const Version v = Context::current()->version();
    CORRADE_VERIFY(Context::current()->isVersionSupported(v));
    CORRADE_VERIFY(Context::current()->isVersionSupported(Version(Int(v)-1)));
    CORRADE_VERIFY(!Context::current()->isVersionSupported(Version(Int(v)+1)));

    /* No assertions should be fired */
    MAGNUM_ASSERT_VERSION_SUPPORTED(v);
    MAGNUM_ASSERT_VERSION_SUPPORTED(Version(Int(v)-1));
}

void ContextGLTest::supportedVersion() {
    const Version v = Context::current()->version();

    /* Selects first supported version (thus not necessarily the highest) */
    CORRADE_VERIFY(Context::current()->supportedVersion({Version(Int(v)+1), v, Version(Int(v)-1)}) == v);
    CORRADE_VERIFY(Context::current()->supportedVersion({Version(Int(v)+1), Version(Int(v)-1), v}) == Version(Int(v)-1));
}

void ContextGLTest::isExtensionSupported() {
    #ifndef MAGNUM_TARGET_GLES
    if(Context::current()->isExtensionSupported<Extensions::GL::GREMEDY::string_marker>())
        CORRADE_SKIP(Extensions::GL::GREMEDY::string_marker::string() + std::string(" extension should not be supported, can't test"));

    if(!Context::current()->isExtensionSupported<Extensions::GL::EXT::texture_filter_anisotropic>())
        CORRADE_SKIP(Extensions::GL::EXT::texture_filter_anisotropic::string() + std::string(" extension should be supported, can't test"));

    if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::explicit_attrib_location>())
        CORRADE_SKIP(Extensions::GL::ARB::explicit_attrib_location::string() + std::string(" extension should be supported, can't test"));

    /* Test that we have proper extension list parser */
    std::string extensions(reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS)));
    CORRADE_VERIFY(extensions.find(Extensions::GL::EXT::texture_filter_anisotropic::string()) != std::string::npos);
    CORRADE_VERIFY(extensions.find(Extensions::GL::GREMEDY::string_marker::string()) == std::string::npos);

    /* This is disabled in GL < 3.2 to work around GLSL compiler bugs */
    CORRADE_VERIFY(!Context::current()->isExtensionSupported<Extensions::GL::ARB::explicit_attrib_location>(Version::GL310));
    CORRADE_VERIFY(Context::current()->isExtensionSupported<Extensions::GL::ARB::explicit_attrib_location>(Version::GL320));
    #else
    CORRADE_SKIP("No useful extensions to test on OpenGL ES");
    #endif
}

void ContextGLTest::isExtensionDisabled() {
    #ifndef MAGNUM_TARGET_GLES
    if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::vertex_array_object>())
        CORRADE_SKIP(Extensions::GL::ARB::vertex_array_object::string() + std::string(" extension should be supported, can't test"));

    if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::explicit_attrib_location>())
        CORRADE_SKIP(Extensions::GL::ARB::explicit_attrib_location::string() + std::string(" extension should be supported, can't test"));

    /* This is not disabled anywhere */
    CORRADE_VERIFY(!Context::current()->isExtensionDisabled<Extensions::GL::ARB::vertex_array_object>());

    /* This is disabled in GL < 3.2 to work around GLSL compiler bugs */
    CORRADE_VERIFY(Context::current()->isExtensionDisabled<Extensions::GL::ARB::explicit_attrib_location>(Version::GL310));
    CORRADE_VERIFY(!Context::current()->isExtensionDisabled<Extensions::GL::ARB::explicit_attrib_location>(Version::GL320));
    #else
    CORRADE_SKIP("No useful extensions to test on OpenGL ES");
    #endif
}

}}

MAGNUM_GL_TEST_MAIN(Magnum::Test::ContextGLTest)
<commit_msg>Don't use raw GL calls (that are even deprecated) in tests.<commit_after>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013, 2014, 2015
              Vladimír Vondruš <mosra@centrum.cz>

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

#include <algorithm>

#include "Magnum/Context.h"
#include "Magnum/Extensions.h"
#include "Magnum/Test/AbstractOpenGLTester.h"

namespace Magnum { namespace Test {

struct ContextGLTest: AbstractOpenGLTester {
    explicit ContextGLTest();

    void constructCopyMove();

    void isVersionSupported();
    void supportedVersion();
    void isExtensionSupported();
    void isExtensionDisabled();
};

ContextGLTest::ContextGLTest() {
    addTests({&ContextGLTest::constructCopyMove,

              &ContextGLTest::isVersionSupported,
              &ContextGLTest::supportedVersion,
              &ContextGLTest::isExtensionSupported,
              &ContextGLTest::isExtensionDisabled});
}

void ContextGLTest::constructCopyMove() {
    /* Only move-construction allowed */
    CORRADE_VERIFY(!(std::is_constructible<Context, const Context&>{}));
    CORRADE_VERIFY((std::is_constructible<Context, Context&&>{}));
    CORRADE_VERIFY(!(std::is_assignable<Context, const Context&>{}));
    CORRADE_VERIFY(!(std::is_assignable<Context, Context&&>{}));
}

void ContextGLTest::isVersionSupported() {
    const Version v = Context::current()->version();
    CORRADE_VERIFY(Context::current()->isVersionSupported(v));
    CORRADE_VERIFY(Context::current()->isVersionSupported(Version(Int(v)-1)));
    CORRADE_VERIFY(!Context::current()->isVersionSupported(Version(Int(v)+1)));

    /* No assertions should be fired */
    MAGNUM_ASSERT_VERSION_SUPPORTED(v);
    MAGNUM_ASSERT_VERSION_SUPPORTED(Version(Int(v)-1));
}

void ContextGLTest::supportedVersion() {
    const Version v = Context::current()->version();

    /* Selects first supported version (thus not necessarily the highest) */
    CORRADE_VERIFY(Context::current()->supportedVersion({Version(Int(v)+1), v, Version(Int(v)-1)}) == v);
    CORRADE_VERIFY(Context::current()->supportedVersion({Version(Int(v)+1), Version(Int(v)-1), v}) == Version(Int(v)-1));
}

void ContextGLTest::isExtensionSupported() {
    #ifndef MAGNUM_TARGET_GLES
    if(Context::current()->isExtensionSupported<Extensions::GL::GREMEDY::string_marker>())
        CORRADE_SKIP(Extensions::GL::GREMEDY::string_marker::string() + std::string(" extension should not be supported, can't test"));

    if(!Context::current()->isExtensionSupported<Extensions::GL::EXT::texture_filter_anisotropic>())
        CORRADE_SKIP(Extensions::GL::EXT::texture_filter_anisotropic::string() + std::string(" extension should be supported, can't test"));

    if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::explicit_attrib_location>())
        CORRADE_SKIP(Extensions::GL::ARB::explicit_attrib_location::string() + std::string(" extension should be supported, can't test"));

    /* Test that we have proper extension list parser */
    std::vector<std::string> extensions = Context::current()->extensionStrings();
    CORRADE_VERIFY(std::find(extensions.begin(), extensions.end(),
        Extensions::GL::EXT::texture_filter_anisotropic::string()) != extensions.end());
    CORRADE_VERIFY(std::find(extensions.begin(), extensions.end(),
        Extensions::GL::GREMEDY::string_marker::string()) == extensions.end());

    /* This is disabled in GL < 3.2 to work around GLSL compiler bugs */
    CORRADE_VERIFY(!Context::current()->isExtensionSupported<Extensions::GL::ARB::explicit_attrib_location>(Version::GL310));
    CORRADE_VERIFY(Context::current()->isExtensionSupported<Extensions::GL::ARB::explicit_attrib_location>(Version::GL320));
    #else
    CORRADE_SKIP("No useful extensions to test on OpenGL ES");
    #endif
}

void ContextGLTest::isExtensionDisabled() {
    #ifndef MAGNUM_TARGET_GLES
    if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::vertex_array_object>())
        CORRADE_SKIP(Extensions::GL::ARB::vertex_array_object::string() + std::string(" extension should be supported, can't test"));

    if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::explicit_attrib_location>())
        CORRADE_SKIP(Extensions::GL::ARB::explicit_attrib_location::string() + std::string(" extension should be supported, can't test"));

    /* This is not disabled anywhere */
    CORRADE_VERIFY(!Context::current()->isExtensionDisabled<Extensions::GL::ARB::vertex_array_object>());

    /* This is disabled in GL < 3.2 to work around GLSL compiler bugs */
    CORRADE_VERIFY(Context::current()->isExtensionDisabled<Extensions::GL::ARB::explicit_attrib_location>(Version::GL310));
    CORRADE_VERIFY(!Context::current()->isExtensionDisabled<Extensions::GL::ARB::explicit_attrib_location>(Version::GL320));
    #else
    CORRADE_SKIP("No useful extensions to test on OpenGL ES");
    #endif
}

}}

MAGNUM_GL_TEST_MAIN(Magnum::Test::ContextGLTest)
<|endoftext|>


<commit_before><commit_msg>Planning: some minor bug fixes.<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2015 - 2018 gtalent2@gmail.com
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#pragma once

#include <ox/std/std.hpp>

namespace ox::ptrarith {

template<typename T, typename size_t, size_t minOffset = 1>
class Ptr {

	private:
		uint8_t *m_dataStart = nullptr;
		size_t m_itemOffset = 0;
		size_t m_itemSize = 0;
		// this should be removed later on, but the excessive validation is
		// desirable during during heavy development
		mutable uint8_t m_validated = false;

	public:
		inline Ptr() = default;

		inline Ptr(std::nullptr_t);

		inline Ptr(void *dataStart, size_t dataSize, size_t itemStart, size_t itemSize = sizeof(T));

		inline bool valid() const;

		inline size_t size() const;

		inline size_t offset() const;

		inline size_t end();

		inline const T *get() const;

		inline T *get();

		inline const T *operator->() const;

		inline T *operator->();

		inline operator const T*() const;

		inline operator T*();

		inline const T &operator*() const;

		inline T &operator*();

		inline operator size_t() const;

		inline bool operator==(const Ptr<T, size_t, minOffset> &other) const;

		inline bool operator!=(const Ptr<T, size_t, minOffset> &other) const;

		template<typename SubT>
		inline const Ptr<SubT, size_t, sizeof(T)> subPtr(size_t offset, size_t size) const;

		template<typename SubT>
		inline const Ptr<SubT, size_t, sizeof(T)> subPtr(size_t offset) const;

		template<typename SubT>
		inline Ptr<SubT, size_t, sizeof(T)> subPtr(size_t offset, size_t size);

		template<typename SubT>
		inline Ptr<SubT, size_t, sizeof(T)> subPtr(size_t offset);

};

template<typename T, typename size_t, size_t minOffset>
inline Ptr<T, size_t, minOffset>::Ptr(std::nullptr_t) {
}

template<typename T, typename size_t, size_t minOffset>
inline Ptr<T, size_t, minOffset>::Ptr(void *dataStart, size_t dataSize, size_t itemStart, size_t itemSize) {
	// do some sanity checks before assuming this is valid
	if (itemSize >= sizeof(T) and
	    dataStart and
	    itemStart >= minOffset and
	    itemStart + itemSize <= dataSize) {
		m_dataStart = reinterpret_cast<uint8_t*>(dataStart);
		m_itemOffset = itemStart;
		m_itemSize = itemSize;
	}
}

template<typename T, typename size_t, size_t minOffset>
inline bool Ptr<T, size_t, minOffset>::valid() const {
	m_validated = m_dataStart != nullptr;
	return m_validated;
}

template<typename T, typename size_t, size_t minOffset>
inline size_t Ptr<T, size_t, minOffset>::size() const {
	return m_itemSize;
}

template<typename T, typename size_t, size_t minOffset>
inline size_t Ptr<T, size_t, minOffset>::offset() const {
	return m_itemOffset;
}

template<typename T, typename size_t, size_t minOffset>
inline size_t Ptr<T, size_t, minOffset>::end() {
	return m_itemOffset + m_itemSize;
}

template<typename T, typename size_t, size_t minOffset>
inline const T *Ptr<T, size_t, minOffset>::get() const {
	oxAssert(m_validated, "Unvalidated pointer access. (ox::fs::Ptr::get())");
	oxAssert(valid(), "Invalid pointer access. (ox::fs::Ptr::get())");
	return reinterpret_cast<T*>(m_dataStart + m_itemOffset);
}

template<typename T, typename size_t, size_t minOffset>
inline T *Ptr<T, size_t, minOffset>::get() {
	oxAssert(m_validated, "Unvalidated pointer access. (ox::fs::Ptr::get())");
	oxAssert(valid(), "Invalid pointer access. (ox::fs::Ptr::get())");
	return reinterpret_cast<T*>(m_dataStart + m_itemOffset);
}

template<typename T, typename size_t, size_t minOffset>
inline const T *Ptr<T, size_t, minOffset>::operator->() const {
	oxAssert(m_validated, "Unvalidated pointer access. (ox::fs::Ptr::operator->())");
	oxAssert(valid(), "Invalid pointer access. (ox::fs::Ptr::operator->())");
	return reinterpret_cast<T*>(m_dataStart + m_itemOffset);
}

template<typename T, typename size_t, size_t minOffset>
inline T *Ptr<T, size_t, minOffset>::operator->() {
	oxAssert(m_validated, "Unvalidated pointer access. (ox::fs::Ptr::operator->())");
	oxAssert(valid(), "Invalid pointer access. (ox::fs::Ptr::operator->())");
	return reinterpret_cast<T*>(m_dataStart + m_itemOffset);
}

template<typename T, typename size_t, size_t minOffset>
inline Ptr<T, size_t, minOffset>::operator const T*() const {
	return reinterpret_cast<T*>(m_dataStart + m_itemOffset);
}

template<typename T, typename size_t, size_t minOffset>
inline Ptr<T, size_t, minOffset>::operator T*() {
	return reinterpret_cast<T*>(m_dataStart + m_itemOffset);
}

template<typename T, typename size_t, size_t minOffset>
inline const T &Ptr<T, size_t, minOffset>::operator*() const {
	oxAssert(m_validated, "Unvalidated pointer dereference. (ox::fs::Ptr::operator*())");
	oxAssert(valid(), "Invalid pointer dereference. (ox::fs::Ptr::operator*())");
	return *reinterpret_cast<T*>(this);
}

template<typename T, typename size_t, size_t minOffset>
inline T &Ptr<T, size_t, minOffset>::operator*() {
	oxAssert(m_validated, "Unvalidated pointer dereference. (ox::fs::Ptr::operator*())");
	oxAssert(valid(), "Invalid pointer dereference. (ox::fs::Ptr::operator*())");
	return *reinterpret_cast<T*>(this);
}

template<typename T, typename size_t, size_t minOffset>
inline Ptr<T, size_t, minOffset>::operator size_t() const {
	if (m_dataStart and m_itemOffset) {
		return m_itemOffset;
	}
	return 0;
}

template<typename T, typename size_t, size_t minOffset>
inline bool Ptr<T, size_t, minOffset>::operator==(const Ptr<T, size_t, minOffset> &other) const {
	return m_dataStart == other.m_dataStart &&
	       m_itemOffset == other.m_itemOffset &&
	       m_itemSize == other.m_itemSize;
}

template<typename T, typename size_t, size_t minOffset>
inline bool Ptr<T, size_t, minOffset>::operator!=(const Ptr<T, size_t, minOffset> &other) const {
	return m_dataStart != other.m_dataStart ||
	       m_itemOffset != other.m_itemOffset ||
	       m_itemSize != other.m_itemSize;
}

template<typename T, typename size_t, size_t minOffset>
template<typename SubT>
inline const Ptr<SubT, size_t, sizeof(T)> Ptr<T, size_t, minOffset>::subPtr(size_t offset, size_t size) const {
	auto out = Ptr<SubT, size_t, sizeof(T)>(get(), this->size(), offset, size);
	return out;
}

template<typename T, typename size_t, size_t minOffset>
template<typename SubT>
inline const Ptr<SubT, size_t, sizeof(T)> Ptr<T, size_t, minOffset>::subPtr(size_t offset) const {
	oxTrace("ox::fs::Ptr::subPtr") << m_itemOffset << this->size() << offset << m_itemSize << (m_itemSize - offset);
	return subPtr<SubT>(offset, m_itemSize - offset);
}

template<typename T, typename size_t, size_t minOffset>
template<typename SubT>
inline Ptr<SubT, size_t, sizeof(T)> Ptr<T, size_t, minOffset>::subPtr(size_t offset, size_t size) {
	auto out = Ptr<SubT, size_t, sizeof(T)>(get(), this->size(), offset, size);
	return out;
}

template<typename T, typename size_t, size_t minOffset>
template<typename SubT>
inline Ptr<SubT, size_t, sizeof(T)> Ptr<T, size_t, minOffset>::subPtr(size_t offset) {
	oxTrace("ox::fs::Ptr::subPtr") << m_itemOffset << this->size() << offset << m_itemSize << (m_itemSize - offset);
	return subPtr<SubT>(offset, m_itemSize - offset);
}

}
<commit_msg>[ox/buffer] Add to to Ptr<commit_after>/*
 * Copyright 2015 - 2018 gtalent2@gmail.com
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#pragma once

#include <ox/std/std.hpp>

namespace ox::ptrarith {

template<typename T, typename size_t, size_t minOffset = 1>
class Ptr {

	private:
		uint8_t *m_dataStart = nullptr;
		size_t m_dataSize = 0;
		size_t m_itemOffset = 0;
		size_t m_itemSize = 0;
		// this should be removed later on, but the excessive validation is
		// desirable during during heavy development
		mutable uint8_t m_validated = false;

	public:
		inline Ptr() = default;

		inline Ptr(std::nullptr_t);

		inline Ptr(void *dataStart, size_t dataSize, size_t itemStart, size_t itemSize = sizeof(T));

		inline bool valid() const;

		inline size_t size() const;

		inline size_t offset() const;

		inline size_t end();

		inline const T *get() const;

		inline T *get();

		inline const T *operator->() const;

		inline T *operator->();

		inline operator const T*() const;

		inline operator T*();

		inline const T &operator*() const;

		inline T &operator*();

		inline operator size_t() const;

		inline bool operator==(const Ptr<T, size_t, minOffset> &other) const;

		inline bool operator!=(const Ptr<T, size_t, minOffset> &other) const;

		template<typename SubT>
		inline const Ptr<SubT, size_t, sizeof(T)> subPtr(size_t offset, size_t size) const;

		template<typename SubT>
		inline const Ptr<SubT, size_t, sizeof(T)> subPtr(size_t offset) const;

		template<typename SubT>
		inline Ptr<SubT, size_t, sizeof(T)> subPtr(size_t offset, size_t size);

		template<typename SubT>
		inline Ptr<SubT, size_t, sizeof(T)> subPtr(size_t offset);

		template<typename SubT>
		inline const Ptr<SubT, size_t, minOffset> to() const;

};

template<typename T, typename size_t, size_t minOffset>
inline Ptr<T, size_t, minOffset>::Ptr(std::nullptr_t) {
}

template<typename T, typename size_t, size_t minOffset>
inline Ptr<T, size_t, minOffset>::Ptr(void *dataStart, size_t dataSize, size_t itemStart, size_t itemSize) {
	// do some sanity checks before assuming this is valid
	if (itemSize >= sizeof(T) and
	    dataStart and
	    itemStart >= minOffset and
	    itemStart + itemSize <= dataSize) {
		m_dataStart = reinterpret_cast<uint8_t*>(dataStart);
		m_dataSize = dataSize;
		m_itemOffset = itemStart;
		m_itemSize = itemSize;
	}
}

template<typename T, typename size_t, size_t minOffset>
inline bool Ptr<T, size_t, minOffset>::valid() const {
	m_validated = m_dataStart != nullptr;
	return m_validated;
}

template<typename T, typename size_t, size_t minOffset>
inline size_t Ptr<T, size_t, minOffset>::size() const {
	return m_itemSize;
}

template<typename T, typename size_t, size_t minOffset>
inline size_t Ptr<T, size_t, minOffset>::offset() const {
	return m_itemOffset;
}

template<typename T, typename size_t, size_t minOffset>
inline size_t Ptr<T, size_t, minOffset>::end() {
	return m_itemOffset + m_itemSize;
}

template<typename T, typename size_t, size_t minOffset>
inline const T *Ptr<T, size_t, minOffset>::get() const {
	oxAssert(m_validated, "Unvalidated pointer access. (ox::fs::Ptr::get())");
	oxAssert(valid(), "Invalid pointer access. (ox::fs::Ptr::get())");
	return reinterpret_cast<T*>(m_dataStart + m_itemOffset);
}

template<typename T, typename size_t, size_t minOffset>
inline T *Ptr<T, size_t, minOffset>::get() {
	oxAssert(m_validated, "Unvalidated pointer access. (ox::fs::Ptr::get())");
	oxAssert(valid(), "Invalid pointer access. (ox::fs::Ptr::get())");
	return reinterpret_cast<T*>(m_dataStart + m_itemOffset);
}

template<typename T, typename size_t, size_t minOffset>
inline const T *Ptr<T, size_t, minOffset>::operator->() const {
	oxAssert(m_validated, "Unvalidated pointer access. (ox::fs::Ptr::operator->())");
	oxAssert(valid(), "Invalid pointer access. (ox::fs::Ptr::operator->())");
	return reinterpret_cast<T*>(m_dataStart + m_itemOffset);
}

template<typename T, typename size_t, size_t minOffset>
inline T *Ptr<T, size_t, minOffset>::operator->() {
	oxAssert(m_validated, "Unvalidated pointer access. (ox::fs::Ptr::operator->())");
	oxAssert(valid(), "Invalid pointer access. (ox::fs::Ptr::operator->())");
	return reinterpret_cast<T*>(m_dataStart + m_itemOffset);
}

template<typename T, typename size_t, size_t minOffset>
inline Ptr<T, size_t, minOffset>::operator const T*() const {
	return reinterpret_cast<T*>(m_dataStart + m_itemOffset);
}

template<typename T, typename size_t, size_t minOffset>
inline Ptr<T, size_t, minOffset>::operator T*() {
	return reinterpret_cast<T*>(m_dataStart + m_itemOffset);
}

template<typename T, typename size_t, size_t minOffset>
inline const T &Ptr<T, size_t, minOffset>::operator*() const {
	oxAssert(m_validated, "Unvalidated pointer dereference. (ox::fs::Ptr::operator*())");
	oxAssert(valid(), "Invalid pointer dereference. (ox::fs::Ptr::operator*())");
	return *reinterpret_cast<T*>(this);
}

template<typename T, typename size_t, size_t minOffset>
inline T &Ptr<T, size_t, minOffset>::operator*() {
	oxAssert(m_validated, "Unvalidated pointer dereference. (ox::fs::Ptr::operator*())");
	oxAssert(valid(), "Invalid pointer dereference. (ox::fs::Ptr::operator*())");
	return *reinterpret_cast<T*>(this);
}

template<typename T, typename size_t, size_t minOffset>
inline Ptr<T, size_t, minOffset>::operator size_t() const {
	if (m_dataStart and m_itemOffset) {
		return m_itemOffset;
	}
	return 0;
}

template<typename T, typename size_t, size_t minOffset>
inline bool Ptr<T, size_t, minOffset>::operator==(const Ptr<T, size_t, minOffset> &other) const {
	return m_dataStart == other.m_dataStart &&
	       m_itemOffset == other.m_itemOffset &&
	       m_itemSize == other.m_itemSize;
}

template<typename T, typename size_t, size_t minOffset>
inline bool Ptr<T, size_t, minOffset>::operator!=(const Ptr<T, size_t, minOffset> &other) const {
	return m_dataStart != other.m_dataStart ||
	       m_itemOffset != other.m_itemOffset ||
	       m_itemSize != other.m_itemSize;
}

template<typename T, typename size_t, size_t minOffset>
template<typename SubT>
inline const Ptr<SubT, size_t, sizeof(T)> Ptr<T, size_t, minOffset>::subPtr(size_t offset, size_t size) const {
	return Ptr<SubT, size_t, sizeof(T)>(get(), this->size(), offset, size);
}

template<typename T, typename size_t, size_t minOffset>
template<typename SubT>
inline const Ptr<SubT, size_t, sizeof(T)> Ptr<T, size_t, minOffset>::subPtr(size_t offset) const {
	oxTrace("ox::fs::Ptr::subPtr") << m_itemOffset << this->size() << offset << m_itemSize << (m_itemSize - offset);
	return subPtr<SubT>(offset, m_itemSize - offset);
}

template<typename T, typename size_t, size_t minOffset>
template<typename SubT>
inline Ptr<SubT, size_t, sizeof(T)> Ptr<T, size_t, minOffset>::subPtr(size_t offset, size_t size) {
	return Ptr<SubT, size_t, sizeof(T)>(get(), this->size(), offset, size);
}

template<typename T, typename size_t, size_t minOffset>
template<typename SubT>
inline Ptr<SubT, size_t, sizeof(T)> Ptr<T, size_t, minOffset>::subPtr(size_t offset) {
	oxTrace("ox::fs::Ptr::subPtr") << m_itemOffset << this->size() << offset << m_itemSize << (m_itemSize - offset);
	return subPtr<SubT>(offset, m_itemSize - offset);
}

template<typename T, typename size_t, size_t minOffset>
template<typename SubT>
inline const Ptr<SubT, size_t, minOffset> Ptr<T, size_t, minOffset>::to() const {
	return Ptr<SubT, size_t, minOffset>(m_dataStart, m_dataSize, m_itemOffset, m_itemSize);
}

}
<|endoftext|>


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

#include "flutter/fml/file.h"

#include <Shlwapi.h>

#include <sstream>

#include "flutter/fml/platform/win/wstring_conversion.h"

namespace fml {

fml::UniqueFD OpenFile(const std::wstring& path,
                       OpenPermission permission,
                       bool is_directory) {
  if (path.size() == 0) {
    return fml::UniqueFD{};
  }

  DWORD desired_access = 0;

  switch (permission) {
    case OpenPermission::kRead:
      desired_access = GENERIC_READ;
      break;
    case OpenPermission::kWrite:
      desired_access = GENERIC_WRITE;
      break;
    case OpenPermission::kReadWrite:
      desired_access = GENERIC_WRITE | GENERIC_READ;
      break;
    case OpenPermission::kExecute:
      desired_access = GENERIC_READ | GENERIC_EXECUTE;
      break;
  }

  return fml::UniqueFD{::CreateFile(
      path.c_str(),           // lpFileName
      desired_access,         // dwDesiredAccess
      FILE_SHARE_READ,        // dwShareMode
      0,                      // lpSecurityAttributes
      OPEN_EXISTING,          // dwCreationDisposition
      FILE_ATTRIBUTE_NORMAL,  // dwFlagsAndAttributes
      0                       // hTemplateFile
      )};
}

fml::UniqueFD OpenFile(const char* path,
                       OpenPermission permission,
                       bool is_directory) {
  return OpenFile(ConvertToWString(path), permission, is_directory);
}

static std::wstring GetFullHandlePath(const fml::UniqueFD& handle) {
  wchar_t buffer[MAX_PATH];

  DWORD returned = ::GetFinalPathNameByHandle(handle.get(), buffer, MAX_PATH,
                                              FILE_NAME_NORMALIZED);
  if (returned == 0 || returned > MAX_PATH) {
    return {};
  }

  return {buffer};
}

fml::UniqueFD OpenFile(const fml::UniqueFD& base_directory,
                       const char* path,
                       OpenPermission permission,
                       bool is_directory) {
  // If the base directory is invalid or the path is absolute, use the generic
  // open file variant.
  if (!base_directory.is_valid()) {
    return OpenFile(path, permission, is_directory);
  }

  const auto wpath = ConvertToWString(path);

  if (!::PathIsRelative(wpath.c_str())) {
    return OpenFile(path, permission, is_directory);
  }

  std::wstringstream stream;
  stream << GetFullHandlePath(base_directory) << "\\" << path;
  return OpenFile(stream.str(), permission, is_directory);
}

fml::UniqueFD Duplicate(fml::UniqueFD::element_type descriptor) {
  if (descriptor == INVALID_HANDLE_VALUE) {
    return fml::UniqueFD{};
  }

  HANDLE duplicated = INVALID_HANDLE_VALUE;

  if (!::DuplicateHandle(
          GetCurrentProcess(),  // source process
          descriptor,           // source handle
          GetCurrentProcess(),  // target process
          &duplicated,          // target handle
          0,      // desired access (ignored because DUPLICATE_SAME_ACCESS)
          FALSE,  // inheritable
          DUPLICATE_SAME_ACCESS)  // options
  ) {
    return fml::UniqueFD{};
  }

  return fml::UniqueFD{duplicated};
}

bool IsDirectory(const fml::UniqueFD& directory) {
  BY_HANDLE_FILE_INFORMATION info;
  if (!::GetFileInformationByHandle(directory.get(), &info)) {
    return false;
  }
  return info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
}

}  // namespace fml
<commit_msg>Fix file flags for directories and backslashes on Windows. (#5387)<commit_after>// Copyright 2018 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "flutter/fml/file.h"

#include <Shlwapi.h>

#include <algorithm>
#include <sstream>

#include "flutter/fml/platform/win/wstring_conversion.h"

namespace fml {

static fml::UniqueFD OpenFile(std::wstring path,
                              OpenPermission permission,
                              bool is_directory) {
  if (path.size() == 0) {
    return fml::UniqueFD{};
  }

  DWORD desired_access = 0;

  switch (permission) {
    case OpenPermission::kRead:
      desired_access = GENERIC_READ;
      break;
    case OpenPermission::kWrite:
      desired_access = GENERIC_WRITE;
      break;
    case OpenPermission::kReadWrite:
      desired_access = GENERIC_WRITE | GENERIC_READ;
      break;
    case OpenPermission::kExecute:
      desired_access = GENERIC_READ | GENERIC_EXECUTE;
      break;
  }

  DWORD flags = FILE_ATTRIBUTE_NORMAL;

  if (is_directory) {
    flags |= FILE_FLAG_BACKUP_SEMANTICS;
  }

  std::replace(path.begin(), path.end(), '/', '\\');

  return fml::UniqueFD{::CreateFile(path.c_str(),     // lpFileName
                                    desired_access,   // dwDesiredAccess
                                    FILE_SHARE_READ,  // dwShareMode
                                    0,                // lpSecurityAttributes
                                    OPEN_EXISTING,    // dwCreationDisposition
                                    flags,            // dwFlagsAndAttributes
                                    0                 // hTemplateFile
                                    )};
}

fml::UniqueFD OpenFile(const char* path,
                       OpenPermission permission,
                       bool is_directory) {
  return OpenFile(ConvertToWString(path), permission, is_directory);
}

static std::wstring GetFullHandlePath(const fml::UniqueFD& handle) {
  wchar_t buffer[MAX_PATH];

  DWORD returned = ::GetFinalPathNameByHandle(handle.get(), buffer, MAX_PATH,
                                              FILE_NAME_NORMALIZED);
  if (returned == 0 || returned > MAX_PATH) {
    return {};
  }

  return {buffer};
}

fml::UniqueFD OpenFile(const fml::UniqueFD& base_directory,
                       const char* path,
                       OpenPermission permission,
                       bool is_directory) {
  // If the base directory is invalid or the path is absolute, use the generic
  // open file variant.
  if (!base_directory.is_valid()) {
    return OpenFile(path, permission, is_directory);
  }

  const auto wpath = ConvertToWString(path);

  if (!::PathIsRelative(wpath.c_str())) {
    return OpenFile(path, permission, is_directory);
  }

  std::wstringstream stream;
  stream << GetFullHandlePath(base_directory) << "\\" << path;
  return OpenFile(stream.str(), permission, is_directory);
}

fml::UniqueFD Duplicate(fml::UniqueFD::element_type descriptor) {
  if (descriptor == INVALID_HANDLE_VALUE) {
    return fml::UniqueFD{};
  }

  HANDLE duplicated = INVALID_HANDLE_VALUE;

  if (!::DuplicateHandle(
          GetCurrentProcess(),  // source process
          descriptor,           // source handle
          GetCurrentProcess(),  // target process
          &duplicated,          // target handle
          0,      // desired access (ignored because DUPLICATE_SAME_ACCESS)
          FALSE,  // inheritable
          DUPLICATE_SAME_ACCESS)  // options
  ) {
    return fml::UniqueFD{};
  }

  return fml::UniqueFD{duplicated};
}

bool IsDirectory(const fml::UniqueFD& directory) {
  BY_HANDLE_FILE_INFORMATION info;
  if (!::GetFileInformationByHandle(directory.get(), &info)) {
    return false;
  }
  return info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
}

}  // namespace fml
<|endoftext|>


<commit_before>//
//
// Description: This file is part of FET
//
//
// Author: Lalescu Liviu <Please see http://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)>
// Copyright (C) 2005 Liviu Lalescu <http://lalescu.ro/liviu/>
//
/***************************************************************************
 *                                                                         *
 *   This program is free software: you can redistribute it and/or modify  *
 *   it under the terms of the GNU Affero General Public License as        *
 *   published by the Free Software Foundation, either version 3 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 ***************************************************************************/

#include "timetable_defs.h"
#include "timetable.h"
#include "fet.h"
#include "activitytagsform.h"
#include "studentsset.h"
#include "teacher.h"
#include "subject.h"
#include "activitytag.h"

#include <QInputDialog>

#include <QMessageBox>

#include <QListWidget>
#include <QAbstractItemView>

#include <QSplitter>
#include <QSettings>
#include <QObject>
#include <QMetaObject>

extern const QString COMPANY;
extern const QString PROGRAM;

ActivityTagsForm::ActivityTagsForm(QWidget* parent): QDialog(parent)
{
	setupUi(this);

	currentActivityTagTextEdit->setReadOnly(true);

	renameActivityTagPushButton->setDefault(true);

	activityTagsListWidget->setSelectionMode(QAbstractItemView::SingleSelection);

	connect(closePushButton, SIGNAL(clicked()), this, SLOT(close()));
	connect(addActivityTagPushButton, SIGNAL(clicked()), this, SLOT(addActivityTag()));
	connect(removeActivityTagPushButton, SIGNAL(clicked()), this, SLOT(removeActivityTag()));
	connect(renameActivityTagPushButton, SIGNAL(clicked()), this, SLOT(renameActivityTag()));

	connect(moveActivityTagUpPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagUp()));
	connect(moveActivityTagDownPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagDown()));

	connect(sortActivityTagsPushButton, SIGNAL(clicked()), this, SLOT(sortActivityTags()));
	connect(activityTagsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(activityTagChanged(int)));
	connect(activateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(activateActivityTag()));
	connect(deactivateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(deactivateActivityTag()));
	connect(activityTagsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(renameActivityTag()));
	connect(helpPushButton, SIGNAL(clicked()), this, SLOT(help()));

	connect(printablePushButton, SIGNAL(clicked()), this, SLOT(printableActivityTag()));
	connect(notPrintablePushButton, SIGNAL(clicked()), this, SLOT(notPrintableActivityTag()));

	connect(commentsPushButton, SIGNAL(clicked()), this, SLOT(comments()));

	centerWidgetOnScreen(this);
	restoreFETDialogGeometry(this);
	//restore splitter state
	QSettings settings(COMPANY, PROGRAM);
	if(settings.contains(this->metaObject()->className()+QString("/splitter-state")))
		splitter->restoreState(settings.value(this->metaObject()->className()+QString("/splitter-state")).toByteArray());

	activityTagsListWidget->clear();
	for(int i=0; i<gt.rules.activityTagsList.size(); i++){
		ActivityTag* sbt=gt.rules.activityTagsList[i];
		activityTagsListWidget->addItem(sbt->name);
	}

	if(activityTagsListWidget->count()>0)
		activityTagsListWidget->setCurrentRow(0);
}

ActivityTagsForm::~ActivityTagsForm()
{
	saveFETDialogGeometry(this);
	//save splitter state
	QSettings settings(COMPANY, PROGRAM);
	settings.setValue(this->metaObject()->className()+QString("/splitter-state"), splitter->saveState());
}

void ActivityTagsForm::addActivityTag()
{
	bool ok = false;
	ActivityTag* sbt=new ActivityTag();
	sbt->name = QInputDialog::getText( this, tr("Add activity tag"), tr("Please enter activity tag's name") ,
	 QLineEdit::Normal, QString(), &ok );

	if ( ok && !((sbt->name).isEmpty()) ){
		// user entered something and pressed OK
		if(!gt.rules.addActivityTag(sbt)){
			QMessageBox::information( this, tr("Activity tag insertion dialog"),
				tr("Could not insert item. Must be a duplicate"));
			delete sbt;
		}
		else{
			activityTagsListWidget->addItem(sbt->name);
			activityTagsListWidget->setCurrentRow(activityTagsListWidget->count()-1);
		}
	}
	else{
		if(ok){ //the user entered nothing
			QMessageBox::information(this, tr("FET information"), tr("Incorrect name"));
		}
		delete sbt;// user entered nothing or pressed Cancel
	}
}

void ActivityTagsForm::removeActivityTag()
{
	int i=activityTagsListWidget->currentRow();
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();
	int activity_tag_ID=gt.rules.searchActivityTag(text);
	if(activity_tag_ID<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	if(QMessageBox::warning( this, tr("FET"),
		tr("Are you sure you want to delete this activity tag?"),
		tr("Yes"), tr("No"), 0, 0, 1 ) == 1)
		return;

	int tmp=gt.rules.removeActivityTag(text);
	if(tmp){
		activityTagsListWidget->setCurrentRow(-1);
		QListWidgetItem* item;
		item=activityTagsListWidget->takeItem(i);
		delete item;

		if(i>=activityTagsListWidget->count())
			i=activityTagsListWidget->count()-1;
		if(i>=0)
			activityTagsListWidget->setCurrentRow(i);
		else
			currentActivityTagTextEdit->setPlainText(QString(""));
	}
}

void ActivityTagsForm::renameActivityTag()
{
	int i=activityTagsListWidget->currentRow();
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString initialActivityTagName=activityTagsListWidget->currentItem()->text();

	int activity_tag_ID=gt.rules.searchActivityTag(initialActivityTagName);
	if(activity_tag_ID<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	bool ok = false;
	QString finalActivityTagName;
	finalActivityTagName = QInputDialog::getText( this, tr("Rename activity tag"), tr("Please enter new activity tag's name") ,
	 QLineEdit::Normal, initialActivityTagName, &ok );

	if ( ok && !(finalActivityTagName.isEmpty()) ){
		// user entered something and pressed OK
		if(gt.rules.searchActivityTag(finalActivityTagName)>=0){
			QMessageBox::information( this, tr("Activity tag insertion dialog"),
				tr("Could not modify item. New name must be a duplicate"));
		}
		else{
			gt.rules.modifyActivityTag(initialActivityTagName, finalActivityTagName);
			activityTagsListWidget->item(i)->setText(finalActivityTagName);
			activityTagChanged(activityTagsListWidget->currentRow());
		}
	}
}

void ActivityTagsForm::moveActivityTagUp()
{
	if(activityTagsListWidget->count()<=1)
		return;
	int i=activityTagsListWidget->currentRow();
	if(i<0 || i>=activityTagsListWidget->count())
		return;
	if(i==0)
		return;

	QString s1=activityTagsListWidget->item(i)->text();
	QString s2=activityTagsListWidget->item(i-1)->text();

	ActivityTag* at1=gt.rules.activityTagsList.at(i);
	ActivityTag* at2=gt.rules.activityTagsList.at(i-1);

	gt.rules.internalStructureComputed=false;
	setRulesModifiedAndOtherThings(&gt.rules);

	activityTagsListWidget->item(i)->setText(s2);
	activityTagsListWidget->item(i-1)->setText(s1);

	gt.rules.activityTagsList[i]=at2;
	gt.rules.activityTagsList[i-1]=at1;

	activityTagsListWidget->setCurrentRow(i-1);
	activityTagChanged(i-1);
}

void ActivityTagsForm::moveActivityTagDown()
{
	if(activityTagsListWidget->count()<=1)
		return;
	int i=activityTagsListWidget->currentRow();
	if(i<0 || i>=activityTagsListWidget->count())
		return;
	if(i==activityTagsListWidget->count()-1)
		return;

	QString s1=activityTagsListWidget->item(i)->text();
	QString s2=activityTagsListWidget->item(i+1)->text();

	ActivityTag* at1=gt.rules.activityTagsList.at(i);
	ActivityTag* at2=gt.rules.activityTagsList.at(i+1);

	gt.rules.internalStructureComputed=false;
	setRulesModifiedAndOtherThings(&gt.rules);

	activityTagsListWidget->item(i)->setText(s2);
	activityTagsListWidget->item(i+1)->setText(s1);

	gt.rules.activityTagsList[i]=at2;
	gt.rules.activityTagsList[i+1]=at1;

	activityTagsListWidget->setCurrentRow(i+1);
	activityTagChanged(i+1);
}

void ActivityTagsForm::sortActivityTags()
{
	gt.rules.sortActivityTagsAlphabetically();

	activityTagsListWidget->clear();
	for(int i=0; i<gt.rules.activityTagsList.size(); i++){
		ActivityTag* sbt=gt.rules.activityTagsList[i];
		activityTagsListWidget->addItem(sbt->name);
	}

	if(activityTagsListWidget->count()>0)
		activityTagsListWidget->setCurrentRow(0);
}

void ActivityTagsForm::activityTagChanged(int index)
{
	if(index<0){
		currentActivityTagTextEdit->setPlainText(QString(""));
		return;
	}

	ActivityTag* st=gt.rules.activityTagsList.at(index);
	assert(st);
	QString s=st->getDetailedDescriptionWithConstraints(gt.rules);
	currentActivityTagTextEdit->setPlainText(s);
}

void ActivityTagsForm::activateActivityTag()
{
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();
	int count=gt.rules.activateActivityTag(text);
	QMessageBox::information(this, tr("FET information"), tr("Activated a number of %1 activities").arg(count));
}

void ActivityTagsForm::deactivateActivityTag()
{
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();
	int count=gt.rules.deactivateActivityTag(text);
	QMessageBox::information(this, tr("FET information"), tr("De-activated a number of %1 activities").arg(count));
}

void ActivityTagsForm::printableActivityTag()
{
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();

	gt.rules.makeActivityTagPrintable(text);

	activityTagChanged(activityTagsListWidget->currentRow());
}

void ActivityTagsForm::notPrintableActivityTag()
{
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();

	gt.rules.makeActivityTagNotPrintable(text);

	activityTagChanged(activityTagsListWidget->currentRow());
}

void ActivityTagsForm::help()
{
	QMessageBox::information(this, tr("FET help on activity tags"),
	 tr("Activity tag is a field which can be used or not, depending on your wish (optional field)."
	 " It is designed to help you with some constraints. Each activity has a possible empty list of activity tags"
	 " (if you don't use activity tags, the list will be empty)"));
}

void ActivityTagsForm::comments()
{
	int ind=activityTagsListWidget->currentRow();
	if(ind<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	ActivityTag* at=gt.rules.activityTagsList[ind];
	assert(at!=NULL);

	QDialog getCommentsDialog(this);

	getCommentsDialog.setWindowTitle(tr("Activity tag comments"));

	QPushButton* okPB=new QPushButton(tr("OK"));
	okPB->setDefault(true);
	QPushButton* cancelPB=new QPushButton(tr("Cancel"));

	connect(okPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(accept()));
	connect(cancelPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(reject()));

	QHBoxLayout* hl=new QHBoxLayout();
	hl->addStretch();
	hl->addWidget(okPB);
	hl->addWidget(cancelPB);

	QVBoxLayout* vl=new QVBoxLayout();

	QPlainTextEdit* commentsPT=new QPlainTextEdit();
	commentsPT->setPlainText(at->comments);
	commentsPT->selectAll();
	commentsPT->setFocus();

	vl->addWidget(commentsPT);
	vl->addLayout(hl);

	getCommentsDialog.setLayout(vl);

	const QString settingsName=QString("ActivityTagCommentsDialog");

	getCommentsDialog.resize(500, 320);
	centerWidgetOnScreen(&getCommentsDialog);
	restoreFETDialogGeometry(&getCommentsDialog, settingsName);

	int t=getCommentsDialog.exec();
	saveFETDialogGeometry(&getCommentsDialog, settingsName);

	if(t==QDialog::Accepted){
		at->comments=commentsPT->toPlainText();

		gt.rules.internalStructureComputed=false;
		setRulesModifiedAndOtherThings(&gt.rules);

		activityTagChanged(ind);
	}
}

<commit_msg>remove empty line<commit_after>//
//
// Description: This file is part of FET
//
//
// Author: Lalescu Liviu <Please see http://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)>
// Copyright (C) 2005 Liviu Lalescu <http://lalescu.ro/liviu/>
//
/***************************************************************************
 *                                                                         *
 *   This program is free software: you can redistribute it and/or modify  *
 *   it under the terms of the GNU Affero General Public License as        *
 *   published by the Free Software Foundation, either version 3 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 ***************************************************************************/

#include "timetable_defs.h"
#include "timetable.h"
#include "fet.h"
#include "activitytagsform.h"
#include "studentsset.h"
#include "teacher.h"
#include "subject.h"
#include "activitytag.h"

#include <QInputDialog>

#include <QMessageBox>

#include <QListWidget>
#include <QAbstractItemView>

#include <QSplitter>
#include <QSettings>
#include <QObject>
#include <QMetaObject>

extern const QString COMPANY;
extern const QString PROGRAM;

ActivityTagsForm::ActivityTagsForm(QWidget* parent): QDialog(parent)
{
	setupUi(this);

	currentActivityTagTextEdit->setReadOnly(true);

	renameActivityTagPushButton->setDefault(true);

	activityTagsListWidget->setSelectionMode(QAbstractItemView::SingleSelection);

	connect(closePushButton, SIGNAL(clicked()), this, SLOT(close()));
	connect(addActivityTagPushButton, SIGNAL(clicked()), this, SLOT(addActivityTag()));
	connect(removeActivityTagPushButton, SIGNAL(clicked()), this, SLOT(removeActivityTag()));
	connect(renameActivityTagPushButton, SIGNAL(clicked()), this, SLOT(renameActivityTag()));

	connect(moveActivityTagUpPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagUp()));
	connect(moveActivityTagDownPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagDown()));

	connect(sortActivityTagsPushButton, SIGNAL(clicked()), this, SLOT(sortActivityTags()));
	connect(activityTagsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(activityTagChanged(int)));
	connect(activateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(activateActivityTag()));
	connect(deactivateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(deactivateActivityTag()));
	connect(activityTagsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(renameActivityTag()));
	connect(helpPushButton, SIGNAL(clicked()), this, SLOT(help()));

	connect(printablePushButton, SIGNAL(clicked()), this, SLOT(printableActivityTag()));
	connect(notPrintablePushButton, SIGNAL(clicked()), this, SLOT(notPrintableActivityTag()));

	connect(commentsPushButton, SIGNAL(clicked()), this, SLOT(comments()));

	centerWidgetOnScreen(this);
	restoreFETDialogGeometry(this);
	//restore splitter state
	QSettings settings(COMPANY, PROGRAM);
	if(settings.contains(this->metaObject()->className()+QString("/splitter-state")))
		splitter->restoreState(settings.value(this->metaObject()->className()+QString("/splitter-state")).toByteArray());

	activityTagsListWidget->clear();
	for(int i=0; i<gt.rules.activityTagsList.size(); i++){
		ActivityTag* sbt=gt.rules.activityTagsList[i];
		activityTagsListWidget->addItem(sbt->name);
	}

	if(activityTagsListWidget->count()>0)
		activityTagsListWidget->setCurrentRow(0);
}

ActivityTagsForm::~ActivityTagsForm()
{
	saveFETDialogGeometry(this);
	//save splitter state
	QSettings settings(COMPANY, PROGRAM);
	settings.setValue(this->metaObject()->className()+QString("/splitter-state"), splitter->saveState());
}

void ActivityTagsForm::addActivityTag()
{
	bool ok = false;
	ActivityTag* sbt=new ActivityTag();
	sbt->name = QInputDialog::getText( this, tr("Add activity tag"), tr("Please enter activity tag's name") ,
	 QLineEdit::Normal, QString(), &ok );

	if ( ok && !((sbt->name).isEmpty()) ){
		// user entered something and pressed OK
		if(!gt.rules.addActivityTag(sbt)){
			QMessageBox::information( this, tr("Activity tag insertion dialog"),
				tr("Could not insert item. Must be a duplicate"));
			delete sbt;
		}
		else{
			activityTagsListWidget->addItem(sbt->name);
			activityTagsListWidget->setCurrentRow(activityTagsListWidget->count()-1);
		}
	}
	else{
		if(ok){ //the user entered nothing
			QMessageBox::information(this, tr("FET information"), tr("Incorrect name"));
		}
		delete sbt;// user entered nothing or pressed Cancel
	}
}

void ActivityTagsForm::removeActivityTag()
{
	int i=activityTagsListWidget->currentRow();
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();
	int activity_tag_ID=gt.rules.searchActivityTag(text);
	if(activity_tag_ID<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	if(QMessageBox::warning( this, tr("FET"),
		tr("Are you sure you want to delete this activity tag?"),
		tr("Yes"), tr("No"), 0, 0, 1 ) == 1)
		return;

	int tmp=gt.rules.removeActivityTag(text);
	if(tmp){
		activityTagsListWidget->setCurrentRow(-1);
		QListWidgetItem* item;
		item=activityTagsListWidget->takeItem(i);
		delete item;

		if(i>=activityTagsListWidget->count())
			i=activityTagsListWidget->count()-1;
		if(i>=0)
			activityTagsListWidget->setCurrentRow(i);
		else
			currentActivityTagTextEdit->setPlainText(QString(""));
	}
}

void ActivityTagsForm::renameActivityTag()
{
	int i=activityTagsListWidget->currentRow();
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString initialActivityTagName=activityTagsListWidget->currentItem()->text();

	int activity_tag_ID=gt.rules.searchActivityTag(initialActivityTagName);
	if(activity_tag_ID<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	bool ok = false;
	QString finalActivityTagName;
	finalActivityTagName = QInputDialog::getText( this, tr("Rename activity tag"), tr("Please enter new activity tag's name") ,
	 QLineEdit::Normal, initialActivityTagName, &ok );

	if ( ok && !(finalActivityTagName.isEmpty()) ){
		// user entered something and pressed OK
		if(gt.rules.searchActivityTag(finalActivityTagName)>=0){
			QMessageBox::information( this, tr("Activity tag insertion dialog"),
				tr("Could not modify item. New name must be a duplicate"));
		}
		else{
			gt.rules.modifyActivityTag(initialActivityTagName, finalActivityTagName);
			activityTagsListWidget->item(i)->setText(finalActivityTagName);
			activityTagChanged(activityTagsListWidget->currentRow());
		}
	}
}

void ActivityTagsForm::moveActivityTagUp()
{
	if(activityTagsListWidget->count()<=1)
		return;
	int i=activityTagsListWidget->currentRow();
	if(i<0 || i>=activityTagsListWidget->count())
		return;
	if(i==0)
		return;

	QString s1=activityTagsListWidget->item(i)->text();
	QString s2=activityTagsListWidget->item(i-1)->text();

	ActivityTag* at1=gt.rules.activityTagsList.at(i);
	ActivityTag* at2=gt.rules.activityTagsList.at(i-1);

	gt.rules.internalStructureComputed=false;
	setRulesModifiedAndOtherThings(&gt.rules);

	activityTagsListWidget->item(i)->setText(s2);
	activityTagsListWidget->item(i-1)->setText(s1);

	gt.rules.activityTagsList[i]=at2;
	gt.rules.activityTagsList[i-1]=at1;

	activityTagsListWidget->setCurrentRow(i-1);
	activityTagChanged(i-1);
}

void ActivityTagsForm::moveActivityTagDown()
{
	if(activityTagsListWidget->count()<=1)
		return;
	int i=activityTagsListWidget->currentRow();
	if(i<0 || i>=activityTagsListWidget->count())
		return;
	if(i==activityTagsListWidget->count()-1)
		return;

	QString s1=activityTagsListWidget->item(i)->text();
	QString s2=activityTagsListWidget->item(i+1)->text();

	ActivityTag* at1=gt.rules.activityTagsList.at(i);
	ActivityTag* at2=gt.rules.activityTagsList.at(i+1);

	gt.rules.internalStructureComputed=false;
	setRulesModifiedAndOtherThings(&gt.rules);

	activityTagsListWidget->item(i)->setText(s2);
	activityTagsListWidget->item(i+1)->setText(s1);

	gt.rules.activityTagsList[i]=at2;
	gt.rules.activityTagsList[i+1]=at1;

	activityTagsListWidget->setCurrentRow(i+1);
	activityTagChanged(i+1);
}

void ActivityTagsForm::sortActivityTags()
{
	gt.rules.sortActivityTagsAlphabetically();

	activityTagsListWidget->clear();
	for(int i=0; i<gt.rules.activityTagsList.size(); i++){
		ActivityTag* sbt=gt.rules.activityTagsList[i];
		activityTagsListWidget->addItem(sbt->name);
	}

	if(activityTagsListWidget->count()>0)
		activityTagsListWidget->setCurrentRow(0);
}

void ActivityTagsForm::activityTagChanged(int index)
{
	if(index<0){
		currentActivityTagTextEdit->setPlainText(QString(""));
		return;
	}

	ActivityTag* st=gt.rules.activityTagsList.at(index);
	assert(st);
	QString s=st->getDetailedDescriptionWithConstraints(gt.rules);
	currentActivityTagTextEdit->setPlainText(s);
}

void ActivityTagsForm::activateActivityTag()
{
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();
	int count=gt.rules.activateActivityTag(text);
	QMessageBox::information(this, tr("FET information"), tr("Activated a number of %1 activities").arg(count));
}

void ActivityTagsForm::deactivateActivityTag()
{
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();
	int count=gt.rules.deactivateActivityTag(text);
	QMessageBox::information(this, tr("FET information"), tr("De-activated a number of %1 activities").arg(count));
}

void ActivityTagsForm::printableActivityTag()
{
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();

	gt.rules.makeActivityTagPrintable(text);

	activityTagChanged(activityTagsListWidget->currentRow());
}

void ActivityTagsForm::notPrintableActivityTag()
{
	if(activityTagsListWidget->currentRow()<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	QString text=activityTagsListWidget->currentItem()->text();

	gt.rules.makeActivityTagNotPrintable(text);

	activityTagChanged(activityTagsListWidget->currentRow());
}

void ActivityTagsForm::help()
{
	QMessageBox::information(this, tr("FET help on activity tags"),
	 tr("Activity tag is a field which can be used or not, depending on your wish (optional field)."
	 " It is designed to help you with some constraints. Each activity has a possible empty list of activity tags"
	 " (if you don't use activity tags, the list will be empty)"));
}

void ActivityTagsForm::comments()
{
	int ind=activityTagsListWidget->currentRow();
	if(ind<0){
		QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
		return;
	}

	ActivityTag* at=gt.rules.activityTagsList[ind];
	assert(at!=NULL);

	QDialog getCommentsDialog(this);

	getCommentsDialog.setWindowTitle(tr("Activity tag comments"));

	QPushButton* okPB=new QPushButton(tr("OK"));
	okPB->setDefault(true);
	QPushButton* cancelPB=new QPushButton(tr("Cancel"));

	connect(okPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(accept()));
	connect(cancelPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(reject()));

	QHBoxLayout* hl=new QHBoxLayout();
	hl->addStretch();
	hl->addWidget(okPB);
	hl->addWidget(cancelPB);

	QVBoxLayout* vl=new QVBoxLayout();

	QPlainTextEdit* commentsPT=new QPlainTextEdit();
	commentsPT->setPlainText(at->comments);
	commentsPT->selectAll();
	commentsPT->setFocus();

	vl->addWidget(commentsPT);
	vl->addLayout(hl);

	getCommentsDialog.setLayout(vl);

	const QString settingsName=QString("ActivityTagCommentsDialog");

	getCommentsDialog.resize(500, 320);
	centerWidgetOnScreen(&getCommentsDialog);
	restoreFETDialogGeometry(&getCommentsDialog, settingsName);

	int t=getCommentsDialog.exec();
	saveFETDialogGeometry(&getCommentsDialog, settingsName);

	if(t==QDialog::Accepted){
		at->comments=commentsPT->toPlainText();

		gt.rules.internalStructureComputed=false;
		setRulesModifiedAndOtherThings(&gt.rules);

		activityTagChanged(ind);
	}
}
<|endoftext|>


<commit_before>//IBM_PROLOG_BEGIN_TAG
//IBM_PROLOG_END_TAG

//--------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------
#include <Instruction.H>

#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <iomanip>

#ifdef OTHER_USE
#include <OutputLite.H>
extern OutputLite out;
#else
#include <CronusData.H>
#endif

std::string InstructionTypeToString(Instruction::InstructionType i_type) {
  switch (i_type) {
    case Instruction::NOINSTRUCTION:
      return "NOINSTRUCTION";
    case Instruction::FSI:
      return "FSI";
    case Instruction::JTAG:
      return "JTAG";
    case Instruction::MULTIPLEJTAG:
      return "MULTIPLEJTAG";
    case Instruction::PSI:
      return "PSI";
    case Instruction::GPIO:
      return "GPIO";
    case Instruction::I2C:
      return "I2C";
    case Instruction::VPD:
      return "VPD";
    case Instruction::DMA:
      return "DMA";
    case Instruction::CONTROL:
      return "CONTROL";
    case Instruction::DMAEXER:
      return "DMAEXER";
    case Instruction::POWR:
      return "POWR";
    case Instruction::FSISTREAM:
      return "FSISTREAM";
    case Instruction::SBEFIFO:
      return "SBEFIFO";
    case Instruction::GSD2PIB:
      return "GSD2PIB";
    case Instruction::FSIMEMPROC:
      return "FSIMEMPROC";
    case Instruction::PNOR:
      return "PNOR";
  }
  return "";
}

std::string InstructionCommandToString(Instruction::InstructionCommand i_command) {
  switch (i_command) {
    case Instruction::NOCOMMAND:
      return "NOCOMMAND";
    case Instruction::SENDCMD:
      return "SENDCMD";
    case Instruction::READ:
      return "READ";
    case Instruction::WRITE:
      return "WRITE";
    case Instruction::LONGIN:
      return "LONGIN";
    case Instruction::LONGOUT:
      return "LONGOUT";
    case Instruction::READ_WRITE:
      return "READ_WRITE";
    case Instruction::SHIFTOUT:
      return "SHIFTOUT";
    case Instruction::DMAIN:
      return "DMAIN";
    case Instruction::DMAOUT:
      return "DMAOUT";
    case Instruction::MISC:
      return "MISC";
    case Instruction::TOTAP:
      return "TOTAP";
    case Instruction::READVPD:
      return "READVPD";
    case Instruction::READSPMEM:
      return "READSPMEM";
    case Instruction::WRITESPMEM:
      return "WRITESPMEM";
    case Instruction::SCOMIN:
      return "SCOMIN";
    case Instruction::SCOMOUT:
      return "SCOMOUT";
    case Instruction::WRITEVPD:
      return "WRITEVPD";
    case Instruction::PSI_RESET:
      return "PSI_RESET";
    case Instruction::PSI_LINK_CALIB:
      return "PSI_LINK_CALIB";
    case Instruction::PSI_EI_REG_READ:
      return "PSI_EI_REG_READ";
    case Instruction::PSI_EI_REG_WRITE:
      return "PSI_EI_REG_WRITE";
    case Instruction::PSI_VERIFY:
      return "PSI_VERIFY";
    case Instruction::PSI_SCOM_READ:
      return "PSI_SCOM_READ";
    case Instruction::PSI_SCOM_WRITE:
      return "PSI_SCOM_WRITE";
    case Instruction::PSI_READ:
      return "PSI_READ";
    case Instruction::PSI_WRITE:
      return "PSI_WRITE";
    case Instruction::PSI_INIT:
      return "PSI_INIT";
    case Instruction::PSI_LINK_ENABLE:
      return "PSI_LINK_ENABLE";
    case Instruction::PSI_SET_SPEED:
      return "PSI_SET_SPEED";
    case Instruction::PSI_LINK_VERIFY:
      return "PSI_LINK_VERIFY";
    case Instruction::I2CWRITE:
      return "I2CWRITE";
    case Instruction::I2CREAD:
      return "I2CREAD";
    case Instruction::GPIO_CONFIGPIN:
      return "GPIO_CONFIGPIN";
    case Instruction::GPIO_READPIN:
      return "GPIO_READPIN";
    case Instruction::GPIO_READPINS:
      return "GPIO_READPINS";
    case Instruction::GPIO_READLATCH:
      return "GPIO_READLATCH";
    case Instruction::GPIO_WRITELATCH:
      return "GPIO_WRITELATCH";
    case Instruction::GPIO_WRITELATCHES:
      return "GPIO_WRITELATCHES";
    case Instruction::GPIO_READCONFIG:
      return "GPIO_READCONFIG";
    case Instruction::GPIO_WRITECONFIG:
      return "GPIO_WRITECONFIG";
    case Instruction::GPIO_WRITECNFGSET:
      return "GPIO_WRITECNFGSET";
    case Instruction::GPIO_WRITECNFGCLR:
      return "GPIO_WRITECNFGCLR";
    case Instruction::DMAEXER_START:
      return "DMAEXER_START";
    case Instruction::DMAEXER_REPORT:
      return "DMAEXER_REPORT";
    case Instruction::DMAEXER_STOP:
      return "DMAEXER_STOP";
    case Instruction::INFO:
      return "INFO";
    case Instruction::RUN_CMD:
      return "RUN_CMD";
    case Instruction::MULTI_ENABLE:
      return "MULTI_ENABLE";
    case Instruction::AUTH:
      return "AUTH";
    case Instruction::ADDAUTH:
      return "ADDAUTH";
    case Instruction::CLEARAUTH:
      return "CLEARAUTH";
    case Instruction::VERSION:
      return "VERSION";
    case Instruction::FLIGHTRECORDER:
      return "FLIGHTRECORDER";
    case Instruction::EXIT:
      return "EXIT";
    case Instruction::SCOMIN_MASK:
      return "SCOMIN_MASK";
    case Instruction::MASK_PERSISTENT:
      return "MASK_PERSISTENT";
    case Instruction::SET_PERSISTENT:
      return "SET_PERSISTENT";
    case Instruction::GET_PERSISTENT:
      return "GET_PERSISTENT";
    case Instruction::READKEYWORD:
      return "READKEYWORD";
    case Instruction::WRITEKEYWORD:
      return "WRITEKEYWORD";
    case Instruction::FRUSTATUS:
      return "FRUSTATUS";
    case Instruction::CHICDOIPL:
      return "CHICDOIPL";
    case Instruction::ENABLE_MEM_VOLTAGES:
      return "ENABLE_MEM_VOLTAGES";
    case Instruction::DISABLE_MEM_VOLTAGES:
      return "DISABLE_MEM_VOLTAGES";
    case Instruction::SNDISTEPMSG:
      return "SNDISTEPMSG";
    case Instruction::MBXTRACEENABLE:
      return "MBXTRACEENABLE";
    case Instruction::MBXTRACEDISABLE:
      return "MBXTRACEDISABLE";
    case Instruction::MBXTRACEREAD:
      return "MBXTRACEREAD";
    case Instruction::PUTMEMPBA:
      return "PUTMEMPBA";
    case Instruction::GETMEMPBA:
      return "GETMEMPBA";
    case Instruction::BULK_SCOMIN:
      return "BULK_SCOMIN";
    case Instruction::BULK_SCOMOUT:
      return "BULK_SCOMOUT";
    case Instruction::STREAM_SETUP:
      return "STREAM_SETUP";
    case Instruction::STREAM_FINISH:
      return "STREAM_FINISH";
    case Instruction::FSPDMAIN:
      return "FSPDMAIN";
    case Instruction::FSPDMAOUT:
      return "FSPDMAOUT";
    case Instruction::SUBMIT:
      return "SUBMIT";
    case Instruction::REQUEST_RESET:
      return "REQUEST_RESET";
    case Instruction::SEND_TAPI_CMD:
      return "SEND_TAPI_CMD";
    case Instruction::PUTMEMPROC:
      return "PUTMEMPROC";
    case Instruction::GETMEMPROC:
      return "GETMEMPROC";
    case Instruction::PNORGETLIST:
      return "PNORGETLIST";
    case Instruction::PNORGET:
      return "PNORGET";
    case Instruction::PNORPUT:
      return "PNORPUT";
    case Instruction::QUERYSP:
      return "QUERYSP";
  }
  return "";
}

/*****************************************************************************/
/* Instruction Implementation ************************************************/
/*****************************************************************************/
Instruction::Instruction(void) : version(0x1), command(NOCOMMAND), type(NOINSTRUCTION), error(0){
}

/* for all of these methods check if we are of a different type */
uint32_t Instruction::execute(ecmdDataBuffer & o_data, InstructionStatus & o_status, Handle ** io_handle) {
  uint32_t rc = 0;

  /* set the version of this instruction in the status */
  o_status.instructionVersion = version;

  o_status.errorMessage.append("Instruction::execute Unknown Instruction specified. New FSP server may be required.");
  o_status.rc = SERVER_UNKNOWN_INSTRUCTION;

  return rc;
}

uint32_t Instruction::decrementVersion(void) {
  if (version > 0x1) {
    version--;
    return 0;
  }
  // return an error if we can not decrement
  return 1;
}

uint32_t Instruction::flatten(uint8_t * o_data, uint32_t i_len) const {
  uint32_t rc = 0;

  uint32_t * o_ptr = (uint32_t *) o_data;
  if (i_len < flattenSize()) {
    out.error("Instruction::flatten", "i_len %d bytes is too small to flatten\n", i_len);
    rc = 1;
  } else {
    // clear memory
    memset(o_data, 0, flattenSize());
    o_ptr[0] = htonl(version);
    o_ptr[1] = htonl(command);
    o_ptr[2] = htonl(flags);
  }

  return rc;
}

uint32_t Instruction::unflatten(const uint8_t * i_data, uint32_t i_len) {
  uint32_t rc = 0;

  uint32_t * i_ptr = (uint32_t *) i_data;
  version = ntohl(i_ptr[0]);
  if(version == 0x1) {
    command = (InstructionCommand) ntohl(i_ptr[1]);
    flags = ntohl(i_ptr[2]);
  } else {
    error = rc = SERVER_UNKNOWN_INSTRUCTION_VERSION;
  }

  return rc;
}

uint32_t Instruction::flattenSize(void) const {
  return (3 * sizeof(uint32_t));
}

std::string Instruction::dumpInstruction(void) const {
  std::ostringstream oss;

  oss << "Instruction" << std::endl;

  return oss.str();
}

uint64_t Instruction::getHash(void) const {
  return ((0x0000000F & type) << 28);
}

uint32_t Instruction::closeHandle(Handle ** i_handle) {
  uint32_t rc = 0;

  *i_handle = NULL;

  return rc;
}

std::string Instruction::getInstructionVars(const InstructionStatus & i_status) const {
  std::ostringstream oss;

  oss << std::hex << std::setfill('0');
  oss << "rc: " << std::setw(8) << i_status.rc;

  return oss.str();
}

Instruction::InstructionType Instruction::getType(void) const { return type; }
Instruction::InstructionCommand Instruction::getCommand(void) const { return command; }
uint32_t Instruction::getFlags(void) const { return flags; }
uint32_t Instruction::getVersion(void) const { return version; }

int Instruction::genWords(const ecmdDataBuffer &data, std::string &words) const {
  // copied from Debug.C
  int rc = 0;

  if (data.getBitLength() == 0) {
    words = "";  // This will kill the genHexLeftStr error if we have no data
  } else if (data.getBitLength() <= 128) {
    words = data.genHexLeftStr(0, data.getBitLength());
  } else {
    words = data.genHexLeftStr(0, 128);
  }

  return rc;
}

std::ostream& operator<<(std::ostream& io_stream, const Instruction& i_instruction ) {
  io_stream << i_instruction.dumpInstruction() << std::endl;
  return io_stream;
}

uint32_t devicestring_genhash(const std::string & i_string, uint32_t & o_hash)
{
    int length = i_string.length();
    const char * data = i_string.c_str();
    int found = 0;
    int type = 0;       // 3 bits
    int fsi = 0;        // 6 bits
    int cfam = 0;       // 2 bits
    int engine = 0;     // 5 bits
    int subfsi = 0;     // 3 bits
    int subcfam = 0;    // 2 bits
    int subengine = 0;  // 5 bits
    int subsubfsi = 0;  // 3 bits
    int subsubcfam = 0; // 2 bits
    o_hash = 0x0;
    if (length == 5)
    {
        type = 1;
        found = sscanf(data, "L%02dC%d", &fsi, &cfam);
        if (found != 2)
        {
            //std::cout << "ERROR reading data from " << i_string << std::endl;
            return 1;
        }
    }
    else if (length == 13)
    {
        type = 2;
        found = sscanf(data, "L%02dC%dE%02d:L%dC%d", &fsi, &cfam, &engine, &subfsi, &subcfam);
        if (found != 5)
        {
            //std::cout << "ERROR reading data from " << i_string << std::endl;
            return 2;
        }
    }
    else if (length == 21)
    {
        type = 3;
        found = sscanf(data, "L%02dC%dE%02d:L%dC%dE%02d:L%dC%d", &fsi, &cfam, &engine, &subfsi, &subcfam,
                       &subengine, &subsubfsi, &subsubcfam);
        if (found != 8)
        {
            //std::cout << "ERROR reading data from " << i_string << std::endl;
            return 3;
        }
    }
    else
    {
        // error
        //std::cout << "ERROR unknown format for device " << i_string << std::endl;
        return 4;
    }
    o_hash |= ((0x07 & type)    << 0);      //0x00000007
    o_hash |= ((0x3F & fsi)     << 3);      //0x000001F8
    o_hash |= ((0x03 & cfam)    << 9);      //0x00000600
    o_hash |= ((0x1F & engine)  << 11);     //0x0000F800
    o_hash |= ((0x07 & subfsi)  << 16);     //0x00070000
    o_hash |= ((0x03 & subcfam)     << 19); //0x00180000
    o_hash |= ((0x1F & subengine)   << 21); //0x03E00000
    o_hash |= ((0x07 & subsubfsi)   << 26); //0x1C000000
    o_hash |= ((0x03 & subsubcfam)  << 29); //0x60000000
    return 0;
}
<commit_msg>fix hash generation for bmc device strings<commit_after>//IBM_PROLOG_BEGIN_TAG
//IBM_PROLOG_END_TAG

//--------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------
#include <Instruction.H>

#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <iomanip>
#include <errno.h>
#include <limits.h>
#include <iostream>

#ifdef OTHER_USE
#include <OutputLite.H>
extern OutputLite out;
#else
#include <CronusData.H>
#endif

std::string InstructionTypeToString(Instruction::InstructionType i_type) {
  switch (i_type) {
    case Instruction::NOINSTRUCTION:
      return "NOINSTRUCTION";
    case Instruction::FSI:
      return "FSI";
    case Instruction::JTAG:
      return "JTAG";
    case Instruction::MULTIPLEJTAG:
      return "MULTIPLEJTAG";
    case Instruction::PSI:
      return "PSI";
    case Instruction::GPIO:
      return "GPIO";
    case Instruction::I2C:
      return "I2C";
    case Instruction::VPD:
      return "VPD";
    case Instruction::DMA:
      return "DMA";
    case Instruction::CONTROL:
      return "CONTROL";
    case Instruction::DMAEXER:
      return "DMAEXER";
    case Instruction::POWR:
      return "POWR";
    case Instruction::FSISTREAM:
      return "FSISTREAM";
    case Instruction::SBEFIFO:
      return "SBEFIFO";
    case Instruction::GSD2PIB:
      return "GSD2PIB";
    case Instruction::FSIMEMPROC:
      return "FSIMEMPROC";
    case Instruction::PNOR:
      return "PNOR";
  }
  return "";
}

std::string InstructionCommandToString(Instruction::InstructionCommand i_command) {
  switch (i_command) {
    case Instruction::NOCOMMAND:
      return "NOCOMMAND";
    case Instruction::SENDCMD:
      return "SENDCMD";
    case Instruction::READ:
      return "READ";
    case Instruction::WRITE:
      return "WRITE";
    case Instruction::LONGIN:
      return "LONGIN";
    case Instruction::LONGOUT:
      return "LONGOUT";
    case Instruction::READ_WRITE:
      return "READ_WRITE";
    case Instruction::SHIFTOUT:
      return "SHIFTOUT";
    case Instruction::DMAIN:
      return "DMAIN";
    case Instruction::DMAOUT:
      return "DMAOUT";
    case Instruction::MISC:
      return "MISC";
    case Instruction::TOTAP:
      return "TOTAP";
    case Instruction::READVPD:
      return "READVPD";
    case Instruction::READSPMEM:
      return "READSPMEM";
    case Instruction::WRITESPMEM:
      return "WRITESPMEM";
    case Instruction::SCOMIN:
      return "SCOMIN";
    case Instruction::SCOMOUT:
      return "SCOMOUT";
    case Instruction::WRITEVPD:
      return "WRITEVPD";
    case Instruction::PSI_RESET:
      return "PSI_RESET";
    case Instruction::PSI_LINK_CALIB:
      return "PSI_LINK_CALIB";
    case Instruction::PSI_EI_REG_READ:
      return "PSI_EI_REG_READ";
    case Instruction::PSI_EI_REG_WRITE:
      return "PSI_EI_REG_WRITE";
    case Instruction::PSI_VERIFY:
      return "PSI_VERIFY";
    case Instruction::PSI_SCOM_READ:
      return "PSI_SCOM_READ";
    case Instruction::PSI_SCOM_WRITE:
      return "PSI_SCOM_WRITE";
    case Instruction::PSI_READ:
      return "PSI_READ";
    case Instruction::PSI_WRITE:
      return "PSI_WRITE";
    case Instruction::PSI_INIT:
      return "PSI_INIT";
    case Instruction::PSI_LINK_ENABLE:
      return "PSI_LINK_ENABLE";
    case Instruction::PSI_SET_SPEED:
      return "PSI_SET_SPEED";
    case Instruction::PSI_LINK_VERIFY:
      return "PSI_LINK_VERIFY";
    case Instruction::I2CWRITE:
      return "I2CWRITE";
    case Instruction::I2CREAD:
      return "I2CREAD";
    case Instruction::GPIO_CONFIGPIN:
      return "GPIO_CONFIGPIN";
    case Instruction::GPIO_READPIN:
      return "GPIO_READPIN";
    case Instruction::GPIO_READPINS:
      return "GPIO_READPINS";
    case Instruction::GPIO_READLATCH:
      return "GPIO_READLATCH";
    case Instruction::GPIO_WRITELATCH:
      return "GPIO_WRITELATCH";
    case Instruction::GPIO_WRITELATCHES:
      return "GPIO_WRITELATCHES";
    case Instruction::GPIO_READCONFIG:
      return "GPIO_READCONFIG";
    case Instruction::GPIO_WRITECONFIG:
      return "GPIO_WRITECONFIG";
    case Instruction::GPIO_WRITECNFGSET:
      return "GPIO_WRITECNFGSET";
    case Instruction::GPIO_WRITECNFGCLR:
      return "GPIO_WRITECNFGCLR";
    case Instruction::DMAEXER_START:
      return "DMAEXER_START";
    case Instruction::DMAEXER_REPORT:
      return "DMAEXER_REPORT";
    case Instruction::DMAEXER_STOP:
      return "DMAEXER_STOP";
    case Instruction::INFO:
      return "INFO";
    case Instruction::RUN_CMD:
      return "RUN_CMD";
    case Instruction::MULTI_ENABLE:
      return "MULTI_ENABLE";
    case Instruction::AUTH:
      return "AUTH";
    case Instruction::ADDAUTH:
      return "ADDAUTH";
    case Instruction::CLEARAUTH:
      return "CLEARAUTH";
    case Instruction::VERSION:
      return "VERSION";
    case Instruction::FLIGHTRECORDER:
      return "FLIGHTRECORDER";
    case Instruction::EXIT:
      return "EXIT";
    case Instruction::SCOMIN_MASK:
      return "SCOMIN_MASK";
    case Instruction::MASK_PERSISTENT:
      return "MASK_PERSISTENT";
    case Instruction::SET_PERSISTENT:
      return "SET_PERSISTENT";
    case Instruction::GET_PERSISTENT:
      return "GET_PERSISTENT";
    case Instruction::READKEYWORD:
      return "READKEYWORD";
    case Instruction::WRITEKEYWORD:
      return "WRITEKEYWORD";
    case Instruction::FRUSTATUS:
      return "FRUSTATUS";
    case Instruction::CHICDOIPL:
      return "CHICDOIPL";
    case Instruction::ENABLE_MEM_VOLTAGES:
      return "ENABLE_MEM_VOLTAGES";
    case Instruction::DISABLE_MEM_VOLTAGES:
      return "DISABLE_MEM_VOLTAGES";
    case Instruction::SNDISTEPMSG:
      return "SNDISTEPMSG";
    case Instruction::MBXTRACEENABLE:
      return "MBXTRACEENABLE";
    case Instruction::MBXTRACEDISABLE:
      return "MBXTRACEDISABLE";
    case Instruction::MBXTRACEREAD:
      return "MBXTRACEREAD";
    case Instruction::PUTMEMPBA:
      return "PUTMEMPBA";
    case Instruction::GETMEMPBA:
      return "GETMEMPBA";
    case Instruction::BULK_SCOMIN:
      return "BULK_SCOMIN";
    case Instruction::BULK_SCOMOUT:
      return "BULK_SCOMOUT";
    case Instruction::STREAM_SETUP:
      return "STREAM_SETUP";
    case Instruction::STREAM_FINISH:
      return "STREAM_FINISH";
    case Instruction::FSPDMAIN:
      return "FSPDMAIN";
    case Instruction::FSPDMAOUT:
      return "FSPDMAOUT";
    case Instruction::SUBMIT:
      return "SUBMIT";
    case Instruction::REQUEST_RESET:
      return "REQUEST_RESET";
    case Instruction::SEND_TAPI_CMD:
      return "SEND_TAPI_CMD";
    case Instruction::PUTMEMPROC:
      return "PUTMEMPROC";
    case Instruction::GETMEMPROC:
      return "GETMEMPROC";
    case Instruction::PNORGETLIST:
      return "PNORGETLIST";
    case Instruction::PNORGET:
      return "PNORGET";
    case Instruction::PNORPUT:
      return "PNORPUT";
    case Instruction::QUERYSP:
      return "QUERYSP";
  }
  return "";
}

/*****************************************************************************/
/* Instruction Implementation ************************************************/
/*****************************************************************************/
Instruction::Instruction(void) : version(0x1), command(NOCOMMAND), type(NOINSTRUCTION), error(0){
}

/* for all of these methods check if we are of a different type */
uint32_t Instruction::execute(ecmdDataBuffer & o_data, InstructionStatus & o_status, Handle ** io_handle) {
  uint32_t rc = 0;

  /* set the version of this instruction in the status */
  o_status.instructionVersion = version;

  o_status.errorMessage.append("Instruction::execute Unknown Instruction specified. New FSP server may be required.");
  o_status.rc = SERVER_UNKNOWN_INSTRUCTION;

  return rc;
}

uint32_t Instruction::decrementVersion(void) {
  if (version > 0x1) {
    version--;
    return 0;
  }
  // return an error if we can not decrement
  return 1;
}

uint32_t Instruction::flatten(uint8_t * o_data, uint32_t i_len) const {
  uint32_t rc = 0;

  uint32_t * o_ptr = (uint32_t *) o_data;
  if (i_len < flattenSize()) {
    out.error("Instruction::flatten", "i_len %d bytes is too small to flatten\n", i_len);
    rc = 1;
  } else {
    // clear memory
    memset(o_data, 0, flattenSize());
    o_ptr[0] = htonl(version);
    o_ptr[1] = htonl(command);
    o_ptr[2] = htonl(flags);
  }

  return rc;
}

uint32_t Instruction::unflatten(const uint8_t * i_data, uint32_t i_len) {
  uint32_t rc = 0;

  uint32_t * i_ptr = (uint32_t *) i_data;
  version = ntohl(i_ptr[0]);
  if(version == 0x1) {
    command = (InstructionCommand) ntohl(i_ptr[1]);
    flags = ntohl(i_ptr[2]);
  } else {
    error = rc = SERVER_UNKNOWN_INSTRUCTION_VERSION;
  }

  return rc;
}

uint32_t Instruction::flattenSize(void) const {
  return (3 * sizeof(uint32_t));
}

std::string Instruction::dumpInstruction(void) const {
  std::ostringstream oss;

  oss << "Instruction" << std::endl;

  return oss.str();
}

uint64_t Instruction::getHash(void) const {
  return ((0x0000000F & type) << 28);
}

uint32_t Instruction::closeHandle(Handle ** i_handle) {
  uint32_t rc = 0;

  *i_handle = NULL;

  return rc;
}

std::string Instruction::getInstructionVars(const InstructionStatus & i_status) const {
  std::ostringstream oss;

  oss << std::hex << std::setfill('0');
  oss << "rc: " << std::setw(8) << i_status.rc;

  return oss.str();
}

Instruction::InstructionType Instruction::getType(void) const { return type; }
Instruction::InstructionCommand Instruction::getCommand(void) const { return command; }
uint32_t Instruction::getFlags(void) const { return flags; }
uint32_t Instruction::getVersion(void) const { return version; }

int Instruction::genWords(const ecmdDataBuffer &data, std::string &words) const {
  // copied from Debug.C
  int rc = 0;

  if (data.getBitLength() == 0) {
    words = "";  // This will kill the genHexLeftStr error if we have no data
  } else if (data.getBitLength() <= 128) {
    words = data.genHexLeftStr(0, data.getBitLength());
  } else {
    words = data.genHexLeftStr(0, 128);
  }

  return rc;
}

std::ostream& operator<<(std::ostream& io_stream, const Instruction& i_instruction ) {
  io_stream << i_instruction.dumpInstruction() << std::endl;
  return io_stream;
}

uint32_t devicestring_genhash(const std::string & i_string, uint32_t & o_hash)
{
    uint32_t rc = 0;
    int length = i_string.length();
    const char * data = i_string.c_str();
    int found = 0;
    int type = 0;       // 3 bits
    int fsi = 0;        // 6 bits
    int cfam = 0;       // 2 bits
    int engine = 0;     // 5 bits
    int subfsi = 0;     // 3 bits
    int subcfam = 0;    // 2 bits
    int subengine = 0;  // 5 bits
    int subsubfsi = 0;  // 3 bits
    int subsubcfam = 0; // 2 bits
    o_hash = 0x0;
    if (length == 5)
    {
        type = 1;
        found = sscanf(data, "L%02dC%d", &fsi, &cfam);
        if (found != 2)
        {
            rc = 1;
        }
    }
    else if (length == 13)
    {
        type = 2;
        found = sscanf(data, "L%02dC%dE%02d:L%dC%d", &fsi, &cfam, &engine, &subfsi, &subcfam);
        if (found != 5)
        {
            rc = 2;
        }
    }
    else if (length == 21)
    {
        type = 3;
        found = sscanf(data, "L%02dC%dE%02d:L%dC%dE%02d:L%dC%d", &fsi, &cfam, &engine, &subfsi, &subcfam,
                       &subengine, &subsubfsi, &subsubcfam);
        if (found != 8)
        {
            rc = 3;
        }
    }
    else
    {
        // BMC device case
        char * endptr = NULL;
        errno = 0;
        fsi = strtol(data, &endptr, 10);
        if (((errno == ERANGE) && ((fsi == LONG_MAX) || (fsi == LONG_MIN))) ||
            ((errno != 0) && (fsi == 0)))
        {
            rc = 5;
        }
        else if (endptr == data)
        {
            rc = 6;
        }
        else if (*endptr != '\0')
        {
            rc = 4;
        }
    }

    if (rc)
    {
        // error
        std::cout << "ERROR unknown format for device " << i_string << " rc = " << rc << std::endl;
    }
    else
    {
        o_hash |= ((0x07 & type)    << 0);      //0x00000007
        o_hash |= ((0x3F & fsi)     << 3);      //0x000001F8
        o_hash |= ((0x03 & cfam)    << 9);      //0x00000600
        o_hash |= ((0x1F & engine)  << 11);     //0x0000F800
        o_hash |= ((0x07 & subfsi)  << 16);     //0x00070000
        o_hash |= ((0x03 & subcfam)     << 19); //0x00180000
        o_hash |= ((0x1F & subengine)   << 21); //0x03E00000
        o_hash |= ((0x07 & subsubfsi)   << 26); //0x1C000000
        o_hash |= ((0x03 & subsubcfam)  << 29); //0x60000000
    }
    return rc;
}
<|endoftext|>


<commit_before>#include "geodrawer_plugin.h"
#include "geodrawer.h"

#include <qqml.h>

#include "geometries.h"
#include "iooptions.h"
#include "drawerfactory.h"
#include "selectiondrawer.h"

void GeodrawerPlugin::registerTypes(const char *uri)
{
    // @uri n52.org.ilwisobjects
    qmlRegisterType<GeoDrawer>(uri, 1, 0, "GeoDrawer");

    Ilwis::Geodrawer::DrawerFactory::registerDrawer("SelectionDrawer", Ilwis::Geodrawer::SelectionDrawer::create);

}

<commit_msg>renamed GeoDrawer to LayerView<commit_after>#include "geodrawer_plugin.h"
#include "visualizationmanager.h"
//#include "geodrawer.h"

#include <qqml.h>

#include "geometries.h"
#include "iooptions.h"
#include "drawerfactory.h"
#include "selectiondrawer.h"
#include "layersview.h"

void GeodrawerPlugin::registerTypes(const char *uri)
{
    // @uri n52.org.ilwisobjects
    qmlRegisterType<LayersView>(uri, 1, 0, "LayersView");

    Ilwis::Geodrawer::DrawerFactory::registerDrawer("SelectionDrawer", Ilwis::Geodrawer::SelectionDrawer::create);

}

<|endoftext|>