<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2010 - 2015, Göteborg Bit Factory.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <Directory.h>

#if defined SOLARIS || defined NETBSD
#include <limits.h>
#endif

////////////////////////////////////////////////////////////////////////////////
Directory::Directory ()
{
}

////////////////////////////////////////////////////////////////////////////////
Directory::Directory (const Directory& other)
: File::File (other)
{
}

////////////////////////////////////////////////////////////////////////////////
Directory::Directory (const File& other)
: File::File (other)
{
}

////////////////////////////////////////////////////////////////////////////////
Directory::Directory (const Path& other)
: File::File (other)
{
}

////////////////////////////////////////////////////////////////////////////////
Directory::Directory (const std::string& in)
: File::File (in)
{
}

////////////////////////////////////////////////////////////////////////////////
Directory::~Directory ()
{
}

////////////////////////////////////////////////////////////////////////////////
Directory& Directory::operator= (const Directory& other)
{
  if (this != &other)
  {
    File::operator= (other);
  }

  return *this;
}

////////////////////////////////////////////////////////////////////////////////
bool Directory::create (int mode /* = 0755 */)
{
  return mkdir (_data.c_str (), mode) == 0 ? true : false;
}

////////////////////////////////////////////////////////////////////////////////
bool Directory::remove () const
{
  return remove_directory (_data);
}

////////////////////////////////////////////////////////////////////////////////
bool Directory::remove_directory (const std::string& dir) const
{
  DIR* dp = opendir (dir.c_str ());
  if (dp != NULL)
  {
    struct dirent* de;
    while ((de = readdir (dp)) != NULL)
    {
      if (!strcmp (de->d_name, ".") ||
          !strcmp (de->d_name, ".."))
        continue;

#if defined (SOLARIS) || defined (HAIKU)
      struct stat s;
      lstat ((dir + "/" + de->d_name).c_str (), &s);
      if (S_ISDIR (s.st_mode))
        remove_directory (dir + "/" + de->d_name);
      else
        unlink ((dir + "/" + de->d_name).c_str ());
#else
      if (de->d_type == DT_UNKNOWN)
      {
        struct stat s;
        lstat ((dir + "/" + de->d_name).c_str (), &s);
        if (S_ISDIR (s.st_mode))
          de->d_type = DT_DIR;
      }
      if (de->d_type == DT_DIR)
        remove_directory (dir + "/" + de->d_name);
      else
        unlink ((dir + "/" + de->d_name).c_str ());
#endif
    }

    closedir (dp);
  }

  return rmdir (dir.c_str ()) ? false : true;
}

////////////////////////////////////////////////////////////////////////////////
std::vector <std::string> Directory::list ()
{
  std::vector <std::string> files;
  list (_data, files, false);
  return files;
}

////////////////////////////////////////////////////////////////////////////////
std::vector <std::string> Directory::listRecursive ()
{
  std::vector <std::string> files;
  list (_data, files, true);
  return files;
}

////////////////////////////////////////////////////////////////////////////////
std::string Directory::cwd ()
{
#ifdef HAVE_GET_CURRENT_DIR_NAME
  char *buf = get_current_dir_name ();
  if (buf == NULL)
    throw std::bad_alloc ();
  std::string result (buf);
  free (buf);
  return result;
#else
  char buf[PATH_MAX];
  getcwd (buf, PATH_MAX - 1);
  return std::string (buf);
#endif
}

////////////////////////////////////////////////////////////////////////////////
bool Directory::up ()
{
  if (_data == "/")
    return false;

  std::string::size_type slash = _data.rfind ('/');
  if (slash == 0)
  {
    _data = "/";  // Root dir should retain the slash.
    return true;
  }
  else if (slash != std::string::npos)
  {
    _data = _data.substr (0, slash);
    return true;
  }

  return false;
}

////////////////////////////////////////////////////////////////////////////////
bool Directory::cd () const
{
  return chdir (_data.c_str ()) == 0 ? true : false;
}

////////////////////////////////////////////////////////////////////////////////
void Directory::list (
  const std::string& base,
  std::vector <std::string>& results,
  bool recursive)
{
  DIR* dp = opendir (base.c_str ());
  if (dp != NULL)
  {
    struct dirent* de;
    while ((de = readdir (dp)) != NULL)
    {
      if (!strcmp (de->d_name, ".") ||
          !strcmp (de->d_name, ".."))
        continue;

#if defined (SOLARIS) || defined (HAIKU)
      struct stat s;
      stat ((base + "/" + de->d_name).c_str (), &s);
      if (recursive && S_ISDIR (s.st_mode))
        list (base + "/" + de->d_name, results, recursive);
      else
        results.push_back (base + "/" + de->d_name);
#else
      if (recursive && de->d_type == DT_UNKNOWN)
      {
        struct stat s;
        lstat ((base + "/" + de->d_name).c_str (), &s);
        if (S_ISDIR (s.st_mode))
          de->d_type = DT_DIR;
      }
      if (recursive && de->d_type == DT_DIR)
        list (base + "/" + de->d_name, results, recursive);
      else
        results.push_back (base + "/" + de->d_name);
#endif
    }

    closedir (dp);
  }
}

////////////////////////////////////////////////////////////////////////////////
<commit_msg>Directory: Migrated improvements over from Taskwarrior<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2010 - 2015, Göteborg Bit Factory.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <Directory.h>

#if defined SOLARIS || defined NETBSD || defined FREEBSD
#include <limits.h>
#endif

////////////////////////////////////////////////////////////////////////////////
Directory::Directory ()
{
}

////////////////////////////////////////////////////////////////////////////////
Directory::Directory (const Directory& other)
: File::File (other)
{
}

////////////////////////////////////////////////////////////////////////////////
Directory::Directory (const File& other)
: File::File (other)
{
}

////////////////////////////////////////////////////////////////////////////////
Directory::Directory (const Path& other)
: File::File (other)
{
}

////////////////////////////////////////////////////////////////////////////////
Directory::Directory (const std::string& in)
: File::File (in)
{
}

////////////////////////////////////////////////////////////////////////////////
Directory::~Directory ()
{
}

////////////////////////////////////////////////////////////////////////////////
Directory& Directory::operator= (const Directory& other)
{
  if (this != &other)
  {
    File::operator= (other);
  }

  return *this;
}

////////////////////////////////////////////////////////////////////////////////
bool Directory::create (int mode /* = 0755 */)
{
  return mkdir (_data.c_str (), mode) == 0 ? true : false;
}

////////////////////////////////////////////////////////////////////////////////
bool Directory::remove () const
{
  return remove_directory (_data);
}

////////////////////////////////////////////////////////////////////////////////
bool Directory::remove_directory (const std::string& dir) const
{
  DIR* dp = opendir (dir.c_str ());
  if (dp != NULL)
  {
    struct dirent* de;
    while ((de = readdir (dp)) != NULL)
    {
      if (!strcmp (de->d_name, ".") ||
          !strcmp (de->d_name, ".."))
        continue;

#if defined (SOLARIS) || defined (HAIKU)
      struct stat s;
      lstat ((dir + "/" + de->d_name).c_str (), &s);
      if (S_ISDIR (s.st_mode))
        remove_directory (dir + "/" + de->d_name);
      else
        unlink ((dir + "/" + de->d_name).c_str ());
#else
      if (de->d_type == DT_UNKNOWN)
      {
        struct stat s;
        lstat ((dir + "/" + de->d_name).c_str (), &s);
        if (S_ISDIR (s.st_mode))
          de->d_type = DT_DIR;
      }
      if (de->d_type == DT_DIR)
        remove_directory (dir + "/" + de->d_name);
      else
        unlink ((dir + "/" + de->d_name).c_str ());
#endif
    }

    closedir (dp);
  }

  return rmdir (dir.c_str ()) ? false : true;
}

////////////////////////////////////////////////////////////////////////////////
std::vector <std::string> Directory::list ()
{
  std::vector <std::string> files;
  list (_data, files, false);
  return files;
}

////////////////////////////////////////////////////////////////////////////////
std::vector <std::string> Directory::listRecursive ()
{
  std::vector <std::string> files;
  list (_data, files, true);
  return files;
}

////////////////////////////////////////////////////////////////////////////////
std::string Directory::cwd ()
{
#ifdef HAVE_GET_CURRENT_DIR_NAME
  char *buf = get_current_dir_name ();
  if (buf == NULL)
    throw std::bad_alloc ();
  std::string result (buf);
  free (buf);
  return result;
#else
  char buf[PATH_MAX];
  getcwd (buf, PATH_MAX - 1);
  return std::string (buf);
#endif
}

////////////////////////////////////////////////////////////////////////////////
bool Directory::up ()
{
  if (_data == "/")
    return false;

  std::string::size_type slash = _data.rfind ('/');
  if (slash == 0)
  {
    _data = "/";  // Root dir should retain the slash.
    return true;
  }
  else if (slash != std::string::npos)
  {
    _data = _data.substr (0, slash);
    return true;
  }

  return false;
}

////////////////////////////////////////////////////////////////////////////////
bool Directory::cd () const
{
  return chdir (_data.c_str ()) == 0 ? true : false;
}

////////////////////////////////////////////////////////////////////////////////
void Directory::list (
  const std::string& base,
  std::vector <std::string>& results,
  bool recursive)
{
  DIR* dp = opendir (base.c_str ());
  if (dp != NULL)
  {
    struct dirent* de;
    while ((de = readdir (dp)) != NULL)
    {
      if (!strcmp (de->d_name, ".") ||
          !strcmp (de->d_name, ".."))
        continue;

#if defined (SOLARIS) || defined (HAIKU)
      struct stat s;
      stat ((base + "/" + de->d_name).c_str (), &s);
      if (recursive && S_ISDIR (s.st_mode))
        list (base + "/" + de->d_name, results, recursive);
      else
        results.push_back (base + "/" + de->d_name);
#else
      if (recursive && de->d_type == DT_UNKNOWN)
      {
        struct stat s;
        lstat ((base + "/" + de->d_name).c_str (), &s);
        if (S_ISDIR (s.st_mode))
          de->d_type = DT_DIR;
      }
      if (recursive && de->d_type == DT_DIR)
        list (base + "/" + de->d_name, results, recursive);
      else
        results.push_back (base + "/" + de->d_name);
#endif
    }

    closedir (dp);
  }
}

////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>

#include <iostream>
#include <fstream>

#include "vtrc-client-base/vtrc-client.h"
#include "vtrc-common/vtrc-exception.h"

#include "rfs-iface.h"

#include "vtrc-memory.h"

#include "utils.h"

namespace rfs_examples {

    using namespace vtrc;

    void list_dir( interfaces::remote_fs &impl)
    {
        typedef vtrc::shared_ptr<interfaces::remote_fs_iterator> iterator;

        size_t dirs(0);
        size_t files(0);
        std::string lstring( 2, ' ' );

        for( iterator i(impl.begin_iterator( )); !i->end( ); i->next( ) ) {

            bool is_dir( i->info( ).is_directory_ );

            dirs  += is_dir ? 1 : 0;
            files += is_dir ? 0 : 1;

            std::cout << lstring
                      << ( i->info( ).is_empty_ ? " " : "+" );
            std::cout << ( is_dir ? "[" : " " )
                      << leaf_of(i->info( ).path_)
                      << ( is_dir ? "]" : " " )
                      << "\n";
        }

        std::cout << "==================================================\n"
                  << "Total dirs:  " << dirs  << "\n"
                  << "Total files: " << files << "\n"
                  ;
    }

}
<commit_msg>stress<commit_after>

#include <iostream>
#include <fstream>

#include "vtrc-client-base/vtrc-client.h"
#include "vtrc-common/vtrc-exception.h"

#include "rfs-iface.h"

#include "vtrc-memory.h"

#include "utils.h"

namespace rfs_examples {

    using namespace vtrc;

