<commit_before>/*
 *   Copyright (c) 2006, Mathieu Champlon
 *   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  the  copyright  holders  nor the names  of the
 *     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 THE COPYRIGHT
 *   OWNERS 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.
 */

#ifndef xeumeuleu_xistream_hpp
#define xeumeuleu_xistream_hpp

#include <xeumeuleu/streams/detail/input_context.hpp>
#include <xeumeuleu/streams/detail/input_base.hpp>
#include <xeumeuleu/streams/detail/output_base.hpp>
#include <xeumeuleu/streams/detail/null_input.hpp>
#include <xeumeuleu/streams/detail/optional_input.hpp>
#include <xeumeuleu/streams/detail/attribute_input.hpp>
#include <string>
#include <memory>

namespace xml
{
    class xostream;

// =============================================================================
/** @class  xistream
    @brief  Xml input stream
*/
// Created: MAT 2006-01-04
// =============================================================================
class xistream : protected input_context
{
public:
    //! @name Constructors/Destructor
    //@{
    explicit xistream( input_base& input )
        : input_( &input )
    {}
    virtual ~xistream()
    {}
    //@}

    //! @name Operations
    //@{
    void start( const std::string& tag )
    {
        input_->start( tag );
    }
    void end()
    {
        input_->end();
    }

    xistream& operator>>( std::string& value ) { input_->read( value ); return *this; }
    xistream& operator>>( bool& value ) { input_->read( value ); return *this; }
    xistream& operator>>( short& value ) { input_->read( value ); return *this; }
    xistream& operator>>( int& value ) { input_->read( value ); return *this; }
    xistream& operator>>( long& value ) { input_->read( value ); return *this; }
    xistream& operator>>( long long& value ) { input_->read( value ); return *this; }
    xistream& operator>>( float& value ) { input_->read( value ); return *this; }
    xistream& operator>>( double& value ) { input_->read( value ); return *this; }
    xistream& operator>>( long double& value ) { input_->read( value ); return *this; }
    xistream& operator>>( unsigned short& value ) { input_->read( value ); return *this; }
    xistream& operator>>( unsigned int& value ) { input_->read( value ); return *this; }
    xistream& operator>>( unsigned long& value ) { input_->read( value ); return *this; }
    xistream& operator>>( unsigned long long& value ) { input_->read( value ); return *this; }
    xistream& operator>>( xostream& xos );

    std::auto_ptr< input_base > branch( bool clone ) const
    {
        return input_->branch( clone );
    }

    void copy( output_base& destination ) const
    {
        destination.copy( *input_ );
    }

    void error( const std::string& message ) const
    {
        throw xml::exception( context() + message );
    }
    //@}

    //! @name Accessors
    //@{
    bool has_child( const std::string& name ) const
    {
        return input_->has_child( name );
    }
    bool has_attribute( const std::string& name ) const
    {
        return input_->has_attribute( name );
    }
    bool has_content() const
    {
        return input_->has_content();
    }
    bool is_optional() const
    {
        return input_ == optional_.get();
    }

    template< typename T > T value() const;
    template< typename T > T value( const T& fallback ) const;
    std::string value( const char* fallback ) const
    {
        return value< std::string >( fallback );
    }

    template< typename T > T content( const std::string& name ) const;
    template< typename T > T content( const std::string& name, const T& fallback ) const;
    std::string content( const std::string& name, const char* fallback ) const
    {
        return content< std::string >( name, fallback );
    }

    template< typename T > void attribute_by_ref( const std::string& name, T& value ) const
    {
        attribute_input input( *input_, name );
        xistream xis( input );
        xis >> value;
    }

    template< typename T > T attribute( const std::string& name ) const;
    template< typename T > T attribute( const std::string& name, const T& fallback ) const;
    std::string attribute( const std::string& name, const char* fallback ) const
    {
        return attribute< std::string >( name, fallback );
    }

    void nodes( const visitor& v ) const
    {
        input_->nodes( v );
    }
    void attributes( const visitor& v ) const
    {
        input_->attributes( v );
    }

    std::string context() const
    {
        return input_->context();
    }
    //@}

    //! @name Modifiers
    //@{
    void optional()
    {
        if( input_ != null_.get() && input_ != optional_.get() )
        {
            null_.reset( new null_input( *input_, *this ) );
            optional_.reset( new optional_input( *input_, *null_, *this ) );
            input_ = optional_.get();
        }
    }
    //@}

private:
    //! @name Copy/Assignment
    //@{
    xistream( const xistream& );            //!< Copy constructor
    xistream& operator=( const xistream& ); //!< Assignment operator
    //@}

    //! @name Operations
    //@{
    virtual input_base& reset( input_base& input )
    {
        input_ = &input;
        return *input_;
    }
    //@}

private:
    //! @name Member data
    //@{
    input_base* input_;
    std::auto_ptr< null_input > null_;
    std::auto_ptr< optional_input > optional_;
    //@}
};

}

#include <xeumeuleu/streams/xostream.hpp>
#include <xeumeuleu/streams/xisubstream.hpp>
#include <xeumeuleu/manipulators/attribute.hpp>

namespace xml
{
    template< typename T > T xistream::value() const
    {
        T value;
        xml::xisubstream xiss( *this );
        xiss >> value;
        return value;
    }
    template< typename T > T xistream::value( const T& fallback ) const
    {
        T value = fallback;
        xml::xisubstream xiss( *this );
        xiss.optional();
        xiss >> value;
        return value;
    }
    template< typename T > T xistream::attribute( const std::string& name ) const
    {
        T value;
        xml::xisubstream xiss( *this );
        xiss >> xml::attribute( name, value );
        return value;
    }
    template< typename T > T xistream::attribute( const std::string& name, const T& fallback ) const
    {
        T value = fallback;
        xml::xisubstream xiss( *this );
        xiss.optional();
        xiss >> xml::attribute( name, value );
        return value;
    }
    template< typename T > T xistream::content( const std::string& name ) const
    {
        T value;
        xml::xisubstream xiss( *this );
        xiss.start( name );
        xiss >> value;
        return value;
    }
    template< typename T > T xistream::content( const std::string& name, const T& fallback ) const
    {
        T value = fallback;
        xml::xisubstream xiss( *this );
        xiss.optional();
        xiss.start( name );
        xiss.optional();
        xiss >> value;
        return value;
    }
    inline xistream& xistream::operator>>( xostream& xos )
    {
        xos << *this;
        return *this;
    }
}

#endif // xeumeuleu_xistream_hpp
<commit_msg>Fix for vc71<commit_after>/*
 *   Copyright (c) 2006, Mathieu Champlon
 *   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  the  copyright  holders  nor the names  of the
 *     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 THE COPYRIGHT
 *   OWNERS 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.
 */

#ifndef xeumeuleu_xistream_hpp
#define xeumeuleu_xistream_hpp

#include <xeumeuleu/streams/detail/input_context.hpp>
#include <xeumeuleu/streams/detail/input_base.hpp>
#include <xeumeuleu/streams/detail/output_base.hpp>
#include <xeumeuleu/streams/detail/null_input.hpp>
#include <xeumeuleu/streams/detail/optional_input.hpp>
#include <xeumeuleu/streams/detail/attribute_input.hpp>
#include <string>
#include <memory>

namespace xml
{
    class xostream;

// =============================================================================
/** @class  xistream
    @brief  Xml input stream
*/
// Created: MAT 2006-01-04
// =============================================================================
class xistream : protected input_context
{
public:
    //! @name Constructors/Destructor
    //@{
    explicit xistream( input_base& input )
        : input_( &input )
    {}
    virtual ~xistream()
    {}
    //@}

    //! @name Operations
    //@{
    void start( const std::string& tag )
    {
        input_->start( tag );
    }
    void end()
    {
        input_->end();
    }

    xistream& operator>>( std::string& value ) { input_->read( value ); return *this; }
    xistream& operator>>( bool& value ) { input_->read( value ); return *this; }
    xistream& operator>>( short& value ) { input_->read( value ); return *this; }
    xistream& operator>>( int& value ) { input_->read( value ); return *this; }
    xistream& operator>>( long& value ) { input_->read( value ); return *this; }
    xistream& operator>>( long long& value ) { input_->read( value ); return *this; }
    xistream& operator>>( float& value ) { input_->read( value ); return *this; }
    xistream& operator>>( double& value ) { input_->read( value ); return *this; }
    xistream& operator>>( long double& value ) { input_->read( value ); return *this; }
    xistream& operator>>( unsigned short& value ) { input_->read( value ); return *this; }
    xistream& operator>>( unsigned int& value ) { input_->read( value ); return *this; }
    xistream& operator>>( unsigned long& value ) { input_->read( value ); return *this; }
    xistream& operator>>( unsigned long long& value ) { input_->read( value ); return *this; }
    xistream& operator>>( xostream& xos );

    std::auto_ptr< input_base > branch( bool clone ) const
    {
        return input_->branch( clone );
    }

    void copy( output_base& destination ) const
    {
        destination.copy( *input_ );
    }

    void error( const std::string& message ) const
    {
        throw xml::exception( context() + message );
    }
    //@}

    //! @name Accessors
    //@{
    bool has_child( const std::string& name ) const
    {
        return input_->has_child( name );
    }
    bool has_attribute( const std::string& name ) const
    {
        return input_->has_attribute( name );
    }
    bool has_content() const
    {
        return input_->has_content();
    }
    bool is_optional() const
    {
        return input_ == optional_.get();
    }

    template< typename T > T value() const;
    std::string value( const char* fallback ) const
    {
        return value( std::string( fallback ) );
    }
    template< typename T > T value( const T& fallback ) const;

    template< typename T > T content( const std::string& name ) const;
    std::string content( const std::string& name, const char* fallback ) const
    {
        return content( name, std::string( fallback ) );
    }
    template< typename T > T content( const std::string& name, const T& fallback ) const;

    template< typename T > void attribute_by_ref( const std::string& name, T& value ) const
    {
        attribute_input input( *input_, name );
        xistream xis( input );
        xis >> value;
    }

    template< typename T > T attribute( const std::string& name ) const;
    std::string attribute( const std::string& name, const char* fallback ) const
    {
        return attribute( name, std::string( fallback ) );
    }
    template< typename T > T attribute( const std::string& name, const T& fallback ) const;

    void nodes( const visitor& v ) const
    {
        input_->nodes( v );
    }
    void attributes( const visitor& v ) const
    {
        input_->attributes( v );
    }

    std::string context() const
    {
        return input_->context();
    }
    //@}

    //! @name Modifiers
    //@{
    void optional()
    {
        if( input_ != null_.get() && input_ != optional_.get() )
        {
            null_.reset( new null_input( *input_, *this ) );
            optional_.reset( new optional_input( *input_, *null_, *this ) );
            input_ = optional_.get();
        }
    }
    //@}

private:
    //! @name Copy/Assignment
    //@{
    xistream( const xistream& );            //!< Copy constructor
    xistream& operator=( const xistream& ); //!< Assignment operator
    //@}

    //! @name Operations
    //@{
    virtual input_base& reset( input_base& input )
    {
        input_ = &input;
        return *input_;
    }
    //@}

private:
    //! @name Member data
    //@{
    input_base* input_;
    std::auto_ptr< null_input > null_;
    std::auto_ptr< optional_input > optional_;
    //@}
};

}

#include <xeumeuleu/streams/xostream.hpp>
#include <xeumeuleu/streams/xisubstream.hpp>
#include <xeumeuleu/manipulators/attribute.hpp>

namespace xml
{
    template< typename T > T xistream::value() const
    {
        T value;
        xml::xisubstream xiss( *this );
        xiss >> value;
        return value;
    }
    template< typename T > T xistream::value( const T& fallback ) const
    {
        T value = fallback;
        xml::xisubstream xiss( *this );
        xiss.optional();
        xiss >> value;
        return value;
    }
    template< typename T > T xistream::attribute( const std::string& name ) const
    {
        T value;
        xml::xisubstream xiss( *this );
        xiss >> xml::attribute( name, value );
        return value;
    }
    template< typename T > T xistream::attribute( const std::string& name, const T& fallback ) const
    {
        T value = fallback;
        xml::xisubstream xiss( *this );
        xiss.optional();
        xiss >> xml::attribute( name, value );
        return value;
    }
    template< typename T > T xistream::content( const std::string& name ) const
    {
        T value;
        xml::xisubstream xiss( *this );
        xiss.start( name );
        xiss >> value;
        return value;
    }
    template< typename T > T xistream::content( const std::string& name, const T& fallback ) const
    {
        T value = fallback;
        xml::xisubstream xiss( *this );
        xiss.optional();
        xiss.start( name );
        xiss.optional();
        xiss >> value;
        return value;
    }
    inline xistream& xistream::operator>>( xostream& xos )
    {
        xos << *this;
        return *this;
    }
}

#endif // xeumeuleu_xistream_hpp
<|endoftext|>


<commit_before>/*
 * Author: Brendan Le Foll <brendan.le.foll@intel.com>
 * Contributors: Manivannan Sadhasivam <manivannan.sadhasivam@linaro.org>
 * Copyright (c) 2015 Intel Corporation.
 *
 * 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.
 *
 * Example usage: Prints "Hello Mraa!" recursively. Press Ctrl+C to exit
 *
 */

/* standard headers */
#include <iostream>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

/* mraa headers */
#include "mraa/common.hpp"
#include "mraa/uart.hpp"

