<commit_before>#ifndef ITER_SLICE_HPP_
#define ITER_SLICE_HPP_

#include "iterbase.hpp"

#include <iterator>
#include <type_traits>
#include <initializer_list>

namespace iter {

    //Forward declarations of Slice and slice
    //template <typename Container, typename DifferenceType>
    //class Slice;

    //template <typename T>
    //Slice<std::initializer_list<T>> slice( std::initializer_list<T>);

    //template <typename Container, typename DifferenceType>
    //Slice<Container> slice(Container &&);
    template <typename Container, typename DifferenceType>
    class Slice {
        private:
            Container container;
            DifferenceType start;
            DifferenceType stop;
            DifferenceType step;

            // The only thing allowed to directly instantiate an Slice is
            // the slice function
            //friend Slice slice<Container, DifferenceType>(Container &&);
            //template <typename T>
            //friend Slice<std::initializer_list<T>> slice(std::initializer_list<T>);
        public:
            Slice(Container&& in_container, DifferenceType start,
                  DifferenceType stop, DifferenceType step)
                : container(std::forward<Container>(in_container)),
                start{start < stop && step > 0 ? start : stop},
                stop{stop},
                step{step}
            { }

            class Iterator
                : public std::iterator<std::input_iterator_tag,
                    iterator_traits_deref<Container>>
            {
                private:
                    iterator_type<Container> sub_iter;
                    iterator_type<Container> sub_end;
                    DifferenceType current;
                    DifferenceType stop;
                    DifferenceType step;

                public:
                    Iterator (iterator_type<Container> si,
                            iterator_type<Container> se,
                            DifferenceType start,
                            DifferenceType stop,
                            DifferenceType step)
                        : sub_iter{std::move(si)},
                        sub_end{std::move(se)},
                        current{start},
                        stop{stop},
                        step{step}
                    { }

                    iterator_deref<Container> operator*() {
                        return *this->sub_iter;
                    }

                    Iterator& operator++() {
                        dumb_advance(this->sub_iter, this->sub_end,this->step);
                        this->current += this->step;
                        if (this->stop < this->current ) {
                            this->current = this->stop;
                        }
                        return *this;
                    }

                    Iterator operator++(int) {
                        auto ret = *this;
                        ++*this;
                        return ret;
                    }

                    bool operator!=(const Iterator& other) const {
                        return this->sub_iter != other.sub_iter
                            && this->current != other.current;
                    }

                    bool operator==(const Iterator& other) const {
                        return !(*this != other);
                    }
            };

            Iterator begin() {
                auto it = std::begin(this->container);
                dumb_advance(it, std::end(this->container), this->start);
                return {std::move(it), std::end(this->container),
                        this->start, this->stop, this->step};
            }

            Iterator end() {
                return {std::end(this->container), std::end(this->container),
                        this->stop, this->stop, this->step};
            }

    };

    // Helper function to instantiate a Slice
    template <typename Container, typename DifferenceType>
    Slice<Container, DifferenceType> slice(
            Container&& container,
            DifferenceType start, DifferenceType stop, DifferenceType step=1) {
        return {std::forward<Container>(container), start, stop, step};
    }

    //only give the end as an arg and assume step  is 1 and begin is 0
    template <typename Container, typename DifferenceType>
    Slice<Container, DifferenceType> slice(
            Container&& container, DifferenceType stop) {
        return {std::forward<Container>(container), 0, stop, 1};
    }

    template <typename T, typename DifferenceType>
    Slice<std::initializer_list<T>, DifferenceType> slice(
            std::initializer_list<T> il, DifferenceType start,
            DifferenceType stop, DifferenceType step=1) {
        return {std::move(il), start, stop, step};
    }

    template <typename T, typename DifferenceType>
    Slice<std::initializer_list<T>, DifferenceType> slice(
            std::initializer_list<T> il, DifferenceType stop) {
        return {std::move(il), 0, stop, 1};
    }
}

#endif
<commit_msg>moves iterators rather than copies<commit_after>#ifndef ITER_SLICE_HPP_
#define ITER_SLICE_HPP_

#include "iterbase.hpp"

#include <iterator>
#include <type_traits>
#include <initializer_list>

namespace iter {

    //Forward declarations of Slice and slice
    //template <typename Container, typename DifferenceType>
    //class Slice;

    //template <typename T>
    //Slice<std::initializer_list<T>> slice( std::initializer_list<T>);

    //template <typename Container, typename DifferenceType>
    //Slice<Container> slice(Container &&);
    template <typename Container, typename DifferenceType>
    class Slice {
        private:
            Container container;
            DifferenceType start;
            DifferenceType stop;
            DifferenceType step;

            // The only thing allowed to directly instantiate an Slice is
            // the slice function
            //friend Slice slice<Container, DifferenceType>(Container &&);
            //template <typename T>
            //friend Slice<std::initializer_list<T>> slice(std::initializer_list<T>);
        public:
            Slice(Container&& in_container, DifferenceType start,
                  DifferenceType stop, DifferenceType step)
                : container(std::forward<Container>(in_container)),
                start{start < stop && step > 0 ? start : stop},
                stop{stop},
                step{step}
            { }

            class Iterator
                : public std::iterator<std::input_iterator_tag,
                    iterator_traits_deref<Container>>
            {
                private:
                    iterator_type<Container> sub_iter;
                    iterator_type<Container> sub_end;
                    DifferenceType current;
                    DifferenceType stop;
                    DifferenceType step;

                public:
                    Iterator (iterator_type<Container>&& si,
                            iterator_type<Container>&& se,
                            DifferenceType start,
                            DifferenceType stop,
                            DifferenceType step)
                        : sub_iter{std::move(si)},
                        sub_end{std::move(se)},
                        current{start},
                        stop{stop},
                        step{step}
                    { }

                    iterator_deref<Container> operator*() {
                        return *this->sub_iter;
                    }

                    Iterator& operator++() {
                        dumb_advance(this->sub_iter, this->sub_end,this->step);
                        this->current += this->step;
                        if (this->stop < this->current ) {
                            this->current = this->stop;
                        }
                        return *this;
                    }

                    Iterator operator++(int) {
                        auto ret = *this;
                        ++*this;
                        return ret;
                    }

                    bool operator!=(const Iterator& other) const {
                        return this->sub_iter != other.sub_iter
                            && this->current != other.current;
                    }

                    bool operator==(const Iterator& other) const {
                        return !(*this != other);
                    }
            };

            Iterator begin() {
                auto it = std::begin(this->container);
                dumb_advance(it, std::end(this->container), this->start);
                return {std::move(it), std::end(this->container),
                        this->start, this->stop, this->step};
            }

            Iterator end() {
                return {std::end(this->container), std::end(this->container),
                        this->stop, this->stop, this->step};
            }

    };

    // Helper function to instantiate a Slice
    template <typename Container, typename DifferenceType>
    Slice<Container, DifferenceType> slice(
            Container&& container,
            DifferenceType start, DifferenceType stop, DifferenceType step=1) {
        return {std::forward<Container>(container), start, stop, step};
    }

    //only give the end as an arg and assume step  is 1 and begin is 0
    template <typename Container, typename DifferenceType>
    Slice<Container, DifferenceType> slice(
            Container&& container, DifferenceType stop) {
        return {std::forward<Container>(container), 0, stop, 1};
    }

    template <typename T, typename DifferenceType>
    Slice<std::initializer_list<T>, DifferenceType> slice(
            std::initializer_list<T> il, DifferenceType start,
            DifferenceType stop, DifferenceType step=1) {
        return {std::move(il), start, stop, step};
    }

    template <typename T, typename DifferenceType>
    Slice<std::initializer_list<T>, DifferenceType> slice(
            std::initializer_list<T> il, DifferenceType stop) {
        return {std::move(il), 0, stop, 1};
    }
}

#endif
<|endoftext|>


<commit_before><commit_msg>*** empty log message ***<commit_after><|endoftext|>


<commit_before>
/*

 samsonPop

 Example app using samsonClient lib
 It connect to a SAMSON system to download contents from a queue

 AUTHOR: Andreu Urruela

 */

#include <stdio.h>      // printf
#include <stdlib.h>     // exit
#include <string.h>     // memcpy
#include <iostream>     // std::cout

#include "parseArgs/parseArgs.h"
#include "logMsg/logMsg.h"