    void list_dir( interfaces::remote_fs &impl)
    {
        typedef vtrc::shared_ptr<interfaces::remote_fs_iterator> iterator;

        size_t dirs(0);
        size_t files(0);
        std::string lstring( 2, ' ' );

        for( iterator i(impl.begin_iterator( )); !i->end( ); i->next( ) ) {

            bool is_dir( i->info( ).is_directory_ );

            dirs  += is_dir ? 1 : 0;
            files += is_dir ? 0 : 1;

            std::cout << lstring
                      << ( i->info( ).is_empty_ ? " " : "+" )
                      << ( is_dir ? "[" : " " )
                      << leaf_of(i->info( ).path_)
                      << ( is_dir ? "]" : " " )
                      << "\n";
        }

        std::cout << "==================================================\n"
                  << "Total dirs:  " << dirs  << "\n"
                  << "Total files: " << files << "\n"
                  ;
    }

}
<|endoftext|>


<commit_before>/*
    Yojimbo Client/Server Network Library.

    Copyright © 2016, The Network Protocol Company, Inc.

    Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

        1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

        2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
           in the documentation and/or other materials provided with the distribution.

        3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived
           from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
    USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "yojimbo_address.h"

#if YOJIMBO_PLATFORM == YOJIMBO_PLATFORM_WINDOWS

    #define NOMINMAX
    #define _WINSOCK_DEPRECATED_NO_WARNINGS
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #include <ws2ipdef.h>
    #pragma comment( lib, "WS2_32.lib" )

    #ifdef SetPort
    #undef SetPort
    #endif // #ifdef SetPort

    #if YOJIMBO_SOCKETS
    #include <iphlpapi.h>
    #pragma comment( lib, "IPHLPAPI.lib" )
    #endif // #if YOJIMBO_SOCKETS

#elif YOJIMBO_PLATFORM == YOJIMBO_PLATFORM_MAC || YOJIMBO_PLATFORM == YOJIMBO_PLATFORM_UNIX

    #include <netdb.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <ifaddrs.h>
    #include <net/if.h>
    #include <fcntl.h>
    #include <netdb.h>
    #include <arpa/inet.h>
    #include <unistd.h>
    #include <errno.h>

#else

    #error yojimbo unknown platform!

#endif

#include <memory.h>
#include <string.h>

namespace yojimbo
{
    Address::Address()
    {
        Clear();
    }

    Address::Address( uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t port )
        : m_type( ADDRESS_IPV4 )
    {

        m_address_ipv4 = uint32_t(a) | (uint32_t(b)<<8) | (uint32_t(c)<<16) | (uint32_t(d)<<24);
        m_port = port;
    }

    Address::Address( uint32_t address, int16_t port )
        : m_type( ADDRESS_IPV4 )
    {
        m_address_ipv4 = htonl( address );        // IMPORTANT: stored in network byte order. eg. big endian!
        m_port = port;
    }

    Address::Address( uint16_t a, uint16_t b, uint16_t c, uint16_t d,
                      uint16_t e, uint16_t f, uint16_t g, uint16_t h,
                      uint16_t port )
        : m_type( ADDRESS_IPV6 )
    {
        m_address_ipv6[0] = htons( a );
        m_address_ipv6[1] = htons( b );
        m_address_ipv6[2] = htons( c );
        m_address_ipv6[3] = htons( d );
        m_address_ipv6[4] = htons( e );
        m_address_ipv6[5] = htons( f );
        m_address_ipv6[6] = htons( g );
        m_address_ipv6[7] = htons( h );
        m_port = port;
    }

    Address::Address( const uint16_t address[], uint16_t port )
        : m_type( ADDRESS_IPV6 )
    {
        for ( int i = 0; i < 8; ++i )
            m_address_ipv6[i] = htons( address[i] );
        m_port = port;
    }

    Address::Address( const sockaddr_storage * addr )
    {
        assert( addr );

        if ( addr->ss_family == AF_INET )
        {
            const sockaddr_in * addr_ipv4 = (const sockaddr_in*) addr;
            m_type = ADDRESS_IPV4;
            m_address_ipv4 = addr_ipv4->sin_addr.s_addr;
            m_port = ntohs( addr_ipv4->sin_port );
        }
        else if ( addr->ss_family == AF_INET6 )
        {
            const sockaddr_in6 * addr_ipv6 = (const sockaddr_in6*) addr;
            m_type = ADDRESS_IPV6;
            memcpy( m_address_ipv6, &addr_ipv6->sin6_addr, 16 );
            m_port = ntohs( addr_ipv6->sin6_port );
        }
        else
        {
            assert( false );
            Clear();
        }
    }

    Address::Address( const char * address )
    {
        Parse( address );
    }

    Address::Address( const char * address, uint16_t port )
    {
        Parse( address );
        m_port = port;
    }

    void Address::Parse( const char * address_in )
    {
        // first try to parse as an IPv6 address:
        // 1. if the first character is '[' then it's probably an ipv6 in form "[addr6]:portnum"
        // 2. otherwise try to parse as raw IPv6 address, parse using inet_pton

        assert( address_in );

        char buffer[MaxAddressLength];
        char * address = buffer;
        strncpy( address, address_in, MaxAddressLength - 1 );
        address[MaxAddressLength-1] = '\0';

        int addressLength = (int) strlen( address );
        m_port = 0;
        if ( address[0] == '[' )
        {
            const int base_index = addressLength - 1;
            for ( int i = 0; i < 6; ++i )   // note: no need to search past 6 characters as ":65535" is longest port value
            {
                const int index = base_index - i;
                if ( index < 3 )
                    break;
                if ( address[index] == ':' )
                {
                    m_port = uint16_t( atoi( &address[index + 1] ) );
                    address[index-1] = '\0';
                }
            }
            address += 1;
        }
        struct in6_addr sockaddr6;
        if ( inet_pton( AF_INET6, address, &sockaddr6 ) == 1 )
        {
            memcpy( m_address_ipv6, &sockaddr6, 16 );
            m_type = ADDRESS_IPV6;
            return;
        }

        // otherwise it's probably an IPv4 address:
        // 1. look for ":portnum", if found save the portnum and strip it out
        // 2. parse remaining ipv4 address via inet_pton

        addressLength = (int) strlen( address );
        const int base_index = addressLength - 1;
        for ( int i = 0; i < 6; ++i )   // note: no need to search past 6 characters as ":65535" is longest port value
        {
            const int index = base_index - i;
            if ( index < 0 )
                break;
            if ( address[index] == ':' )
            {
                m_port = (uint16_t) atoi( &address[index+1] );
                address[index] = '\0';
            }
        }

        struct sockaddr_in sockaddr4;
        if ( inet_pton( AF_INET, address, &sockaddr4.sin_addr ) == 1 )
        {
            m_type = ADDRESS_IPV4;
            m_address_ipv4 = sockaddr4.sin_addr.s_addr;
        }
        else
        {
            // nope: it's not an IPv4 address. maybe it's a hostname? set address as invalid.
            Clear();
        }
    }

    void Address::Clear()
    {
        m_type = ADDRESS_NONE;
        memset( m_address_ipv6, 0, sizeof( m_address_ipv6 ) );
        m_address_ipv4 = 0;
        m_port = 0;
    }

    uint32_t Address::GetAddress4() const
    {
        assert( m_type == ADDRESS_IPV4 );
        return m_address_ipv4;
    }

    const uint16_t * Address::GetAddress6() const
    {
        assert( m_type == ADDRESS_IPV6 );
        return m_address_ipv6;
    }

    void Address::SetPort( uint16_t port )
    {
        m_port = port;
    }

    uint16_t Address::GetPort() const
    {
        return m_port;
    }

    AddressType Address::GetType() const
    {
        return m_type;
    }

    const char * Address::ToString( char buffer[], int bufferSize ) const
    {
        if ( m_type == ADDRESS_IPV4 )
        {
            const uint8_t a =   m_address_ipv4 & 0xff;
            const uint8_t b = ( m_address_ipv4 >> 8  ) & 0xff;
            const uint8_t c = ( m_address_ipv4 >> 16 ) & 0xff;
            const uint8_t d = ( m_address_ipv4 >> 24 ) & 0xff;
            if ( m_port != 0 )
                snprintf( buffer, bufferSize, "%d.%d.%d.%d:%d", a, b, c, d, m_port );
            else
                snprintf( buffer, bufferSize, "%d.%d.%d.%d", a, b, c, d );
            return buffer;
        }
        else if ( m_type == ADDRESS_IPV6 )
        {
            if ( m_port == 0 )
            {
                inet_ntop( AF_INET6, (void*) &m_address_ipv6, buffer, bufferSize );
                return buffer;
            }
            else
            {
                char addressString[INET6_ADDRSTRLEN];
                inet_ntop( AF_INET6, (void*) &m_address_ipv6, addressString, INET6_ADDRSTRLEN );
                snprintf( buffer, bufferSize, "[%s]:%d", addressString, m_port );
                return buffer;
            }
        }
        else
        {
            snprintf( buffer, bufferSize, "%s", "NONE" );
            return buffer;
        }
    }

    bool Address::IsValid() const
    {
        return m_type != ADDRESS_NONE;
    }

    bool Address::IsLinkLocal() const
    {
        return m_type == ADDRESS_IPV6 && m_address_ipv6[0] == htons( 0xfe80 );
    }

    bool Address::IsSiteLocal() const
    {
        return m_type == ADDRESS_IPV6 && m_address_ipv6[0] == htons( 0xfec0 );
    }

    bool Address::IsMulticast() const
    {
        return m_type == ADDRESS_IPV6 && m_address_ipv6[0] == htons( 0xff00 );
    }

    bool Address::IsLoopback() const
    {
        return ( m_type == ADDRESS_IPV4 && m_address_ipv4 == htonl( 0x7F000001 ) )
                                            ||
               ( m_type == ADDRESS_IPV6 && m_address_ipv6[0] == 0
                                          && m_address_ipv6[1] == 0
                                        && m_address_ipv6[2] == 0
                                        && m_address_ipv6[3] == 0
                                        && m_address_ipv6[4] == 0
                                        && m_address_ipv6[5] == 0
                                        && m_address_ipv6[6] == 0
                                        && m_address_ipv6[7] == htons( 0x0001 ) );
    }

    bool Address::IsGlobalUnicast() const
    {
        return m_type == ADDRESS_IPV6 && m_address_ipv6[0] != htons( 0xfe80 )
                                      && m_address_ipv6[0] != htons( 0xfec0 )
                                      && m_address_ipv6[0] != htons( 0xff00 )
                                      && !IsLoopback();
    }

    bool Address::operator ==( const Address & other ) const
    {
        if ( m_type != other.m_type )
            return false;
        if ( m_port != other.m_port )
            return false;
        if ( m_type == ADDRESS_IPV4 && m_address_ipv4 == other.m_address_ipv4 )
            return true;
        else if ( m_type == ADDRESS_IPV6 && memcmp( m_address_ipv6, other.m_address_ipv6, sizeof( m_address_ipv6 ) ) == 0 )
            return true;
        else
            return false;
    }

    bool Address::operator !=( const Address & other ) const
    {
        return !( *this == other );
    }
}
<commit_msg>Revert "Set both ipv4 and ipv6 to 0 in Address::Clear()"<commit_after>/*
    Yojimbo Client/Server Network Library.

    Copyright © 2016, The Network Protocol Company, Inc.

    Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

        1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

        2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
           in the documentation and/or other materials provided with the distribution.

        3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived
           from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
    USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "yojimbo_address.h"

#if YOJIMBO_PLATFORM == YOJIMBO_PLATFORM_WINDOWS

    #define NOMINMAX
    #define _WINSOCK_DEPRECATED_NO_WARNINGS
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #include <ws2ipdef.h>
    #pragma comment( lib, "WS2_32.lib" )

    #ifdef SetPort
    #undef SetPort
    #endif // #ifdef SetPort

    #if YOJIMBO_SOCKETS
    #include <iphlpapi.h>
    #pragma comment( lib, "IPHLPAPI.lib" )
    #endif // #if YOJIMBO_SOCKETS

#elif YOJIMBO_PLATFORM == YOJIMBO_PLATFORM_MAC || YOJIMBO_PLATFORM == YOJIMBO_PLATFORM_UNIX

    #include <netdb.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <ifaddrs.h>
    #include <net/if.h>
    #include <fcntl.h>
    #include <netdb.h>
    #include <arpa/inet.h>
    #include <unistd.h>
    #include <errno.h>

#else

    #error yojimbo unknown platform!

#endif

#include <memory.h>
#include <string.h>

namespace yojimbo
{
    Address::Address()
    {
        Clear();
    }

    Address::Address( uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t port )
        : m_type( ADDRESS_IPV4 )
    {

        m_address_ipv4 = uint32_t(a) | (uint32_t(b)<<8) | (uint32_t(c)<<16) | (uint32_t(d)<<24);
        m_port = port;
    }

    Address::Address( uint32_t address, int16_t port )
        : m_type( ADDRESS_IPV4 )
    {
        m_address_ipv4 = htonl( address );        // IMPORTANT: stored in network byte order. eg. big endian!
        m_port = port;
    }

    Address::Address( uint16_t a, uint16_t b, uint16_t c, uint16_t d,
                      uint16_t e, uint16_t f, uint16_t g, uint16_t h,
                      uint16_t port )
        : m_type( ADDRESS_IPV6 )
    {
        m_address_ipv6[0] = htons( a );
        m_address_ipv6[1] = htons( b );
        m_address_ipv6[2] = htons( c );
        m_address_ipv6[3] = htons( d );
        m_address_ipv6[4] = htons( e );
        m_address_ipv6[5] = htons( f );
        m_address_ipv6[6] = htons( g );
        m_address_ipv6[7] = htons( h );
        m_port = port;
    }

    Address::Address( const uint16_t address[], uint16_t port )
        : m_type( ADDRESS_IPV6 )
    {
        for ( int i = 0; i < 8; ++i )
            m_address_ipv6[i] = htons( address[i] );
        m_port = port;
    }

    Address::Address( const sockaddr_storage * addr )
    {
        assert( addr );

        if ( addr->ss_family == AF_INET )
        {
            const sockaddr_in * addr_ipv4 = (const sockaddr_in*) addr;
            m_type = ADDRESS_IPV4;
            m_address_ipv4 = addr_ipv4->sin_addr.s_addr;
            m_port = ntohs( addr_ipv4->sin_port );
        }
        else if ( addr->ss_family == AF_INET6 )
        {
            const sockaddr_in6 * addr_ipv6 = (const sockaddr_in6*) addr;
            m_type = ADDRESS_IPV6;
            memcpy( m_address_ipv6, &addr_ipv6->sin6_addr, 16 );
            m_port = ntohs( addr_ipv6->sin6_port );
        }
        else
        {
            assert( false );
            Clear();
        }
    }

    Address::Address( const char * address )
    {
        Parse( address );
    }

    Address::Address( const char * address, uint16_t port )
    {
        Parse( address );
        m_port = port;
    }

    void Address::Parse( const char * address_in )
    {
        // first try to parse as an IPv6 address:
        // 1. if the first character is '[' then it's probably an ipv6 in form "[addr6]:portnum"
        // 2. otherwise try to parse as raw IPv6 address, parse using inet_pton

        assert( address_in );

        char buffer[MaxAddressLength];
        char * address = buffer;
        strncpy( address, address_in, MaxAddressLength - 1 );
        address[MaxAddressLength-1] = '\0';

        int addressLength = (int) strlen( address );
        m_port = 0;
        if ( address[0] == '[' )
        {
            const int base_index = addressLength - 1;
            for ( int i = 0; i < 6; ++i )   // note: no need to search past 6 characters as ":65535" is longest port value
            {
                const int index = base_index - i;
                if ( index < 3 )
                    break;
                if ( address[index] == ':' )
                {
                    m_port = uint16_t( atoi( &address[index + 1] ) );
                    address[index-1] = '\0';
                }
            }
            address += 1;
        }
        struct in6_addr sockaddr6;
        if ( inet_pton( AF_INET6, address, &sockaddr6 ) == 1 )
        {
            memcpy( m_address_ipv6, &sockaddr6, 16 );
            m_type = ADDRESS_IPV6;
            return;
        }

        // otherwise it's probably an IPv4 address:
        // 1. look for ":portnum", if found save the portnum and strip it out
        // 2. parse remaining ipv4 address via inet_pton

        addressLength = (int) strlen( address );
        const int base_index = addressLength - 1;
        for ( int i = 0; i < 6; ++i )   // note: no need to search past 6 characters as ":65535" is longest port value
        {
            const int index = base_index - i;
            if ( index < 0 )
                break;
            if ( address[index] == ':' )
            {
                m_port = (uint16_t) atoi( &address[index+1] );
                address[index] = '\0';
            }
        }

        struct sockaddr_in sockaddr4;
        if ( inet_pton( AF_INET, address, &sockaddr4.sin_addr ) == 1 )
        {
            m_type = ADDRESS_IPV4;
            m_address_ipv4 = sockaddr4.sin_addr.s_addr;
        }
        else
        {
            // nope: it's not an IPv4 address. maybe it's a hostname? set address as invalid.
            Clear();
        }
    }

    void Address::Clear()
    {
        m_type = ADDRESS_NONE;
        memset( m_address_ipv6, 0, sizeof( m_address_ipv6 ) );
        m_port = 0;
    }

    uint32_t Address::GetAddress4() const
    {
        assert( m_type == ADDRESS_IPV4 );
        return m_address_ipv4;
    }

    const uint16_t * Address::GetAddress6() const
    {
        assert( m_type == ADDRESS_IPV6 );
        return m_address_ipv6;
    }

    void Address::SetPort( uint16_t port )
    {
        m_port = port;
    }

    uint16_t Address::GetPort() const
    {
        return m_port;
    }

    AddressType Address::GetType() const
    {
        return m_type;
    }

    const char * Address::ToString( char buffer[], int bufferSize ) const
    {
        if ( m_type == ADDRESS_IPV4 )
        {
            const uint8_t a =   m_address_ipv4 & 0xff;
            const uint8_t b = ( m_address_ipv4 >> 8  ) & 0xff;
            const uint8_t c = ( m_address_ipv4 >> 16 ) & 0xff;
            const uint8_t d = ( m_address_ipv4 >> 24 ) & 0xff;
            if ( m_port != 0 )
                snprintf( buffer, bufferSize, "%d.%d.%d.%d:%d", a, b, c, d, m_port );
            else
                snprintf( buffer, bufferSize, "%d.%d.%d.%d", a, b, c, d );
            return buffer;
        }
        else if ( m_type == ADDRESS_IPV6 )
        {
            if ( m_port == 0 )
            {
                inet_ntop( AF_INET6, (void*) &m_address_ipv6, buffer, bufferSize );
                return buffer;
            }
            else
            {
                char addressString[INET6_ADDRSTRLEN];
                inet_ntop( AF_INET6, (void*) &m_address_ipv6, addressString, INET6_ADDRSTRLEN );
                snprintf( buffer, bufferSize, "[%s]:%d", addressString, m_port );
                return buffer;
            }
        }
        else
        {
            snprintf( buffer, bufferSize, "%s", "NONE" );
            return buffer;
        }
    }

    bool Address::IsValid() const
    {
        return m_type != ADDRESS_NONE;
    }

    bool Address::IsLinkLocal() const
    {
        return m_type == ADDRESS_IPV6 && m_address_ipv6[0] == htons( 0xfe80 );
    }

    bool Address::IsSiteLocal() const
    {
        return m_type == ADDRESS_IPV6 && m_address_ipv6[0] == htons( 0xfec0 );
    }

    bool Address::IsMulticast() const
    {
        return m_type == ADDRESS_IPV6 && m_address_ipv6[0] == htons( 0xff00 );
    }

    bool Address::IsLoopback() const
    {
        return ( m_type == ADDRESS_IPV4 && m_address_ipv4 == htonl( 0x7F000001 ) )
                                            ||
               ( m_type == ADDRESS_IPV6 && m_address_ipv6[0] == 0
                                          && m_address_ipv6[1] == 0
                                        && m_address_ipv6[2] == 0
                                        && m_address_ipv6[3] == 0
                                        && m_address_ipv6[4] == 0
                                        && m_address_ipv6[5] == 0
                                        && m_address_ipv6[6] == 0
                                        && m_address_ipv6[7] == htons( 0x0001 ) );
    }

    bool Address::IsGlobalUnicast() const
    {
        return m_type == ADDRESS_IPV6 && m_address_ipv6[0] != htons( 0xfe80 )
                                      && m_address_ipv6[0] != htons( 0xfec0 )
                                      && m_address_ipv6[0] != htons( 0xff00 )
                                      && !IsLoopback();
    }

    bool Address::operator ==( const Address & other ) const
    {
        if ( m_type != other.m_type )
            return false;
        if ( m_port != other.m_port )
            return false;
        if ( m_type == ADDRESS_IPV4 && m_address_ipv4 == other.m_address_ipv4 )
            return true;
        else if ( m_type == ADDRESS_IPV6 && memcmp( m_address_ipv6, other.m_address_ipv6, sizeof( m_address_ipv6 ) ) == 0 )
            return true;
        else
            return false;
    }

    bool Address::operator !=( const Address & other ) const
    {
        return !( *this == other );
    }
}
<|endoftext|>


<commit_before>#include "Execvpcmd.h"

using namespace std;

Execvpcmd::Execvpcmd(std::string& s) : Command(s)
{
    int start = s.find_first_not_of(" ");
    int end = s.find_last_not_of(" ");
    cmd = s.substr(start, end - start + 1);
}

bool Execvpcmd::run()
{
   stringstream s;
   s.str(cmd);
   vector<string> a;
   string m, n;
   s >> m;
   a.push_back(m);
   while(s >> n)
   {
       a.push_back(n);
   }

   char ** b = new char * [a.size() + 1];

   for (unsigned i = 0; i < a.size(); i++)
   {
       b[i] = (char *)(a[i].c_str());
   }

   b[a.size()] = NULL;

    string flag;
    string info;

    if((cmd.at(0) == '[' || cmd.substr(0,4) == "test") && a.size() > 1)
    {

        if(a.size() != 2)
        {
            flag = a.at(1);
            info = a.at(2);
        }

        else
        {

            flag = "-e"; //if e flag is detected
            info = a.at(1);
        }

        struct stat testf;
        char temp[1024];
        strcpy(temp, info.c_str());
        const char* path = temp;

        if(stat(path, &testf) == -1) //Checks if the file or info exists
        {
            cout << "(False)" << endl;  //Prints out (False) if it does not exists
            return false;
        }

        if(flag == "-f") //if f flag is detected
        {
            if(S_ISREG(testf.st_mode) == false)   //Checks if it exists and is a file
            {
                cout << "(False)" << endl; //Prints out (False) if it does not exists or is not a file
                return false;

            }
                cout << "(True)" << endl;  //Prints out (True) if it exists and is a file
                return true;

        }
        else if(flag == "-d") //if d flag is detected
        {
            if(S_ISDIR(testf.st_mode))  //Checks if it exists and is a info
            {
                cout << "(True)" << endl; //Prints out (True) if it exists and is a info
                return true;
            }
            cout << "(False)" << endl;  //Prints out (False) if it does not exists or is not a info
            return false;
        }

        cout << "(True)" << endl;  //Prints out (True) if it does exist
        return true;
    }

  int error;

  int pid = fork();  //Creates parent and child
    switch(pid)
    {

        case -1:
            perror("Error in forking"); //Forking fails
            return 0;

        case 0:

            execvp(m.c_str(), b); //Executes parent/child process
            perror(cmd.c_str());
            exit(0);

       default:

            if (waitpid(pid, &error, 0) == -1) // Waits for parent/child process to finish
            {
                   perror("Error in wait"); //waits fails
                   return 0;
            }

       return error == 0;

    }

}
<commit_msg>Update Execvpcmd.cpp<commit_after>#include "Execvpcmd.h"
#include <stdio.h>
#include <string.h>

using namespace std;

Execvpcmd::Execvpcmd(std::string& s) : Command(s)
{
    int start = s.find_first_not_of(" ");
    int end = s.find_last_not_of(" ");
    cmd = s.substr(start, end - start + 1);
}

bool Execvpcmd::run()
{
   stringstream s;
   s.str(cmd);
   vector<string> a;
   string m, n;
   s >> m;
   a.push_back(m);
   while(s >> n)
   {
       a.push_back(n);
   }

   char ** b = new char * [a.size() + 1];

   for (unsigned i = 0; i < a.size(); i++)
   {
       b[i] = (char *)(a[i].c_str());
   }

   b[a.size()] = NULL;

    string flag;
    string info;

    if((cmd.at(0) == '[' || cmd.substr(0,4) == "test") && a.size() > 1)
    {

        if(a.size() != 2)
        {
            flag = a.at(1);
            info = a.at(2);
        }

        else
        {

            flag = "-e"; //if e flag is detected
            info = a.at(1);
        }

        struct stat testf;
        char temp[1024];
        strcpy(temp, info.c_str());
        const char* path = temp;

        if(stat(path, &testf) == -1) //Checks if the file or info exists
        {
            cout << "(False)" << endl;  //Prints out (False) if it does not exists
            return false;
        }

        if(flag == "-f") //if f flag is detected
        {
            if(S_ISREG(testf.st_mode) == false)   //Checks if it exists and is a file
            {
                cout << "(False)" << endl; //Prints out (False) if it does not exists or is not a file
                return false;

            }
                cout << "(True)" << endl;  //Prints out (True) if it exists and is a file
                return true;

        }
        else if(flag == "-d") //if d flag is detected
        {
            if(S_ISDIR(testf.st_mode))  //Checks if it exists and is a info
            {
                cout << "(True)" << endl; //Prints out (True) if it exists and is a info
                return true;
            }
            cout << "(False)" << endl;  //Prints out (False) if it does not exists or is not a info
            return false;
        }

        cout << "(True)" << endl;  //Prints out (True) if it does exist
        return true;
    }

  int error;

  int pid = fork();  //Creates parent and child
    switch(pid)
    {

        case -1:
            perror("Error in forking"); //Forking fails
            return 0;

        case 0:

            execvp(m.c_str(), b); //Executes parent/child process
            perror(cmd.c_str());
            exit(0);

       default:

            if (waitpid(pid, &error, 0) == -1) // Waits for parent/child process to finish
            {
                   perror("Error in wait"); //waits fails
                   return 0;
            }

       return error == 0;

    }

}
<|endoftext|>


<commit_before>// Copyright (C) 2010 - 2013 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2005 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include "copasi.h"

#include "CSlider.h"
#include "report/CKeyFactory.h"
#include "report/CCopasiObjectReference.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiRootContainer.h"
#include "model/CModel.h"

const char * CSlider::TypeName[] =
{"float", "unsignedFloat", "integer", "unsignedInteger", "Undefined", NULL};

const char * CSlider::ScaleName[] =
{"linear", "logarithmic", "undefined", NULL};

CSlider::CSlider(const std::string & name,
                 const CCopasiContainer * pParent):
  CCopasiContainer(name, pParent, "Slider"),
  mKey(CCopasiRootContainer::getKeyFactory()->add("Slider", this)),
  mAssociatedEntityKey(),
  mpSliderObject(NULL),
  mSliderType(Float),
  mValue(0.0),
  mMinValue(0),
  mMaxValue(0),
  mTickNumber(1000),
  mTickFactor(100),
  mSync(true),
  mScaling(CSlider::linear),
  mCN(),
  mInitialRefreshes()
{}

CSlider::CSlider(const CSlider & src,
                 const CCopasiContainer * pParent):
  CCopasiContainer(src, pParent),
  mKey(CCopasiRootContainer::getKeyFactory()->add("Slider", this)),
  mAssociatedEntityKey(src.mAssociatedEntityKey),
  mpSliderObject(src.mpSliderObject),
  mSliderType(src.mSliderType),
  mValue(src.mValue),
  mMinValue(src.mMinValue),
  mMaxValue(src.mMaxValue),
  mTickNumber(src.mTickNumber),
  mTickFactor(src.mTickFactor),
  mSync(src.mSync),
  mScaling(src.mScaling),
  mCN(src.mCN),
  mInitialRefreshes(src.mInitialRefreshes)
{}

CSlider::~CSlider()
{CCopasiRootContainer::getKeyFactory()->remove(mKey);}

bool CSlider::compile(const std::vector< CCopasiContainer * > & listOfContainer)
{
  //setSliderObject(CCopasiContainer::ObjectFromName(listOfContainer, getObjectName()));
  setSliderObject(getObjectDataModel()->ObjectFromName(listOfContainer, mCN));

  if (this->mSync) this->sync();

  return (mpSliderObject != NULL);
}

void CSlider::setSynced(bool synced)
{
  this->mSync = synced;
}

bool CSlider::getSynced() const
{
  return this->mSync;
}

const std::string & CSlider::getKey() const
{return mKey;}

bool CSlider::setAssociatedEntityKey(const std::string & associatedEntityKey)
{
  mAssociatedEntityKey = associatedEntityKey;

  return (CCopasiRootContainer::getKeyFactory()->get(associatedEntityKey) != NULL);
}

const std::string & CSlider::getAssociatedEntityKey() const
{return mAssociatedEntityKey;}

bool CSlider::setSliderObject(CCopasiObject * pObject)
{
  mpSliderObject = pObject;

  if (!pObject)
    {
      mInitialRefreshes.clear();
      return false;
    }

  mCN = pObject->getCN();

  std::set< const CCopasiObject * > ChangedObjects;
  ChangedObjects.insert(pObject);

  CCopasiDataModel* pDataModel = getObjectDataModel();
  assert(pDataModel != NULL);
  mInitialRefreshes = pDataModel->getModel()->buildInitialRefreshSequence(ChangedObjects);

  if (mpSliderObject->isValueInt())
    {
      this->setSliderType(Integer);
    }
  else if (mpSliderObject->isValueDbl())
    {
      this->setSliderType(Float);
    }
  else
    {
      this->setSliderType(Undefined);
    }

  if (this->mSync) this->sync();

  C_FLOAT64 value = this->getSliderValue();
  this->mOriginalValue = value;

  if (this->mMinValue > value)
    {
      this->mMinValue = value;
    }

  if (this->mMaxValue < value)
    {
      this->mMaxValue = value;
    }

  return true;
}

void CSlider::resetValue()
{
  this->setSliderValue(this->mOriginalValue);
}

void CSlider::resetRange()
{
  if (this->mSliderType != Undefined)
    {
      C_FLOAT64 value = this->getSliderValue();
      this->mMinValue = value / 2.0;
      this->mMaxValue = value == 0 ? 1.0 :  value * 2.0;
    }
}

bool CSlider::setSliderObject(const CCopasiObjectName & objectCN)
{
  //return setObjectName(objectCN);
  mCN = objectCN;
  return true;
}

CCopasiObject * CSlider::getSliderObject()
{return mpSliderObject;}

const std::string & CSlider::getSliderObjectCN() const
{return mCN; /*getObjectName();*/}