/* UART port */
#define UART_PORT 0

const char* dev_path = "/dev/ttyS0";

volatile sig_atomic_t flag = 1;

void
sig_handler(int signum)
{
    if (signum == SIGINT) {
        std::cout << "Exiting..." << std::endl;
        flag = 0;
    }
}

int
main(void)
{
    signal(SIGINT, sig_handler);

    //! [Interesting]
    // If you have a valid platform configuration use numbers to represent uart
    // device. If not use raw mode where std::string is taken as a constructor
    // parameter
    mraa::Uart* uart;
    try {
        uart = new mraa::Uart(UART_PORT);
    } catch (std::exception& e) {
        std::cerr << e.what() << ", likely invalid platform config" << std::endl;
    }

    try {
        uart = new mraa::Uart(dev_path);
    } catch (std::exception& e) {
        std::cerr << "Error while setting up raw UART, do you have a uart?" << std::endl;
        std::terminate();
    }

    if (uart->setBaudRate(115200) != mraa::SUCCESS) {
        std::cerr << "Error setting parity on UART" << std::endl;
    }

    if (uart->setMode(8, mraa::UART_PARITY_NONE, 1) != mraa::SUCCESS) {
        std::cerr << "Error setting parity on UART" << std::endl;
    }

    if (uart->setFlowcontrol(false, false) != mraa::SUCCESS) {
        std::cerr << "Error setting flow control UART" << std::endl;
    }

    while (flag) {
        /* send data through uart */
        uart->writeStr("Hello Mraa!");

        sleep(1);
    }
    //! [Interesting]

    delete uart;

    return EXIT_SUCCESS;
}
<commit_msg>examples/c++/uart.cpp: Add fix for potential memory leak<commit_after>/*
 * Author: Brendan Le Foll <brendan.le.foll@intel.com>
 * Contributors: Manivannan Sadhasivam <manivannan.sadhasivam@linaro.org>
 * Copyright (c) 2015 Intel Corporation.
 *
 * 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.
 *
 * Example usage: Prints "Hello Mraa!" recursively. Press Ctrl+C to exit
 *
 */

/* standard headers */
#include <iostream>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

/* mraa headers */
#include "mraa/common.hpp"
#include "mraa/uart.hpp"

/* UART port */
#define UART_PORT 0

const char* dev_path = "/dev/ttyS0";

volatile sig_atomic_t flag = 1;

void
sig_handler(int signum)
{
    if (signum == SIGINT) {
        std::cout << "Exiting..." << std::endl;
        flag = 0;
    }
}