#include "au/string.h"              // au::str()

#include "samson/client/SamsonClient.h"         // samson::SamsonClient

size_t buffer_size;
size_t timeOut;

char controller[1024];
int port_node;
char queue_name[1024];
char format[81];
char user[1024];
char password[1024];
bool show_header;
bool flag_new;
bool flag_remove;
int limit;
int max_size; // Max size downloading in bytes ( just for testing )

PaArgument paArgs[] =
{
	{ "-node",      controller,    "",  PaString,  PaOpt, _i "localhost"  , PaNL, PaNL,       "SAMSON node to connect with "         },
	{ "-port_node", &port_node,    "",  PaInt,     PaOpt, SAMSON_WORKER_PORT,  1,    99999, "SAMSON server port"                     },
	{ "-user",      user,          "",  PaString,  PaOpt,  _i "anonymous", PaNL, PaNL, "User to connect to SAMSON cluster"  },
	{ "-password",  password,      "",  PaString,  PaOpt,  _i "anonymous", PaNL, PaNL, "Password to connect to SAMSON cluster"  },
	{ "-header",    &show_header,  "",  PaBool,    PaOpt,  false, false,  true,     "Show only header of blocks"   },
	{ "-remove",    &flag_remove,  "",  PaBool,    PaOpt,  false, false,  true,     "Remove downloaded stuff"   },
	{ "-new",       &flag_new,     "",  PaBool,    PaOpt,  false, false,  true,     "Get only new data"   },
	{ "-limit",     &limit,        "",  PaInt,     PaOpt,     0,      0,    10000,  "number of kvs to be shown for each block"   },
    { "-format",    format,        "",  PaString,  PaOpt,     _i "plain",      PaNL,    PaNL,  "type of output format: [plain|json|xml]"   },
	{ "-max_size",  &max_size,     "",  PaInt,     PaOpt, SAMSON_WORKER_PORT,  0,  100000000, "Max size to download"                     },
	{ " ",          queue_name,    "",  PaString,  PaReq,  (long) "null",   PaNL,   PaNL,  "name of the queue to pop data from"         },
    PA_END_OF_ARGS
};

static const char* manSynopsis =
"[-help] [-node str_samson_node] [-port_node int_port] [-header bool] [-limit int_n] [-format plain|json|xml] queue\n";

static const char* manShortDescription =
"samsonPop is an easy-to-use client to receive data from a particular queue in a SAMSON system.\n";

int logFd = -1;

void find_and_replace( std::string &source, const std::string find, std::string replace ) {
   size_t j;
   for ( ; (j = source.find( find )) != std::string::npos ; ) {
	  source.replace( j, find.length(), replace );
   }
}

void literal_string( std::string& txt )
{
   std::string slash = "\n";
   std::string replace_slash = "\\n";
   find_and_replace( txt , slash , replace_slash );
}

size_t full_read( int fd , char* data , size_t size)
{
    size_t read_size = 0;

    while( read_size < size )
    {
        ssize_t t = read( fd , data+read_size , size - read_size );

        if( t==-1)
            LM_X(1,("Error reading input data"));

        if( t == 0)
            break;
        else
            read_size+=t;
    }

    return read_size;
}

int main( int argC , const char *argV[] )
{
    paConfig("usage and exit on any warning", (void*) true);

    paConfig("log to screen",         (void*) true);
    paConfig("log to file",           (void*) false);
    paConfig("screen line format",    (void*) "TYPE:EXEC: TEXT");
    paConfig("man shortdescription",  (void*) manShortDescription);
    paConfig("man synopsis",          (void*) manSynopsis);
    paConfig("log to stderr",         (void*) true);

    // Parse input arguments
    paParse(paArgs, argC, (char**) argV, 1, false);

    if ((strcmp(format, "plain") != 0) && (strcmp(format,"json") != 0) && (strcmp(format,"xml") != 0))
    {
        fprintf(stderr, "Format '%s' not supported. Please select \"plain\", \"json\" or \"xml\"\n", format);
        exit(-1);
    }
    logFd = lmFirstDiskFileDescriptor();

    // Random initialization
    struct timeval tp;
    gettimeofday(&tp, NULL);
    int rand_seq = tp.tv_sec*1000 + tp.tv_usec%1000;
    srand( rand_seq );

    // Set 1G RAM for uploading content
    samson::SamsonClient::general_init(  1024*1024*1024 );

    // Instance of the client to connect to SAMSON system
    samson::SamsonClient client("pop");

    LM_V(("Connecting to %s ..." , controller));

    // Init connection
    au::ErrorManager error;
    client.initConnection( &error, controller , port_node , user , password );
    if( error.isActivated() )
    {
        fprintf(stderr, "Error connecting with samson cluster: %s\n" , error.getMessage().c_str() );
        exit(0);
    }
    LM_V(("Conection to %s OK" , controller));

    // Connect to a particular queue
    LM_V(("Connecting to queue %s" , queue_name ));
    client.connect_to_queue( queue_name , flag_new , flag_remove );
    LM_V(("Connected to queue %s" , queue_name ));

    size_t downloaded_content = 0;

    while( true )
    {
        samson::SamsonClientBlockInterface *block = client.getNextBlock( queue_name );
        if( block )
        {

            if( show_header )
                std::cout << block->get_header_content();
            else
            {
                std::string content = block->get_content( limit, format );
                std::cout << content;
                downloaded_content += content.length();
            }

            // Flush output
            std::cout.flush();

            delete block;

            if( max_size > 0 )
                if( downloaded_content >= max_size )
                    break;

        }
        else
            usleep(100000);

    }

    // Wait until all operations are complete
    LM_V(("Waiting for all the push operations to complete..."));
    client.waitUntilFinish();
    LM_V(("Finish correctly\n"));

}
<commit_msg>Fix broken compilation on linux<commit_after>
/*

 samsonPop

 Example app using samsonClient lib
 It connect to a SAMSON system to download contents from a queue

 AUTHOR: Andreu Urruela

 */

#include <stdio.h>      // printf
#include <stdlib.h>     // exit
#include <string.h>     // memcpy
#include <iostream>     // std::cout

#include "parseArgs/parseArgs.h"
#include "logMsg/logMsg.h"

#include "au/string.h"              // au::str()

#include "samson/client/SamsonClient.h"         // samson::SamsonClient

size_t buffer_size;
size_t timeOut;

char controller[1024];
int port_node;
char queue_name[1024];
char format[81];
char user[1024];
char password[1024];
bool show_header;
bool flag_new;
bool flag_remove;
int limit;
int max_size; // Max size downloading in bytes ( just for testing )

PaArgument paArgs[] =
{
	{ "-node",      controller,    "",  PaString,  PaOpt, _i "localhost"  , PaNL, PaNL,       "SAMSON node to connect with "         },
	{ "-port_node", &port_node,    "",  PaInt,     PaOpt, SAMSON_WORKER_PORT,  1,    99999, "SAMSON server port"                     },
	{ "-user",      user,          "",  PaString,  PaOpt,  _i "anonymous", PaNL, PaNL, "User to connect to SAMSON cluster"  },
	{ "-password",  password,      "",  PaString,  PaOpt,  _i "anonymous", PaNL, PaNL, "Password to connect to SAMSON cluster"  },
	{ "-header",    &show_header,  "",  PaBool,    PaOpt,  false, false,  true,     "Show only header of blocks"   },
	{ "-remove",    &flag_remove,  "",  PaBool,    PaOpt,  false, false,  true,     "Remove downloaded stuff"   },
	{ "-new",       &flag_new,     "",  PaBool,    PaOpt,  false, false,  true,     "Get only new data"   },
	{ "-limit",     &limit,        "",  PaInt,     PaOpt,     0,      0,    10000,  "number of kvs to be shown for each block"   },
    { "-format",    format,        "",  PaString,  PaOpt,     _i "plain",      PaNL,    PaNL,  "type of output format: [plain|json|xml]"   },
	{ "-max_size",  &max_size,     "",  PaInt,     PaOpt, SAMSON_WORKER_PORT,  0,  100000000, "Max size to download"                     },
	{ " ",          queue_name,    "",  PaString,  PaReq,  (long) "null",   PaNL,   PaNL,  "name of the queue to pop data from"         },
    PA_END_OF_ARGS
};