bool CSlider::setSliderType(const CSlider::Type type)
{
  mSliderType = type;
  return true;
}

CSlider::Type CSlider::getSliderType() const
{return mSliderType;}

bool CSlider::setOriginalValue(const C_FLOAT64 value)
{
  if (mSliderType != Undefined)
    {
      mOriginalValue = value;

      if (mOriginalValue < this->mMinValue)
        {
          mOriginalValue = this->mMinValue;
        }

      if (mOriginalValue > this->mMaxValue)
        {
          mOriginalValue = this->mMaxValue;
        }

      return true;
    }
  else
    {
      return false;
    }
}

bool CSlider::setSliderValue(const C_FLOAT64 value,
                             const bool & writeToObject)
{
  if (mSliderType != Undefined)
    {
      mValue = value;

      if (mValue < this->mMinValue)
        {
          mValue = this->mMinValue;
        }

      if (mValue > this->mMaxValue)
        {
          mValue = this->mMaxValue;
        }

      if (this->mSync && writeToObject)
        {
          this->writeToObject();
        }

      return true;
    }
  else
    {
      return false;
    }
}

void CSlider::sync()
{
  if (!this->mpSliderObject) return;

  if (mSliderType == CSlider::Integer || mSliderType == CSlider::UnsignedInteger)
    {
      C_INT32* reference =
        (C_INT32*)(((CCopasiObjectReference<C_INT32>*)mpSliderObject)->getValuePointer());

      mValue = *reference;
    }
  else if (mSliderType == CSlider::Float || mSliderType == CSlider::UnsignedFloat)
    {
      C_FLOAT64* reference =
        (C_FLOAT64*)(((CCopasiObjectReference<C_FLOAT64>*)mpSliderObject)->getValuePointer());

      mValue = *reference;
    }
}