int
main(void)
{
    signal(SIGINT, sig_handler);

    //! [Interesting]
    // If you have a valid platform configuration use numbers to represent uart
    // device. If not use raw mode where std::string is taken as a constructor
    // parameter
    mraa::Uart* uart, *temp;
    try {
        uart = new mraa::Uart(UART_PORT);
        temp = uart;
    } catch (std::exception& e) {
        std::cerr << e.what() << ", likely invalid platform config" << std::endl;
    }

    try {
        uart = new mraa::Uart(dev_path);
    } catch (std::exception& e) {
        std::cerr << "Error while setting up raw UART, do you have a uart?" << std::endl;
        std::terminate();
    }

    if (uart->setBaudRate(115200) != mraa::SUCCESS) {
        std::cerr << "Error setting parity on UART" << std::endl;
    }

    if (uart->setMode(8, mraa::UART_PARITY_NONE, 1) != mraa::SUCCESS) {
        std::cerr << "Error setting parity on UART" << std::endl;
    }

    if (uart->setFlowcontrol(false, false) != mraa::SUCCESS) {
        std::cerr << "Error setting flow control UART" << std::endl;
    }

    while (flag) {
        /* send data through uart */
        uart->writeStr("Hello Mraa!");

        sleep(1);
    }
    //! [Interesting]

    delete uart;
    delete temp;

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
fileedit.cpp

஢ 䠩 - ன  editor.cpp

*/

/* Revision: 1.02 29.06.2000 $ */

/*
Modify:
  29.06.2000 tran
    +   㭪樮
  28.06.2000 tran
    - (NT Console resize bug)
      adding FileEditor::SetScreenPosition
  25.06.2000 SVS
    ! ⮢ Master Copy
    ! 뤥  ⢥ ᠬ⥫쭮
*/

#include "headers.hpp"
#pragma hdrstop

/* $ 30.06.2000 IS
   ⠭
*/
#include "internalheaders.hpp"
/* IS $ */

FileEditor::FileEditor(char *Name,int CreateNewFile,int EnableSwitch,
                       int StartLine,int StartChar,int DisableHistory,
                       char *PluginData)
{
  SetPosition(0,0,ScrX,ScrY);
  FullScreen=TRUE;
  Init(Name,CreateNewFile,EnableSwitch,StartLine,StartChar,DisableHistory,PluginData);
}

FileEditor::FileEditor(char *Name,int CreateNewFile,int EnableSwitch,
            int StartLine,int StartChar,char *Title,
            int X1,int Y1,int X2,int Y2)
{
  SetPosition(X1,Y1,X2,Y2);
  FullScreen=(X1==0 && Y1==0 && X2==ScrX && Y2==ScrY);
  FEdit.SetTitle(Title);
  Init(Name,CreateNewFile,EnableSwitch,StartLine,StartChar,TRUE,"");
}

void FileEditor::Init(char *Name,int CreateNewFile,int EnableSwitch,
                      int StartLine,int StartChar,int DisableHistory,
                      char *PluginData)
{
  if (*Name==0)
    return;
  FEdit.SetPluginData(PluginData);
  FEdit.SetHostFileEditor(this);
  SetEnableSwitch(EnableSwitch);
  GetCurrentDirectory(sizeof(StartDir),StartDir);
  strcpy(FileName,Name);
  ConvertNameToFull(FileName,FullFileName);
  if (EnableSwitch)
  {
    int ModalPos=CtrlObject->ModalManager.FindModalByFile(MODALTYPE_EDITOR,FullFileName);
    if (ModalPos!=-1)
    {
      int MsgCode=Message(0,2,MSG(MEditTitle),FullFileName,MSG(MAskReload),
                          MSG(MCurrent),MSG(MReload));
      switch(MsgCode)
      {
        case 0:
          CtrlObject->ModalManager.SetModalPos(ModalPos);
          CtrlObject->ModalManager.NextModal(0);
          return;
        case 1:
          break;
        default:
          return;
      }
    }
  }
  FEdit.SetPosition(X1,Y1,X2,Y2-1);
  FEdit.SetStartPos(StartLine,StartChar);
  int UserBreak;
  if (!FEdit.ReadFile(FileName,UserBreak) && (!CreateNewFile || UserBreak))
  {
    if (UserBreak!=1)
    {
      Message(MSG_WARNING|MSG_ERRORTYPE,1,MSG(MEditTitle),MSG(MEditCannotOpen),FileName,MSG(MOk));
      ExitCode=0;
    }
    else
      ExitCode=3;
    return;
  }
  ShowConsoleTitle();
  EditKeyBar.SetOwner(this);
  EditKeyBar.SetPosition(X1,Y2,X2,Y2);

  /* $ 29.06.2000 tran
        㭪樮  */
  char *FEditKeys[]={MSG(MEditF1),MSG(MEditF2),MSG(MEditF3),MSG(MEditF4),MSG(MEditF5),EnableSwitch ? MSG(MEditF6):"",MSG(MEditF7),MSG(MEditF8),MSG(MEditF9),MSG(MEditF10),MSG(MEditF11),MSG(MEditF12)};
  char *FEditShiftKeys[]={MSG(MEditShiftF1),MSG(MEditShiftF2),MSG(MEditShiftF3),MSG(MEditShiftF4),MSG(MEditShiftF5),MSG(MEditShiftF6),MSG(MEditShiftF7),MSG(MEditShiftF8),MSG(MEditShiftF9),MSG(MEditShiftF10),MSG(MEditShiftF11),MSG(MEditShiftF12)};
  char *FEditAltKeys[]={MSG(MEditAltF1),MSG(MEditAltF2),MSG(MEditAltF3),MSG(MEditAltF4),MSG(MEditAltF5),MSG(MEditAltF6),MSG(MEditAltF7),MSG(MEditAltF8),MSG(MEditAltF9),MSG(MEditAltF10),MSG(MEditAltF11),MSG(MEditAltF12)};
  char *FEditCtrlKeys[]={MSG(MEditCtrlF1),MSG(MEditCtrlF2),MSG(MEditCtrlF3),MSG(MEditCtrlF4),MSG(MEditCtrlF5),MSG(MEditCtrlF6),MSG(MEditCtrlF7),MSG(MEditCtrlF8),MSG(MEditCtrlF9),MSG(MEditCtrlF10),MSG(MEditCtrlF11),MSG(MEditCtrlF12)};
  /* tran $ */

  EditKeyBar.Set(FEditKeys,sizeof(FEditKeys)/sizeof(FEditKeys[0]));
  EditKeyBar.SetShift(FEditShiftKeys,sizeof(FEditShiftKeys)/sizeof(FEditShiftKeys[0]));
  EditKeyBar.SetAlt(FEditAltKeys,sizeof(FEditAltKeys)/sizeof(FEditAltKeys[0]));
  EditKeyBar.SetCtrl(FEditCtrlKeys,sizeof(FEditCtrlKeys)/sizeof(FEditCtrlKeys[0]));
  EditKeyBar.Show();
  SetKeyBar(&EditKeyBar);
  FEdit.SetEditKeyBar(&EditKeyBar);
  Process();
  ExitCode=IsFileChanged() ? 1 : 2;
  if (!DisableHistory)
    CtrlObject->ViewHistory->AddToHistory(FullFileName,MSG(MHistoryEdit),1);
}

void FileEditor::Process()
{
  ChangeMacroMode MacroMode(MACRO_EDITOR);
  Modal::Process();
}

void FileEditor::Show()
{
  if (FullScreen)
  {
    EditKeyBar.SetPosition(0,ScrY,ScrX,ScrY);
    EditKeyBar.Redraw();
    SetPosition(0,0,ScrX,ScrY-1);
    FEdit.SetPosition(0,0,ScrX,ScrY-1);
  }
  ScreenObject::Show();
}

void FileEditor::DisplayObject()
{
  FEdit.Show();
}

int FileEditor::ProcessKey(int Key)
{
  switch(Key)
  {
    case KEY_CTRLO:
      Hide();
      if (CtrlObject->LeftPanel!=CtrlObject->RightPanel)
        CtrlObject->ModalManager.ShowBackground();
      else
      {
        EditKeyBar.Hide();
        WaitKey();
      }
      EditKeyBar.Show();
      Show();
      return(TRUE);
    case KEY_CTRLTAB:
    case KEY_CTRLSHIFTTAB:
    case KEY_F12:
      if (GetEnableSwitch())
      {
        FEdit.KeepInitParameters();
        if (Key==KEY_CTRLSHIFTTAB)
          SetExitCode(3);
        else
          SetExitCode(Key==KEY_CTRLTAB ? 1:2);
      }
      return(TRUE);
    case KEY_F2:
    case KEY_SHIFTF2:
      {
        static int TextFormat=0;
        int NameChanged=FALSE;
        if (Key==KEY_SHIFTF2)
        {
          const char *HistoryName="NewEdit";
          static struct DialogData EditDlgData[]=
          {
            DI_DOUBLEBOX,3,1,72,10,0,0,0,0,(char *)MEditTitle,
            DI_TEXT,5,2,0,0,0,0,DIF_SHOWAMPERSAND,0,(char *)MEditSaveAs,
            DI_EDIT,5,3,70,3,1,(DWORD)HistoryName,DIF_HISTORY,1,"",
            DI_TEXT,3,4,0,0,0,0,DIF_BOXCOLOR|DIF_SEPARATOR,0,"",
            DI_RADIOBUTTON,5,5,0,0,0,0,DIF_GROUP,0,(char *)MEditSaveOriginal,
            DI_RADIOBUTTON,5,6,0,0,0,0,0,0,(char *)MEditSaveDOS,
            DI_RADIOBUTTON,5,7,0,0,0,0,0,0,(char *)MEditSaveUnix,
            DI_TEXT,3,8,0,0,0,0,DIF_BOXCOLOR|DIF_SEPARATOR,0,"",
            DI_BUTTON,0,9,0,0,0,0,DIF_CENTERGROUP,1,(char *)MOk,
            DI_BUTTON,0,9,0,0,0,0,DIF_CENTERGROUP,0,(char *)MCancel,
          };
          MakeDialogItems(EditDlgData,EditDlg);
          strcpy(EditDlg[2].Data,FileName);
          EditDlg[4].Selected=EditDlg[5].Selected=EditDlg[6].Selected=0;
          EditDlg[4+TextFormat].Selected=TRUE;
          Dialog Dlg(EditDlg,sizeof(EditDlg)/sizeof(EditDlg[0]));
          Dlg.SetPosition(-1,-1,76,12);
          Dlg.Process();
          if (Dlg.GetExitCode()!=8 || *EditDlg[2].Data==0)
            return(FALSE);
          Unquote(EditDlg[2].Data);
          RemoveTrailingSpaces(EditDlg[2].Data);
          NameChanged=LocalStricmp(EditDlg[2].Data,FileName)!=0;
          strcpy(FileName,EditDlg[2].Data);
          ConvertNameToFull(FileName,FullFileName);
          if (EditDlg[4].Selected)
            TextFormat=0;
          if (EditDlg[5].Selected)
            TextFormat=1;
          if (EditDlg[6].Selected)
            TextFormat=2;
        }
        ShowConsoleTitle();
        chdir(StartDir);

        if (NameChanged && GetFileAttributes(FileName)!=0xFFFFFFFF)
          if (Message(MSG_WARNING,2,MSG(MEditTitle),FileName,MSG(MEditExists),
                      MSG(MEditOvr),MSG(MYes),MSG(MNo))!=0)
            return(TRUE);

        while (FEdit.SaveFile(FileName,0,Key==KEY_SHIFTF2 ? TextFormat:0)==0)
          if (Message(MSG_WARNING|MSG_ERRORTYPE,2,MSG(MEditTitle),MSG(MEditCannotSave),
                      FileName,MSG(MRetry),MSG(MCancel))!=0)
            break;
      }
      return(TRUE);
    case KEY_F6:
      if (GetEnableSwitch() &&
          (FEdit.IsFileChanged() || GetFileAttributes(FullFileName)!=0xFFFFFFFF))
      {
        long FilePos=FEdit.GetCurPos();
        ProcessKey(KEY_ESC);
        if (Done())
          CtrlObject->ModalManager.SetNextWindow(TRUE,FileName,FilePos);
        ShowTime(2);
      }
      return(TRUE);
    case KEY_SHIFTF10:
      ProcessKey(KEY_F2);
    case KEY_ESC:
    case KEY_F10:
      {
        int FirstSave=1;
        while (1)
        {
          chdir(StartDir);
          int SaveCode=FEdit.SaveFile(FileName,FirstSave,0);
          if (SaveCode==2)
            break;
          if (SaveCode==1)
          {
            SetExitCode(0);
            break;
          }
          if (Message(MSG_WARNING|MSG_ERRORTYPE,2,MSG(MEditTitle),MSG(MEditCannotSave),
                      FileName,MSG(MRetry),MSG(MCancel))!=0)
            break;
          FirstSave=0;
        }
      }
      return(TRUE);
    default:
      if (CtrlObject->Macro.IsExecuting() || !FEdit.ProcessEditorInput(&ReadRec))
        return(FEdit.ProcessKey(Key));
      return(TRUE);
  }
}

int FileEditor::ProcessMouse(MOUSE_EVENT_RECORD *MouseEvent)
{
  if (!EditKeyBar.ProcessMouse(MouseEvent))
    if (!FEdit.ProcessEditorInput(&ReadRec))
      if (!FEdit.ProcessMouse(MouseEvent))
        return(FALSE);
  return(TRUE);
}

int FileEditor::GetTypeAndName(char *Type,char *Name)
{
  strcpy(Type,MSG(MScreensEdit));
  strcpy(Name,FullFileName);
  return(MODALTYPE_EDITOR);
}

void FileEditor::ShowConsoleTitle()
{
  char Title[NM+20];
  sprintf(Title,MSG(MInEditor),PointToName(FileName));
  SetFarTitle(Title);
}

int FileEditor::GetExitCode()
{
  return(ExitCode);
}

/* $ 28.06.2000 tran
 (NT Console resize)
 resize editor */
void FileEditor::SetScreenPosition()
{
  if (FullScreen)
  {
    SetPosition(0,0,ScrX,ScrY);
    Show();
  }
}
/* tran $ */
<commit_msg>FAR patch 00078.CtrlF10 Дата              : 21.07.2000 Сделал            : Konstantin Stupnik Описание          : Выход из редактора с позиционированием на                     редактируемом файле по Ctrl+F10. Измененные файлы  : fileedit.cpp Состав            : 00078.CtrlF10.txt                     fileedit.cpp.78.diff Основан на патче  : 77 Дополнение        :<commit_after>/*
fileedit.cpp

஢ 䠩 - ன  editor.cpp

*/

/* Revision: 1.03 21.07.2000 $ */

/*
Modify:
  21.07.2000 SKV
    + 室  樮஢  ।㥬 䠩  CTRLF10
  29.06.2000 tran
    +   㭪樮
  28.06.2000 tran
    - (NT Console resize bug)
      adding FileEditor::SetScreenPosition
  25.06.2000 SVS
    ! ⮢ Master Copy
    ! 뤥  ⢥ ᠬ⥫쭮
*/

#include "headers.hpp"
#pragma hdrstop

/* $ 30.06.2000 IS
   ⠭
*/
#include "internalheaders.hpp"
/* IS $ */

FileEditor::FileEditor(char *Name,int CreateNewFile,int EnableSwitch,
                       int StartLine,int StartChar,int DisableHistory,
                       char *PluginData)
{
  SetPosition(0,0,ScrX,ScrY);
  FullScreen=TRUE;
  Init(Name,CreateNewFile,EnableSwitch,StartLine,StartChar,DisableHistory,PluginData);
}

FileEditor::FileEditor(char *Name,int CreateNewFile,int EnableSwitch,
            int StartLine,int StartChar,char *Title,
            int X1,int Y1,int X2,int Y2)
{
  SetPosition(X1,Y1,X2,Y2);
  FullScreen=(X1==0 && Y1==0 && X2==ScrX && Y2==ScrY);
  FEdit.SetTitle(Title);
  Init(Name,CreateNewFile,EnableSwitch,StartLine,StartChar,TRUE,"");
}

void FileEditor::Init(char *Name,int CreateNewFile,int EnableSwitch,
                      int StartLine,int StartChar,int DisableHistory,
                      char *PluginData)
{
  if (*Name==0)
    return;
  FEdit.SetPluginData(PluginData);
  FEdit.SetHostFileEditor(this);
  SetEnableSwitch(EnableSwitch);
  GetCurrentDirectory(sizeof(StartDir),StartDir);
  strcpy(FileName,Name);
  ConvertNameToFull(FileName,FullFileName);
  if (EnableSwitch)
  {
    int ModalPos=CtrlObject->ModalManager.FindModalByFile(MODALTYPE_EDITOR,FullFileName);
    if (ModalPos!=-1)
    {
      int MsgCode=Message(0,2,MSG(MEditTitle),FullFileName,MSG(MAskReload),
                          MSG(MCurrent),MSG(MReload));
      switch(MsgCode)
      {
        case 0:
          CtrlObject->ModalManager.SetModalPos(ModalPos);
          CtrlObject->ModalManager.NextModal(0);
          return;
        case 1:
          break;
        default:
          return;
      }
    }
  }
  FEdit.SetPosition(X1,Y1,X2,Y2-1);
  FEdit.SetStartPos(StartLine,StartChar);
  int UserBreak;
  if (!FEdit.ReadFile(FileName,UserBreak) && (!CreateNewFile || UserBreak))
  {
    if (UserBreak!=1)
    {
      Message(MSG_WARNING|MSG_ERRORTYPE,1,MSG(MEditTitle),MSG(MEditCannotOpen),FileName,MSG(MOk));
      ExitCode=0;
    }
    else
      ExitCode=3;
    return;
  }
  ShowConsoleTitle();
  EditKeyBar.SetOwner(this);
  EditKeyBar.SetPosition(X1,Y2,X2,Y2);

  /* $ 29.06.2000 tran
        㭪樮  */
  char *FEditKeys[]={MSG(MEditF1),MSG(MEditF2),MSG(MEditF3),MSG(MEditF4),MSG(MEditF5),EnableSwitch ? MSG(MEditF6):"",MSG(MEditF7),MSG(MEditF8),MSG(MEditF9),MSG(MEditF10),MSG(MEditF11),MSG(MEditF12)};
  char *FEditShiftKeys[]={MSG(MEditShiftF1),MSG(MEditShiftF2),MSG(MEditShiftF3),MSG(MEditShiftF4),MSG(MEditShiftF5),MSG(MEditShiftF6),MSG(MEditShiftF7),MSG(MEditShiftF8),MSG(MEditShiftF9),MSG(MEditShiftF10),MSG(MEditShiftF11),MSG(MEditShiftF12)};
  char *FEditAltKeys[]={MSG(MEditAltF1),MSG(MEditAltF2),MSG(MEditAltF3),MSG(MEditAltF4),MSG(MEditAltF5),MSG(MEditAltF6),MSG(MEditAltF7),MSG(MEditAltF8),MSG(MEditAltF9),MSG(MEditAltF10),MSG(MEditAltF11),MSG(MEditAltF12)};
  char *FEditCtrlKeys[]={MSG(MEditCtrlF1),MSG(MEditCtrlF2),MSG(MEditCtrlF3),MSG(MEditCtrlF4),MSG(MEditCtrlF5),MSG(MEditCtrlF6),MSG(MEditCtrlF7),MSG(MEditCtrlF8),MSG(MEditCtrlF9),MSG(MEditCtrlF10),MSG(MEditCtrlF11),MSG(MEditCtrlF12)};
  /* tran $ */

  EditKeyBar.Set(FEditKeys,sizeof(FEditKeys)/sizeof(FEditKeys[0]));
  EditKeyBar.SetShift(FEditShiftKeys,sizeof(FEditShiftKeys)/sizeof(FEditShiftKeys[0]));
  EditKeyBar.SetAlt(FEditAltKeys,sizeof(FEditAltKeys)/sizeof(FEditAltKeys[0]));
  EditKeyBar.SetCtrl(FEditCtrlKeys,sizeof(FEditCtrlKeys)/sizeof(FEditCtrlKeys[0]));
  EditKeyBar.Show();
  SetKeyBar(&EditKeyBar);
  FEdit.SetEditKeyBar(&EditKeyBar);
  Process();
  ExitCode=IsFileChanged() ? 1 : 2;
  if (!DisableHistory)
    CtrlObject->ViewHistory->AddToHistory(FullFileName,MSG(MHistoryEdit),1);
}

void FileEditor::Process()
{
  ChangeMacroMode MacroMode(MACRO_EDITOR);
  Modal::Process();
}

void FileEditor::Show()
{
  if (FullScreen)
  {
    EditKeyBar.SetPosition(0,ScrY,ScrX,ScrY);
    EditKeyBar.Redraw();
    SetPosition(0,0,ScrX,ScrY-1);
    FEdit.SetPosition(0,0,ScrX,ScrY-1);
  }
  ScreenObject::Show();
}

void FileEditor::DisplayObject()
{
  FEdit.Show();
}

int FileEditor::ProcessKey(int Key)
{
  switch(Key)
  {
    case KEY_CTRLO:
      Hide();
      if (CtrlObject->LeftPanel!=CtrlObject->RightPanel)
        CtrlObject->ModalManager.ShowBackground();
      else
      {
        EditKeyBar.Hide();
        WaitKey();
      }
      EditKeyBar.Show();
      Show();
      return(TRUE);
    case KEY_CTRLTAB:
    case KEY_CTRLSHIFTTAB:
    case KEY_F12:
      if (GetEnableSwitch())
      {
        FEdit.KeepInitParameters();
        if (Key==KEY_CTRLSHIFTTAB)
          SetExitCode(3);
        else
          SetExitCode(Key==KEY_CTRLTAB ? 1:2);
      }
      return(TRUE);
    case KEY_F2:
    case KEY_SHIFTF2:
      {
        static int TextFormat=0;
        int NameChanged=FALSE;
        if (Key==KEY_SHIFTF2)
        {
          const char *HistoryName="NewEdit";
          static struct DialogData EditDlgData[]=
          {
            DI_DOUBLEBOX,3,1,72,10,0,0,0,0,(char *)MEditTitle,
            DI_TEXT,5,2,0,0,0,0,DIF_SHOWAMPERSAND,0,(char *)MEditSaveAs,
            DI_EDIT,5,3,70,3,1,(DWORD)HistoryName,DIF_HISTORY,1,"",
            DI_TEXT,3,4,0,0,0,0,DIF_BOXCOLOR|DIF_SEPARATOR,0,"",
            DI_RADIOBUTTON,5,5,0,0,0,0,DIF_GROUP,0,(char *)MEditSaveOriginal,
            DI_RADIOBUTTON,5,6,0,0,0,0,0,0,(char *)MEditSaveDOS,
            DI_RADIOBUTTON,5,7,0,0,0,0,0,0,(char *)MEditSaveUnix,
            DI_TEXT,3,8,0,0,0,0,DIF_BOXCOLOR|DIF_SEPARATOR,0,"",
            DI_BUTTON,0,9,0,0,0,0,DIF_CENTERGROUP,1,(char *)MOk,
            DI_BUTTON,0,9,0,0,0,0,DIF_CENTERGROUP,0,(char *)MCancel,
          };
          MakeDialogItems(EditDlgData,EditDlg);
          strcpy(EditDlg[2].Data,FileName);
          EditDlg[4].Selected=EditDlg[5].Selected=EditDlg[6].Selected=0;
          EditDlg[4+TextFormat].Selected=TRUE;
          Dialog Dlg(EditDlg,sizeof(EditDlg)/sizeof(EditDlg[0]));
          Dlg.SetPosition(-1,-1,76,12);
          Dlg.Process();
          if (Dlg.GetExitCode()!=8 || *EditDlg[2].Data==0)
            return(FALSE);
          Unquote(EditDlg[2].Data);
          RemoveTrailingSpaces(EditDlg[2].Data);
          NameChanged=LocalStricmp(EditDlg[2].Data,FileName)!=0;
          strcpy(FileName,EditDlg[2].Data);
          ConvertNameToFull(FileName,FullFileName);
          if (EditDlg[4].Selected)
            TextFormat=0;
          if (EditDlg[5].Selected)
            TextFormat=1;
          if (EditDlg[6].Selected)
            TextFormat=2;
        }
        ShowConsoleTitle();
        chdir(StartDir);

        if (NameChanged && GetFileAttributes(FileName)!=0xFFFFFFFF)
          if (Message(MSG_WARNING,2,MSG(MEditTitle),FileName,MSG(MEditExists),
                      MSG(MEditOvr),MSG(MYes),MSG(MNo))!=0)
            return(TRUE);

        while (FEdit.SaveFile(FileName,0,Key==KEY_SHIFTF2 ? TextFormat:0)==0)
          if (Message(MSG_WARNING|MSG_ERRORTYPE,2,MSG(MEditTitle),MSG(MEditCannotSave),
                      FileName,MSG(MRetry),MSG(MCancel))!=0)
            break;
      }
      return(TRUE);
    case KEY_F6:
      if (GetEnableSwitch() &&
          (FEdit.IsFileChanged() || GetFileAttributes(FullFileName)!=0xFFFFFFFF))
      {
        long FilePos=FEdit.GetCurPos();
        ProcessKey(KEY_ESC);
        if (Done())
          CtrlObject->ModalManager.SetNextWindow(TRUE,FileName,FilePos);
        ShowTime(2);
      }
      return(TRUE);
    /*$ 21.07.2000 SKV
        + 室  樮஢  ।㥬 䠩  CTRLF10
    */
    case KEY_CTRLF10:
      {
        if(GetEnableSwitch())
        {
          ProcessKey(KEY_F10);
          if(strchr(FileName,'\\') || strchr(FileName,'/'))
          {
            char DirTmp[NM],*NameTmp;
            strncpy(DirTmp,FileName,NM);
            NameTmp=PointToName(DirTmp);
            if(NameTmp>DirTmp)NameTmp[-1]=0;
            CtrlObject->ActivePanel->SetCurDir(DirTmp,TRUE);
            CtrlObject->ActivePanel->GoToFile(NameTmp);
          }else
          {
            CtrlObject->ActivePanel->SetCurDir(StartDir,TRUE);
            CtrlObject->ActivePanel->GoToFile(FileName);
          }
        }
        return (TRUE);
      }
    /* SKV $*/

    case KEY_SHIFTF10:
      ProcessKey(KEY_F2);
    case KEY_ESC:
    case KEY_F10:
      {
        int FirstSave=1;
        while (1)
        {
          chdir(StartDir);
          int SaveCode=FEdit.SaveFile(FileName,FirstSave,0);
          if (SaveCode==2)
            break;
          if (SaveCode==1)
          {
            SetExitCode(0);
            break;
          }
          if (Message(MSG_WARNING|MSG_ERRORTYPE,2,MSG(MEditTitle),MSG(MEditCannotSave),
                      FileName,MSG(MRetry),MSG(MCancel))!=0)
            break;
          FirstSave=0;
        }
      }
      return(TRUE);
    default:
      if (CtrlObject->Macro.IsExecuting() || !FEdit.ProcessEditorInput(&ReadRec))
        return(FEdit.ProcessKey(Key));
      return(TRUE);
  }
}

int FileEditor::ProcessMouse(MOUSE_EVENT_RECORD *MouseEvent)
{
  if (!EditKeyBar.ProcessMouse(MouseEvent))
    if (!FEdit.ProcessEditorInput(&ReadRec))
      if (!FEdit.ProcessMouse(MouseEvent))
        return(FALSE);
  return(TRUE);
}

int FileEditor::GetTypeAndName(char *Type,char *Name)
{
  strcpy(Type,MSG(MScreensEdit));
  strcpy(Name,FullFileName);
  return(MODALTYPE_EDITOR);
}

void FileEditor::ShowConsoleTitle()
{
  char Title[NM+20];
  sprintf(Title,MSG(MInEditor),PointToName(FileName));
  SetFarTitle(Title);
}

int FileEditor::GetExitCode()
{
  return(ExitCode);
}

/* $ 28.06.2000 tran
 (NT Console resize)
 resize editor */
void FileEditor::SetScreenPosition()
{
  if (FullScreen)
  {
    SetPosition(0,0,ScrX,ScrY);
    Show();
  }
}
/* tran $ */
<|endoftext|>


<commit_before>include "mc_type.cp"

proc MCD : (type mcd_request/type mcd_reply client, [type mcd_request/type mcd_reply] backends)
  # NOTE (possibly shared) dictionaries are application-level primitives we supply.
  # FIXME specift what parameters to give? e.g., whether to randomise, and initial allocation.
  global cache : dictionary <string * string> := empty_dictionary

  # Any time we get something from a backend, cache it and forward it to the
  # client.
  backends => update_cache(cache) => client

  client => test_cache_or_pass_on(client, backends)

fun update_cache : (cache : ref dictionary <string * string>, response : type mcd_reply) -> (type mcd_reply)
  # NOTE relying on pass-by-reference of cache
  cache[response.key] := response
  response

fun test_cache_or_pass_on : (type mcd_request/type mcd_reply client, [type mcd_request/type mcd_reply] backend; request : type mcd_request) -> ()
  if cache[request.key] = None:
    # Work out which backend memcached to forward this request to, and send.
    request => backends[hash(request.key) mod len(backends)]
  else:
    cache[request.key] => client
<commit_msg>updated comments;<commit_after>include "mc_type.cp"

proc MCD : (type mcd_request/type mcd_reply client, [type mcd_request/type mcd_reply] backends)
  # NOTE (possibly shared) dictionaries are application-level primitives we supply.
  # FIXME specify what parameters to give? e.g., whether to randomise, and initial allocation.
  global cache : dictionary <string * string> := empty_dictionary

  # Any time we get something from a backend, cache it and forward it to the
  # client.
  backends => update_cache(cache) => client

  # Any time we get something from a client, see if we have a response in our
  # cache, and forward the request to a backend if it isn't.
  client => test_cache_or_pass_on(client, backends)

fun update_cache : (cache : ref dictionary <string * string>, response : type mcd_reply) -> (type mcd_reply)
  # NOTE relying on pass-by-reference of cache
  cache[response.key] := response
  response

fun test_cache_or_pass_on : (type mcd_request/type mcd_reply client, [type mcd_request/type mcd_reply] backend; request : type mcd_request) -> ()
  if cache[request.key] = None:
    # Work out which backend memcached to forward this request to, and send.
    request => backends[hash(request.key) mod len(backends)]
  else:
    cache[request.key] => client
<|endoftext|>


<commit_before><commit_msg>Port to kmime::message<commit_after><|endoftext|>


<commit_before>//
// cpl.cc
//
//
// Copyright (c) 2011, JF Gigand
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//

#include "php.h"
#include "cpl_error.h"
#include "cpl_conv.h"
#include "cpl_string.h"
#include "cpl_port.h"
#include "cpl.h"

PHP_FUNCTION(cplerrorreset)
{
  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }

  php_log_err("php5-gdal: CPLErrorReset");
  CPLErrorReset();
}