static const char* manSynopsis =
"[-help] [-node str_samson_node] [-port_node int_port] [-header bool] [-limit int_n] [-format plain|json|xml] queue\n";

static const char* manShortDescription =
"samsonPop is an easy-to-use client to receive data from a particular queue in a SAMSON system.\n";

int logFd = -1;

void find_and_replace( std::string &source, const std::string find, std::string replace ) {
   size_t j;
   for ( ; (j = source.find( find )) != std::string::npos ; ) {
	  source.replace( j, find.length(), replace );
   }
}

void literal_string( std::string& txt )
{
   std::string slash = "\n";
   std::string replace_slash = "\\n";
   find_and_replace( txt , slash , replace_slash );
}

size_t full_read( int fd , char* data , size_t size)
{
    size_t read_size = 0;

    while( read_size < size )
    {
        ssize_t t = read( fd , data+read_size , size - read_size );

        if( t==-1)
            LM_X(1,("Error reading input data"));

        if( t == 0)
            break;
        else
            read_size+=t;
    }

    return read_size;
}

int main( int argC , const char *argV[] )
{
    paConfig("usage and exit on any warning", (void*) true);

    paConfig("log to screen",         (void*) true);
    paConfig("log to file",           (void*) false);
    paConfig("screen line format",    (void*) "TYPE:EXEC: TEXT");
    paConfig("man shortdescription",  (void*) manShortDescription);
    paConfig("man synopsis",          (void*) manSynopsis);
    paConfig("log to stderr",         (void*) true);

    // Parse input arguments
    paParse(paArgs, argC, (char**) argV, 1, false);

    if ((strcmp(format, "plain") != 0) && (strcmp(format,"json") != 0) && (strcmp(format,"xml") != 0))
    {
        fprintf(stderr, "Format '%s' not supported. Please select \"plain\", \"json\" or \"xml\"\n", format);
        exit(-1);
    }
    logFd = lmFirstDiskFileDescriptor();

    // Random initialization
    struct timeval tp;
    gettimeofday(&tp, NULL);
    int rand_seq = tp.tv_sec*1000 + tp.tv_usec%1000;
    srand( rand_seq );

    // Set 1G RAM for uploading content
    samson::SamsonClient::general_init(  1024*1024*1024 );

    // Instance of the client to connect to SAMSON system
    samson::SamsonClient client("pop");

    LM_V(("Connecting to %s ..." , controller));

    // Init connection
    au::ErrorManager error;
    client.initConnection( &error, controller , port_node , user , password );
    if( error.isActivated() )
    {
        fprintf(stderr, "Error connecting with samson cluster: %s\n" , error.getMessage().c_str() );
        exit(0);
    }
    LM_V(("Conection to %s OK" , controller));

    // Connect to a particular queue
    LM_V(("Connecting to queue %s" , queue_name ));
    client.connect_to_queue( queue_name , flag_new , flag_remove );
    LM_V(("Connected to queue %s" , queue_name ));

    size_t downloaded_content = 0;

    while( true )
    {
        samson::SamsonClientBlockInterface *block = client.getNextBlock( queue_name );
        if( block )
        {

            if( show_header )
                std::cout << block->get_header_content();
            else
            {
                std::string content = block->get_content( limit, format );
                std::cout << content;
                downloaded_content += content.length();
            }

            // Flush output
            std::cout.flush();

            delete block;

            if( max_size > 0 )
			   if( downloaded_content >= (size_t)max_size )
                    break;

        }
        else
            usleep(100000);

    }

    // Wait until all operations are complete
    LM_V(("Waiting for all the push operations to complete..."));
    client.waitUntilFinish();
    LM_V(("Finish correctly\n"));

}
<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include <assert.h>
#include "partition.hpp"

using namespace SorterThreadedHelper;

int main(int argc, char **argv) {
  int testSize = 18;
  std::vector<double> testVec(testSize);
  for (int i = 0; i < testSize; ++i) {
    testVec[i] = i;
  }
  random_shuffle(testVec.begin(), testVec.end());
  int numPivots = 2;
  std::set<double> pivots;
  for (int i = 0; i < numPivots; i++) {
    pivots.insert(testVec[i]);
  }
  random_shuffle(testVec.begin(), testVec.end());

  Partition part(pivots);
  part.fill(testVec.begin(), testVec.end());
  int numTasks = part.numTasks();
  assert(numTasks == numPivots+1);

  std::vector<size_t> taskSizes(numTasks);
  part.taskSizes(taskSizes);
  int sumTaskSizes = 0;
  for (int i = 0; i < numTasks; ++i) {
    sumTaskSizes += taskSizes[i];
  }
  assert(sumTaskSizes == testSize);

  std::vector<double> task(testSize);
  std::set<double>::iterator pivIt = pivots.begin();
  for (int i = 0; i < numTasks; ++i) {
    assert(i == part.curTask());
    part.popTask(task.begin());
    for (int j = 0; j < taskSizes[i]; j++ ) {
      if (i != numPivots)
        assert(task[j] < *pivIt);
      else
        assert(task[j] >= *pivIt);
    }
    if (i != numPivots-1) {
      ++pivIt;
    }
  }
}
<commit_msg>increased the size of the test<commit_after>#include <iostream>
#include <algorithm>
#include <assert.h>
#include "partition.hpp"

using namespace SorterThreadedHelper;