void CSlider::writeToObject()
{
  if (!mpSliderObject) return;

  if (mpSliderObject->isValueDbl())
    mpSliderObject->setObjectValue(mValue);
  else if (mpSliderObject->isValueInt())
    mpSliderObject->setObjectValue((C_INT32) floor(mValue + 0.5));
  else if (mpSliderObject->isValueBool())
    mpSliderObject->setObjectValue(mValue != 0.0);

  std::vector< Refresh * >::iterator it = mInitialRefreshes.begin();
  std::vector< Refresh * >::iterator end = mInitialRefreshes.end();

  for (; it != end; ++it)
    (**it)();

  return;
}

const C_FLOAT64 & CSlider::getOriginalValue() const
{
  return this->mOriginalValue;
}

const C_FLOAT64 & CSlider::getSliderValue() const
{
  return this->mValue;
}

bool CSlider::setMinValue(const C_FLOAT64 minValue)
{
  if (mSliderType != Undefined)
    {
      mMinValue = minValue;

      if (mMaxValue < mMinValue)
        {
          mMaxValue = mMinValue;
        }

      if (mpSliderObject && getSliderValue() < mMinValue)
        {
          this->mValue = this->mMinValue;
          this->writeToObject();
        }

      return true;
    }
  else
    {
      return false;
    }
}

const C_FLOAT64 & CSlider::getMinValue() const
{return mMinValue;}

bool CSlider::setMaxValue(const C_FLOAT64 maxValue)
{
  if (mSliderType != Undefined)
    {
      mMaxValue = maxValue;

      if (mMaxValue < mMinValue)
        {
          mMinValue = mMaxValue;
        }

      if (mpSliderObject && getSliderValue() > mMaxValue)
        {
          this->mValue = this->mMaxValue;
          this->writeToObject();
        }

      return true;
    }
  else
    {
      return false;
    }
}

const C_FLOAT64 & CSlider::getMaxValue() const
{return mMaxValue;}

bool CSlider::setTickNumber(const unsigned C_INT32 tickNumber)
{
  mTickNumber = tickNumber;
  return true;
}

unsigned C_INT32 CSlider::getTickNumber() const
{return mTickNumber;}

bool CSlider::setTickFactor(const unsigned C_INT32 tickFactor)
{
  mTickFactor = tickFactor;
  return true;
}

unsigned C_INT32 CSlider::getTickFactor() const
{return mTickFactor;}

CSlider::Scale CSlider::getScaling() const
{
  return this->mScaling;
}

bool CSlider::setScaling(CSlider::Scale scaling)
{
  this->mScaling = scaling;
  return true;
}

CSlider::Scale CSlider::convertScaleNameToScale(const char* scaleName)
{
  if (!strncmp("linear", scaleName, 7))
    {
      return CSlider::linear;
    }
  else if (!strncmp("logarithmic", scaleName, 12))
    {
      return CSlider::logarithmic;
    }
  else
    {
      return CSlider::undefinedScale;
    }
}

const char* CSlider::convertScaleToScaleName(Scale scale)
{
  if (scale < 0 || scale > CSlider::undefinedScale) return ScaleName[undefinedScale];

  return ScaleName[scale];
}