PHP_FUNCTION(cplgetlasterrorno)
{
  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }

  php_log_err("php5-gdal: CPLGetLastErrorNo");
  RETURN_LONG(CPLGetLastErrorNo());
}

PHP_FUNCTION(cplgetlasterrortype)
{
  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }
  php_log_err("php5-gdal: CPLGetLastErrorType");
  RETURN_LONG(CPLGetLastErrorType());
}

PHP_FUNCTION(cplgetlasterrormsg)
{
  const char *pszMsg;

  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }

  php_log_err("php5-gdal: CPLGetLastErrorMsg");
  if ((pszMsg = CPLGetLastErrorMsg()) != NULL) {
    RETURN_STRING((char *)pszMsg, 1);
  } else {
    RETURN_NULL();
  }
}

PHP_FUNCTION(cplsetconfigoption)
{
  char *key = NULL;
  char *value = NULL;
  int key_len;
  int value_len;
  int argc = ZEND_NUM_ARGS();

  if (zend_parse_parameters(argc TSRMLS_CC, (char*)"ss", &key, &key_len,
                            &value, &value_len) == FAILURE)
    return;

  php_log_err("php5-gdal: CPLSetConfigOption");
  CPLSetConfigOption(key, value);
}

PHP_FUNCTION(cplgetconfigoption)
{
  char *key = NULL;
  char *_default = NULL;
  int key_len;
  int _default_len;
  const char *value;
  int argc = ZEND_NUM_ARGS();

  if (zend_parse_parameters(argc TSRMLS_CC, (char*)"ss", &key, &key_len,
                            &_default, &_default_len) == FAILURE)
    return;

  php_log_err("php5-gdal: CPLGetConfigOption");
  value = CPLGetConfigOption(key, _default);
  if (value) {
    RETURN_STRING((char *)value, 1);
  } else {
    RETURN_NULL();
  }
}

# define CPLE_CONST_FLAG CONST_CS | CONST_PERSISTENT
void php_gdal_cpl_startup(INIT_FUNC_ARGS)
{
  REGISTER_LONG_CONSTANT("CPLE_None", CPLE_None, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_AppDefined", CPLE_AppDefined, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_OutOfMemory", CPLE_OutOfMemory, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_FileIO", CPLE_FileIO, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_OpenFailed", CPLE_OpenFailed, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_IllegalArg", CPLE_IllegalArg, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_NotSupported", CPLE_NotSupported, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_AssertionFailed", CPLE_AssertionFailed, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_NoWriteAccess", CPLE_NoWriteAccess, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_UserInterrupt", CPLE_UserInterrupt, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_ObjectNull", CPLE_ObjectNull, CPLE_CONST_FLAG);
}
<commit_msg>remove writing to PHPs error_log when CPL* functions are called<commit_after>//
// cpl.cc
//
//
// Copyright (c) 2011, JF Gigand
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//

#include "php.h"
#include "cpl_error.h"
#include "cpl_conv.h"
#include "cpl_string.h"
#include "cpl_port.h"
#include "cpl.h"
#include "debug.h"

PHP_FUNCTION(cplerrorreset)
{
  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }

  DEBUG_LOG("php5-gdal: CPLErrorReset");
  CPLErrorReset();
}

PHP_FUNCTION(cplgetlasterrorno)
{
  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }

  DEBUG_LOG("php5-gdal: CPLGetLastErrorNo");
  RETURN_LONG(CPLGetLastErrorNo());
}

PHP_FUNCTION(cplgetlasterrortype)
{
  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }
  DEBUG_LOG("php5-gdal: CPLGetLastErrorType");
  RETURN_LONG(CPLGetLastErrorType());
}

PHP_FUNCTION(cplgetlasterrormsg)
{
  const char *pszMsg;

  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }

  DEBUG_LOG("php5-gdal: CPLGetLastErrorMsg");
  if ((pszMsg = CPLGetLastErrorMsg()) != NULL) {
    RETURN_STRING((char *)pszMsg, 1);
  } else {
    RETURN_NULL();
  }
}

PHP_FUNCTION(cplsetconfigoption)
{
  char *key = NULL;
  char *value = NULL;
  int key_len;
  int value_len;
  int argc = ZEND_NUM_ARGS();

  if (zend_parse_parameters(argc TSRMLS_CC, (char*)"ss", &key, &key_len,
                            &value, &value_len) == FAILURE)
    return;

  DEBUG_LOG("php5-gdal: CPLSetConfigOption");
  CPLSetConfigOption(key, value);
}

PHP_FUNCTION(cplgetconfigoption)
{
  char *key = NULL;
  char *_default = NULL;
  int key_len;
  int _default_len;
  const char *value;
  int argc = ZEND_NUM_ARGS();

  if (zend_parse_parameters(argc TSRMLS_CC, (char*)"ss", &key, &key_len,
                            &_default, &_default_len) == FAILURE)
    return;

  DEBUG_LOG("php5-gdal: CPLGetConfigOption");
  value = CPLGetConfigOption(key, _default);
  if (value) {
    RETURN_STRING((char *)value, 1);
  } else {
    RETURN_NULL();
  }
}