int main(int argc, char **argv) {
  int testSize = 100000;
  std::vector<double> testVec(testSize);
  for (int i = 0; i < testSize; ++i) {
    testVec[i] = i;
  }
  random_shuffle(testVec.begin(), testVec.end());
  int numPivots = 4;
  std::set<double> pivots;
  for (int i = 0; i < numPivots; i++) {
    pivots.insert(testVec[i]);
  }
  random_shuffle(testVec.begin(), testVec.end());

  Partition part(pivots);
  part.fill(testVec.begin(), testVec.end());
  int numTasks = part.numTasks();
  assert(numTasks == numPivots+1);

  std::vector<size_t> taskSizes(numTasks);
  part.taskSizes(taskSizes);
  int sumTaskSizes = 0;
  for (int i = 0; i < numTasks; ++i) {
    sumTaskSizes += taskSizes[i];
  }
  assert(sumTaskSizes == testSize);

  std::vector<double> task(testSize);
  std::set<double>::iterator pivIt = pivots.begin();
  for (int i = 0; i < numTasks; ++i) {
    assert(i == part.curTask());
    part.popTask(task.begin());
    for (int j = 0; j < taskSizes[i]; j++ ) {
      if (i != numPivots)
        assert(task[j] < *pivIt);
      else
        assert(task[j] >= *pivIt);
    }
    if (i != numPivots-1) {
      ++pivIt;
    }
  }
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/generic/memory/lib/utils/c_str.C $                 */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file c_str.C
/// @brief Storage for the C-string name of a thing
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Jacob Harvey <jlharvey@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP

#include <fapi2.H>
#include <generic/memory/lib/utils/c_str.H>

using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_DIMM;

using fapi2::FAPI2_RC_SUCCESS;

namespace mss
{

// Thread local storage for the string we're going to create.
//TODO RTC:153924 Remove the else case when issue is resolved
#ifndef PLAT_NO_THREAD_LOCAL_STORAGE
    thread_local char c_str_storage[fapi2::MAX_ECMD_STRING_LEN];
#else
    char c_str_storage[fapi2::MAX_ECMD_STRING_LEN];
#endif

}
<commit_msg>Add snapshot of generic/memory for master-p10<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/generic/memory/lib/utils/c_str.C $                 */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file c_str.C
/// @brief Storage for the C-string name of a thing
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP

#include <fapi2.H>
#include <generic/memory/lib/utils/c_str.H>

using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_DIMM;

using fapi2::FAPI2_RC_SUCCESS;

namespace mss
{

// Thread local storage for the string we're going to create.
//TODO RTC:153924 Remove the else case when issue is resolved
#ifndef PLAT_NO_THREAD_LOCAL_STORAGE
    thread_local char c_str_storage[fapi2::MAX_ECMD_STRING_LEN];
#else
    char c_str_storage[fapi2::MAX_ECMD_STRING_LEN];
#endif

}
<|endoftext|>


<commit_before>/*
* Software License Agreement (BSD License)
*
*  Copyright (c) 2011, Willow Garage, Inc.
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of Willow Garage, Inc. 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 OWNER 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.
*
*  Author: Anatoly Baskeheev, Itseez Ltd, (myname.mysurname@mycompany.com)
*/

#include <pcl/gpu/containers/initialization.h>
#include <pcl/gpu/utils/safe_call.hpp>

#include "cuda.h"
#include <stdio.h>

#define HAVE_CUDA
//#include <pcl_config.h>

#if !defined(HAVE_CUDA)

void throw_nogpu() { throw "PCL 2.0 exception"; }
int  pcl::gpu::getCudaEnabledDeviceCount() { return 0; }
void pcl::gpu::setDevice(int /*device*/) { throw_nogpu(); }
std::string pcl::gpu::getDeviceName(int /*device*/) { throw_nogpu(); }
void pcl::gpu::printCudaDeviceInfo(int /*deivce*/){ throw_nogpu(); }
void pcl::gpu::printShortCudaDeviceInfo(int /*device*/) { throw_nogpu(); }

#else

int pcl::gpu::getCudaEnabledDeviceCount()
{
    int count;
    cudaError_t error = cudaGetDeviceCount( &count );

    if (error == cudaErrorInsufficientDriver)
        return -1;

    if (error == cudaErrorNoDevice)
        return 0;

    cudaSafeCall(error);
    return count;
}

void pcl::gpu::setDevice(int device)
{
    cudaSafeCall( cudaSetDevice( device ) );
}

std::string pcl::gpu::getDeviceName(int device)
{
    cudaDeviceProp prop;
    cudaSafeCall( cudaGetDeviceProperties(&prop, device) );

    return prop.name;
}

bool pcl::gpu::checkIfPreFermiGPU(int device)
{
  if (device < 0)
    cudaSafeCall( cudaGetDevice(&device) );

  cudaDeviceProp prop;
  cudaSafeCall( cudaGetDeviceProperties(&prop, device) );
  return prop.major < 2; // CC == 1.x
}

namespace
{
    template <class T> inline void getCudaAttribute(T *attribute, CUdevice_attribute device_attribute, int device)
    {
        *attribute = T();
        CUresult error = CUDA_SUCCESS;// = cuDeviceGetAttribute( attribute, device_attribute, device );
        if( CUDA_SUCCESS == error )
            return;

        printf("Driver API error = %04d\n", error);
        pcl::gpu::error("driver API error", __FILE__, __LINE__);
    }

    inline int convertSMVer2Cores(int major, int minor)
    {
        // Defines for GPU Architecture types (using the SM version to determine the # of cores per SM
        typedef struct {
            int SM; // 0xMm (hexidecimal notation), M = SM Major version, and m = SM minor version
            int Cores;
        } SMtoCores;

        SMtoCores gpuArchCoresPerSM[] =  { { 0x10,  8 }, { 0x11,  8 }, { 0x12,  8 }, { 0x13,  8 }, { 0x20, 32 }, { 0x21, 48 }, { -1, -1 }, {0x30, 192} };

        int index = 0;
        while (gpuArchCoresPerSM[index].SM != -1)
        {
            if (gpuArchCoresPerSM[index].SM == ((major << 4) + minor) )
                return gpuArchCoresPerSM[index].Cores;
            index++;
        }
        printf("\nMapSMtoCores undefined SMversion %d.%d!\n", major, minor);
        return -1;
    }
}

void pcl::gpu::printCudaDeviceInfo(int device)
{
    int count = getCudaEnabledDeviceCount();
    bool valid = (device >= 0) && (device < count);

    int beg = valid ? device   : 0;
    int end = valid ? device+1 : count;

    printf("*** CUDA Device Query (Runtime API) version (CUDART static linking) *** \n\n");
    printf("Device count: %d\n", count);

    int driverVersion = 0, runtimeVersion = 0;
    cudaSafeCall( cudaDriverGetVersion(&driverVersion) );
    cudaSafeCall( cudaRuntimeGetVersion(&runtimeVersion) );

    const char *computeMode[] = {
        "Default (multiple host threads can use ::cudaSetDevice() with device simultaneously)",
        "Exclusive (only one host thread in one process is able to use ::cudaSetDevice() with this device)",
        "Prohibited (no host thread can use ::cudaSetDevice() with this device)",
        "Exclusive Process (many threads in one process is able to use ::cudaSetDevice() with this device)",
        "Unknown",
        NULL
    };

    for(int dev = beg; dev < end; ++dev)
    {
        cudaDeviceProp prop;
        cudaSafeCall( cudaGetDeviceProperties(&prop, dev) );

        printf("\nDevice %d: \"%s\"\n", dev, prop.name);
        printf("  CUDA Driver Version / Runtime Version          %d.%d / %d.%d\n", driverVersion/1000, driverVersion%100, runtimeVersion/1000, runtimeVersion%100);
        printf("  CUDA Capability Major/Minor version number:    %d.%d\n", prop.major, prop.minor);
        printf("  Total amount of global memory:                 %.0f MBytes (%llu bytes)\n", (float)prop.totalGlobalMem/1048576.0f, (unsigned long long) prop.totalGlobalMem);
        printf("  (%2d) Multiprocessors x (%2d) CUDA Cores/MP:     %d CUDA Cores\n",
            prop.multiProcessorCount, convertSMVer2Cores(prop.major, prop.minor),
            convertSMVer2Cores(prop.major, prop.minor) * prop.multiProcessorCount);
        printf("  GPU Clock Speed:                               %.2f GHz\n", prop.clockRate * 1e-6f);

#if (CUDART_VERSION >= 4000)
        // This is not available in the CUDA Runtime API, so we make the necessary calls the driver API to support this for output
        int memoryClock, memBusWidth, L2CacheSize;
        getCudaAttribute<int>( &memoryClock, CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE, dev );
        getCudaAttribute<int>( &memBusWidth, CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH, dev );
        getCudaAttribute<int>( &L2CacheSize, CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE, dev );

        printf("  Memory Clock rate:                             %.2f Mhz\n", memoryClock * 1e-3f);
        printf("  Memory Bus Width:                              %d-bit\n", memBusWidth);
        if (L2CacheSize)
            printf("  L2 Cache Size:                                 %d bytes\n", L2CacheSize);

        printf("  Max Texture Dimension Size (x,y,z)             1D=(%d), 2D=(%d,%d), 3D=(%d,%d,%d)\n",
            prop.maxTexture1D, prop.maxTexture2D[0], prop.maxTexture2D[1],
            prop.maxTexture3D[0], prop.maxTexture3D[1], prop.maxTexture3D[2]);
        printf("  Max Layered Texture Size (dim) x layers        1D=(%d) x %d, 2D=(%d,%d) x %d\n",
            prop.maxTexture1DLayered[0], prop.maxTexture1DLayered[1],
            prop.maxTexture2DLayered[0], prop.maxTexture2DLayered[1], prop.maxTexture2DLayered[2]);
#endif
        printf("  Total amount of constant memory:               %u bytes\n", (int)prop.totalConstMem);
        printf("  Total amount of shared memory per block:       %u bytes\n", (int)prop.sharedMemPerBlock);
        printf("  Total number of registers available per block: %d\n", prop.regsPerBlock);
        printf("  Warp size:                                     %d\n", prop.warpSize);
        printf("  Maximum number of threads per block:           %d\n", prop.maxThreadsPerBlock);
        printf("  Maximum sizes of each dimension of a block:    %d x %d x %d\n", prop.maxThreadsDim[0], prop.maxThreadsDim[1], prop.maxThreadsDim[2]);
        printf("  Maximum sizes of each dimension of a grid:     %d x %d x %d\n", prop.maxGridSize[0], prop.maxGridSize[1],  prop.maxGridSize[2]);
        printf("  Maximum memory pitch:                          %u bytes\n", (int)prop.memPitch);
        printf("  Texture alignment:                             %u bytes\n", (int)prop.textureAlignment);

#if CUDART_VERSION >= 4000
        printf("  Concurrent copy and execution:                 %s with %d copy engine(s)\n", (prop.deviceOverlap ? "Yes" : "No"), prop.asyncEngineCount);
#else
        printf("  Concurrent copy and execution:                 %s\n", prop.deviceOverlap ? "Yes" : "No");
#endif
        printf("  Run time limit on kernels:                     %s\n", prop.kernelExecTimeoutEnabled ? "Yes" : "No");
        printf("  Integrated GPU sharing Host Memory:            %s\n", prop.integrated ? "Yes" : "No");
        printf("  Support host page-locked memory mapping:       %s\n", prop.canMapHostMemory ? "Yes" : "No");

        printf("  Concurrent kernel execution:                   %s\n", prop.concurrentKernels ? "Yes" : "No");
        printf("  Alignment requirement for Surfaces:            %s\n", prop.surfaceAlignment ? "Yes" : "No");
        printf("  Device has ECC support enabled:                %s\n", prop.ECCEnabled ? "Yes" : "No");
        printf("  Device is using TCC driver mode:               %s\n", prop.tccDriver ? "Yes" : "No");
#if CUDART_VERSION >= 4000
        printf("  Device supports Unified Addressing (UVA):      %s\n", prop.unifiedAddressing ? "Yes" : "No");
        printf("  Device PCI Bus ID / PCI location ID:           %d / %d\n", prop.pciBusID, prop.pciDeviceID );
#endif
        printf("  Compute Mode:\n");
        printf("      %s \n", computeMode[prop.computeMode]);
    }

    printf("\n");
    printf("deviceQuery, CUDA Driver = CUDART");
    printf(", CUDA Driver Version  = %d.%d", driverVersion / 1000, driverVersion % 100);
    printf(", CUDA Runtime Version = %d.%d", runtimeVersion/1000, runtimeVersion%100);
    printf(", NumDevs = %d\n\n", count);
    fflush(stdout);
}

void pcl::gpu::printShortCudaDeviceInfo(int device)
{
    int count = getCudaEnabledDeviceCount();
    bool valid = (device >= 0) && (device < count);

    int beg = valid ? device   : 0;
    int end = valid ? device+1 : count;

    int driverVersion = 0, runtimeVersion = 0;
    cudaSafeCall( cudaDriverGetVersion(&driverVersion) );
    cudaSafeCall( cudaRuntimeGetVersion(&runtimeVersion) );

    for(int dev = beg; dev < end; ++dev)
    {
        cudaDeviceProp prop;
        cudaSafeCall( cudaGetDeviceProperties(&prop, dev) );

        const char *arch_str = prop.major < 2 ? " (not Fermi)" : "";
        printf("Device %d:  \"%s\"  %.0fMb", dev, prop.name, (float)prop.totalGlobalMem/1048576.0f);
        printf(", sm_%d%d%s, %d cores", prop.major, prop.minor, arch_str, convertSMVer2Cores(prop.major, prop.minor) * prop.multiProcessorCount);
        printf(", Driver/Runtime ver.%d.%d/%d.%d\n", driverVersion/1000, driverVersion%100, runtimeVersion/1000, runtimeVersion%100);
    }
    fflush(stdout);
}

#endif
<commit_msg>updated printCudaDeviceInfo to support Kepler<commit_after>/*
* Software License Agreement (BSD License)
*
*  Copyright (c) 2011, Willow Garage, Inc.
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of Willow Garage, Inc. 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 OWNER 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.
*
*  Author: Anatoly Baskeheev, Itseez Ltd, (myname.mysurname@mycompany.com)
*/

#include <pcl/gpu/containers/initialization.h>
#include <pcl/gpu/utils/safe_call.hpp>

#include "cuda.h"
#include <stdio.h>

#define HAVE_CUDA
//#include <pcl_config.h>

#if !defined(HAVE_CUDA)

void throw_nogpu() { throw "PCL 2.0 exception"; }
int  pcl::gpu::getCudaEnabledDeviceCount() { return 0; }
void pcl::gpu::setDevice(int /*device*/) { throw_nogpu(); }
std::string pcl::gpu::getDeviceName(int /*device*/) { throw_nogpu(); }
void pcl::gpu::printCudaDeviceInfo(int /*deivce*/){ throw_nogpu(); }
void pcl::gpu::printShortCudaDeviceInfo(int /*device*/) { throw_nogpu(); }

#else

int pcl::gpu::getCudaEnabledDeviceCount()
{
    int count;
    cudaError_t error = cudaGetDeviceCount( &count );

    if (error == cudaErrorInsufficientDriver)
        return -1;

    if (error == cudaErrorNoDevice)
        return 0;

    cudaSafeCall(error);
    return count;
}

void pcl::gpu::setDevice(int device)
{
    cudaSafeCall( cudaSetDevice( device ) );
}

std::string pcl::gpu::getDeviceName(int device)
{
    cudaDeviceProp prop;
    cudaSafeCall( cudaGetDeviceProperties(&prop, device) );

    return prop.name;
}

bool pcl::gpu::checkIfPreFermiGPU(int device)
{
  if (device < 0)
    cudaSafeCall( cudaGetDevice(&device) );

  cudaDeviceProp prop;
  cudaSafeCall( cudaGetDeviceProperties(&prop, device) );
  return prop.major < 2; // CC == 1.x
}

namespace
{
    template <class T> inline void getCudaAttribute(T *attribute, CUdevice_attribute device_attribute, int device)
    {
        *attribute = T();
        CUresult error = CUDA_SUCCESS;// = cuDeviceGetAttribute( attribute, device_attribute, device );
        if( CUDA_SUCCESS == error )
            return;

        printf("Driver API error = %04d\n", error);
        pcl::gpu::error("driver API error", __FILE__, __LINE__);
    }

    inline int convertSMVer2Cores(int major, int minor)
    {
        // Defines for GPU Architecture types (using the SM version to determine the # of cores per SM
        typedef struct {
            int SM; // 0xMm (hexidecimal notation), M = SM Major version, and m = SM minor version
            int Cores;
        } SMtoCores;

        SMtoCores gpuArchCoresPerSM[] =  { { 0x10,  8 }, { 0x11,  8 }, { 0x12,  8 }, { 0x13,  8 }, { 0x20, 32 }, { 0x21, 48 }, {0x30, 192}, { -1, -1 }  };

        int index = 0;
        while (gpuArchCoresPerSM[index].SM != -1)
        {
            if (gpuArchCoresPerSM[index].SM == ((major << 4) + minor) )
                return gpuArchCoresPerSM[index].Cores;
            index++;
        }
        printf("\nMapSMtoCores undefined SMversion %d.%d!\n", major, minor);
        return -1;
    }
}

void pcl::gpu::printCudaDeviceInfo(int device)
{
    int count = getCudaEnabledDeviceCount();
    bool valid = (device >= 0) && (device < count);

    int beg = valid ? device   : 0;
    int end = valid ? device+1 : count;

    printf("*** CUDA Device Query (Runtime API) version (CUDART static linking) *** \n\n");
    printf("Device count: %d\n", count);

    int driverVersion = 0, runtimeVersion = 0;
    cudaSafeCall( cudaDriverGetVersion(&driverVersion) );
    cudaSafeCall( cudaRuntimeGetVersion(&runtimeVersion) );

    const char *computeMode[] = {
        "Default (multiple host threads can use ::cudaSetDevice() with device simultaneously)",
        "Exclusive (only one host thread in one process is able to use ::cudaSetDevice() with this device)",
        "Prohibited (no host thread can use ::cudaSetDevice() with this device)",
        "Exclusive Process (many threads in one process is able to use ::cudaSetDevice() with this device)",
        "Unknown",
        NULL
    };

    for(int dev = beg; dev < end; ++dev)
    {
        cudaDeviceProp prop;
        cudaSafeCall( cudaGetDeviceProperties(&prop, dev) );

        printf("\nDevice %d: \"%s\"\n", dev, prop.name);
        printf("  CUDA Driver Version / Runtime Version          %d.%d / %d.%d\n", driverVersion/1000, driverVersion%100, runtimeVersion/1000, runtimeVersion%100);
        printf("  CUDA Capability Major/Minor version number:    %d.%d\n", prop.major, prop.minor);
        printf("  Total amount of global memory:                 %.0f MBytes (%llu bytes)\n", (float)prop.totalGlobalMem/1048576.0f, (unsigned long long) prop.totalGlobalMem);
        printf("  (%2d) Multiprocessors x (%2d) CUDA Cores/MP:     %d CUDA Cores\n",
            prop.multiProcessorCount, convertSMVer2Cores(prop.major, prop.minor),
            convertSMVer2Cores(prop.major, prop.minor) * prop.multiProcessorCount);
        printf("  GPU Clock Speed:                               %.2f GHz\n", prop.clockRate * 1e-6f);

#if (CUDART_VERSION >= 4000)
        // This is not available in the CUDA Runtime API, so we make the necessary calls the driver API to support this for output
        int memoryClock, memBusWidth, L2CacheSize;
        getCudaAttribute<int>( &memoryClock, CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE, dev );
        getCudaAttribute<int>( &memBusWidth, CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH, dev );
        getCudaAttribute<int>( &L2CacheSize, CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE, dev );

        printf("  Memory Clock rate:                             %.2f Mhz\n", memoryClock * 1e-3f);
        printf("  Memory Bus Width:                              %d-bit\n", memBusWidth);
        if (L2CacheSize)
            printf("  L2 Cache Size:                                 %d bytes\n", L2CacheSize);

        printf("  Max Texture Dimension Size (x,y,z)             1D=(%d), 2D=(%d,%d), 3D=(%d,%d,%d)\n",
            prop.maxTexture1D, prop.maxTexture2D[0], prop.maxTexture2D[1],
            prop.maxTexture3D[0], prop.maxTexture3D[1], prop.maxTexture3D[2]);
        printf("  Max Layered Texture Size (dim) x layers        1D=(%d) x %d, 2D=(%d,%d) x %d\n",
            prop.maxTexture1DLayered[0], prop.maxTexture1DLayered[1],
            prop.maxTexture2DLayered[0], prop.maxTexture2DLayered[1], prop.maxTexture2DLayered[2]);
#endif
        printf("  Total amount of constant memory:               %u bytes\n", (int)prop.totalConstMem);
        printf("  Total amount of shared memory per block:       %u bytes\n", (int)prop.sharedMemPerBlock);
        printf("  Total number of registers available per block: %d\n", prop.regsPerBlock);
        printf("  Warp size:                                     %d\n", prop.warpSize);
        printf("  Maximum number of threads per block:           %d\n", prop.maxThreadsPerBlock);
        printf("  Maximum sizes of each dimension of a block:    %d x %d x %d\n", prop.maxThreadsDim[0], prop.maxThreadsDim[1], prop.maxThreadsDim[2]);
        printf("  Maximum sizes of each dimension of a grid:     %d x %d x %d\n", prop.maxGridSize[0], prop.maxGridSize[1],  prop.maxGridSize[2]);
        printf("  Maximum memory pitch:                          %u bytes\n", (int)prop.memPitch);
        printf("  Texture alignment:                             %u bytes\n", (int)prop.textureAlignment);

#if CUDART_VERSION >= 4000
        printf("  Concurrent copy and execution:                 %s with %d copy engine(s)\n", (prop.deviceOverlap ? "Yes" : "No"), prop.asyncEngineCount);
#else
        printf("  Concurrent copy and execution:                 %s\n", prop.deviceOverlap ? "Yes" : "No");
#endif
        printf("  Run time limit on kernels:                     %s\n", prop.kernelExecTimeoutEnabled ? "Yes" : "No");
        printf("  Integrated GPU sharing Host Memory:            %s\n", prop.integrated ? "Yes" : "No");
        printf("  Support host page-locked memory mapping:       %s\n", prop.canMapHostMemory ? "Yes" : "No");

        printf("  Concurrent kernel execution:                   %s\n", prop.concurrentKernels ? "Yes" : "No");
        printf("  Alignment requirement for Surfaces:            %s\n", prop.surfaceAlignment ? "Yes" : "No");
        printf("  Device has ECC support enabled:                %s\n", prop.ECCEnabled ? "Yes" : "No");
        printf("  Device is using TCC driver mode:               %s\n", prop.tccDriver ? "Yes" : "No");
#if CUDART_VERSION >= 4000
        printf("  Device supports Unified Addressing (UVA):      %s\n", prop.unifiedAddressing ? "Yes" : "No");
        printf("  Device PCI Bus ID / PCI location ID:           %d / %d\n", prop.pciBusID, prop.pciDeviceID );
#endif
        printf("  Compute Mode:\n");
        printf("      %s \n", computeMode[prop.computeMode]);
    }

    printf("\n");
    printf("deviceQuery, CUDA Driver = CUDART");
    printf(", CUDA Driver Version  = %d.%d", driverVersion / 1000, driverVersion % 100);
    printf(", CUDA Runtime Version = %d.%d", runtimeVersion/1000, runtimeVersion%100);
    printf(", NumDevs = %d\n\n", count);
    fflush(stdout);
}

void pcl::gpu::printShortCudaDeviceInfo(int device)
{
    int count = getCudaEnabledDeviceCount();
    bool valid = (device >= 0) && (device < count);

    int beg = valid ? device   : 0;
    int end = valid ? device+1 : count;

    int driverVersion = 0, runtimeVersion = 0;
    cudaSafeCall( cudaDriverGetVersion(&driverVersion) );
    cudaSafeCall( cudaRuntimeGetVersion(&runtimeVersion) );

    for(int dev = beg; dev < end; ++dev)
    {
        cudaDeviceProp prop;
        cudaSafeCall( cudaGetDeviceProperties(&prop, dev) );

        const char *arch_str = prop.major < 2 ? " (not Fermi)" : "";
        printf("Device %d:  \"%s\"  %.0fMb", dev, prop.name, (float)prop.totalGlobalMem/1048576.0f);
        printf(", sm_%d%d%s, %d cores", prop.major, prop.minor, arch_str, convertSMVer2Cores(prop.major, prop.minor) * prop.multiProcessorCount);
        printf(", Driver/Runtime ver.%d.%d/%d.%d\n", driverVersion/1000, driverVersion%100, runtimeVersion/1000, runtimeVersion%100);
    }
    fflush(stdout);
}

#endif
<|endoftext|>


<commit_before>/************************************************************************
	filename: 	CEGUIFontManager.cpp
	created:	21/2/2004
	author:		Paul D Turner

	purpose:	Implements the FontManager class
*************************************************************************/
/*************************************************************************
    Crazy Eddie's GUI System (http://www.cegui.org.uk)
    Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)

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

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

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*************************************************************************/
#include "CEGUIFontManager.h"
#include "CEGUIExceptions.h"
#include "CEGUILogger.h"
#include "CEGUIFont.h"
#include "CEGUIFontManager_implData.h"
#include "CEGUIFont_implData.h"

#include <ft2build.h>
#include FT_FREETYPE_H

// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
	Static Data Definitions
*************************************************************************/
// singleton instance pointer
template<> FontManager* Singleton<FontManager>::ms_Singleton	= NULL;

/*************************************************************************
	constructor
*************************************************************************/
FontManager::FontManager(void)
{
	d_implData = new FontManagerImplData;

	if (FT_Init_FreeType(&d_implData->d_ftlib))
	{
		throw GenericException((utf8*)"FontManager::FontManager - Failed to initialise the FreeType library.");
	}

	Logger::getSingleton().logEvent((utf8*)"CEGUI::FontManager singleton created.");
}

/*************************************************************************
	Destructor
*************************************************************************/
FontManager::~FontManager(void)
{
	Logger::getSingleton().logEvent((utf8*)"---- Begining cleanup of Font system ----");
	destroyAllFonts();

	FT_Done_FreeType(d_implData->d_ftlib);
	delete d_implData;

	Logger::getSingleton().logEvent((utf8*)"CEGUI::FontManager singleton destroyed.");
}

/*************************************************************************
	Create a font from a definition file
*************************************************************************/
Font* FontManager::createFont(const String& filename, const String& resourceGroup)
{
	Logger::getSingleton().logEvent((utf8*)"Attempting to create Font from the information specified in file '" + filename + "'.");

	Font* temp = new Font(filename, resourceGroup, new Font::FontImplData(d_implData->d_ftlib));

	String name = temp->getName();

	if (isFontPresent(name))
	{
		delete temp;

		throw AlreadyExistsException((utf8*)"FontManager::createFont - A font named '" + name + "' already exists.");
	}

	d_fonts[name] = temp;

	return temp;
}

/*************************************************************************
	Create a font from an installed OS font
*************************************************************************/
Font* FontManager::createFont(const String& name, const String& fontname, uint size, uint flags, const String& resourceGroup)
{
	char strbuf[16];
	sprintf(strbuf, "%d", size);
	Logger::getSingleton().logEvent((utf8*)"Attempting to create Font '" + name + "' using the font file '" + fontname + "' and a size of " + strbuf + ".");

	// first ensure name uniqueness
	if (isFontPresent(name))
	{
		throw AlreadyExistsException((utf8*)"FontManager::createFont - A font named '" + name + "' already exists.");
	}

	Font* temp = new Font(name, fontname, resourceGroup, size, flags, new Font::FontImplData(d_implData->d_ftlib));
	d_fonts[name] = temp;

	return temp;
}

/*************************************************************************
	Destroy the named font
*************************************************************************/
void FontManager::destroyFont(const String& name)
{
	 FontRegistry::iterator	pos = d_fonts.find(name);

	if (pos != d_fonts.end())
	{
		String tmpName(name);

		delete pos->second;
		d_fonts.erase(pos);

		Logger::getSingleton().logEvent((utf8*)"Font '" + tmpName +"' has been destroyed.");
	}

}

/*************************************************************************
	Destroys the given Font object
*************************************************************************/
void FontManager::destroyFont(Font* font)
{
	if (font != NULL)
	{
		destroyFont(font->getName());
	}

}

/*************************************************************************
	Destroys all Font objects registered in the system
*************************************************************************/
void FontManager::destroyAllFonts(void)
{
	while (!d_fonts.empty())
	{
		destroyFont(d_fonts.begin()->first);
	}

}

/*************************************************************************
	Check to see if a font is available
*************************************************************************/
bool FontManager::isFontPresent(const String& name) const
{
	return (d_fonts.find(name) != d_fonts.end());
}

/*************************************************************************
	Return a pointer to the named font
*************************************************************************/
Font* FontManager::getFont(const String& name) const
{
	FontRegistry::const_iterator pos = d_fonts.find(name);

	if (pos == d_fonts.end())
	{
		throw UnknownObjectException("FontManager::getFont - A Font object with the specified name '" + name +"' does not exist within the system");
	}

	return pos->second;
}

/*************************************************************************
	Notify the FontManager of the current (usually new) display
	resolution.
*************************************************************************/
void FontManager::notifyScreenResolution(const Size& size)
{
	// notify all attached Font objects of the change in resolution
	FontRegistry::iterator pos = d_fonts.begin(), end = d_fonts.end();

	for (; pos != end; ++pos)
	{
		pos->second->notifyScreenResolution(size);
	}

}

FontManager& FontManager::getSingleton(void)
{
	return Singleton<FontManager>::getSingleton();
}

FontManager* FontManager::getSingletonPtr(void)
{
	return Singleton<FontManager>::getSingletonPtr();
}

/*************************************************************************
	Return a FontManager::FontIterator object to iterate over the
	available Font objects.
*************************************************************************/
FontManager::FontIterator FontManager::getIterator(void) const
{
	return FontIterator(d_fonts.begin(), d_fonts.end());
}

} // End of  CEGUI namespace section
<commit_msg>Modified FontManager to automatically set the first Font created as the default.<commit_after>/************************************************************************
	filename: 	CEGUIFontManager.cpp
	created:	21/2/2004
	author:		Paul D Turner

	purpose:	Implements the FontManager class
*************************************************************************/
/*************************************************************************
    Crazy Eddie's GUI System (http://www.cegui.org.uk)
    Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)

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

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

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*************************************************************************/
#include "CEGUIFontManager.h"
#include "CEGUIExceptions.h"
#include "CEGUILogger.h"
#include "CEGUIFont.h"
#include "CEGUIFontManager_implData.h"
#include "CEGUIFont_implData.h"
#include "CEGUISystem.h"