/**
 * Checks whether the object the slider points to actually
 * exists.
 * Returns true if it does.
 */
bool CSlider::isValid() const
{
  bool result = false;
  // check which object if any belongs to the CN and if it is the same as
  // the pointer currently stored in the slider
  assert(getObjectDataModel() != NULL);
  const CModel* pModel = getObjectDataModel()->getModel();
  assert(pModel != NULL);
  std::vector<CCopasiContainer*> listOfContainers;
  listOfContainers.push_back(const_cast<CModel*>(pModel));
  const CCopasiObject* pObject = getObjectDataModel()->ObjectFromName(listOfContainers, this->mCN);
  result = (pObject != NULL && pObject == this->mpSliderObject);
  return result;
}
<commit_msg>- commit fix for dereferencing potential NULL pointer<commit_after>// Copyright (C) 2010 - 2014 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2005 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include "copasi.h"

#include "CSlider.h"
#include "report/CKeyFactory.h"
#include "report/CCopasiObjectReference.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiRootContainer.h"
#include "model/CModel.h"

const char * CSlider::TypeName[] =
{"float", "unsignedFloat", "integer", "unsignedInteger", "Undefined", NULL};

const char * CSlider::ScaleName[] =
{"linear", "logarithmic", "undefined", NULL};

CSlider::CSlider(const std::string & name,
                 const CCopasiContainer * pParent):
  CCopasiContainer(name, pParent, "Slider"),
  mKey(CCopasiRootContainer::getKeyFactory()->add("Slider", this)),
  mAssociatedEntityKey(),
  mpSliderObject(NULL),
  mSliderType(Float),
  mValue(0.0),
  mMinValue(0),
  mMaxValue(0),
  mTickNumber(1000),
  mTickFactor(100),
  mSync(true),
  mScaling(CSlider::linear),
  mCN(),
  mInitialRefreshes()
{}

CSlider::CSlider(const CSlider & src,
                 const CCopasiContainer * pParent):
  CCopasiContainer(src, pParent),
  mKey(CCopasiRootContainer::getKeyFactory()->add("Slider", this)),
  mAssociatedEntityKey(src.mAssociatedEntityKey),
  mpSliderObject(src.mpSliderObject),
  mSliderType(src.mSliderType),
  mValue(src.mValue),
  mMinValue(src.mMinValue),
  mMaxValue(src.mMaxValue),
  mTickNumber(src.mTickNumber),
  mTickFactor(src.mTickFactor),
  mSync(src.mSync),
  mScaling(src.mScaling),
  mCN(src.mCN),
  mInitialRefreshes(src.mInitialRefreshes)
{}

CSlider::~CSlider()
{CCopasiRootContainer::getKeyFactory()->remove(mKey);}

bool CSlider::compile(const std::vector< CCopasiContainer * > & listOfContainer)
{
  if (getObjectDataModel() == NULL) return false;

  //setSliderObject(CCopasiContainer::ObjectFromName(listOfContainer, getObjectName()));
  setSliderObject(getObjectDataModel()->ObjectFromName(listOfContainer, mCN));

  if (this->mSync) this->sync();

  return (mpSliderObject != NULL);
}

void CSlider::setSynced(bool synced)
{
  this->mSync = synced;
}

bool CSlider::getSynced() const
{
  return this->mSync;
}

const std::string & CSlider::getKey() const
{return mKey;}

bool CSlider::setAssociatedEntityKey(const std::string & associatedEntityKey)
{
  mAssociatedEntityKey = associatedEntityKey;

  return (CCopasiRootContainer::getKeyFactory()->get(associatedEntityKey) != NULL);
}

const std::string & CSlider::getAssociatedEntityKey() const
{return mAssociatedEntityKey;}

bool CSlider::setSliderObject(CCopasiObject * pObject)
{
  mpSliderObject = pObject;

  if (!pObject)
    {
      mInitialRefreshes.clear();
      return false;
    }

  mCN = pObject->getCN();

  std::set< const CCopasiObject * > ChangedObjects;
  ChangedObjects.insert(pObject);

  CCopasiDataModel* pDataModel = getObjectDataModel();
  assert(pDataModel != NULL);
  mInitialRefreshes = pDataModel->getModel()->buildInitialRefreshSequence(ChangedObjects);

  if (mpSliderObject->isValueInt())
    {
      this->setSliderType(Integer);
    }
  else if (mpSliderObject->isValueDbl())
    {
      this->setSliderType(Float);
    }
  else
    {
      this->setSliderType(Undefined);
    }

  if (this->mSync) this->sync();

  C_FLOAT64 value = this->getSliderValue();
  this->mOriginalValue = value;

  if (this->mMinValue > value)
    {
      this->mMinValue = value;
    }

  if (this->mMaxValue < value)
    {
      this->mMaxValue = value;
    }

  return true;
}

void CSlider::resetValue()
{
  this->setSliderValue(this->mOriginalValue);
}

void CSlider::resetRange()
{
  if (this->mSliderType != Undefined)
    {
      C_FLOAT64 value = this->getSliderValue();
      this->mMinValue = value / 2.0;
      this->mMaxValue = value == 0 ? 1.0 :  value * 2.0;
    }
}

bool CSlider::setSliderObject(const CCopasiObjectName & objectCN)
{
  //return setObjectName(objectCN);
  mCN = objectCN;
  return true;
}

CCopasiObject * CSlider::getSliderObject()
{return mpSliderObject;}

const std::string & CSlider::getSliderObjectCN() const
{return mCN; /*getObjectName();*/}

bool CSlider::setSliderType(const CSlider::Type type)
{
  mSliderType = type;
  return true;
}

CSlider::Type CSlider::getSliderType() const
{return mSliderType;}

bool CSlider::setOriginalValue(const C_FLOAT64 value)
{
  if (mSliderType != Undefined)
    {
      mOriginalValue = value;

      if (mOriginalValue < this->mMinValue)
        {
          mOriginalValue = this->mMinValue;
        }

      if (mOriginalValue > this->mMaxValue)
        {
          mOriginalValue = this->mMaxValue;
        }

      return true;
    }
  else
    {
      return false;
    }
}

bool CSlider::setSliderValue(const C_FLOAT64 value,
                             const bool & writeToObject)
{
  if (mSliderType != Undefined)
    {
      mValue = value;

      if (mValue < this->mMinValue)
        {
          mValue = this->mMinValue;
        }

      if (mValue > this->mMaxValue)
        {
          mValue = this->mMaxValue;
        }

      if (this->mSync && writeToObject)
        {
          this->writeToObject();
        }

      return true;
    }
  else
    {
      return false;
    }
}

void CSlider::sync()
{
  if (!this->mpSliderObject) return;

  if (mSliderType == CSlider::Integer || mSliderType == CSlider::UnsignedInteger)
    {
      C_INT32* reference =
        (C_INT32*)(((CCopasiObjectReference<C_INT32>*)mpSliderObject)->getValuePointer());

      mValue = *reference;
    }
  else if (mSliderType == CSlider::Float || mSliderType == CSlider::UnsignedFloat)
    {
      C_FLOAT64* reference =
        (C_FLOAT64*)(((CCopasiObjectReference<C_FLOAT64>*)mpSliderObject)->getValuePointer());

      mValue = *reference;
    }
}

void CSlider::writeToObject()
{
  if (!mpSliderObject) return;

  if (mpSliderObject->isValueDbl())
    mpSliderObject->setObjectValue(mValue);
  else if (mpSliderObject->isValueInt())
    mpSliderObject->setObjectValue((C_INT32) floor(mValue + 0.5));
  else if (mpSliderObject->isValueBool())
    mpSliderObject->setObjectValue(mValue != 0.0);

  std::vector< Refresh * >::iterator it = mInitialRefreshes.begin();
  std::vector< Refresh * >::iterator end = mInitialRefreshes.end();

  for (; it != end; ++it)
    (**it)();

  return;
}

const C_FLOAT64 & CSlider::getOriginalValue() const
{
  return this->mOriginalValue;
}

const C_FLOAT64 & CSlider::getSliderValue() const
{
  return this->mValue;
}

bool CSlider::setMinValue(const C_FLOAT64 minValue)
{
  if (mSliderType != Undefined)
    {
      mMinValue = minValue;

      if (mMaxValue < mMinValue)
        {
          mMaxValue = mMinValue;
        }

      if (mpSliderObject && getSliderValue() < mMinValue)
        {
          this->mValue = this->mMinValue;
          this->writeToObject();
        }

      return true;
    }
  else
    {
      return false;
    }
}

const C_FLOAT64 & CSlider::getMinValue() const
{return mMinValue;}

bool CSlider::setMaxValue(const C_FLOAT64 maxValue)
{
  if (mSliderType != Undefined)
    {
      mMaxValue = maxValue;

      if (mMaxValue < mMinValue)
        {
          mMinValue = mMaxValue;
        }

      if (mpSliderObject && getSliderValue() > mMaxValue)
        {
          this->mValue = this->mMaxValue;
          this->writeToObject();
        }

      return true;
    }
  else
    {
      return false;
    }
}

const C_FLOAT64 & CSlider::getMaxValue() const
{return mMaxValue;}

bool CSlider::setTickNumber(const unsigned C_INT32 tickNumber)
{
  mTickNumber = tickNumber;
  return true;
}

unsigned C_INT32 CSlider::getTickNumber() const
{return mTickNumber;}

bool CSlider::setTickFactor(const unsigned C_INT32 tickFactor)
{
  mTickFactor = tickFactor;
  return true;
}

unsigned C_INT32 CSlider::getTickFactor() const
{return mTickFactor;}

CSlider::Scale CSlider::getScaling() const
{
  return this->mScaling;
}

bool CSlider::setScaling(CSlider::Scale scaling)
{
  this->mScaling = scaling;
  return true;
}

CSlider::Scale CSlider::convertScaleNameToScale(const char* scaleName)
{
  if (!strncmp("linear", scaleName, 7))
    {
      return CSlider::linear;
    }
  else if (!strncmp("logarithmic", scaleName, 12))
    {
      return CSlider::logarithmic;
    }
  else
    {
      return CSlider::undefinedScale;
    }
}

const char* CSlider::convertScaleToScaleName(Scale scale)
{
  if (scale < 0 || scale > CSlider::undefinedScale) return ScaleName[undefinedScale];

  return ScaleName[scale];
}

/**
 * Checks whether the object the slider points to actually
 * exists.
 * Returns true if it does.
 */
bool CSlider::isValid() const
{
  bool result = false;
  // check which object if any belongs to the CN and if it is the same as
  // the pointer currently stored in the slider
  assert(getObjectDataModel() != NULL);
  const CModel* pModel = getObjectDataModel()->getModel();
  assert(pModel != NULL);
  std::vector<CCopasiContainer*> listOfContainers;
  listOfContainers.push_back(const_cast<CModel*>(pModel));
  const CCopasiObject* pObject = getObjectDataModel()->ObjectFromName(listOfContainers, this->mCN);
  result = (pObject != NULL && pObject == this->mpSliderObject);
  return result;
}
<|endoftext|>