# define CPLE_CONST_FLAG CONST_CS | CONST_PERSISTENT
void php_gdal_cpl_startup(INIT_FUNC_ARGS)
{
  REGISTER_LONG_CONSTANT("CPLE_None", CPLE_None, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_AppDefined", CPLE_AppDefined, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_OutOfMemory", CPLE_OutOfMemory, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_FileIO", CPLE_FileIO, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_OpenFailed", CPLE_OpenFailed, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_IllegalArg", CPLE_IllegalArg, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_NotSupported", CPLE_NotSupported, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_AssertionFailed", CPLE_AssertionFailed, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_NoWriteAccess", CPLE_NoWriteAccess, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_UserInterrupt", CPLE_UserInterrupt, CPLE_CONST_FLAG);
  REGISTER_LONG_CONSTANT("CPLE_ObjectNull", CPLE_ObjectNull, CPLE_CONST_FLAG);
}
<|endoftext|>


<commit_before>#include "rcMisc.hpp"

#include "irods_gsi_object.hpp"
#include "irods_auth_manager.hpp"
#include "irods_auth_plugin.hpp"

namespace irods {

gsi_auth_object::gsi_auth_object(
    rError_t* _r_error ) : auth_object( _r_error ) {
    creds_ = GSS_C_NO_CREDENTIAL;
}

gsi_auth_object::~gsi_auth_object() {
    // TODO - stub
}

error gsi_auth_object::resolve(
    const std::string& _interface,
    plugin_ptr& _ptr ) {
    error result = SUCCESS();
    if ( ( result = ASSERT_ERROR( _interface == AUTH_INTERFACE, SYS_INVALID_INPUT_PARAM,
                                  "gsi_auth_object does not support a \"%s\" plugin interface.",
                                  _interface.c_str() ) ).ok() ) {
        auth_ptr ath;
        error ret = auth_mgr.resolve( AUTH_GSI_SCHEME, ath );
        if ( !( result = ASSERT_PASS( ret, "Failed to resolve the GSI auth plugin." ) ).ok() ) {

            // Attempt to load the plugin.
            std::string empty_context( "" );
            ret = auth_mgr.init_from_type( AUTH_GSI_SCHEME, AUTH_GSI_SCHEME, AUTH_GSI_SCHEME, empty_context, ath );
            result = ASSERT_PASS( ret, "Failed to load the GSI auth plugin." );
        }

        if ( result.ok() ) {
            _ptr = boost::dynamic_pointer_cast<plugin_base>( ath );
        }
    }
    return result;
}

bool gsi_auth_object::operator==(
    const gsi_auth_object& _rhs ) const {
    return creds_ == _rhs.creds_;
}

// =-=-=-=-=-=-=-
// public - serialize object to kvp
error gsi_auth_object::get_re_vars(
    keyValPair_t& _kvp ) {
    irods::error result = SUCCESS();

    // =-=-=-=-=-=-=-
    // all we have in this object is the auth results
    std::stringstream sock_msg;
    sock_msg << sock_;
    addKeyVal( &_kvp, "socket", sock_msg.str().c_str() );
    addKeyVal( &_kvp, "serverDN", server_dn_.c_str() );
    addKeyVal( &_kvp, "digest", digest_.c_str() );

    return result;

} // get_re_vars

}; // namespace irods
<commit_msg>[#2212] CID26106:<commit_after>#include "rcMisc.hpp"

#include "irods_gsi_object.hpp"
#include "irods_auth_manager.hpp"
#include "irods_auth_plugin.hpp"

namespace irods {

gsi_auth_object::gsi_auth_object(
    rError_t* _r_error ) :
    auth_object( _r_error ),
    sock_( 0 ) {
    creds_ = GSS_C_NO_CREDENTIAL;
}

gsi_auth_object::~gsi_auth_object() {
    // TODO - stub
}

error gsi_auth_object::resolve(
    const std::string& _interface,
    plugin_ptr& _ptr ) {
    error result = SUCCESS();
    if ( ( result = ASSERT_ERROR( _interface == AUTH_INTERFACE, SYS_INVALID_INPUT_PARAM,
                                  "gsi_auth_object does not support a \"%s\" plugin interface.",
                                  _interface.c_str() ) ).ok() ) {
        auth_ptr ath;
        error ret = auth_mgr.resolve( AUTH_GSI_SCHEME, ath );
        if ( !( result = ASSERT_PASS( ret, "Failed to resolve the GSI auth plugin." ) ).ok() ) {

            // Attempt to load the plugin.
            std::string empty_context( "" );
            ret = auth_mgr.init_from_type( AUTH_GSI_SCHEME, AUTH_GSI_SCHEME, AUTH_GSI_SCHEME, empty_context, ath );
            result = ASSERT_PASS( ret, "Failed to load the GSI auth plugin." );
        }

        if ( result.ok() ) {
            _ptr = boost::dynamic_pointer_cast<plugin_base>( ath );
        }
    }
    return result;
}

bool gsi_auth_object::operator==(
    const gsi_auth_object& _rhs ) const {
    return creds_ == _rhs.creds_;
}

// =-=-=-=-=-=-=-
// public - serialize object to kvp
error gsi_auth_object::get_re_vars(
    keyValPair_t& _kvp ) {
    irods::error result = SUCCESS();

    // =-=-=-=-=-=-=-
    // all we have in this object is the auth results
    std::stringstream sock_msg;
    sock_msg << sock_;
    addKeyVal( &_kvp, "socket", sock_msg.str().c_str() );
    addKeyVal( &_kvp, "serverDN", server_dn_.c_str() );
    addKeyVal( &_kvp, "digest", digest_.c_str() );

    return result;

} // get_re_vars

}; // namespace irods
<|endoftext|>


<commit_before>// $Id$

#include <qdir.h>
#include <qstring.h>
#include <qfont.h>
#include <qcolor.h>
#include <qstringlist.h>

#include "koprefs.h"

#include <kconfig.h>
#include <ksimpleconfig.h>
#include <kstddirs.h>
#include <klocale.h>
#include <kdebug.h>
#include <kemailsettings.h>

KOPrefs *KOPrefs::mInstance = 0;

KOPrefs::KOPrefs() :
  KPrefs("korganizerrc")
{
  mCategoryColors.setAutoDelete(true);

  mDefaultCategoryColor           = QColor(196,196,196);
  QColor defaultHolidayColor      = QColor("red");
  QColor defaultHighlightColor    = QColor("blue");
  QColor defaultAgendaBgColor     = QColor(128,128,128);
  QColor defaultWorkingHoursColor = QColor(160,160,160);

  mDefaultTimeBarFont = QFont("helvetica",12,QFont::Bold);
  mDefaultViewFont = QFont("helvetica",12);

  KPrefsItem::setCurrentGroup("General");

  addPrefsItem(new KPrefsItemBool("Enable Group Scheduling",
                                  &mEnableGroupScheduling,false));
  addPrefsItem(new KPrefsItemBool("Enable Project View",
                                  &mEnableProjectView,false));

  KPrefsItem::setCurrentGroup("Personal Settings");

  addPrefsItem(new KPrefsItemInt("Mail Client",&mMailClient,
                                 MailClientKMail));
  addPrefsItem(new KPrefsItemBool("Use Control Center Email",
                                  &mEmailControlCenter,false));

  KPrefsItem::setCurrentGroup("AlarmDaemon");

  addPrefsItem(new KPrefsItemBool("Autostart",&mAlarmdAutostart,true));

  KPrefsItem::setCurrentGroup("Calendar");

  addPrefsItem(new KPrefsItemInt("Default Calendar Format",&mDefaultFormat,
                                 FormatICalendar));

  KPrefsItem::setCurrentGroup("Colors");

  addPrefsItem(new KPrefsItemColor("Holiday Color",&mHolidayColor,
                                   defaultHolidayColor));
  addPrefsItem(new KPrefsItemColor("Highlight Color",&mHighlightColor,
                                   defaultHighlightColor));
  addPrefsItem(new KPrefsItemColor("Event Color",&mEventColor,
                                   mDefaultCategoryColor));
  addPrefsItem(new KPrefsItemColor("Agenda Background Color",&mAgendaBgColor,
                                   defaultAgendaBgColor));
  addPrefsItem(new KPrefsItemColor("WorkingHours Color",&mWorkingHoursColor,
                                   defaultWorkingHoursColor));

  KPrefsItem::setCurrentGroup("Views");

  addPrefsItem(new KPrefsItemBool("Show Daily Recurrences",&mDailyRecur,true));
  addPrefsItem(new KPrefsItemBool("Show Weekly Recurrences",&mWeeklyRecur,
                                  true));
  addPrefsItem(new KPrefsItemBool("Enable ToolTips",&mEnableToolTips,false));
  addPrefsItem(new KPrefsItemBool("Enable MonthView ScrollBars",
                                  &mEnableMonthScroll,false));

  addPrefsItem(new KPrefsItemInt("Day Begins",&mDayBegins,7));
  addPrefsItem(new KPrefsItemInt("Working Hours Start",&mWorkingHoursStart,8));
  addPrefsItem(new KPrefsItemInt("Working Hours End",&mWorkingHoursEnd,17));
  addPrefsItem(new KPrefsItemBool("Exclude Holidays",&mExcludeHolidays,true));
  addPrefsItem(new KPrefsItemBool("Exclude Saturdays",&mExcludeSaturdays,true));

  addPrefsItem(new KPrefsItemBool("Full View Month",&mFullViewMonth,false));
  addPrefsItem(new KPrefsItemBool("Full View Todo",&mFullViewTodo,true));
}

KOPrefs::~KOPrefs()
{
  kdDebug() << "KOPrefs::~KOPrefs()" << endl;

  delete mInstance;
  mInstance = 0;
}

KOPrefs *KOPrefs::instance()
{
  if (!mInstance) {
    mInstance = new KOPrefs();
    mInstance->readConfig();
  }

  return mInstance;
}

void KOPrefs::usrSetDefaults()
{
  // Default should be set a bit smarter, respecting username and locale
  // settings for example.

  mAutoSave = false;
  mAutoSaveInterval = 10;
  mConfirm = true;

  KEMailSettings settings;
  mName = settings.getSetting(KEMailSettings::RealName);
  mEmail = settings.getSetting(KEMailSettings::RealName);
  fillMailDefaults();
  mBcc = false;

  mAdditional = "";
  mHoliday = KGlobal::locale()->country();

  mTimeZone = "+0000";
  mStartTime = 10;
  mDefaultDuration = 2;
  mAlarmTime = 0;
  mDaylightSavings = 0;

//  mDayBegins = 8;
  mHourSize = 10;
//  mDailyRecur = true;
//  mWeeklyRecur = true;
//  mEnableToolTips = false;

  mTimeBarFont = mDefaultTimeBarFont;
  mMonthViewFont = mDefaultViewFont;
  mAgendaViewFont = mDefaultViewFont;

//  mHolidayColor = mDefaultHolidayColor;
//  mHighlightColor = mDefaultHighlightColor;
//  mEventColor = mDefaultCategoryColor;
//  mAgendaBgColor = mDefaultAgendaBgColor;

  mPrinter = "";
  mPaperSize = 0;
  mPaperOrientation = 0;
  mPrintPreview = "kghostview";

  setCategoryDefaults();
}

void KOPrefs::fillMailDefaults()
{
  if (mName.isEmpty()) mName = i18n("Anonymous");
  if (mEmail.isEmpty()) mEmail = i18n("nobody@nowhere");
}

void KOPrefs::setCategoryDefaults()
{
  mCustomCategories.clear();

  mCustomCategories << i18n("Appointment") << i18n("Business")
      << i18n("Meeting") << i18n("Phone Call") << i18n("Education")
      << i18n("Holiday") << i18n("Vacation") << i18n("Special Occasion")
      << i18n("Personal") << i18n("Travel") << i18n("Miscellaneous")
      << i18n("Birthday");

  QStringList::Iterator it;
  for (it = mCustomCategories.begin();it != mCustomCategories.end();++it ) {
    setCategoryColor(*it,mDefaultCategoryColor);
  }
}

void KOPrefs::usrReadConfig()
{
  kdDebug() << "KOPrefs::usrReadConfig()" << endl;

  mConfig->setGroup("General");
  mAutoSave = mConfig->readBoolEntry("Auto Save",false);
  mAutoSaveInterval = mConfig->readNumEntry("Auto Save Interval",10);
  mConfirm = mConfig->readBoolEntry("Confirm Deletes",true);
  mCustomCategories = mConfig->readListEntry("Custom Categories");
  if (mCustomCategories.isEmpty()) setCategoryDefaults();

  mArchiveFile = mConfig->readEntry("Archive File");
  mHtmlExportFile = mConfig->readEntry("Html Export File",QDir::homeDirPath() +
                                       "/calendar.html");

  mConfig->setGroup("Personal Settings");
  mName = mConfig->readEntry("user_name","");
  mEmail = mConfig->readEntry("user_email","");
  fillMailDefaults();
  mAdditional = mConfig->readEntry("Additional","");
  mBcc = mConfig->readBoolEntry("Bcc",false);

  mHoliday = mConfig->readEntry("Holidays", KGlobal::locale()->country());

  mConfig->setGroup("Time & Date");
  mTimeZone = mConfig->readEntry("Time Zone","+0000");
  mStartTime = mConfig->readNumEntry("Default Start Time",10);
  mDefaultDuration = mConfig->readNumEntry("Default Duration",2);
  mAlarmTime = mConfig->readNumEntry("Default Alarm Time",0);
  mDaylightSavings = mConfig->readNumEntry("Daylight Savings", 0);

  mConfig->setGroup("Views");
//  mDayBegins = mConfig->readNumEntry("Day Begins",8);
  mHourSize = mConfig->readNumEntry("Hour Size",10);
//  mDailyRecur = mConfig->readBoolEntry("Show Daily Recurrences",true);
//  mWeeklyRecur = mConfig->readBoolEntry("Show Weekly Recurrences",true);
//  mEnableToolTips = mConfig->readBoolEntry("Enable ToolTips",false);

  mConfig->setGroup("Fonts");
  mTimeBarFont = mConfig->readFontEntry("TimeBar Font",&mDefaultTimeBarFont);
  mMonthViewFont = mConfig->readFontEntry("MonthView Font",
                                          &mDefaultViewFont);
  mAgendaViewFont = mConfig->readFontEntry("AgendaView Font",
                                          &mDefaultViewFont);

  mConfig->setGroup("Colors");
//  mHolidayColor = mConfig->readColorEntry("Holiday Color",
//                                         &mDefaultHolidayColor);
//  mHighlightColor = mConfig->readColorEntry("Highlight Color",
//                                            &mDefaultHighlightColor);
//  mEventColor = mConfig->readColorEntry("Event Color",
//                                            &mDefaultCategoryColor);
//  mAgendaBgColor = mConfig->readColorEntry("Agenda Background Color",
//                                            &mDefaultAgendaBgColor);

  mConfig->setGroup("Category Colors");
  QStringList::Iterator it;
  for (it = mCustomCategories.begin();it != mCustomCategories.end();++it ) {
    setCategoryColor(*it,mConfig->readColorEntry(*it,&mDefaultCategoryColor));
  }

  mConfig->setGroup("Printer");
  mPrinter = mConfig->readEntry("Printer Name",0);
  mPaperSize = mConfig->readNumEntry("Paper Size",0);
  mPaperOrientation = mConfig->readNumEntry("Paper Orientation",0);
  mPrintPreview = mConfig->readEntry("Preview","kghostview");

  kdDebug() << "KOPrefs::usrReadConfig() done" << endl;
}

void KOPrefs::usrWriteConfig()
{
//  kdDebug() << "KOPrefs::writeConfig()" << endl;

  mConfig->setGroup("General");
  mConfig->writeEntry("Auto Save",mAutoSave);
  mConfig->writeEntry("Auto Save Interval",mAutoSaveInterval);
  mConfig->writeEntry("Confirm Deletes",mConfirm);
  mConfig->writeEntry("Custom Categories",mCustomCategories);

  mConfig->writeEntry("Archive File",mArchiveFile);
  mConfig->writeEntry("Html Export File",mHtmlExportFile);

  mConfig->setGroup("Personal Settings");
  mConfig->writeEntry("user_name",mName);
  mConfig->writeEntry("user_email",mEmail);
  mConfig->writeEntry("Additional",mAdditional);
  mConfig->writeEntry("Bcc",mBcc);
  mConfig->writeEntry("Holidays",mHoliday);

  mConfig->setGroup("Time & Date");
  mConfig->writeEntry("Time Zone",mTimeZone);
  mConfig->writeEntry("Default Start Time",mStartTime);
  mConfig->writeEntry("Default Duration",mDefaultDuration);
  mConfig->writeEntry("Default Alarm Time",mAlarmTime);
  mConfig->writeEntry("Daylight Savings",mDaylightSavings);

  mConfig->setGroup("Views");
//  mConfig->writeEntry("Day Begins",mDayBegins);
  mConfig->writeEntry("Hour Size",mHourSize);
//  mConfig->writeEntry("Show Daily Recurrences",mDailyRecur);
//  mConfig->writeEntry("Show Weekly Recurrences",mWeeklyRecur);
//  mConfig->writeEntry("Enable ToolTips",mEnableToolTips);

  mConfig->setGroup("Fonts");
  mConfig->writeEntry("TimeBar Font",mTimeBarFont);
  mConfig->writeEntry("MonthView Font",mMonthViewFont);
  mConfig->writeEntry("AgendaView Font",mAgendaViewFont);

  mConfig->setGroup("Colors");
//  mConfig->writeEntry("Holiday Color",mHolidayColor);
//  mConfig->writeEntry("Highlight Color",mHighlightColor);
//  mConfig->writeEntry("Event Color",mEventColor);
//  mConfig->writeEntry("Agenda Background Color",mAgendaBgColor);

  mConfig->setGroup("Category Colors");
  QDictIterator<QColor> it(mCategoryColors);
  while (it.current()) {
    mConfig->writeEntry(it.currentKey(),*(it.current()));
    ++it;
  }

  mConfig->setGroup("Printer");
  mConfig->writeEntry("Printer Name",mPrinter);
  mConfig->writeEntry("Paper Size",mPaperSize);
  mConfig->writeEntry("Paper Orientation",mPaperOrientation);
  mConfig->writeEntry("Preview",mPrintPreview);
}

void KOPrefs::setCategoryColor(QString cat,const QColor & color)
{
  mCategoryColors.replace(cat,new QColor(color));
}

QColor *KOPrefs::categoryColor(QString cat)
{
  QColor *color = 0;

  if (!cat.isEmpty()) color = mCategoryColors[cat];

  if (color) return color;
  else return &mDefaultCategoryColor;
}

void KOPrefs::setFullName(const QString &name)
{
  mName = name;
}

void KOPrefs::setEmail(const QString &email)
{
  mEmail = email;
}

QString KOPrefs::fullName()
{
  if (mEmailControlCenter) {
    KEMailSettings settings;
    return settings.getSetting(KEMailSettings::RealName);
  } else {
    return mName;
  }
}

QString KOPrefs::email()
{
  if (mEmailControlCenter) {
    KEMailSettings settings;
    return settings.getSetting(KEMailSettings::EmailAddress);
  } else {
    return mEmail;
  }
}
<commit_msg>-  mHtmlExportFile = mConfig->readEntry("Html Export File",QDir::homeDirPath() + -                                       "/calendar.html"); +  mHtmlExportFile = mConfig->readEntry("Html Export File",QDir::homeDirPath() + "/" + +                                       i18n("Default export file", "calendar.html"));<commit_after>// $Id$

#include <qdir.h>
#include <qstring.h>
#include <qfont.h>
#include <qcolor.h>
#include <qstringlist.h>

#include "koprefs.h"

#include <kconfig.h>
#include <ksimpleconfig.h>
#include <kstddirs.h>
#include <klocale.h>
#include <kdebug.h>
#include <kemailsettings.h>

KOPrefs *KOPrefs::mInstance = 0;

KOPrefs::KOPrefs() :
  KPrefs("korganizerrc")
{
  mCategoryColors.setAutoDelete(true);

  mDefaultCategoryColor           = QColor(196,196,196);
  QColor defaultHolidayColor      = QColor("red");
  QColor defaultHighlightColor    = QColor("blue");
  QColor defaultAgendaBgColor     = QColor(128,128,128);
  QColor defaultWorkingHoursColor = QColor(160,160,160);

  mDefaultTimeBarFont = QFont("helvetica",12,QFont::Bold);
  mDefaultViewFont = QFont("helvetica",12);

  KPrefsItem::setCurrentGroup("General");

  addPrefsItem(new KPrefsItemBool("Enable Group Scheduling",
                                  &mEnableGroupScheduling,false));
  addPrefsItem(new KPrefsItemBool("Enable Project View",
                                  &mEnableProjectView,false));

  KPrefsItem::setCurrentGroup("Personal Settings");

  addPrefsItem(new KPrefsItemInt("Mail Client",&mMailClient,
                                 MailClientKMail));
  addPrefsItem(new KPrefsItemBool("Use Control Center Email",
                                  &mEmailControlCenter,false));

  KPrefsItem::setCurrentGroup("AlarmDaemon");

  addPrefsItem(new KPrefsItemBool("Autostart",&mAlarmdAutostart,true));

  KPrefsItem::setCurrentGroup("Calendar");

  addPrefsItem(new KPrefsItemInt("Default Calendar Format",&mDefaultFormat,
                                 FormatICalendar));

  KPrefsItem::setCurrentGroup("Colors");

  addPrefsItem(new KPrefsItemColor("Holiday Color",&mHolidayColor,
                                   defaultHolidayColor));
  addPrefsItem(new KPrefsItemColor("Highlight Color",&mHighlightColor,
                                   defaultHighlightColor));
  addPrefsItem(new KPrefsItemColor("Event Color",&mEventColor,
                                   mDefaultCategoryColor));
  addPrefsItem(new KPrefsItemColor("Agenda Background Color",&mAgendaBgColor,
                                   defaultAgendaBgColor));
  addPrefsItem(new KPrefsItemColor("WorkingHours Color",&mWorkingHoursColor,
                                   defaultWorkingHoursColor));

  KPrefsItem::setCurrentGroup("Views");

  addPrefsItem(new KPrefsItemBool("Show Daily Recurrences",&mDailyRecur,true));
  addPrefsItem(new KPrefsItemBool("Show Weekly Recurrences",&mWeeklyRecur,
                                  true));
  addPrefsItem(new KPrefsItemBool("Enable ToolTips",&mEnableToolTips,false));
  addPrefsItem(new KPrefsItemBool("Enable MonthView ScrollBars",
                                  &mEnableMonthScroll,false));

  addPrefsItem(new KPrefsItemInt("Day Begins",&mDayBegins,7));
  addPrefsItem(new KPrefsItemInt("Working Hours Start",&mWorkingHoursStart,8));
  addPrefsItem(new KPrefsItemInt("Working Hours End",&mWorkingHoursEnd,17));
  addPrefsItem(new KPrefsItemBool("Exclude Holidays",&mExcludeHolidays,true));
  addPrefsItem(new KPrefsItemBool("Exclude Saturdays",&mExcludeSaturdays,true));

  addPrefsItem(new KPrefsItemBool("Full View Month",&mFullViewMonth,false));
  addPrefsItem(new KPrefsItemBool("Full View Todo",&mFullViewTodo,true));
}

KOPrefs::~KOPrefs()
{
  kdDebug() << "KOPrefs::~KOPrefs()" << endl;

  delete mInstance;
  mInstance = 0;
}

KOPrefs *KOPrefs::instance()
{
  if (!mInstance) {
    mInstance = new KOPrefs();
    mInstance->readConfig();
  }

  return mInstance;
}

void KOPrefs::usrSetDefaults()
{
  // Default should be set a bit smarter, respecting username and locale
  // settings for example.

  mAutoSave = false;
  mAutoSaveInterval = 10;
  mConfirm = true;

  KEMailSettings settings;
  mName = settings.getSetting(KEMailSettings::RealName);
  mEmail = settings.getSetting(KEMailSettings::RealName);
  fillMailDefaults();
  mBcc = false;

  mAdditional = "";
  mHoliday = KGlobal::locale()->country();

  mTimeZone = "+0000";
  mStartTime = 10;
  mDefaultDuration = 2;
  mAlarmTime = 0;
  mDaylightSavings = 0;

//  mDayBegins = 8;
  mHourSize = 10;
//  mDailyRecur = true;
//  mWeeklyRecur = true;
//  mEnableToolTips = false;

  mTimeBarFont = mDefaultTimeBarFont;
  mMonthViewFont = mDefaultViewFont;
  mAgendaViewFont = mDefaultViewFont;

//  mHolidayColor = mDefaultHolidayColor;
//  mHighlightColor = mDefaultHighlightColor;
//  mEventColor = mDefaultCategoryColor;
//  mAgendaBgColor = mDefaultAgendaBgColor;

  mPrinter = "";
  mPaperSize = 0;
  mPaperOrientation = 0;
  mPrintPreview = "kghostview";

  setCategoryDefaults();
}

void KOPrefs::fillMailDefaults()
{
  if (mName.isEmpty()) mName = i18n("Anonymous");
  if (mEmail.isEmpty()) mEmail = i18n("nobody@nowhere");
}

void KOPrefs::setCategoryDefaults()
{
  mCustomCategories.clear();

  mCustomCategories << i18n("Appointment") << i18n("Business")
      << i18n("Meeting") << i18n("Phone Call") << i18n("Education")
      << i18n("Holiday") << i18n("Vacation") << i18n("Special Occasion")
      << i18n("Personal") << i18n("Travel") << i18n("Miscellaneous")
      << i18n("Birthday");

  QStringList::Iterator it;
  for (it = mCustomCategories.begin();it != mCustomCategories.end();++it ) {
    setCategoryColor(*it,mDefaultCategoryColor);
  }
}

void KOPrefs::usrReadConfig()
{
  kdDebug() << "KOPrefs::usrReadConfig()" << endl;

  mConfig->setGroup("General");
  mAutoSave = mConfig->readBoolEntry("Auto Save",false);
  mAutoSaveInterval = mConfig->readNumEntry("Auto Save Interval",10);
  mConfirm = mConfig->readBoolEntry("Confirm Deletes",true);
  mCustomCategories = mConfig->readListEntry("Custom Categories");
  if (mCustomCategories.isEmpty()) setCategoryDefaults();

  mArchiveFile = mConfig->readEntry("Archive File");
  mHtmlExportFile = mConfig->readEntry("Html Export File",QDir::homeDirPath() + "/" +
                                       i18n("Default export file", "calendar.html"));

  mConfig->setGroup("Personal Settings");
  mName = mConfig->readEntry("user_name","");
  mEmail = mConfig->readEntry("user_email","");
  fillMailDefaults();
  mAdditional = mConfig->readEntry("Additional","");
  mBcc = mConfig->readBoolEntry("Bcc",false);

  mHoliday = mConfig->readEntry("Holidays", KGlobal::locale()->country());

  mConfig->setGroup("Time & Date");
  mTimeZone = mConfig->readEntry("Time Zone","+0000");
  mStartTime = mConfig->readNumEntry("Default Start Time",10);
  mDefaultDuration = mConfig->readNumEntry("Default Duration",2);
  mAlarmTime = mConfig->readNumEntry("Default Alarm Time",0);
  mDaylightSavings = mConfig->readNumEntry("Daylight Savings", 0);

  mConfig->setGroup("Views");
//  mDayBegins = mConfig->readNumEntry("Day Begins",8);
  mHourSize = mConfig->readNumEntry("Hour Size",10);
//  mDailyRecur = mConfig->readBoolEntry("Show Daily Recurrences",true);
//  mWeeklyRecur = mConfig->readBoolEntry("Show Weekly Recurrences",true);
//  mEnableToolTips = mConfig->readBoolEntry("Enable ToolTips",false);

  mConfig->setGroup("Fonts");
  mTimeBarFont = mConfig->readFontEntry("TimeBar Font",&mDefaultTimeBarFont);
  mMonthViewFont = mConfig->readFontEntry("MonthView Font",
                                          &mDefaultViewFont);
  mAgendaViewFont = mConfig->readFontEntry("AgendaView Font",
                                          &mDefaultViewFont);

  mConfig->setGroup("Colors");
//  mHolidayColor = mConfig->readColorEntry("Holiday Color",
//                                         &mDefaultHolidayColor);
//  mHighlightColor = mConfig->readColorEntry("Highlight Color",
//                                            &mDefaultHighlightColor);
//  mEventColor = mConfig->readColorEntry("Event Color",
//                                            &mDefaultCategoryColor);
//  mAgendaBgColor = mConfig->readColorEntry("Agenda Background Color",
//                                            &mDefaultAgendaBgColor);

  mConfig->setGroup("Category Colors");
  QStringList::Iterator it;
  for (it = mCustomCategories.begin();it != mCustomCategories.end();++it ) {
    setCategoryColor(*it,mConfig->readColorEntry(*it,&mDefaultCategoryColor));
  }

  mConfig->setGroup("Printer");
  mPrinter = mConfig->readEntry("Printer Name",0);
  mPaperSize = mConfig->readNumEntry("Paper Size",0);
  mPaperOrientation = mConfig->readNumEntry("Paper Orientation",0);
  mPrintPreview = mConfig->readEntry("Preview","kghostview");

  kdDebug() << "KOPrefs::usrReadConfig() done" << endl;
}

void KOPrefs::usrWriteConfig()
{
//  kdDebug() << "KOPrefs::writeConfig()" << endl;

  mConfig->setGroup("General");
  mConfig->writeEntry("Auto Save",mAutoSave);
  mConfig->writeEntry("Auto Save Interval",mAutoSaveInterval);
  mConfig->writeEntry("Confirm Deletes",mConfirm);
  mConfig->writeEntry("Custom Categories",mCustomCategories);

  mConfig->writeEntry("Archive File",mArchiveFile);
  mConfig->writeEntry("Html Export File",mHtmlExportFile);

  mConfig->setGroup("Personal Settings");
  mConfig->writeEntry("user_name",mName);
  mConfig->writeEntry("user_email",mEmail);
  mConfig->writeEntry("Additional",mAdditional);
  mConfig->writeEntry("Bcc",mBcc);
  mConfig->writeEntry("Holidays",mHoliday);

  mConfig->setGroup("Time & Date");
  mConfig->writeEntry("Time Zone",mTimeZone);
  mConfig->writeEntry("Default Start Time",mStartTime);
  mConfig->writeEntry("Default Duration",mDefaultDuration);
  mConfig->writeEntry("Default Alarm Time",mAlarmTime);
  mConfig->writeEntry("Daylight Savings",mDaylightSavings);

  mConfig->setGroup("Views");
//  mConfig->writeEntry("Day Begins",mDayBegins);
  mConfig->writeEntry("Hour Size",mHourSize);
//  mConfig->writeEntry("Show Daily Recurrences",mDailyRecur);
//  mConfig->writeEntry("Show Weekly Recurrences",mWeeklyRecur);
//  mConfig->writeEntry("Enable ToolTips",mEnableToolTips);

  mConfig->setGroup("Fonts");
  mConfig->writeEntry("TimeBar Font",mTimeBarFont);
  mConfig->writeEntry("MonthView Font",mMonthViewFont);
  mConfig->writeEntry("AgendaView Font",mAgendaViewFont);

  mConfig->setGroup("Colors");
//  mConfig->writeEntry("Holiday Color",mHolidayColor);
//  mConfig->writeEntry("Highlight Color",mHighlightColor);
//  mConfig->writeEntry("Event Color",mEventColor);
//  mConfig->writeEntry("Agenda Background Color",mAgendaBgColor);

  mConfig->setGroup("Category Colors");
  QDictIterator<QColor> it(mCategoryColors);
  while (it.current()) {
    mConfig->writeEntry(it.currentKey(),*(it.current()));
    ++it;
  }

  mConfig->setGroup("Printer");
  mConfig->writeEntry("Printer Name",mPrinter);
  mConfig->writeEntry("Paper Size",mPaperSize);
  mConfig->writeEntry("Paper Orientation",mPaperOrientation);
  mConfig->writeEntry("Preview",mPrintPreview);
}

void KOPrefs::setCategoryColor(QString cat,const QColor & color)
{
  mCategoryColors.replace(cat,new QColor(color));
}

QColor *KOPrefs::categoryColor(QString cat)
{
  QColor *color = 0;

  if (!cat.isEmpty()) color = mCategoryColors[cat];

  if (color) return color;
  else return &mDefaultCategoryColor;
}

void KOPrefs::setFullName(const QString &name)
{
  mName = name;
}

void KOPrefs::setEmail(const QString &email)
{
  mEmail = email;
}

QString KOPrefs::fullName()
{
  if (mEmailControlCenter) {
    KEMailSettings settings;
    return settings.getSetting(KEMailSettings::RealName);
  } else {
    return mName;
  }
}

QString KOPrefs::email()
{
  if (mEmailControlCenter) {
    KEMailSettings settings;
    return settings.getSetting(KEMailSettings::EmailAddress);
  } else {
    return mEmail;
  }
}
<|endoftext|>


<commit_before><commit_msg>optional verbose mode for --integrity<commit_after><|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

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

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

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

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

#include <mitkTestFixture.h>
#include <mitkTestingMacros.h>
#include <mitkImage.h>
#include <mitkImageReadAccessor.h>
#include <mitkBeamformingFilter.h>
#include <mitkIOUtil.h>
#include <usModuleResource.h>
#include <random>

class SyntheticPAImageData
{
public:
  SyntheticPAImageData(float spacing_x, float spacing_y, unsigned int samples, unsigned int num_transducers, float speedOfSound)
  {
    m_Spacing_x = spacing_x;
    m_Spacing_y = spacing_y;
    m_TransducerElements = num_transducers;
    m_Samples = samples;
    m_SpeedOfSound = speedOfSound;
    m_Data = new float[m_Samples*m_TransducerElements];
  }

  ~SyntheticPAImageData()
  {
    delete[] m_Data;
  }

  void AddWave(float origin_depth, float origin_x, float base_value= 10000)
  {
    AddLine(origin_depth, origin_x, base_value);
    AddLine(origin_depth + 0.0001, origin_x, -base_value);
  }

  const float* GetData()
  {
    return (const float*)m_Data;
  }

private:
  void AddLine(float origin_depth, unsigned int origin_x, float base_value = 10000)
  {
    for (unsigned int x = 0; x < m_TransducerElements; ++x)
    {
      float distance = std::abs((int)x - (int)origin_x);
      float delay_in_seconds = std::sqrt(std::pow(origin_depth, 2) + std::pow(distance*m_Spacing_x, 2)) / m_SpeedOfSound;
      unsigned int pixels = int(delay_in_seconds / m_Spacing_y);

      for (int index = -2; index < 5; ++index)
      {
        if ((int)pixels + index < (int)m_Samples && (int)pixels + index > 0)
        {
          //MITK_INFO << "yep: " << base_value / std::sqrt(distance + 1);
          m_Data[x + (pixels + index)*m_TransducerElements] += base_value / std::sqrt(distance + 1);
        }
      }
    }
  }

  float* m_Data;
  float m_Spacing_x;
  float m_Spacing_y;
  unsigned int m_TransducerElements;
  unsigned int m_Samples;
  float m_SpeedOfSound;
};

class mitkBeamformingFilterTestSuite : public mitk::TestFixture
{
  CPPUNIT_TEST_SUITE(mitkBeamformingFilterTestSuite);
  MITK_TEST(testBeamformingCPU_DAS);
  MITK_TEST(testBeamformingGPU_DAS);
  CPPUNIT_TEST_SUITE_END();

private:

  mitk::BeamformingFilter::Pointer m_BeamformingFilter;
  const unsigned int NUM_ITERATIONS = 15;
  const unsigned int SAMPLES = 5000;
  const unsigned int RECONSTRUCTED_SAMPLES = 2048;
  const unsigned int ELEMENTS = 128;
  const unsigned int RECONSTRUCTED_LINES = 128;
  const float SPEED_OF_SOUND = 1540; // m/s
  const float SPACING_X = 0.3; // mm
  const float SPACING_Y = 0.00625; // us

public:

  void setUp() override
  {

  }

  void test()
  {
    std::random_device r;
    std::default_random_engine randGen(r());
    float maxDepthInMeters = SAMPLES * (SPACING_Y / 1000000) * SPEED_OF_SOUND / 2;
    std::uniform_real_distribution<float> randDistrDepth(maxDepthInMeters*0.1, maxDepthInMeters*0.8);

    for (unsigned int iteration = 0; iteration < NUM_ITERATIONS; ++iteration)
    {
      // create some synthetic input data
      float depth_in_meters1 = randDistrDepth(randGen);
      float depth_in_meters2 = randDistrDepth(randGen);
      float depth_in_meters3 = randDistrDepth(randGen);

      unsigned int element1 = 29;
      unsigned int element2 = 63;
      unsigned int element3 = 98;

      SyntheticPAImageData image(SPACING_X, SPACING_Y, SAMPLES, ELEMENTS, SPEED_OF_SOUND);
      image.AddWave(depth_in_meters1, 98);
      image.AddWave(depth_in_meters2, 29);
      image.AddWave(depth_in_meters3, 63);

      mitk::Image::Pointer inputImage = mitk::Image::New();
      unsigned int dimension[3]{ ELEMENTS, SAMPLES, 1 };
      inputImage->Initialize(mitk::MakeScalarPixelType<float>(), 3, dimension);
      mitk::Vector3D spacing;
      spacing[0] = SPACING_X;
      spacing[1] = SPACING_Y;
      spacing[2] = 1;
      inputImage->SetSpacing(spacing);
      inputImage->SetImportVolume(image.GetData());
      mitk::IOUtil::Save(inputImage, "D:/dff.nrrd");

      // setup the beamforming filter
      m_BeamformingFilter->SetInput(inputImage);
      m_BeamformingFilter->Update();

      mitk::Image::Pointer outputImage = m_BeamformingFilter->GetOutput();
      mitk::ImageReadAccessor readAccess(outputImage);
      const float* outputData = (const float*)readAccess.GetData();

      unsigned int pos1[3] = { element1, (unsigned int)std::round(depth_in_meters1 * 1000 / outputImage->GetGeometry()->GetSpacing()[1]), 0 };
      unsigned int pos2[3] = { element2, (unsigned int)std::round(depth_in_meters2 * 1000 / outputImage->GetGeometry()->GetSpacing()[1]), 0 };
      unsigned int pos3[3] = { element3, (unsigned int)std::round(depth_in_meters3 * 1000 / outputImage->GetGeometry()->GetSpacing()[1]), 0 };

      double average = 0;

      for (unsigned int i = 0; i < RECONSTRUCTED_LINES*RECONSTRUCTED_SAMPLES; ++i)
      {
        average += outputData[i] / RECONSTRUCTED_LINES*RECONSTRUCTED_SAMPLES;
      }

      MITK_INFO << "itssssssssssssss" << average;
      CPPUNIT_ASSERT_MESSAGE(std::string("first point source incorrectly reconstructed"), abs(outputData[pos1[0] + pos1[1]*RECONSTRUCTED_LINES] / average) > 100);
      CPPUNIT_ASSERT_MESSAGE(std::string("second point source incorrectly reconstructed"), abs(outputData[pos2[0] + pos2[1] * RECONSTRUCTED_LINES] / average) > 100);
      CPPUNIT_ASSERT_MESSAGE(std::string("third point source incorrectly reconstructed"), abs(outputData[pos3[0] + pos3[1] * RECONSTRUCTED_LINES] / average) > 100);

    }
  }

  mitk::BeamformingSettings::Pointer createConfig(bool UseGPU, unsigned int* inputDim, mitk::BeamformingSettings::BeamformingAlgorithm alg)
  {
    return mitk::BeamformingSettings::New(SPACING_X / 1000,
      SPEED_OF_SOUND,
      SPACING_Y,
      27.f,
      true,
      RECONSTRUCTED_SAMPLES,
      RECONSTRUCTED_LINES,
      0,
      false,
      nullptr,
      inputDim,
      UseGPU,
      mitk::BeamformingSettings::DelayCalc::Spherical,
      mitk::BeamformingSettings::Apodization::Box,
      ELEMENTS * 2,
      alg,
      false,
      0,
      0);
  }

  void testBeamformingCPU_DAS()
  {
    unsigned int* inputDim = new unsigned int[3];
    inputDim[0] = ELEMENTS;
    inputDim[1] = RECONSTRUCTED_SAMPLES;
    inputDim[2] = 1;
    m_BeamformingFilter = mitk::BeamformingFilter::New(createConfig(false, inputDim, mitk::BeamformingSettings::BeamformingAlgorithm::DAS));

    test();
    delete[] inputDim;
  }

  void testBeamformingGPU_DAS()
  {
    unsigned int* inputDim = new unsigned int[3];
    inputDim[0] = ELEMENTS;
    inputDim[1] = RECONSTRUCTED_SAMPLES;
    inputDim[2] = 1;
    m_BeamformingFilter = mitk::BeamformingFilter::New(createConfig(true, inputDim, mitk::BeamformingSettings::BeamformingAlgorithm::DAS));

    test();
    delete[] inputDim;
  }

  void testBeamformingCPU_sDMAS()
  {
    unsigned int* inputDim = new unsigned int[3];
    inputDim[0] = ELEMENTS;
    inputDim[1] = RECONSTRUCTED_SAMPLES;
    inputDim[2] = 1;
    m_BeamformingFilter = mitk::BeamformingFilter::New(createConfig(false, inputDim, mitk::BeamformingSettings::BeamformingAlgorithm::sDMAS));

    test();
    delete[] inputDim;
  }

  void testBeamformingGPU_sDMAS()
  {
    unsigned int* inputDim = new unsigned int[3];
    inputDim[0] = ELEMENTS;
    inputDim[1] = RECONSTRUCTED_SAMPLES;
    inputDim[2] = 1;
    m_BeamformingFilter = mitk::BeamformingFilter::New(createConfig(true, inputDim, mitk::BeamformingSettings::BeamformingAlgorithm::sDMAS));

    test();
    delete[] inputDim;
  }

  void testBeamformingCPU_DMAS()
  {
    unsigned int* inputDim = new unsigned int[3];
    inputDim[0] = ELEMENTS;
    inputDim[1] = RECONSTRUCTED_SAMPLES;
    inputDim[2] = 1;
    m_BeamformingFilter = mitk::BeamformingFilter::New(createConfig(false, inputDim, mitk::BeamformingSettings::BeamformingAlgorithm::DMAS));

    test();
    delete[] inputDim;
  }

  void testBeamformingGPU_DMAS()
  {
    unsigned int* inputDim = new unsigned int[3];
    inputDim[0] = ELEMENTS;
    inputDim[1] = RECONSTRUCTED_SAMPLES;
    inputDim[2] = 1;
    m_BeamformingFilter = mitk::BeamformingFilter::New(createConfig(true, inputDim, mitk::BeamformingSettings::BeamformingAlgorithm::DMAS));

    test();
    delete[] inputDim;
  }
};

MITK_TEST_SUITE_REGISTRATION(mitkBeamformingFilter)
<commit_msg>The Beamforming Test works now!<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

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

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

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

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

#include <mitkTestFixture.h>
#include <mitkTestingMacros.h>
#include <mitkImage.h>
#include <mitkImageReadAccessor.h>
#include <mitkBeamformingFilter.h>
#include <mitkIOUtil.h>
#include <usModuleResource.h>
#include <random>

class SyntheticPAImageData
{
public:
  SyntheticPAImageData(float spacing_x, float spacing_y, unsigned int samples, unsigned int num_transducers, float speedOfSound)
  {
    m_Spacing_x = spacing_x;
    m_Spacing_y = spacing_y;
    m_TransducerElements = num_transducers;
    m_Samples = samples;
    m_SpeedOfSound = speedOfSound;
    m_Data = new float[m_Samples*m_TransducerElements];

    for (size_t i = 0; i < m_Samples * m_TransducerElements; ++i)
    {
      m_Data[i] = 0;
    }
  }

  ~SyntheticPAImageData()
  {
    delete[] m_Data;
  }

  void AddWave(float origin_depth, float origin_x, float base_value= 10000)
  {
    AddLine(origin_depth, origin_x, base_value);
    AddLine(origin_depth + 0.0001f, origin_x, -base_value);
  }

  const float* GetData()
  {
    return (const float*)m_Data;
  }

private:
  void AddLine(float origin_depth, unsigned int origin_x, float base_value = 10000)
  {
    for (unsigned int x = 0; x < m_TransducerElements; ++x)
    {
      float distance = std::abs((int)x - (int)origin_x);
      float delay_in_seconds = std::sqrt(std::pow(origin_depth, 2) + std::pow(distance*m_Spacing_x, 2)) / m_SpeedOfSound;
      int pixels = std::round(delay_in_seconds / m_Spacing_y);

      for (int index = -4; index < 9; ++index)
      {
        if ((int)pixels + index < (int)m_Samples && (int)pixels + index > 0)
        {
          m_Data[(size_t)(x + (pixels + index)*m_TransducerElements)] += base_value / std::sqrt(distance + 1);
        }
      }
    }
  }

  float* m_Data;
  float m_Spacing_x;
  float m_Spacing_y;
  unsigned int m_TransducerElements;
  unsigned int m_Samples;
  float m_SpeedOfSound;
};

class mitkBeamformingFilterTestSuite : public mitk::TestFixture
{
  CPPUNIT_TEST_SUITE(mitkBeamformingFilterTestSuite);
  MITK_TEST(testBeamformingCPU_DAS);
  MITK_TEST(testBeamformingGPU_DAS);
  MITK_TEST(testBeamformingCPU_DMAS);
  MITK_TEST(testBeamformingGPU_DMAS);
  MITK_TEST(testBeamformingCPU_sDMAS);
  MITK_TEST(testBeamformingGPU_sDMAS);
  CPPUNIT_TEST_SUITE_END();

private:

  mitk::BeamformingFilter::Pointer m_BeamformingFilter;
  const unsigned int NUM_ITERATIONS = 15;
  const unsigned int SAMPLES = 5000 * 2;
  const unsigned int RECONSTRUCTED_SAMPLES = 2048;
  const unsigned int ELEMENTS = 128;
  const unsigned int RECONSTRUCTED_LINES = 128;
  const float SPEED_OF_SOUND = 1540; // m/s
  const float SPACING_X = 0.3; // mm
  const float SPACING_Y = 0.00625 / 2; // us

public:

  void setUp() override
  {

  }

  void test()
  {
    std::random_device r;
    std::default_random_engine randGen(r());
    float maxDepthInMeters = SAMPLES * (SPACING_Y / 1000000) * SPEED_OF_SOUND / 2;
    std::uniform_real_distribution<float> randDistrDepth(maxDepthInMeters*0.1, maxDepthInMeters*0.8);

    for (unsigned int iteration = 0; iteration < NUM_ITERATIONS; ++iteration)
    {
      // create some synthetic input data
      float depth_in_meters1 = randDistrDepth(randGen);
      float depth_in_meters2 = randDistrDepth(randGen);
      float depth_in_meters3 = randDistrDepth(randGen);

      unsigned int element1 = 29;
      unsigned int element2 = 63;
      unsigned int element3 = 98;

      SyntheticPAImageData image(SPACING_X / 1000.f, SPACING_Y / 1000000.f, SAMPLES, ELEMENTS, SPEED_OF_SOUND);
      image.AddWave(depth_in_meters1, 29);
      image.AddWave(depth_in_meters2, 63);
      image.AddWave(depth_in_meters3, 98);

      mitk::Image::Pointer inputImage = mitk::Image::New();
      unsigned int dimension[3]{ ELEMENTS, SAMPLES, 1 };
      inputImage->Initialize(mitk::MakeScalarPixelType<float>(), 3, dimension);
      mitk::Vector3D spacing;
      spacing[0] = SPACING_X;
      spacing[1] = SPACING_Y;
      spacing[2] = 1;
      inputImage->SetSpacing(spacing);
      inputImage->SetImportVolume((const void*)image.GetData(), mitk::Image::RtlCopyMemory);

      // setup the beamforming filter
      m_BeamformingFilter->SetInput(inputImage);
      m_BeamformingFilter->Update();

      mitk::Image::Pointer outputImage = m_BeamformingFilter->GetOutput();
      mitk::ImageReadAccessor readAccess(outputImage);
      const float* outputData = (const float*)readAccess.GetData();

      unsigned int pos1[3] = { element1, (unsigned int)std::round(depth_in_meters1 * 1000.f / outputImage->GetGeometry()->GetSpacing()[1]), 0 };
      unsigned int pos2[3] = { element2, (unsigned int)std::round(depth_in_meters2 * 1000.f / outputImage->GetGeometry()->GetSpacing()[1]), 0 };
      unsigned int pos3[3] = { element3, (unsigned int)std::round(depth_in_meters3 * 1000.f / outputImage->GetGeometry()->GetSpacing()[1]), 0 };

      double average = 0;

      for (unsigned int i = 0; i < RECONSTRUCTED_LINES*RECONSTRUCTED_SAMPLES; ++i)
      {
        average += outputData[i] / (RECONSTRUCTED_LINES*RECONSTRUCTED_SAMPLES);
      }

      CPPUNIT_ASSERT_MESSAGE(std::string("Iteration " + std::to_string(iteration) + ": first point source incorrectly reconstructed; should be > average*100, is " +
        std::to_string(abs(outputData[pos1[0] + pos1[1] * RECONSTRUCTED_LINES]))) + " < " + std::to_string(average) + "*100"
        , abs(outputData[pos1[0] + pos1[1]*RECONSTRUCTED_LINES] / average) > 100);
      CPPUNIT_ASSERT_MESSAGE(std::string("Iteration " + std::to_string(iteration) + ": second point source incorrectly reconstructed; should be > average*100, is " +
        std::to_string(abs(outputData[pos2[0] + pos2[1] * RECONSTRUCTED_LINES]))) + " < " + std::to_string(average) + "*100"
        , abs(outputData[pos2[0] + pos2[1] * RECONSTRUCTED_LINES] / average) > 100);
      CPPUNIT_ASSERT_MESSAGE(std::string("Iteration " + std::to_string(iteration) + ": third point source incorrectly reconstructed; should be > average*100, is " +
        std::to_string(abs(outputData[pos3[0] + pos3[1] * RECONSTRUCTED_LINES]))) + " < " + std::to_string(average) + "*100"
        , abs(outputData[pos3[0] + pos3[1] * RECONSTRUCTED_LINES] / average) > 100);
    }
  }

  mitk::BeamformingSettings::Pointer createConfig(bool UseGPU, unsigned int* inputDim, mitk::BeamformingSettings::BeamformingAlgorithm alg)
  {
    return mitk::BeamformingSettings::New(SPACING_X / 1000,
      SPEED_OF_SOUND,
      SPACING_Y / 1000000,
      27.f,
      true,
      RECONSTRUCTED_SAMPLES,
      RECONSTRUCTED_LINES,
      0,
      false,
      nullptr,
      inputDim,
      UseGPU,
      mitk::BeamformingSettings::DelayCalc::Spherical,
      mitk::BeamformingSettings::Apodization::Box,
      ELEMENTS * 2,
      alg,
      false,
      0,
      0);
  }

  void testBeamformingCPU_DAS()
  {
    MITK_INFO << "Started DAS test on CPU";
    unsigned int* inputDim = new unsigned int[3];
    inputDim[0] = ELEMENTS;
    inputDim[1] = SAMPLES;
    inputDim[2] = 1;
    m_BeamformingFilter = mitk::BeamformingFilter::New(createConfig(false, inputDim, mitk::BeamformingSettings::BeamformingAlgorithm::DAS));

    test();
    delete[] inputDim;
  }

  void testBeamformingGPU_DAS()
  {
    MITK_INFO << "Started DAS test on GPU";
    unsigned int* inputDim = new unsigned int[3];
    inputDim[0] = ELEMENTS;
    inputDim[1] = SAMPLES;
    inputDim[2] = 1;
    m_BeamformingFilter = mitk::BeamformingFilter::New(createConfig(true, inputDim, mitk::BeamformingSettings::BeamformingAlgorithm::DAS));

    test();
    delete[] inputDim;
  }

  void testBeamformingCPU_sDMAS()
  {
    MITK_INFO << "Started sDMAS test on CPU";
    unsigned int* inputDim = new unsigned int[3];
    inputDim[0] = ELEMENTS;
    inputDim[1] = SAMPLES;
    inputDim[2] = 1;
    m_BeamformingFilter = mitk::BeamformingFilter::New(createConfig(false, inputDim, mitk::BeamformingSettings::BeamformingAlgorithm::sDMAS));

    test();
    delete[] inputDim;
  }

  void testBeamformingGPU_sDMAS()
  {
    MITK_INFO << "Started sDMAS test on GPU";
    unsigned int* inputDim = new unsigned int[3];
    inputDim[0] = ELEMENTS;
    inputDim[1] = SAMPLES;
    inputDim[2] = 1;
    m_BeamformingFilter = mitk::BeamformingFilter::New(createConfig(true, inputDim, mitk::BeamformingSettings::BeamformingAlgorithm::sDMAS));

    test();
    delete[] inputDim;
  }

  void testBeamformingCPU_DMAS()
  {
    MITK_INFO << "Started DMAS test on CPU";
    unsigned int* inputDim = new unsigned int[3];
    inputDim[0] = ELEMENTS;
    inputDim[1] = SAMPLES;
    inputDim[2] = 1;
    m_BeamformingFilter = mitk::BeamformingFilter::New(createConfig(false, inputDim, mitk::BeamformingSettings::BeamformingAlgorithm::DMAS));

    test();
    delete[] inputDim;
  }

  void testBeamformingGPU_DMAS()
  {
    MITK_INFO << "Started DMAS test on GPU";
    unsigned int* inputDim = new unsigned int[3];
    inputDim[0] = ELEMENTS;
    inputDim[1] = SAMPLES;
    inputDim[2] = 1;
    m_BeamformingFilter = mitk::BeamformingFilter::New(createConfig(true, inputDim, mitk::BeamformingSettings::BeamformingAlgorithm::DMAS));

    test();
    delete[] inputDim;
  }
};

MITK_TEST_SUITE_REGISTRATION(mitkBeamformingFilter)
<|endoftext|>