#include <ft2build.h>
#include FT_FREETYPE_H

// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
	Static Data Definitions
*************************************************************************/
// singleton instance pointer
template<> FontManager* Singleton<FontManager>::ms_Singleton	= NULL;

/*************************************************************************
	constructor
*************************************************************************/
FontManager::FontManager(void)
{
	d_implData = new FontManagerImplData;

	if (FT_Init_FreeType(&d_implData->d_ftlib))
	{
		throw GenericException((utf8*)"FontManager::FontManager - Failed to initialise the FreeType library.");
	}

	Logger::getSingleton().logEvent((utf8*)"CEGUI::FontManager singleton created.");
}

/*************************************************************************
	Destructor
*************************************************************************/
FontManager::~FontManager(void)
{
	Logger::getSingleton().logEvent((utf8*)"---- Begining cleanup of Font system ----");
	destroyAllFonts();

	FT_Done_FreeType(d_implData->d_ftlib);
	delete d_implData;

	Logger::getSingleton().logEvent((utf8*)"CEGUI::FontManager singleton destroyed.");
}

/*************************************************************************
	Create a font from a definition file
*************************************************************************/
Font* FontManager::createFont(const String& filename, const String& resourceGroup)
{
	Logger::getSingleton().logEvent((utf8*)"Attempting to create Font from the information specified in file '" + filename + "'.");

	Font* temp = new Font(filename, resourceGroup, new Font::FontImplData(d_implData->d_ftlib));

	String name = temp->getName();

	if (isFontPresent(name))
	{
		delete temp;

		throw AlreadyExistsException((utf8*)"FontManager::createFont - A font named '" + name + "' already exists.");
	}

	d_fonts[name] = temp;

    // if this was the first font created, set it as the default font
    if (d_fonts.size() == 1)
    {
        System::getSingleton().setDefaultFont(temp);
    }

	return temp;
}