<commit_before>/* medBrowserArea.cpp ---
 *
 * Author: Julien Wintz
 * Copyright (C) 2008 - Julien Wintz, Inria.
 * Created: Fri Sep 25 12:23:43 2009 (+0200)
 * Version: $Id$
 * Last-Updated: Wed Nov 10 11:15:55 2010 (+0100)
 *           By: Julien Wintz
 *     Update #: 461
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "medBrowserArea.h"

#include "medBrowserToolBoxSource.h"
#include "medPacsDataSource.h"
#include "medDatabaseDataSource.h"
#include "medFileSystemDataSource.h"

#include <QtGui>

#include <dtkCore/dtkGlobal.h>
#include <dtkGui/dtkFinder.h>

#include <medMessageController.h>
#include <medJobManager.h>
#include <medDataManager.h>
#include <medAbstractDataSource.h>
#include <medAbstractDataSourceFactory.h>
#include <medStorage.h>

#include <medDatabaseController.h>
#include <medDatabaseExporter.h>
#include <medDatabaseImporter.h>

#include <medProgressionStack.h>
#include <medToolBox.h>
#include <medToolBoxFactory.h>
#include <medToolBoxContainer.h>
#include <medBrowserToolBoxJobs.h>
#include <medPacsMover.h>
#include <medPacsWidget.h>
#include <medToolBoxCompositeDataSetImporter.h>

class medBrowserAreaPrivate
{
public:
    medDatabaseDataSource* dbSource;
    medFileSystemDataSource* fsSource;
    medPacsDataSource* pacsSource;

    medToolBoxContainer *toolbox_container;
    medBrowserToolBoxJobs *toolbox_jobs;
    medBrowserToolBoxSource *toolbox_source;
    medToolBoxCompositeDataSetImporter *toolbox_compositeimporter;

    QList <medAbstractDataSource *> data_sources;

    QStackedWidget *stack;
    QStatusBar *status;
};

// /////////////////////////////////////////////////////////////////
// medBrowserArea
// /////////////////////////////////////////////////////////////////

medBrowserArea::medBrowserArea(QWidget *parent) : QWidget(parent), d(new medBrowserAreaPrivate)
{
    // /////////////////////////////////////////////////////////////////

    d->stack = new QStackedWidget(this);

    // Source toolbox ///////////////////////////////////////////////

    d->toolbox_source = new medBrowserToolBoxSource(this);
    connect(d->toolbox_source, SIGNAL(indexChanged(int)), this, SLOT(onSourceIndexChanged(int)));

    // Jobs //////////////////////////////////////////

    d->toolbox_jobs = new medBrowserToolBoxJobs(this);
    d->toolbox_jobs->setVisible(false);
    // connect the job-manager with the visual representation
    connect(medJobManager::instance(), SIGNAL(jobRegistered(medJobItem*, QString)),
        d->toolbox_jobs->stack(),SLOT(addJobItem(medJobItem*, QString)));

    // Toolbox container /////////////////////////////////////////////

    d->toolbox_container = new medToolBoxContainer(this);
    d->toolbox_container->setFixedWidth(300);
    d->toolbox_container->addToolBox(d->toolbox_source);

    // static data sources ////////////////

    d->dbSource = new medDatabaseDataSource();
    addDataSource(d->dbSource);
    connect(d->dbSource, SIGNAL(open(const medDataIndex&)), this,SIGNAL(open(const medDataIndex&)));
    connect(medDatabaseController::instance(), SIGNAL(updated(const medDataIndex &)),d->dbSource,SLOT(update(const medDataIndex&)));
    connect(medDatabaseController::instance(), SIGNAL(displayJobItem(medJobItem *, QString)),this,SLOT(displayJobItem(medJobItem *, QString)));

    d->fsSource = new medFileSystemDataSource(this);
    addDataSource(d->fsSource);
    connect(d->fsSource, SIGNAL(open(QString)), this, SIGNAL(open(QString)));
    connect(d->fsSource, SIGNAL(load(QString)), this, SIGNAL(load(QString)));

    d->pacsSource = new medPacsDataSource(this);

    medPacsWidget * mainPacsWidget = dynamic_cast<medPacsWidget *> (d->pacsSource->mainViewWidget());
    if (mainPacsWidget->isServerFunctional())
        addDataSource(d->pacsSource);

    // dynamic data sources (from plugins) ////////////////
    foreach(QString dataSourceName, medAbstractDataSourceFactory::instance()->dataSourcePlugins()) {
        qDebug()<< "factory creates dataSource:" << dataSourceName;
        medAbstractDataSource *dataSource = medAbstractDataSourceFactory::instance()->create(dataSourceName,this);
        addDataSource(dataSource);
    }

    // Jobs should be added as the last item so that they appear at the bottom
    d->toolbox_container->addToolBox(d->toolbox_jobs);

    connect(this,SIGNAL(showError(QObject*,const QString&,unsigned int)),
            medMessageController::instance(),SLOT(showError(QObject*,const QString&,unsigned int)));

    d->toolbox_compositeimporter = new medToolBoxCompositeDataSetImporter(this);
    d->toolbox_compositeimporter->setVisible(true);
    d->toolbox_container->addToolBox(d->toolbox_compositeimporter);

    // Layout /////////////////////////////////////////////
    QHBoxLayout *layout = new QHBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    layout->addWidget(d->stack);
    layout->addWidget(d->toolbox_container);

    // make toolboxes visible
    onSourceIndexChanged(d->stack->currentIndex());

    connect(medDataManager::instance(), SIGNAL(failedToOpen(const medDataIndex&)), this, SLOT(onOpeningFailed(const medDataIndex&)));
 }

medBrowserArea::~medBrowserArea(void)
{
    delete d;
    d = NULL;
}

void medBrowserArea::setup(QStatusBar *status)
{
    d->status = status;
}

void medBrowserArea::setdw(QStatusBar *status)
{
    d->status = status;
}

void medBrowserArea::onFileImport(QString path)
{
    medDatabaseController::instance()->import(path,false);
}

void medBrowserArea::onFileIndex(QString path)
{
     medDatabaseController::instance()->import(path,true);
}

void medBrowserArea::onPartialImportAttempted(const QString& message)
{
    QMessageBox msgBox;
    msgBox.setWindowTitle("Import warning");
    msgBox.setText(message);
    msgBox.exec();
}

void medBrowserArea::onOpeningFailed(const medDataIndex& index)
{
    d->dbSource->onOpeningFailed(index);
}

void medBrowserArea::displayJobItem(medJobItem *importer, QString infoBaseName)
{
    d->toolbox_jobs->stack()->addJobItem(importer, infoBaseName);
}

void medBrowserArea::onDataImport(dtkAbstractData *data)
{
    QString patientName = data->metaDataValues(medMetaDataKeys::PatientName.key())[0];
    QString studyName   = data->metaDataValues(medMetaDataKeys::StudyDescription.key())[0];
    QString seriesName  = data->metaDataValues(medMetaDataKeys::SeriesDescription.key())[0];

    QString s_patientName = patientName.simplified();
    QString s_studyName   = studyName.simplified();
    QString s_seriesName  = seriesName.simplified();

    if ((s_patientName == "")||(s_studyName == "")||(s_seriesName == ""))
        return;

    QFileInfo fileInfo (medStorage::dataLocation() + "/" + s_patientName + "/" + s_studyName   + "/");

    if (!fileInfo.dir().exists() && !medStorage::mkpath (fileInfo.dir().path()))
    {
        qDebug() << "Cannot create directory: " << fileInfo.dir().path();
        return;
    }

    medDatabaseController::instance()->import(data);
}

void medBrowserArea::onDataReceivingFailed(QString fileName)
{
  emit(showError(this, tr("Unable to get from source the data named ") + fileName,3000));
}

void medBrowserArea::onSourceIndexChanged(int index)
{
    setToolBoxesVisible(d->stack->currentIndex(),false);
    setToolBoxesVisible(index, true);
    d->stack->setCurrentIndex(index);
}

void medBrowserArea::setToolBoxesVisible(int index, bool visible )
{
    QList<medToolBox*> toolBoxes = d->data_sources[index]->getToolboxes();
    foreach(medToolBox* toolBox, toolBoxes)
        toolBox->setVisible(visible);
}

void medBrowserArea::addDataSource( medAbstractDataSource* dataSource )
{
    d->data_sources.push_back(dataSource);
    d->stack->addWidget(dataSource->mainViewWidget());
    d->toolbox_source->addTab(dataSource->tabName(),dataSource->sourceSelectorWidget());
    QList<medToolBox*> toolBoxes = dataSource->getToolboxes();
    foreach(medToolBox* toolBox, toolBoxes) {
        toolBox->setVisible(false);
        d->toolbox_container->addToolBox(toolBox);
    }

    connect(dataSource,SIGNAL(dataToImportReceived(QString)),this,SLOT(onFileImport(QString)));
    connect(dataSource,SIGNAL(dataToIndexReceived(QString)),this,SLOT(onFileIndex(QString)));
    connect(dataSource,SIGNAL(dataReceived(dtkAbstractData *)),this,SLOT(onDataImport(dtkAbstractData *)));
    connect(dataSource,SIGNAL(dataReceivingFailed(QString)), this, SLOT(onDataReceivingFailed(QString)));
    connect(dataSource, SIGNAL(exportData(const medDataIndex&)), this, SLOT(onExportData(const medDataIndex&)));
    connect(dataSource, SIGNAL(dataRemoved(const medDataIndex&)), this, SLOT(onDataRemoved(const medDataIndex&)));
}

void medBrowserArea::onExportData(const medDataIndex &index)
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save as"), "", "*.*");

    if (fileName.isEmpty())
        return;

    dtkSmartPointer<dtkAbstractData> data = medDataManager::instance()->data(index);

    if (!data)
        return;

    medDatabaseExporter *exporter = new medDatabaseExporter (data, fileName);

    connect(exporter, SIGNAL(progressed(QObject*,int)), d->toolbox_jobs->stack(), SLOT(setProgress(QObject*,int)));

    QThreadPool::globalInstance()->start(exporter);
}

void medBrowserArea::addToolBox(medToolBox *toolbox)
{
    d->toolbox_container->addToolBox(toolbox);
}

void medBrowserArea::removeToolBox(medToolBox *toolbox)
{
    d->toolbox_container->removeToolBox(toolbox);
}

void medBrowserArea::onDataRemoved( const medDataIndex &index )
{
    d->dbSource->update(index);
}
<commit_msg>Fix bug #100: when exporting and no extension is provided the app defaults to .nii.gz<commit_after>/* medBrowserArea.cpp ---
 *
 * Author: Julien Wintz
 * Copyright (C) 2008 - Julien Wintz, Inria.
 * Created: Fri Sep 25 12:23:43 2009 (+0200)
 * Version: $Id$
 * Last-Updated: Wed Nov 10 11:15:55 2010 (+0100)
 *           By: Julien Wintz
 *     Update #: 461
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "medBrowserArea.h"

#include "medBrowserToolBoxSource.h"
#include "medPacsDataSource.h"
#include "medDatabaseDataSource.h"
#include "medFileSystemDataSource.h"

#include <QtGui>

#include <dtkCore/dtkGlobal.h>
#include <dtkGui/dtkFinder.h>

#include <medMessageController.h>
#include <medJobManager.h>
#include <medDataManager.h>
#include <medAbstractDataSource.h>
#include <medAbstractDataSourceFactory.h>
#include <medStorage.h>

#include <medDatabaseController.h>
#include <medDatabaseExporter.h>
#include <medDatabaseImporter.h>

#include <medProgressionStack.h>
#include <medToolBox.h>
#include <medToolBoxFactory.h>
#include <medToolBoxContainer.h>
#include <medBrowserToolBoxJobs.h>
#include <medPacsMover.h>
#include <medPacsWidget.h>
#include <medToolBoxCompositeDataSetImporter.h>

class medBrowserAreaPrivate
{
public:
    medDatabaseDataSource* dbSource;
    medFileSystemDataSource* fsSource;
    medPacsDataSource* pacsSource;

    medToolBoxContainer *toolbox_container;
    medBrowserToolBoxJobs *toolbox_jobs;
    medBrowserToolBoxSource *toolbox_source;
    medToolBoxCompositeDataSetImporter *toolbox_compositeimporter;

    QList <medAbstractDataSource *> data_sources;

    QStackedWidget *stack;
    QStatusBar *status;
};

// /////////////////////////////////////////////////////////////////
// medBrowserArea
// /////////////////////////////////////////////////////////////////

medBrowserArea::medBrowserArea(QWidget *parent) : QWidget(parent), d(new medBrowserAreaPrivate)
{
    // /////////////////////////////////////////////////////////////////

    d->stack = new QStackedWidget(this);

    // Source toolbox ///////////////////////////////////////////////

    d->toolbox_source = new medBrowserToolBoxSource(this);
    connect(d->toolbox_source, SIGNAL(indexChanged(int)), this, SLOT(onSourceIndexChanged(int)));

    // Jobs //////////////////////////////////////////

    d->toolbox_jobs = new medBrowserToolBoxJobs(this);
    d->toolbox_jobs->setVisible(false);
    // connect the job-manager with the visual representation
    connect(medJobManager::instance(), SIGNAL(jobRegistered(medJobItem*, QString)),
        d->toolbox_jobs->stack(),SLOT(addJobItem(medJobItem*, QString)));

    // Toolbox container /////////////////////////////////////////////

    d->toolbox_container = new medToolBoxContainer(this);
    d->toolbox_container->setFixedWidth(300);
    d->toolbox_container->addToolBox(d->toolbox_source);

    // static data sources ////////////////

    d->dbSource = new medDatabaseDataSource();
    addDataSource(d->dbSource);
    connect(d->dbSource, SIGNAL(open(const medDataIndex&)), this,SIGNAL(open(const medDataIndex&)));
    connect(medDatabaseController::instance(), SIGNAL(updated(const medDataIndex &)),d->dbSource,SLOT(update(const medDataIndex&)));
    connect(medDatabaseController::instance(), SIGNAL(displayJobItem(medJobItem *, QString)),this,SLOT(displayJobItem(medJobItem *, QString)));

    d->fsSource = new medFileSystemDataSource(this);
    addDataSource(d->fsSource);
    connect(d->fsSource, SIGNAL(open(QString)), this, SIGNAL(open(QString)));
    connect(d->fsSource, SIGNAL(load(QString)), this, SIGNAL(load(QString)));

    d->pacsSource = new medPacsDataSource(this);

    medPacsWidget * mainPacsWidget = dynamic_cast<medPacsWidget *> (d->pacsSource->mainViewWidget());
    if (mainPacsWidget->isServerFunctional())
        addDataSource(d->pacsSource);

    // dynamic data sources (from plugins) ////////////////
    foreach(QString dataSourceName, medAbstractDataSourceFactory::instance()->dataSourcePlugins()) {
        qDebug()<< "factory creates dataSource:" << dataSourceName;
        medAbstractDataSource *dataSource = medAbstractDataSourceFactory::instance()->create(dataSourceName,this);
        addDataSource(dataSource);
    }

    // Jobs should be added as the last item so that they appear at the bottom
    d->toolbox_container->addToolBox(d->toolbox_jobs);

    connect(this,SIGNAL(showError(QObject*,const QString&,unsigned int)),
            medMessageController::instance(),SLOT(showError(QObject*,const QString&,unsigned int)));

    d->toolbox_compositeimporter = new medToolBoxCompositeDataSetImporter(this);
    d->toolbox_compositeimporter->setVisible(true);
    d->toolbox_container->addToolBox(d->toolbox_compositeimporter);

    // Layout /////////////////////////////////////////////
    QHBoxLayout *layout = new QHBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    layout->addWidget(d->stack);
    layout->addWidget(d->toolbox_container);

    // make toolboxes visible
    onSourceIndexChanged(d->stack->currentIndex());

    connect(medDataManager::instance(), SIGNAL(failedToOpen(const medDataIndex&)), this, SLOT(onOpeningFailed(const medDataIndex&)));
 }

medBrowserArea::~medBrowserArea(void)
{
    delete d;
    d = NULL;
}

void medBrowserArea::setup(QStatusBar *status)
{
    d->status = status;
}

void medBrowserArea::setdw(QStatusBar *status)
{
    d->status = status;
}

void medBrowserArea::onFileImport(QString path)
{
    medDatabaseController::instance()->import(path,false);
}

void medBrowserArea::onFileIndex(QString path)
{
     medDatabaseController::instance()->import(path,true);
}

void medBrowserArea::onPartialImportAttempted(const QString& message)
{
    QMessageBox msgBox;
    msgBox.setWindowTitle("Import warning");
    msgBox.setText(message);
    msgBox.exec();
}

void medBrowserArea::onOpeningFailed(const medDataIndex& index)
{
    d->dbSource->onOpeningFailed(index);
}

void medBrowserArea::displayJobItem(medJobItem *importer, QString infoBaseName)
{
    d->toolbox_jobs->stack()->addJobItem(importer, infoBaseName);
}

void medBrowserArea::onDataImport(dtkAbstractData *data)
{
    QString patientName = data->metaDataValues(medMetaDataKeys::PatientName.key())[0];
    QString studyName   = data->metaDataValues(medMetaDataKeys::StudyDescription.key())[0];
    QString seriesName  = data->metaDataValues(medMetaDataKeys::SeriesDescription.key())[0];

    QString s_patientName = patientName.simplified();
    QString s_studyName   = studyName.simplified();
    QString s_seriesName  = seriesName.simplified();

    if ((s_patientName == "")||(s_studyName == "")||(s_seriesName == ""))
        return;

    QFileInfo fileInfo (medStorage::dataLocation() + "/" + s_patientName + "/" + s_studyName   + "/");

    if (!fileInfo.dir().exists() && !medStorage::mkpath (fileInfo.dir().path()))
    {
        qDebug() << "Cannot create directory: " << fileInfo.dir().path();
        return;
    }

    medDatabaseController::instance()->import(data);
}

void medBrowserArea::onDataReceivingFailed(QString fileName)
{
  emit(showError(this, tr("Unable to get from source the data named ") + fileName,3000));
}

void medBrowserArea::onSourceIndexChanged(int index)
{
    setToolBoxesVisible(d->stack->currentIndex(),false);
    setToolBoxesVisible(index, true);
    d->stack->setCurrentIndex(index);
}

void medBrowserArea::setToolBoxesVisible(int index, bool visible )
{
    QList<medToolBox*> toolBoxes = d->data_sources[index]->getToolboxes();
    foreach(medToolBox* toolBox, toolBoxes)
        toolBox->setVisible(visible);
}

void medBrowserArea::addDataSource( medAbstractDataSource* dataSource )
{
    d->data_sources.push_back(dataSource);
    d->stack->addWidget(dataSource->mainViewWidget());
    d->toolbox_source->addTab(dataSource->tabName(),dataSource->sourceSelectorWidget());
    QList<medToolBox*> toolBoxes = dataSource->getToolboxes();
    foreach(medToolBox* toolBox, toolBoxes) {
        toolBox->setVisible(false);
        d->toolbox_container->addToolBox(toolBox);
    }

    connect(dataSource,SIGNAL(dataToImportReceived(QString)),this,SLOT(onFileImport(QString)));
    connect(dataSource,SIGNAL(dataToIndexReceived(QString)),this,SLOT(onFileIndex(QString)));
    connect(dataSource,SIGNAL(dataReceived(dtkAbstractData *)),this,SLOT(onDataImport(dtkAbstractData *)));
    connect(dataSource,SIGNAL(dataReceivingFailed(QString)), this, SLOT(onDataReceivingFailed(QString)));
    connect(dataSource, SIGNAL(exportData(const medDataIndex&)), this, SLOT(onExportData(const medDataIndex&)));
    connect(dataSource, SIGNAL(dataRemoved(const medDataIndex&)), this, SLOT(onDataRemoved(const medDataIndex&)));
}

void medBrowserArea::onExportData(const medDataIndex &index)
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save as"), "", "*.*");

    if (fileName.isEmpty())
        return;

    QFileInfo fileInfo(fileName);

    if(fileInfo.suffix().isEmpty())
        fileName.append(".nii.gz");

    dtkSmartPointer<dtkAbstractData> data = medDataManager::instance()->data(index);

    if (!data)
        return;

    medDatabaseExporter *exporter = new medDatabaseExporter (data, fileName);

    connect(exporter, SIGNAL(progressed(QObject*,int)), d->toolbox_jobs->stack(), SLOT(setProgress(QObject*,int)));

    QThreadPool::globalInstance()->start(exporter);
}

void medBrowserArea::addToolBox(medToolBox *toolbox)
{
    d->toolbox_container->addToolBox(toolbox);
}

void medBrowserArea::removeToolBox(medToolBox *toolbox)
{
    d->toolbox_container->removeToolBox(toolbox);
}

void medBrowserArea::onDataRemoved( const medDataIndex &index )
{
    d->dbSource->update(index);
}
<|endoftext|>


<commit_before>#pragma once

namespace iod
{

  template <typename F>
  void mimosa_backend::serve(F f)
  {
    mimosa_handler<F> handler(f);
    mh::Server::Ptr server = new mh::Server;
    server->setHandler(&handler);

    if (!server->listenInet4(8888))
    {
      std::cerr << "failed to listen on the port " << 8888 << " " << ::strerror(errno) << std::endl;
      exit(1);
    }

    while(true)
      server->serveOne(0, true);
    std::cout << "serve end. " << std::endl;
  }

}
<commit_msg>mimosa backend: Access to the location and take the port as argument.<commit_after>#pragma once

namespace iod
{

  template <typename F>
  void mimosa_backend::serve(int port, F f)
  {
    mimosa_handler<F> handler(f);
    mh::Server::Ptr server = new mh::Server;
    server->setHandler(&handler);

    if (!server->listenInet4(port))
    {
      std::cerr << "Error: Failed to listen on the port " << port << " " << ::strerror(errno) << std::endl;
      return;
    }

    while(true)
      server->serveOne(0, true);
  }

}
<|endoftext|>


<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 Module:       FGJSBBase.cpp
 Author:       Jon S. Berndt
 Date started: 07/01/01
 Purpose:      Encapsulates the JSBBase object

 ------------- Copyright (C) 2001  Jon S. Berndt (jsb@hal-pc.org) -------------

 This program is free software; you can redistribute it and/or modify it under
 the terms of the GNU Lesser General Public License as published by the Free Software
 Foundation; either version 2 of the License, or (at your option) any later
 version.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
 details.

 You should have received a copy of the GNU Lesser General Public License along with
 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA  02111-1307, USA.

 Further information about the GNU Lesser General Public License can also be found on
 the world wide web at http://www.gnu.org.

FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------

HISTORY
--------------------------------------------------------------------------------
07/01/01  JSB  Created

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#include "FGJSBBase.h"

namespace JSBSim {

static const char *IdSrc = "$Id: FGJSBBase.cpp,v 1.18 2007/01/15 23:11:14 jberndt Exp $";
static const char *IdHdr = ID_JSBBASE;

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#ifndef _MSC_VER
    char FGJSBBase::highint[5]  = {27, '[', '1', 'm', '\0'      };
    char FGJSBBase::halfint[5]  = {27, '[', '2', 'm', '\0'      };
    char FGJSBBase::normint[6]  = {27, '[', '2', '2', 'm', '\0' };
    char FGJSBBase::reset[5]    = {27, '[', '0', 'm', '\0'      };
    char FGJSBBase::underon[5]  = {27, '[', '4', 'm', '\0'      };
    char FGJSBBase::underoff[6] = {27, '[', '2', '4', 'm', '\0' };
    char FGJSBBase::fgblue[6]   = {27, '[', '3', '4', 'm', '\0' };
    char FGJSBBase::fgcyan[6]   = {27, '[', '3', '6', 'm', '\0' };
    char FGJSBBase::fgred[6]    = {27, '[', '3', '1', 'm', '\0' };
    char FGJSBBase::fggreen[6]  = {27, '[', '3', '2', 'm', '\0' };
    char FGJSBBase::fgdef[6]    = {27, '[', '3', '9', 'm', '\0' };
#else
    char FGJSBBase::highint[5]  = {'\0' };
    char FGJSBBase::halfint[5]  = {'\0' };
    char FGJSBBase::normint[6]  = {'\0' };
    char FGJSBBase::reset[5]    = {'\0' };
    char FGJSBBase::underon[5]  = {'\0' };
    char FGJSBBase::underoff[6] = {'\0' };
    char FGJSBBase::fgblue[6]   = {'\0' };
    char FGJSBBase::fgcyan[6]   = {'\0' };
    char FGJSBBase::fgred[6]    = {'\0' };
    char FGJSBBase::fggreen[6]  = {'\0' };
    char FGJSBBase::fgdef[6]    = {'\0' };
#endif

const double FGJSBBase::radtodeg = 57.29578;
const double FGJSBBase::degtorad = 1.745329E-2;
const double FGJSBBase::hptoftlbssec = 550.0;
const double FGJSBBase::psftoinhg = 0.014138;
const double FGJSBBase::psftopa = 47.88;
const double FGJSBBase::fpstokts = 0.592484;
const double FGJSBBase::ktstofps = 1.68781;
const double FGJSBBase::inchtoft = 0.08333333;
const double FGJSBBase::in3tom3 = 1.638706E-5;
double FGJSBBase::Reng = 1716.0;
const double FGJSBBase::SHRatio = 1.40;

// Note that definition of lbtoslug by the inverse of slugtolb and not
// to a different constant you can also get from some tables will make
// lbtoslug*slugtolb == 1 up to the magnitude of roundoff. So converting from
// slug to lb and back will yield to the original value you started with up
// to the magnitude of roundoff.
// Taken from units gnu commandline tool
const double FGJSBBase::slugtolb = 32.174049;
const double FGJSBBase::lbtoslug = 1.0/slugtolb;

const string FGJSBBase::needed_cfg_version = "2.0";
const string FGJSBBase::JSBSim_version = "0.9.12 "__DATE__" "__TIME__;

std::queue <FGJSBBase::Message*> FGJSBBase::Messages;
FGJSBBase::Message FGJSBBase::localMsg;
unsigned int FGJSBBase::messageId = 0;

short FGJSBBase::debug_lvl  = 1;

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGJSBBase::Message* FGJSBBase::PutMessage(Message* msg)
{
  Messages.push(msg);
  return msg;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGJSBBase::Message* FGJSBBase::PutMessage(const string& text)
{
  Message *msg = new Message();
  msg->text = text;
  msg->messageId = messageId++;
  msg->subsystem = "FDM";
  msg->type = Message::eText;
  Messages.push(msg);
  return msg;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGJSBBase::Message* FGJSBBase::PutMessage(const string& text, bool bVal)
{
  Message *msg = new Message();
  msg->text = text;
  msg->messageId = messageId++;
  msg->subsystem = "FDM";
  msg->type = Message::eBool;
  msg->bVal = bVal;
  Messages.push(msg);
  return msg;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGJSBBase::Message* FGJSBBase::PutMessage(const string& text, int iVal)
{
  Message *msg = new Message();
  msg->text = text;
  msg->messageId = messageId++;
  msg->subsystem = "FDM";
  msg->type = Message::eInteger;
  msg->bVal = (iVal != 0);
  Messages.push(msg);
  return msg;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGJSBBase::Message* FGJSBBase::PutMessage(const string& text, double dVal)
{
  Message *msg = new Message();
  msg->text = text;
  msg->messageId = messageId++;
  msg->subsystem = "FDM";
  msg->type = Message::eDouble;
  msg->bVal = (dVal != 0.0);
  Messages.push(msg);
  return msg;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGJSBBase::Message* FGJSBBase::ReadMessage(void)
{
  if (!Messages.empty()) return Messages.front();
  else                   return NULL;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGJSBBase::Message* FGJSBBase::ProcessMessage(void)
{
  if (!Messages.empty())
    localMsg = *(Messages.front());
  else
    return NULL;
  Messages.pop();
  return &localMsg;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGJSBBase::disableHighLighting(void) {
  highint[0]='\0';
  halfint[0]='\0';
  normint[0]='\0';
  reset[0]='\0';
  underon[0]='\0';
  underoff[0]='\0';
  fgblue[0]='\0';
  fgcyan[0]='\0';
  fgred[0]='\0';
  fggreen[0]='\0';
  fgdef[0]='\0';
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

} // namespace JSBSim

<commit_msg>Incremented version number<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 Module:       FGJSBBase.cpp
 Author:       Jon S. Berndt
 Date started: 07/01/01
 Purpose:      Encapsulates the JSBBase object

 ------------- Copyright (C) 2001  Jon S. Berndt (jsb@hal-pc.org) -------------

 This program is free software; you can redistribute it and/or modify it under
 the terms of the GNU Lesser General Public License as published by the Free Software
 Foundation; either version 2 of the License, or (at your option) any later
 version.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
 details.

 You should have received a copy of the GNU Lesser General Public License along with
 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA  02111-1307, USA.

 Further information about the GNU Lesser General Public License can also be found on
 the world wide web at http://www.gnu.org.

FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------

HISTORY
--------------------------------------------------------------------------------
07/01/01  JSB  Created

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#include "FGJSBBase.h"

namespace JSBSim {

static const char *IdSrc = "$Id: FGJSBBase.cpp,v 1.19 2007/01/21 15:21:42 jberndt Exp $";
static const char *IdHdr = ID_JSBBASE;

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#ifndef _MSC_VER
    char FGJSBBase::highint[5]  = {27, '[', '1', 'm', '\0'      };
    char FGJSBBase::halfint[5]  = {27, '[', '2', 'm', '\0'      };
    char FGJSBBase::normint[6]  = {27, '[', '2', '2', 'm', '\0' };
    char FGJSBBase::reset[5]    = {27, '[', '0', 'm', '\0'      };
    char FGJSBBase::underon[5]  = {27, '[', '4', 'm', '\0'      };
    char FGJSBBase::underoff[6] = {27, '[', '2', '4', 'm', '\0' };
    char FGJSBBase::fgblue[6]   = {27, '[', '3', '4', 'm', '\0' };
    char FGJSBBase::fgcyan[6]   = {27, '[', '3', '6', 'm', '\0' };
    char FGJSBBase::fgred[6]    = {27, '[', '3', '1', 'm', '\0' };
    char FGJSBBase::fggreen[6]  = {27, '[', '3', '2', 'm', '\0' };
    char FGJSBBase::fgdef[6]    = {27, '[', '3', '9', 'm', '\0' };
#else
    char FGJSBBase::highint[5]  = {'\0' };
    char FGJSBBase::halfint[5]  = {'\0' };
    char FGJSBBase::normint[6]  = {'\0' };
    char FGJSBBase::reset[5]    = {'\0' };
    char FGJSBBase::underon[5]  = {'\0' };
    char FGJSBBase::underoff[6] = {'\0' };
    char FGJSBBase::fgblue[6]   = {'\0' };
    char FGJSBBase::fgcyan[6]   = {'\0' };
    char FGJSBBase::fgred[6]    = {'\0' };
    char FGJSBBase::fggreen[6]  = {'\0' };
    char FGJSBBase::fgdef[6]    = {'\0' };
#endif

const double FGJSBBase::radtodeg = 57.29578;
const double FGJSBBase::degtorad = 1.745329E-2;
const double FGJSBBase::hptoftlbssec = 550.0;
const double FGJSBBase::psftoinhg = 0.014138;
const double FGJSBBase::psftopa = 47.88;
const double FGJSBBase::fpstokts = 0.592484;
const double FGJSBBase::ktstofps = 1.68781;
const double FGJSBBase::inchtoft = 0.08333333;
const double FGJSBBase::in3tom3 = 1.638706E-5;
double FGJSBBase::Reng = 1716.0;
const double FGJSBBase::SHRatio = 1.40;

// Note that definition of lbtoslug by the inverse of slugtolb and not
// to a different constant you can also get from some tables will make
// lbtoslug*slugtolb == 1 up to the magnitude of roundoff. So converting from
// slug to lb and back will yield to the original value you started with up
// to the magnitude of roundoff.
// Taken from units gnu commandline tool
const double FGJSBBase::slugtolb = 32.174049;
const double FGJSBBase::lbtoslug = 1.0/slugtolb;

const string FGJSBBase::needed_cfg_version = "2.0";
const string FGJSBBase::JSBSim_version = "0.9.13 "__DATE__" "__TIME__;

std::queue <FGJSBBase::Message*> FGJSBBase::Messages;
FGJSBBase::Message FGJSBBase::localMsg;
unsigned int FGJSBBase::messageId = 0;

short FGJSBBase::debug_lvl  = 1;

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGJSBBase::Message* FGJSBBase::PutMessage(Message* msg)
{
  Messages.push(msg);
  return msg;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGJSBBase::Message* FGJSBBase::PutMessage(const string& text)
{
  Message *msg = new Message();
  msg->text = text;
  msg->messageId = messageId++;
  msg->subsystem = "FDM";
  msg->type = Message::eText;
  Messages.push(msg);
  return msg;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGJSBBase::Message* FGJSBBase::PutMessage(const string& text, bool bVal)
{
  Message *msg = new Message();
  msg->text = text;
  msg->messageId = messageId++;
  msg->subsystem = "FDM";
  msg->type = Message::eBool;
  msg->bVal = bVal;
  Messages.push(msg);
  return msg;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGJSBBase::Message* FGJSBBase::PutMessage(const string& text, int iVal)
{
  Message *msg = new Message();
  msg->text = text;
  msg->messageId = messageId++;
  msg->subsystem = "FDM";
  msg->type = Message::eInteger;
  msg->bVal = (iVal != 0);
  Messages.push(msg);
  return msg;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGJSBBase::Message* FGJSBBase::PutMessage(const string& text, double dVal)
{
  Message *msg = new Message();
  msg->text = text;
  msg->messageId = messageId++;
  msg->subsystem = "FDM";
  msg->type = Message::eDouble;
  msg->bVal = (dVal != 0.0);
  Messages.push(msg);
  return msg;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGJSBBase::Message* FGJSBBase::ReadMessage(void)
{
  if (!Messages.empty()) return Messages.front();
  else                   return NULL;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGJSBBase::Message* FGJSBBase::ProcessMessage(void)
{
  if (!Messages.empty())
    localMsg = *(Messages.front());
  else
    return NULL;
  Messages.pop();
  return &localMsg;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGJSBBase::disableHighLighting(void) {
  highint[0]='\0';
  halfint[0]='\0';
  normint[0]='\0';
  reset[0]='\0';
  underon[0]='\0';
  underoff[0]='\0';
  fgblue[0]='\0';
  fgcyan[0]='\0';
  fgred[0]='\0';
  fggreen[0]='\0';
  fgdef[0]='\0';
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

} // namespace JSBSim

<|endoftext|>


<commit_before>#include	"FTGLPolygonFont.h"
#include	"FTGlyphContainer.h"
#include	"FTGL.h"
#include	"FTPolyGlyph.h"

FTGLPolygonFont::FTGLPolygonFont()
:	tempGlyph(0)
{}

FTGLPolygonFont::~FTGLPolygonFont()
{}

bool FTGLPolygonFont::MakeGlyphList()
{
	FT_Face* ftFace = face.Face();

	numGlyphs = 127; // FIXME hack

	for( int n = 0; n < numGlyphs; ++n)
	{
		err = FT_Load_Glyph( *ftFace, n, FT_LOAD_DEFAULT);
		FT_Glyph ftGlyph;

		err = FT_Get_Glyph( (*ftFace)->glyph, &ftGlyph);

		tempGlyph = new FTPolyGlyph( ftGlyph, n);
		glyphList->Add( tempGlyph);
	}

	return !err;
}
<commit_msg>Changed the mode in FT_Load_Glyph()<commit_after>#include	"FTGLPolygonFont.h"
#include	"FTGlyphContainer.h"
#include	"FTGL.h"
#include	"FTPolyGlyph.h"

FTGLPolygonFont::FTGLPolygonFont()
:	tempGlyph(0)
{}

FTGLPolygonFont::~FTGLPolygonFont()
{}

bool FTGLPolygonFont::MakeGlyphList()
{
	FT_Face* ftFace = face.Face();

	numGlyphs = 127; // FIXME hack

	for( int n = 0; n < numGlyphs; ++n)
	{
		err = FT_Load_Glyph( *ftFace, n, FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP); // FT_LOAD_DEFAULT... FT_LOAD_NO_SCALE
		FT_Glyph ftGlyph;

		err = FT_Get_Glyph( (*ftFace)->glyph, &ftGlyph);

		tempGlyph = new FTPolyGlyph( ftGlyph, n);
		glyphList->Add( tempGlyph);
	}

	return !err;
}
<|endoftext|>