/*************************************************************************
	Create a font from an installed OS font
*************************************************************************/
Font* FontManager::createFont(const String& name, const String& fontname, uint size, uint flags, const String& resourceGroup)
{
	char strbuf[16];
	sprintf(strbuf, "%d", size);
	Logger::getSingleton().logEvent((utf8*)"Attempting to create Font '" + name + "' using the font file '" + fontname + "' and a size of " + strbuf + ".");

	// first ensure name uniqueness
	if (isFontPresent(name))
	{
		throw AlreadyExistsException((utf8*)"FontManager::createFont - A font named '" + name + "' already exists.");
	}

	Font* temp = new Font(name, fontname, resourceGroup, size, flags, new Font::FontImplData(d_implData->d_ftlib));
	d_fonts[name] = temp;

    // if this was the first font created, set it as the default font
    if (d_fonts.size() == 1)
    {
        System::getSingleton().setDefaultFont(temp);
    }

	return temp;
}

/*************************************************************************
	Destroy the named font
*************************************************************************/
void FontManager::destroyFont(const String& name)
{
	 FontRegistry::iterator	pos = d_fonts.find(name);

	if (pos != d_fonts.end())
	{
		String tmpName(name);

		delete pos->second;
		d_fonts.erase(pos);

		Logger::getSingleton().logEvent((utf8*)"Font '" + tmpName +"' has been destroyed.");
	}

}

/*************************************************************************
	Destroys the given Font object
*************************************************************************/
void FontManager::destroyFont(Font* font)
{
	if (font != NULL)
	{
		destroyFont(font->getName());
	}

}

/*************************************************************************
	Destroys all Font objects registered in the system
*************************************************************************/
void FontManager::destroyAllFonts(void)
{
	while (!d_fonts.empty())
	{
		destroyFont(d_fonts.begin()->first);
	}

}

/*************************************************************************
	Check to see if a font is available
*************************************************************************/
bool FontManager::isFontPresent(const String& name) const
{
	return (d_fonts.find(name) != d_fonts.end());
}

/*************************************************************************
	Return a pointer to the named font
*************************************************************************/
Font* FontManager::getFont(const String& name) const
{
	FontRegistry::const_iterator pos = d_fonts.find(name);

	if (pos == d_fonts.end())
	{
		throw UnknownObjectException("FontManager::getFont - A Font object with the specified name '" + name +"' does not exist within the system");
	}

	return pos->second;
}

/*************************************************************************
	Notify the FontManager of the current (usually new) display
	resolution.
*************************************************************************/
void FontManager::notifyScreenResolution(const Size& size)
{
	// notify all attached Font objects of the change in resolution
	FontRegistry::iterator pos = d_fonts.begin(), end = d_fonts.end();

	for (; pos != end; ++pos)
	{
		pos->second->notifyScreenResolution(size);
	}

}

FontManager& FontManager::getSingleton(void)
{
	return Singleton<FontManager>::getSingleton();
}

FontManager* FontManager::getSingletonPtr(void)
{
	return Singleton<FontManager>::getSingletonPtr();
}

/*************************************************************************
	Return a FontManager::FontIterator object to iterate over the
	available Font objects.
*************************************************************************/
FontManager::FontIterator FontManager::getIterator(void) const
{
	return FontIterator(d_fonts.begin(), d_fonts.end());
}

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: dndentry.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: jl $ $Date: 2001-02-08 14:30:48 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XSET_HPP_
#include <com/sun/star/container/XSet.hpp>
#endif

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#include "source.hxx"
#include "target.hxx"

using namespace ::rtl                       ;
using namespace ::com::sun::star::uno       ;
using namespace ::com::sun::star::registry  ;
using namespace ::cppu                      ;
using namespace ::com::sun::star::lang;

Reference< XInterface > SAL_CALL createDragSource( const Reference< XMultiServiceFactory >& rServiceManager )
{
    DragSource* pSource= new DragSource( rServiceManager );
    return Reference<XInterface>( static_cast<XInitialization*>(pSource), UNO_QUERY);
}

Reference< XInterface > SAL_CALL createDropTarget( const Reference< XMultiServiceFactory >& rServiceManager )
{
    DropTarget* pTarget= new DropTarget( rServiceManager );
    return Reference<XInterface>( static_cast<XInitialization*>(pTarget), UNO_QUERY);
}

extern "C"
{

//----------------------------------------------------------------------
// component_getImplementationEnvironment
//----------------------------------------------------------------------

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

//-------------------------------------------------------------------------
// component_writeInfo - to register a UNO-Service
// to register a UNO-Service use: regcomp -register -r *.rdb -c *.dll
// to view the registry use: regview *.rdb /SERVICES/ServiceName
// (you must use the full services name e.g. com.sun.star.frame.FilePicker
//-------------------------------------------------------------------------

sal_Bool SAL_CALL component_writeInfo( void* pServiceManager, void* pRegistryKey )
{
    sal_Bool bRetVal = sal_False;

    if ( pRegistryKey )
    {
        try
        {
            Reference< XRegistryKey > pXNewKey( static_cast< XRegistryKey* >( pRegistryKey ) );
            pXNewKey->createKey( OUString( RTL_CONSTASCII_USTRINGPARAM( DNDSOURCE_REGKEY_NAME ) ) );
            bRetVal = sal_True;

            pXNewKey=  static_cast< XRegistryKey* >( pRegistryKey );
            pXNewKey->createKey( OUString( RTL_CONSTASCII_USTRINGPARAM( DNDTARGET_REGKEY_NAME ) ) );
            bRetVal = sal_True;
        }
        catch( InvalidRegistryException& )
        {
            OSL_ENSHURE(sal_False, "InvalidRegistryException caught");
            bRetVal = sal_False;
        }
    }

    return bRetVal;
}

//----------------------------------------------------------------------
// component_getFactory
// returns a factory to create XFilePicker-Services
//----------------------------------------------------------------------

void* SAL_CALL component_getFactory( const sal_Char* pImplName, uno_Interface* pSrvManager, uno_Interface* pRegistryKey )
{
    void* pRet = 0;
    Reference< XSingleServiceFactory > xFactory;

    if ( pSrvManager && ( 0 == rtl_str_compare( pImplName, DNDSOURCE_IMPL_NAME ) ) )
    {
        Sequence< OUString > aSNS( 1 );
        aSNS.getArray( )[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( DNDSOURCE_SERVICE_NAME ) );

        xFactory= createSingleFactory(
            reinterpret_cast< XMultiServiceFactory* > ( pSrvManager ),
            OUString::createFromAscii( pImplName ),
            createDragSource,
            aSNS);

    }
    else if( pSrvManager && ( 0 == rtl_str_compare( pImplName, DNDTARGET_IMPL_NAME ) ) )
    {
        Sequence< OUString > aSNS( 1 );
        aSNS.getArray( )[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( DNDTARGET_SERVICE_NAME ) );

        xFactory= createSingleFactory(
            reinterpret_cast< XMultiServiceFactory* > ( pSrvManager ),
            OUString::createFromAscii( pImplName ),
            createDropTarget,
            aSNS);

    }

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

    return pRet;
}

} // extern "C"
<commit_msg>OSL_ENSHURE replaced by OSL_ENSURE<commit_after>/*************************************************************************
 *
 *  $RCSfile: dndentry.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: jl $ $Date: 2001-03-12 16:35:40 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XSET_HPP_
#include <com/sun/star/container/XSet.hpp>
#endif

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#include "source.hxx"
#include "target.hxx"

using namespace ::rtl                       ;
using namespace ::com::sun::star::uno       ;
using namespace ::com::sun::star::registry  ;
using namespace ::cppu                      ;
using namespace ::com::sun::star::lang;

Reference< XInterface > SAL_CALL createDragSource( const Reference< XMultiServiceFactory >& rServiceManager )
{
    DragSource* pSource= new DragSource( rServiceManager );
    return Reference<XInterface>( static_cast<XInitialization*>(pSource), UNO_QUERY);
}

Reference< XInterface > SAL_CALL createDropTarget( const Reference< XMultiServiceFactory >& rServiceManager )
{
    DropTarget* pTarget= new DropTarget( rServiceManager );
    return Reference<XInterface>( static_cast<XInitialization*>(pTarget), UNO_QUERY);
}

extern "C"
{

//----------------------------------------------------------------------
// component_getImplementationEnvironment
//----------------------------------------------------------------------

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

//-------------------------------------------------------------------------
// component_writeInfo - to register a UNO-Service
// to register a UNO-Service use: regcomp -register -r *.rdb -c *.dll
// to view the registry use: regview *.rdb /SERVICES/ServiceName
// (you must use the full services name e.g. com.sun.star.frame.FilePicker
//-------------------------------------------------------------------------

sal_Bool SAL_CALL component_writeInfo( void* pServiceManager, void* pRegistryKey )
{
    sal_Bool bRetVal = sal_False;

    if ( pRegistryKey )
    {
        try
        {
            Reference< XRegistryKey > pXNewKey( static_cast< XRegistryKey* >( pRegistryKey ) );
            pXNewKey->createKey( OUString( RTL_CONSTASCII_USTRINGPARAM( DNDSOURCE_REGKEY_NAME ) ) );
            bRetVal = sal_True;

            pXNewKey=  static_cast< XRegistryKey* >( pRegistryKey );
            pXNewKey->createKey( OUString( RTL_CONSTASCII_USTRINGPARAM( DNDTARGET_REGKEY_NAME ) ) );
            bRetVal = sal_True;
        }
        catch( InvalidRegistryException& )
        {
            OSL_ENSURE(sal_False, "InvalidRegistryException caught");
            bRetVal = sal_False;
        }
    }

    return bRetVal;
}

//----------------------------------------------------------------------
// component_getFactory
// returns a factory to create XFilePicker-Services
//----------------------------------------------------------------------

void* SAL_CALL component_getFactory( const sal_Char* pImplName, uno_Interface* pSrvManager, uno_Interface* pRegistryKey )
{
    void* pRet = 0;
    Reference< XSingleServiceFactory > xFactory;

    if ( pSrvManager && ( 0 == rtl_str_compare( pImplName, DNDSOURCE_IMPL_NAME ) ) )
    {
        Sequence< OUString > aSNS( 1 );
        aSNS.getArray( )[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( DNDSOURCE_SERVICE_NAME ) );

        xFactory= createSingleFactory(
            reinterpret_cast< XMultiServiceFactory* > ( pSrvManager ),
            OUString::createFromAscii( pImplName ),
            createDragSource,
            aSNS);

    }
    else if( pSrvManager && ( 0 == rtl_str_compare( pImplName, DNDTARGET_IMPL_NAME ) ) )
    {
        Sequence< OUString > aSNS( 1 );
        aSNS.getArray( )[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( DNDTARGET_SERVICE_NAME ) );

        xFactory= createSingleFactory(
            reinterpret_cast< XMultiServiceFactory* > ( pSrvManager ),
            OUString::createFromAscii( pImplName ),
            createDropTarget,
            aSNS);

    }

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

    return pRet;
}

} // extern "C"
<|endoftext|>