<commit_before>/*

Copyright (c) 2007, Arvid Norberg
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 author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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

*/

#ifndef TORRENT_UPNP_HPP
#define TORRENT_UPNP_HPP

#include "libtorrent/socket.hpp"
#include "libtorrent/http_connection.hpp"
#include "libtorrent/connection_queue.hpp"

#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <set>

#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
#include <fstream>
#endif

namespace libtorrent
{

// int: external tcp port
// int: external udp port
// std::string: error message
typedef boost::function<void(int, int, std::string const&)> portmap_callback_t;

class upnp : boost::noncopyable
{
public:
	upnp(io_service& ios, connection_queue& cc
		, address const& listen_interface, std::string const& user_agent
		, portmap_callback_t const& cb);
	~upnp();

	void rebind(address const& listen_interface);

	// maps the ports, if a port is set to 0
	// it will not be mapped
	void set_mappings(int tcp, int udp);

	void close();

private:

	static address_v4 upnp_multicast_address;
	static udp::endpoint upnp_multicast_endpoint;

	enum { num_mappings = 2 };
	enum { default_lease_time = 3600 };

	void update_mapping(int i, int port);
	void resend_request(asio::error_code const& e);
	void on_reply(asio::error_code const& e
		, std::size_t bytes_transferred);
	void discover_device();

	struct rootdevice;

	void on_upnp_xml(asio::error_code const& e
		, libtorrent::http_parser const& p, rootdevice& d);
	void on_upnp_map_response(asio::error_code const& e
		, libtorrent::http_parser const& p, rootdevice& d
		, int mapping);
	void on_upnp_unmap_response(asio::error_code const& e
		, libtorrent::http_parser const& p, rootdevice& d
		, int mapping);
	void on_expire(asio::error_code const& e);

	void post(rootdevice& d, std::stringstream const& s
		, std::string const& soap_action);
	void map_port(rootdevice& d, int i);
	void unmap_port(rootdevice& d, int i);

	struct mapping_t
	{
		mapping_t()
			: need_update(false)
			, local_port(0)
			, external_port(0)
			, protocol(1)
		{}

		// the time the port mapping will expire
		ptime expires;

		bool need_update;

		// the local port for this mapping. If this is set
		// to 0, the mapping is not in use
		int local_port;

		// the external (on the NAT router) port
		// for the mapping. This is the port we
		// should announce to others
		int external_port;

		// 1 = udp, 0 = tcp
		int protocol;
	};

	struct rootdevice
	{
		rootdevice(): lease_duration(default_lease_time)
			, supports_specific_external(true)
			, service_namespace(0)
		{
			mapping[0].protocol = 0;
			mapping[1].protocol = 1;
		}

		// the interface url, through which the list of
		// supported interfaces are fetched
		std::string url;

		// the url to the WANIP or WANPPP interface
		std::string control_url;
		// either the WANIP namespace or the WANPPP namespace
		char const* service_namespace;

		mapping_t mapping[num_mappings];

		std::string hostname;
		int port;
		std::string path;

		int lease_duration;
		// true if the device supports specifying a
		// specific external port, false if it doesn't
		bool supports_specific_external;

		boost::shared_ptr<http_connection> upnp_connection;

		void close() const { if (upnp_connection) upnp_connection->close(); }

		bool operator<(rootdevice const& rhs) const
		{ return url < rhs.url; }
	};

	int m_udp_local_port;
	int m_tcp_local_port;

	std::string const& m_user_agent;

	// the set of devices we've found
	std::set<rootdevice> m_devices;

	portmap_callback_t m_callback;

	// current retry count
	int m_retry_count;

	// used to receive responses in
	char m_receive_buffer[1024];

	// the endpoint we received the message from
	udp::endpoint m_remote;

	// the local address we're listening on
	address_v4 m_local_ip;

	// the udp socket used to send and receive
	// multicast messages on the network
	datagram_socket m_socket;

	// used to resend udp packets in case
	// they time out
	deadline_timer m_broadcast_timer;

	// timer used to refresh mappings
	deadline_timer m_refresh_timer;

	asio::strand m_strand;

	bool m_disabled;
	bool m_closing;

	connection_queue& m_cc;

#ifdef TORRENT_UPNP_LOGGING
	std::ofstream m_log;
#endif
};

}

#endif

<commit_msg>fixed warnings in previous check in<commit_after>/*

Copyright (c) 2007, Arvid Norberg
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 author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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

*/

#ifndef TORRENT_UPNP_HPP
#define TORRENT_UPNP_HPP

#include "libtorrent/socket.hpp"
#include "libtorrent/http_connection.hpp"
#include "libtorrent/connection_queue.hpp"

#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <set>

#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
#include <fstream>
#endif

namespace libtorrent
{

// int: external tcp port
// int: external udp port
// std::string: error message
typedef boost::function<void(int, int, std::string const&)> portmap_callback_t;

class upnp : boost::noncopyable
{
public:
	upnp(io_service& ios, connection_queue& cc
		, address const& listen_interface, std::string const& user_agent
		, portmap_callback_t const& cb);
	~upnp();

	void rebind(address const& listen_interface);

	// maps the ports, if a port is set to 0
	// it will not be mapped
	void set_mappings(int tcp, int udp);

	void close();

private:

	static address_v4 upnp_multicast_address;
	static udp::endpoint upnp_multicast_endpoint;

	enum { num_mappings = 2 };
	enum { default_lease_time = 3600 };

	void update_mapping(int i, int port);
	void resend_request(asio::error_code const& e);
	void on_reply(asio::error_code const& e
		, std::size_t bytes_transferred);
	void discover_device();

	struct rootdevice;

	void on_upnp_xml(asio::error_code const& e
		, libtorrent::http_parser const& p, rootdevice& d);
	void on_upnp_map_response(asio::error_code const& e
		, libtorrent::http_parser const& p, rootdevice& d
		, int mapping);
	void on_upnp_unmap_response(asio::error_code const& e
		, libtorrent::http_parser const& p, rootdevice& d
		, int mapping);
	void on_expire(asio::error_code const& e);

	void post(rootdevice& d, std::stringstream const& s
		, std::string const& soap_action);
	void map_port(rootdevice& d, int i);
	void unmap_port(rootdevice& d, int i);

	struct mapping_t
	{
		mapping_t()
			: need_update(false)
			, local_port(0)
			, external_port(0)
			, protocol(1)
		{}

		// the time the port mapping will expire
		ptime expires;

		bool need_update;

		// the local port for this mapping. If this is set
		// to 0, the mapping is not in use
		int local_port;

		// the external (on the NAT router) port
		// for the mapping. This is the port we
		// should announce to others
		int external_port;

		// 1 = udp, 0 = tcp
		int protocol;
	};

	struct rootdevice
	{
		rootdevice(): service_namespace(0)
			, lease_duration(default_lease_time)
			, supports_specific_external(true)
		{
			mapping[0].protocol = 0;
			mapping[1].protocol = 1;
		}

		// the interface url, through which the list of
		// supported interfaces are fetched
		std::string url;

		// the url to the WANIP or WANPPP interface
		std::string control_url;
		// either the WANIP namespace or the WANPPP namespace
		char const* service_namespace;

		mapping_t mapping[num_mappings];

		std::string hostname;
		int port;
		std::string path;

		int lease_duration;
		// true if the device supports specifying a
		// specific external port, false if it doesn't
		bool supports_specific_external;

		boost::shared_ptr<http_connection> upnp_connection;

		void close() const { if (upnp_connection) upnp_connection->close(); }

		bool operator<(rootdevice const& rhs) const
		{ return url < rhs.url; }
	};

	int m_udp_local_port;
	int m_tcp_local_port;

	std::string const& m_user_agent;

	// the set of devices we've found
	std::set<rootdevice> m_devices;

	portmap_callback_t m_callback;

	// current retry count
	int m_retry_count;

	// used to receive responses in
	char m_receive_buffer[1024];

	// the endpoint we received the message from
	udp::endpoint m_remote;

	// the local address we're listening on
	address_v4 m_local_ip;

	// the udp socket used to send and receive
	// multicast messages on the network
	datagram_socket m_socket;

	// used to resend udp packets in case
	// they time out
	deadline_timer m_broadcast_timer;

	// timer used to refresh mappings
	deadline_timer m_refresh_timer;

	asio::strand m_strand;

	bool m_disabled;
	bool m_closing;

	connection_queue& m_cc;

#ifdef TORRENT_UPNP_LOGGING
	std::ofstream m_log;
#endif
};

}

#endif

<|endoftext|>


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

#pragma hdrstop

#define _SVSTDARR_STRINGSDTOR

#ifndef _TOOLS_RESID_HXX
#include <tools/resid.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFXSLSTITM_HXX
#include <svtools/slstitm.hxx>
#endif

#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx>                   // fuer Undo-Ids
#endif
#ifndef _SWDTFLVR_HXX
#include <swdtflvr.hxx>
#endif

#ifndef _WRTSH_HRC
#include <wrtsh.hrc>
#endif
#include <sfx2/sfx.hrc>

// Undo beendet alle Modi. Falls eine Selektion durch das Undo entstanden
// ist, muss die fuer die weiteren Aktionen beruecksichtigt werden.

void SwWrtShell::Do( DoType eDoType, USHORT nCnt )
{
    // #105332# save current state of DoesUndo()
    sal_Bool bSaveDoesUndo = DoesUndo();

    StartAllAction();
    switch( eDoType )
    {
        case UNDO:
            DoUndo(sal_False); // #i21739#
            // Modi zuruecksetzen
            EnterStdMode();
            SwEditShell::Undo(0, nCnt );
            break;
        case REDO:
            DoUndo(sal_False); // #i21739#
            // Modi zuruecksetzen
            EnterStdMode();
            SwEditShell::Redo( nCnt );
            break;
        case REPEAT:
            // #i21739# do not touch undo flag here !!!
            SwEditShell::Repeat( nCnt );
            break;
    }
    EndAllAction();
    // #105332# restore undo state
    DoUndo(bSaveDoesUndo);

    BOOL bCreateXSelection = FALSE;
    const FASTBOOL bFrmSelected = IsFrmSelected() || IsObjSelected();
    if ( IsSelection() )
    {
        if ( bFrmSelected )
            UnSelectFrm();

        // Funktionspointer fuer das Aufheben der Selektion setzen
        // bei Cursor setzen
        fnKillSel = &SwWrtShell::ResetSelect;
        fnSetCrsr = &SwWrtShell::SetCrsrKillSel;
        bCreateXSelection = TRUE;
    }
    else if ( bFrmSelected )
    {
        EnterSelFrmMode();
        bCreateXSelection = TRUE;
    }
    else if( (CNT_GRF | CNT_OLE ) & GetCntType() )
    {
        SelectObj( GetCharRect().Pos() );
        EnterSelFrmMode();
        bCreateXSelection = TRUE;
    }

    if( bCreateXSelection )
        SwTransferable::CreateSelection( *this );

    // Bug 32918: nach loeschen der Numerierung bleibt die Obj. Leiste stehen
    //          Warum wird hier nicht immer ein CallChgLink gerufen?
    CallChgLnk();
}

String SwWrtShell::GetDoString( DoType eDoType ) const
{
    String aStr, aUndoStr;
    USHORT nResStr;
    switch( eDoType )
    {
    case UNDO:
        nResStr = STR_UNDO;
        aUndoStr = GetUndoIdsStr();
        break;
    case REDO:
        nResStr = STR_REDO;
        aUndoStr = GetRedoIdsStr();
        break;
    }

    aStr.Insert( String(ResId( nResStr, SFX_APP()->GetSfxResManager())), 0 );
    aStr += aUndoStr;

    return aStr;
}

USHORT SwWrtShell::GetDoStrings( DoType eDoType, SfxStringListItem& rStrs ) const
{
    SwUndoIds aIds;
    switch( eDoType )
    {
    case UNDO:
        GetUndoIds( 0, &aIds );
        break;
    case REDO:
        GetRedoIds( 0, &aIds );
        break;
    }

    String sList;
    for( USHORT n = 0, nEnd = aIds.Count(); n < nEnd; ++n )
    {
        const SwUndoIdAndName& rIdNm = *aIds[ n ];
        if( rIdNm.GetUndoStr() )
            sList += *rIdNm.GetUndoStr();
        else
        {
            ASSERT( !this, "no Undo/Redo Test set" );
        }
        sList += '\n';
    }
    rStrs.SetString( sList );
    return aIds.Count();
}

String SwWrtShell::GetRepeatString() const
{
    String aStr;
    String aUndoStr = GetRepeatIdsStr();

    if (aUndoStr.Len() > 0)
    {
        aStr.Insert( ResId( STR_REPEAT, SFX_APP()->GetSfxResManager()), 0 );
        aStr += aUndoStr;
    }

    return aStr;
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.9.476); FILE MERGED 2006/09/01 17:53:37 kaib 1.9.476.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: wrtundo.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 23:40:57 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#define _SVSTDARR_STRINGSDTOR

#ifndef _TOOLS_RESID_HXX
#include <tools/resid.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFXSLSTITM_HXX
#include <svtools/slstitm.hxx>
#endif

#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx>                   // fuer Undo-Ids
#endif
#ifndef _SWDTFLVR_HXX
#include <swdtflvr.hxx>
#endif

#ifndef _WRTSH_HRC
#include <wrtsh.hrc>
#endif
#include <sfx2/sfx.hrc>

// Undo beendet alle Modi. Falls eine Selektion durch das Undo entstanden
// ist, muss die fuer die weiteren Aktionen beruecksichtigt werden.

void SwWrtShell::Do( DoType eDoType, USHORT nCnt )
{
    // #105332# save current state of DoesUndo()
    sal_Bool bSaveDoesUndo = DoesUndo();

    StartAllAction();
    switch( eDoType )
    {
        case UNDO:
            DoUndo(sal_False); // #i21739#
            // Modi zuruecksetzen
            EnterStdMode();
            SwEditShell::Undo(0, nCnt );
            break;
        case REDO:
            DoUndo(sal_False); // #i21739#
            // Modi zuruecksetzen
            EnterStdMode();
            SwEditShell::Redo( nCnt );
            break;
        case REPEAT:
            // #i21739# do not touch undo flag here !!!
            SwEditShell::Repeat( nCnt );
            break;
    }
    EndAllAction();
    // #105332# restore undo state
    DoUndo(bSaveDoesUndo);

    BOOL bCreateXSelection = FALSE;
    const FASTBOOL bFrmSelected = IsFrmSelected() || IsObjSelected();
    if ( IsSelection() )
    {
        if ( bFrmSelected )
            UnSelectFrm();

        // Funktionspointer fuer das Aufheben der Selektion setzen
        // bei Cursor setzen
        fnKillSel = &SwWrtShell::ResetSelect;
        fnSetCrsr = &SwWrtShell::SetCrsrKillSel;
        bCreateXSelection = TRUE;
    }
    else if ( bFrmSelected )
    {
        EnterSelFrmMode();
        bCreateXSelection = TRUE;
    }
    else if( (CNT_GRF | CNT_OLE ) & GetCntType() )
    {
        SelectObj( GetCharRect().Pos() );
        EnterSelFrmMode();
        bCreateXSelection = TRUE;
    }

    if( bCreateXSelection )
        SwTransferable::CreateSelection( *this );

    // Bug 32918: nach loeschen der Numerierung bleibt die Obj. Leiste stehen
    //          Warum wird hier nicht immer ein CallChgLink gerufen?
    CallChgLnk();
}

String SwWrtShell::GetDoString( DoType eDoType ) const
{
    String aStr, aUndoStr;
    USHORT nResStr;
    switch( eDoType )
    {
    case UNDO:
        nResStr = STR_UNDO;
        aUndoStr = GetUndoIdsStr();
        break;
    case REDO:
        nResStr = STR_REDO;
        aUndoStr = GetRedoIdsStr();
        break;
    }

    aStr.Insert( String(ResId( nResStr, SFX_APP()->GetSfxResManager())), 0 );
    aStr += aUndoStr;

    return aStr;
}

USHORT SwWrtShell::GetDoStrings( DoType eDoType, SfxStringListItem& rStrs ) const
{
    SwUndoIds aIds;
    switch( eDoType )
    {
    case UNDO:
        GetUndoIds( 0, &aIds );
        break;
    case REDO:
        GetRedoIds( 0, &aIds );
        break;
    }

    String sList;
    for( USHORT n = 0, nEnd = aIds.Count(); n < nEnd; ++n )
    {
        const SwUndoIdAndName& rIdNm = *aIds[ n ];
        if( rIdNm.GetUndoStr() )
            sList += *rIdNm.GetUndoStr();
        else
        {
            ASSERT( !this, "no Undo/Redo Test set" );
        }
        sList += '\n';
    }
    rStrs.SetString( sList );
    return aIds.Count();
}

String SwWrtShell::GetRepeatString() const
{
    String aStr;
    String aUndoStr = GetRepeatIdsStr();

    if (aUndoStr.Len() > 0)
    {
        aStr.Insert( ResId( STR_REPEAT, SFX_APP()->GetSfxResManager()), 0 );
        aStr += aUndoStr;
    }

    return aStr;
}

<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (c) 2019, OpenROAD
// 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 holder nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include "scriptWidget.h"
#include "spdlog/sinks/base_sink.h"
#include "spdlog/formatter.h"

#include <unistd.h>
#include <errno.h>

#include <QCoreApplication>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QLineEdit>
#include <QTimer>
#include <QVBoxLayout>

#include "openroad/OpenRoad.hh"
#include "openroad/Logger.h"

namespace gui {

ScriptWidget::ScriptWidget(QWidget* parent)
    : QDockWidget("Scripting", parent),
      input_(new QLineEdit),
      output_(new QTextEdit),
      pauser_(new QPushButton("Idle")),
      historyPosition_(0)
{
  setObjectName("scripting");  // for settings

  output_->setReadOnly(true);
  pauser_->setEnabled(false);

  QHBoxLayout* inner_layout = new QHBoxLayout;
  inner_layout->addWidget(pauser_);
  inner_layout->addWidget(input_, /* stretch */ 1);

  QVBoxLayout* layout = new QVBoxLayout;
  layout->addWidget(output_, /* stretch */ 1);
  layout->addLayout(inner_layout);

  QWidget* container = new QWidget;
  container->setLayout(layout);

  QTimer::singleShot(200, this, &ScriptWidget::setupTcl);

  connect(input_, SIGNAL(returnPressed()), this, SLOT(executeCommand()));
  connect(pauser_, SIGNAL(pressed()), this, SLOT(pauserClicked()));

  setWidget(container);
}

int channelClose(ClientData instanceData, Tcl_Interp* interp)
{
  // This channel should never be closed
  return EINVAL;
}

int ScriptWidget::channelOutput(ClientData instanceData,
                                const char* buf,
                                int toWrite,
                                int* errorCodePtr)
{
  // Buffer up the output
  ScriptWidget* widget = (ScriptWidget*) instanceData;
  widget->outputBuffer_.append(QString::fromLatin1(buf, toWrite).trimmed());
  return toWrite;
}

void channelWatch(ClientData instanceData, int mask)
{
  // watch is not supported inside OpenROAD GUI
}

Tcl_ChannelType ScriptWidget::stdoutChannelType = {
    // Tcl stupidly defines this a non-cost char*
    ((char*) "stdout_channel"),  /* typeName */
    TCL_CHANNEL_VERSION_2,       /* version */
    channelClose,                /* closeProc */
    nullptr,                     /* inputProc */
    ScriptWidget::channelOutput, /* outputProc */
    nullptr,                     /* seekProc */
    nullptr,                     /* setOptionProc */
    nullptr,                     /* getOptionProc */
    channelWatch,                /* watchProc */
    nullptr,                     /* getHandleProc */
    nullptr,                     /* close2Proc */
    nullptr,                     /* blockModeProc */
    nullptr,                     /* flushProc */
    nullptr,                     /* handlerProc */
    nullptr,                     /* wideSeekProc */
    nullptr,                     /* threadActionProc */
    nullptr                      /* truncateProc */
};

void ScriptWidget::setupTcl()
{
  interp_ = Tcl_CreateInterp();

  Tcl_Channel stdoutChannel = Tcl_CreateChannel(
      &stdoutChannelType, "stdout", (ClientData) this, TCL_WRITABLE);
  if (stdoutChannel) {
    Tcl_SetChannelOption(nullptr, stdoutChannel, "-translation", "lf");
    Tcl_SetChannelOption(nullptr, stdoutChannel, "-buffering", "none");
    Tcl_RegisterChannel(interp_, stdoutChannel);  // per man page: some tcl bug
    Tcl_SetStdChannel(stdoutChannel, TCL_STDOUT);
  }

  pauser_->setText("Running");
  pauser_->setStyleSheet("background-color: red");
  ord::tclAppInit(interp_);
  pauser_->setText("Idle");
  pauser_->setStyleSheet("");

  // TODO: tclAppInit should return the status which we could
  // pass to updateOutput
  updateOutput(TCL_OK, /* command_finished */ true);
}

void ScriptWidget::executeCommand()
{
  pauser_->setText("Running");
  pauser_->setStyleSheet("background-color: red");
  QString command = input_->text();
  input_->clear();

  // Show the command that we executed
  output_->setTextColor(Qt::black);
  output_->append("> " + command);

  // Make changes visible while command runs
  QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);

  int return_code = Tcl_Eval(interp_, command.toLatin1().data());

  // Show its output
  updateOutput(return_code, /* command_finished */ true);

  // Update history; ignore repeated commands and keep last 100
  const int history_limit = 100;
  if (history_.empty() || command != history_.last()) {
    if (history_.size() == history_limit) {
      history_.pop_front();
    }

    history_.append(command);
  }
  historyPosition_ = history_.size();
  pauser_->setText("Idle");
  pauser_->setStyleSheet("");
  emit commandExecuted();
}

void ScriptWidget::updateOutput(int return_code, bool command_finished)
{
  // Show whatever we captured from the output channel in grey
  output_->setTextColor(QColor(0x30, 0x30, 0x30));
  for (auto& out : outputBuffer_) {
    if (!out.isEmpty()) {
      output_->append(out);
    }
  }
  outputBuffer_.clear();

  if (command_finished) {
    // Show the return value color-coded by ok/err.
    const char* result = Tcl_GetString(Tcl_GetObjResult(interp_));
    if (result[0] != '\0') {
      output_->setTextColor((return_code == TCL_OK) ? Qt::blue : Qt::red);
      output_->append(result);
    }
  }
}

ScriptWidget::~ScriptWidget()
{
  // TODO: I am being lazy and not cleaning up the tcl interpreter.
  // We are likely exiting anyways
}

void ScriptWidget::keyPressEvent(QKeyEvent* e)
{
  // Handle up/down through history
  int key = e->key();
  if (key == Qt::Key_Down) {
    if (historyPosition_ < history_.size() - 1) {
      ++historyPosition_;
      input_->setText(history_[historyPosition_]);
    } else if (historyPosition_ == history_.size() - 1) {
      ++historyPosition_;
      input_->clear();
    }
    return;
  } else if (key == Qt::Key_Up) {
    if (historyPosition_ > 0) {
      --historyPosition_;
      input_->setText(history_[historyPosition_]);
    }
    return;
  }
  QDockWidget::keyPressEvent(e);
}

void ScriptWidget::readSettings(QSettings* settings)
{
  settings->beginGroup("scripting");
  history_ = settings->value("history").toStringList();
  historyPosition_ = history_.size();
  settings->endGroup();
}

void ScriptWidget::writeSettings(QSettings* settings)
{
  settings->beginGroup("scripting");
  settings->setValue("history", history_);
  settings->endGroup();
}

void ScriptWidget::pause()
{
  QString prior_text = pauser_->text();
  bool prior_enable = pauser_->isEnabled();
  QString prior_style = pauser_->styleSheet();
  pauser_->setText("Continue");
  pauser_->setStyleSheet("background-color: yellow");
  pauser_->setEnabled(true);
  paused_ = true;

  // Keep processing events until the user continues
  while (paused_) {
    QCoreApplication::processEvents();
  }

  pauser_->setText(prior_text);
  pauser_->setStyleSheet(prior_style);
  pauser_->setEnabled(prior_enable);

  // Make changes visible while command runs
  QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}

void ScriptWidget::pauserClicked()
{
  paused_ = false;
}

// This class is an spdlog sink that writes the messages into the output
// area.
template<typename Mutex>
class ScriptWidget::GuiSink : public spdlog::sinks::base_sink<Mutex>
{
public:
  GuiSink(ScriptWidget* widget)
    : widget_(widget)
  {
  }

protected:
  void sink_it_(const spdlog::details::log_msg& msg) override
  {
    // Convert the msg into a formatted string
    spdlog::memory_buf_t formatted;
    this->formatter_->format(msg, formatted);
    // -1 is to drop the final '\n' character
    auto str = QString::fromLatin1(formatted.data(), (int) formatted.size() - 1);
    widget_->outputBuffer_.append(str);

    // Make it appear now
    widget_->updateOutput(0, /* command_finished */ false);
    widget_->output_->update();
    QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
  }

  void flush_() override
  {
  }

private:
  ScriptWidget* widget_;
};

using GuiSinkMT = ScriptWidget::GuiSink<std::mutex>;

void ScriptWidget::setLogger(ord::Logger* logger)
{
  logger->addSink(std::make_shared<GuiSinkMT>(this));
}

}  // namespace gui
<commit_msg>fix ubuntu20/gcc8 compile error<commit_after>///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (c) 2019, OpenROAD
// 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 holder nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include "scriptWidget.h"
#include "spdlog/sinks/base_sink.h"
#include "spdlog/formatter.h"

#include <unistd.h>
#include <errno.h>

#include <QCoreApplication>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QLineEdit>
#include <QTimer>
#include <QVBoxLayout>

#include "openroad/OpenRoad.hh"
#include "openroad/Logger.h"

namespace gui {

ScriptWidget::ScriptWidget(QWidget* parent)
    : QDockWidget("Scripting", parent),
      input_(new QLineEdit),
      output_(new QTextEdit),
      pauser_(new QPushButton("Idle")),
      historyPosition_(0)
{
  setObjectName("scripting");  // for settings

  output_->setReadOnly(true);
  pauser_->setEnabled(false);

  QHBoxLayout* inner_layout = new QHBoxLayout;
  inner_layout->addWidget(pauser_);
  inner_layout->addWidget(input_, /* stretch */ 1);

  QVBoxLayout* layout = new QVBoxLayout;
  layout->addWidget(output_, /* stretch */ 1);
  layout->addLayout(inner_layout);

  QWidget* container = new QWidget;
  container->setLayout(layout);

  QTimer::singleShot(200, this, &ScriptWidget::setupTcl);

  connect(input_, SIGNAL(returnPressed()), this, SLOT(executeCommand()));
  connect(pauser_, SIGNAL(pressed()), this, SLOT(pauserClicked()));

  setWidget(container);
}

int channelClose(ClientData instanceData, Tcl_Interp* interp)
{
  // This channel should never be closed
  return EINVAL;
}

int ScriptWidget::channelOutput(ClientData instanceData,
                                const char* buf,
                                int toWrite,
                                int* errorCodePtr)
{
  // Buffer up the output
  ScriptWidget* widget = (ScriptWidget*) instanceData;
  widget->outputBuffer_.append(QString::fromLatin1(buf, toWrite).trimmed());
  return toWrite;
}

void channelWatch(ClientData instanceData, int mask)
{
  // watch is not supported inside OpenROAD GUI
}

Tcl_ChannelType ScriptWidget::stdoutChannelType = {
    // Tcl stupidly defines this a non-cost char*
    ((char*) "stdout_channel"),  /* typeName */
    TCL_CHANNEL_VERSION_2,       /* version */
    channelClose,                /* closeProc */
    nullptr,                     /* inputProc */
    ScriptWidget::channelOutput, /* outputProc */
    nullptr,                     /* seekProc */
    nullptr,                     /* setOptionProc */
    nullptr,                     /* getOptionProc */
    channelWatch,                /* watchProc */
    nullptr,                     /* getHandleProc */
    nullptr,                     /* close2Proc */
    nullptr,                     /* blockModeProc */
    nullptr,                     /* flushProc */
    nullptr,                     /* handlerProc */
    nullptr,                     /* wideSeekProc */
    nullptr,                     /* threadActionProc */
    nullptr                      /* truncateProc */
};

void ScriptWidget::setupTcl()
{
  interp_ = Tcl_CreateInterp();

  Tcl_Channel stdoutChannel = Tcl_CreateChannel(
      &stdoutChannelType, "stdout", (ClientData) this, TCL_WRITABLE);
  if (stdoutChannel) {
    Tcl_SetChannelOption(nullptr, stdoutChannel, "-translation", "lf");
    Tcl_SetChannelOption(nullptr, stdoutChannel, "-buffering", "none");
    Tcl_RegisterChannel(interp_, stdoutChannel);  // per man page: some tcl bug
    Tcl_SetStdChannel(stdoutChannel, TCL_STDOUT);
  }

  pauser_->setText("Running");
  pauser_->setStyleSheet("background-color: red");
  ord::tclAppInit(interp_);
  pauser_->setText("Idle");
  pauser_->setStyleSheet("");

  // TODO: tclAppInit should return the status which we could
  // pass to updateOutput
  updateOutput(TCL_OK, /* command_finished */ true);
}

void ScriptWidget::executeCommand()
{
  pauser_->setText("Running");
  pauser_->setStyleSheet("background-color: red");
  QString command = input_->text();
  input_->clear();

  // Show the command that we executed
  output_->setTextColor(Qt::black);
  output_->append("> " + command);

  // Make changes visible while command runs
  QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);

  int return_code = Tcl_Eval(interp_, command.toLatin1().data());

  // Show its output
  updateOutput(return_code, /* command_finished */ true);

  // Update history; ignore repeated commands and keep last 100
  const int history_limit = 100;
  if (history_.empty() || command != history_.last()) {
    if (history_.size() == history_limit) {
      history_.pop_front();
    }

    history_.append(command);
  }
  historyPosition_ = history_.size();
  pauser_->setText("Idle");
  pauser_->setStyleSheet("");
  emit commandExecuted();
}

void ScriptWidget::updateOutput(int return_code, bool command_finished)
{
  // Show whatever we captured from the output channel in grey
  output_->setTextColor(QColor(0x30, 0x30, 0x30));
  for (auto& out : outputBuffer_) {
    if (!out.isEmpty()) {
      output_->append(out);
    }
  }
  outputBuffer_.clear();

  if (command_finished) {
    // Show the return value color-coded by ok/err.
    const char* result = Tcl_GetString(Tcl_GetObjResult(interp_));
    if (result[0] != '\0') {
      output_->setTextColor((return_code == TCL_OK) ? Qt::blue : Qt::red);
      output_->append(result);
    }
  }
}

ScriptWidget::~ScriptWidget()
{
  // TODO: I am being lazy and not cleaning up the tcl interpreter.
  // We are likely exiting anyways
}

void ScriptWidget::keyPressEvent(QKeyEvent* e)
{
  // Handle up/down through history
  int key = e->key();
  if (key == Qt::Key_Down) {
    if (historyPosition_ < history_.size() - 1) {
      ++historyPosition_;
      input_->setText(history_[historyPosition_]);
    } else if (historyPosition_ == history_.size() - 1) {
      ++historyPosition_;
      input_->clear();
    }
    return;
  } else if (key == Qt::Key_Up) {
    if (historyPosition_ > 0) {
      --historyPosition_;
      input_->setText(history_[historyPosition_]);
    }
    return;
  }
  QDockWidget::keyPressEvent(e);
}

void ScriptWidget::readSettings(QSettings* settings)
{
  settings->beginGroup("scripting");
  history_ = settings->value("history").toStringList();
  historyPosition_ = history_.size();
  settings->endGroup();
}

void ScriptWidget::writeSettings(QSettings* settings)
{
  settings->beginGroup("scripting");
  settings->setValue("history", history_);
  settings->endGroup();
}

void ScriptWidget::pause()
{
  QString prior_text = pauser_->text();
  bool prior_enable = pauser_->isEnabled();
  QString prior_style = pauser_->styleSheet();
  pauser_->setText("Continue");
  pauser_->setStyleSheet("background-color: yellow");
  pauser_->setEnabled(true);
  paused_ = true;

  // Keep processing events until the user continues
  while (paused_) {
    QCoreApplication::processEvents();
  }

  pauser_->setText(prior_text);
  pauser_->setStyleSheet(prior_style);
  pauser_->setEnabled(prior_enable);

  // Make changes visible while command runs
  QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}

void ScriptWidget::pauserClicked()
{
  paused_ = false;
}

// This class is an spdlog sink that writes the messages into the output
// area.
template<typename Mutex>
class ScriptWidget::GuiSink : public spdlog::sinks::base_sink<Mutex>
{
public:
  GuiSink(ScriptWidget* widget)
    : widget_(widget)
  {
  }

protected:
  void sink_it_(const spdlog::details::log_msg& msg) override
  {
    // Convert the msg into a formatted string
    spdlog::memory_buf_t formatted;
    this->formatter_->format(msg, formatted);
    // -1 is to drop the final '\n' character
    auto str = QString::fromLatin1(formatted.data(), (int) formatted.size() - 1);
    widget_->outputBuffer_.append(str);

    // Make it appear now
    widget_->updateOutput(0, /* command_finished */ false);
    widget_->output_->update();
    QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
  }

  void flush_() override
  {
  }

private:
  ScriptWidget* widget_;
};

void ScriptWidget::setLogger(ord::Logger* logger)
{
  logger->addSink(std::make_shared<GuiSink<std::mutex>>(this));
}

}  // namespace gui
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <OpenNI.h>
#include "onimeshfunctions.h"

namespace onimesh
{
	const int FRAME_DATA_MOD = 100;

	/// <summary>
	/// Creates a name for an output file
	/// </summary>
	std::string getOutputFileName(const char* outputDirectory, const char* inputFile, const char* fileExtension)
	{
		// If the path contains '/' characters
		if (std::string(inputFile).find_last_of('/') != std::string::npos)
			return std::string(outputDirectory + std::string(inputFile).substr(std::string(inputFile).find_last_of('/') + 1) + std::string(fileExtension));
		// If the path contains '\' characters
		else if(std::string(inputFile).find_last_of('\\') == std::string::npos)
			return std::string(outputDirectory + std::string(inputFile).substr(std::string(inputFile).find_last_of('\\') + 1) + std::string(fileExtension));

		// Otherwise the input file does not contain a path
		return std::string(std::string(outputDirectory) + std::string(inputFile) + std::string(fileExtension));
	}

	/// <summary>
	/// Reads oni input and exports data as excel docs
	/// </summary>
	void outputExcel(const int argc, const char** argv)
	{
		std::cout << "Start excel data output...\n";
		const char* outputDirectory = argv[1];
		char* inputFile;
		const int numberInputFiles = argc - 2;
		openni::Device device;
		openni::VideoStream ir;
		openni::VideoFrameRef irf;
		OniDepthPixel* pDepth;
		int frameHeight, frameWidth;
		long frameIndex, numberOfFrames;
		std::ofstream out;
		openni::OpenNI::initialize();

		// Output excel doc for each input file
		for (int w = 0; w < numberInputFiles; ++w)
		{
			inputFile = (char*)argv[w + 2];
			std::cout << "Working on file " << inputFile << "...\n";

			// Open the .oni file
			device.open(inputFile);
			ir.create(device, openni::SENSOR_DEPTH);

			// Device Check
			if (!device.isValid())
			{
				std::cerr << "\nError opening oni file.\n";
				exit(2);
			}

			// Verify the device is a file
			if (!device.isFile())
			{
				std::cerr << "\nThe device is not a file.\n";
				exit(3);
			}
			std::cout << "File open success...\n";

			// Set playback controls
			openni::PlaybackControl* pbc = device.getPlaybackControl();
			pbc->setSpeed(-1);
			pbc->setRepeatEnabled(false);

			// Open output file
			std::string outputFile = getOutputFileName(outputDirectory, inputFile, ".csv");
			out.open(outputFile);

			// Read all frames
			numberOfFrames = pbc->getNumberOfFrames(ir);
			std::cout << "Start reading frame data...\n";
			ir.start();
			while (true)
			{
				// Read a frame
				ir.readFrame(&irf);

				// Verify frame data is valid
				if (!irf.isValid())
				{
					std::cerr << "Error reading video stream frame\n";
					break;
				}

				// Gather frame data
				pDepth = (OniDepthPixel*)irf.getData();
				frameIndex = irf.getFrameIndex();

				// Skip unneeded frames
				if (frameIndex % FRAME_DATA_MOD == 0)
				{
					frameHeight = irf.getHeight();
					frameWidth = irf.getWidth();
					std::cout << "Processing " << frameWidth << "x" << frameHeight << " frame number " << frameIndex << "...\n";
					out << "FrameNumber=" << frameIndex << ",FrameWidth=" << frameWidth << ",FrameHeight=" << frameHeight << ",\n";
					for (int y = 0; y < frameHeight; ++y)  // All heights
					{
						for (int x = 0; x < frameWidth; ++x, ++pDepth)  // All witdths
						{
							out << *pDepth << ",";
						}
						out << "\n";
					}
					out << ",\n";
				}
				else
				{
					//std::cout << "Skipping frame " << frameIndex << "\n";
				}

				// Break if reading the last frame
				if (numberOfFrames == frameIndex)
				{
					std::cout << "Last frame has been read...\n";
					break;
				}
			}

			// Cleanup
			out.clear();
			out.close();
			ir.stop();
			ir.destroy();
			device.close();
		}

		// OpenNI cleanup
		openni::OpenNI::shutdown();
		std::cout << "Excel data output complete.\n";
	}

	/// <summary>
	/// Reads oni input and exports data as point clouds
	/// </summary>
	void outputPointCloud(const int argc, const char** argv)
	{

	}
}<commit_msg>Added better error messaging<commit_after>#include <iostream>
#include <fstream>
#include <OpenNI.h>
#include "onimeshfunctions.h"

namespace onimesh
{
	const int FRAME_DATA_MOD = 100;

	/// <summary>
	/// Creates a name for an output file
	/// </summary>
	std::string getOutputFileName(const char* outputDirectory, const char* inputFile, const char* fileExtension)
	{
		// If the path contains '/' characters
		if (std::string(inputFile).find_last_of('/') != std::string::npos)
			return std::string(outputDirectory + std::string(inputFile).substr(std::string(inputFile).find_last_of('/') + 1) + std::string(fileExtension));
		// If the path contains '\' characters
		else if(std::string(inputFile).find_last_of('\\') == std::string::npos)
			return std::string(outputDirectory + std::string(inputFile).substr(std::string(inputFile).find_last_of('\\') + 1) + std::string(fileExtension));

		// Otherwise the input file does not contain a path
		return std::string(std::string(outputDirectory) + std::string(inputFile) + std::string(fileExtension));
	}

	/// <summary>
	/// Reads oni input and exports data as excel docs
	/// </summary>
	void outputExcel(const int argc, const char** argv)
	{
		std::cout << "Start excel data output...\n";

        const char* outputDirectory = argv[1];
        char* inputFile;
		const int numberInputFiles = argc - 2;
		openni::Device device;
		openni::VideoStream ir;
		openni::VideoFrameRef irf;
		OniDepthPixel* pDepth;
		int frameHeight, frameWidth;
		long frameIndex, numberOfFrames;
		std::ofstream out;

        // Initialize openni
        openni::Status rc = openni::OpenNI::initialize();
        if (rc != openni::STATUS_OK)
        {
            printf("Initialize failed\n%s\n", openni::OpenNI::getExtendedError());
            exit(2);
        }

		// Output excel doc for each input file
		for (int w = 0; w < numberInputFiles; ++w)
		{
			inputFile = (char*)argv[w + 2];
			std::cout << "Working on file " << inputFile << "...\n";

			// Open the .oni file
			rc = device.open(inputFile);
            if (rc != openni::STATUS_OK)
            {
                printf("Couldn't open device\n%s\n", openni::OpenNI::getExtendedError());
                exit(3);
            }

            // Create the Video Stream
			rc = ir.create(device, openni::SENSOR_DEPTH);
            if (rc != openni::STATUS_OK)
            {
                printf("Couldn't create depth stream\n%s\n", openni::OpenNI::getExtendedError());
                exit(4);
            }

			// Device Check
			if (!device.isValid())
			{
				std::cerr << "\nThe device is not valid.\n";
				exit(5);
			}

			// Verify the device is a file
			if (!device.isFile())
			{
				std::cerr << "\nThe device is not a file.\n";
				exit(6);
			}
			std::cout << "File open success...\n";

			// Set playback controls
			openni::PlaybackControl* pbc = device.getPlaybackControl();
			pbc->setSpeed(-1);
			pbc->setRepeatEnabled(false);

			// Open output file
			std::string outputFile = getOutputFileName(outputDirectory, inputFile, ".csv");
			out.open(outputFile);

			// Read all frames
			numberOfFrames = pbc->getNumberOfFrames(ir);
			std::cout << "Start reading frame data...\n";
			rc = ir.start();
            if (rc != openni::STATUS_OK)
            {
                printf("Couldn't start the depth stream\n%s\n", openni::OpenNI::getExtendedError());
                exit(7);
            }

			while (true)
			{
				// Read a frame
				rc = ir.readFrame(&irf);
                if (rc != openni::STATUS_OK)
                {
                    printf("Read failed!\n%s\n", openni::OpenNI::getExtendedError());
                    continue;
                }

				// Verify frame data is valid
				if (!irf.isValid())
				{
					std::cerr << "Error reading video stream frame\n";
					break;
				}

				// Gather frame data
				pDepth = (OniDepthPixel*)irf.getData();
				frameIndex = irf.getFrameIndex();

				// Skip unneeded frames
				if (frameIndex % FRAME_DATA_MOD == 0)
				{
					frameHeight = irf.getHeight();
					frameWidth = irf.getWidth();
					std::cout << "Processing " << frameWidth << "x" << frameHeight << " frame number " << frameIndex << "...\n";
					out << "FrameNumber=" << frameIndex << ",FrameWidth=" << frameWidth << ",FrameHeight=" << frameHeight << ",\n";
					for (int y = 0; y < frameHeight; ++y)  // All heights
					{
						for (int x = 0; x < frameWidth; ++x, ++pDepth)  // All witdths
						{
							out << *pDepth << ",";
						}
						out << "\n";
					}
					out << ",\n";
				}
				else
				{
					//std::cout << "Skipping frame " << frameIndex << "\n";
				}

				// Break if reading the last frame
				if (numberOfFrames == frameIndex)
				{
					std::cout << "Last frame has been read...\n";
					break;
				}
			}

			// Cleanup
			out.clear();
			out.close();
			ir.stop();
			ir.destroy();
			device.close();
		}

		// OpenNI cleanup
		openni::OpenNI::shutdown();
		std::cout << "Excel data output complete.\n";
	}

	/// <summary>
	/// Reads oni input and exports data as point clouds
	/// </summary>
	void outputPointCloud(const int argc, const char** argv)
	{

	}
}<|endoftext|>


<commit_before>#include <iostream>
#include <set>
#include <queue>
#include <ontology/node.h>
#include <ontology/ontology.h>
#include <ontology/modinterface.h>

using namespace std;

int main()
{
  Ontology oComplete("interface.ont");

  ModInterface currentInterface;
  ModInterface testInterface;

  int ReqID = oComplete.getReqID();
  Node ReqNode = oComplete.getNode(ReqID);

  currentInterface.addModality(ReqNode);
  currentInterface.print();
  currentInterface.addModality(oComplete.getNode(18));
  currentInterface.print();
  currentInterface.addModality(oComplete.getNode(9));
  currentInterface.print();
  currentInterface.addModality(oComplete.getNode(0));
  currentInterface.print();

  testInterface.addModality(ReqNode);
  testInterface.print();
  testInterface.addModality(oComplete.getNode(18));
  testInterface.print();
  testInterface.addModality(oComplete.getNode(9));
  testInterface.print();
  testInterface.addModality(oComplete.getNode(0));
  testInterface.print();

  if (currentInterface.compare(testInterface)) cout << "True!!!\n";
  else cout << "False!!!\n";

  if (currentInterface == testInterface) cout << "True!!!\n";
  else cout << "False!!!\n";
}
<commit_msg>exe: Cleaned up test_interface.cpp and used std::cin instead of hard-coded path for ontology<commit_after>#include <iostream>
#include <set>
#include <queue>
#include <ontology/node.h>
#include <ontology/ontology.h>
#include <ontology/modinterface.h>

int main()
{
    Ontology ontology( std::cin );

    ModInterface current_interface;
    ModInterface test_interface;

    int requirements_node_id = ontology.getRequirementsNodeID();
    Node requirements_node = ontology.getNode( requirements_node_id );

    current_interface.addModality( requirements_node );
    current_interface.print();
    current_interface.addModality( ontology.getNode( 18 ));
    current_interface.print();
    current_interface.addModality( ontology.getNode( 9 ) );
    current_interface.print();
    current_interface.addModality( ontology.getNode( 0 ) );
    current_interface.print();

    test_interface.addModality( requirements_node );
    test_interface.print();
    test_interface.addModality( ontology.getNode( 18 ) );
    test_interface.print();
    test_interface.addModality( ontology.getNode( 9 ) );
    test_interface.print();
    test_interface.addModality( ontology.getNode( 0 ) );
    test_interface.print();

    if( current_interface.compare( test_interface ) )
    {
   	    std::cout << "True!!!" << std::endl;
    }
    else
    {
        std::cout << "False!!!" << std::endl;
    }

    if( current_interface == test_interface )
    {
        std::cout << "True!!!" << std::endl;
    }
    else
    {
        std::cout << "False!!!" << std::endl;
    }

    return 0;
}
<|endoftext|>


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

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

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

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _RESOURCEPROVIDER_HXX_
#include "resourceprovider.hxx"
#endif

#ifndef _TOOLS_RESMGR_HXX
#include <tools/resmgr.hxx>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif

#include <svtools/svtools.hrc>

//------------------------------------------------------------
// namespace directives
//------------------------------------------------------------

using rtl::OUString;
using namespace ::com::sun::star::ui::dialogs::ExtendedFilePickerElementIds;
using namespace ::com::sun::star::ui::dialogs::CommonFilePickerElementIds;

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

#define RES_NAME svt

// because the label of a listbox is
// a control itself (static text) we
// have defined a control id for this
// label which is the listbox control
// id + 100
#define LB_LABEL_OFFSET 100

#define FOLDERPICKER_TITLE            500
#define FOLDER_PICKER_DEF_DESCRIPTION 501

//------------------------------------------------------------
// we have to translate control ids to resource ids
//------------------------------------------------------------

struct _Entry
{
    sal_Int32 ctrlId;
    sal_Int16 resId;
};

_Entry CtrlIdToResIdTable[] = {
    { CHECKBOX_AUTOEXTENSION,                   STR_SVT_FILEPICKER_AUTO_EXTENSION },
    { CHECKBOX_PASSWORD,                        STR_SVT_FILEPICKER_PASSWORD },
    { CHECKBOX_FILTEROPTIONS,                   STR_SVT_FILEPICKER_FILTER_OPTIONS },
    { CHECKBOX_READONLY,                        STR_SVT_FILEPICKER_READONLY },
    { CHECKBOX_LINK,                            STR_SVT_FILEPICKER_INSERT_AS_LINK },
    { CHECKBOX_PREVIEW,                         STR_SVT_FILEPICKER_SHOW_PREVIEW },
    { PUSHBUTTON_PLAY,                          STR_SVT_FILEPICKER_PLAY },
    { LISTBOX_VERSION + LB_LABEL_OFFSET,        STR_SVT_FILEPICKER_VERSION },
    { LISTBOX_TEMPLATE + LB_LABEL_OFFSET,       STR_SVT_FILEPICKER_TEMPLATES },
    { LISTBOX_IMAGE_TEMPLATE + LB_LABEL_OFFSET, STR_SVT_FILEPICKER_IMAGE_TEMPLATE },
    { CHECKBOX_SELECTION,                       STR_SVT_FILEPICKER_SELECTION },
    { FOLDERPICKER_TITLE,                       STR_SVT_FOLDERPICKER_DEFAULT_TITLE },
    { FOLDER_PICKER_DEF_DESCRIPTION,            STR_SVT_FOLDERPICKER_DEFAULT_DESCRIPTION }
};

const sal_Int32 SIZE_TABLE = sizeof( CtrlIdToResIdTable ) / sizeof( _Entry );

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

sal_Int16 CtrlIdToResId( sal_Int32 aControlId )
{
    sal_Int16 aResId = -1;

    for ( sal_Int32 i = 0; i < SIZE_TABLE; i++ )
    {
        if ( CtrlIdToResIdTable[i].ctrlId == aControlId )
        {
            aResId = CtrlIdToResIdTable[i].resId;
            break;
        }
    }

    return aResId;
}

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

class CResourceProvider_Impl
{
public:

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

    CResourceProvider_Impl( )
    {
        m_ResMgr = CREATEVERSIONRESMGR( RES_NAME );
    }

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

    ~CResourceProvider_Impl( )
    {
        delete m_ResMgr;
    }

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

    OUString getResString( sal_Int16 aId )
    {
        String   aResString;
        OUString aResOUString;

        try
        {
            OSL_ASSERT( m_ResMgr );

            // translate the control id to a resource id
            sal_Int16 aResId = CtrlIdToResId( aId );

            if ( aResId > -1 )
            {
                aResString = String( ResId( aResId, m_ResMgr ) );
                aResOUString = OUString( aResString );
            }
        }
        catch(...)
        {
        }

        return aResOUString;
    }

public:
    ResMgr* m_ResMgr;
};

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

CResourceProvider::CResourceProvider( ) :
    m_pImpl( new CResourceProvider_Impl() )
{
}

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

CResourceProvider::~CResourceProvider( )
{
    delete m_pImpl;
}

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

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

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

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

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _RESOURCEPROVIDER_HXX_
#include "resourceprovider.hxx"
#endif

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _TOOLS_RESMGR_HXX
#include <tools/resmgr.hxx>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif

#include <svtools/svtools.hrc>

//------------------------------------------------------------
// namespace directives
//------------------------------------------------------------

using rtl::OUString;
using namespace ::com::sun::star::ui::dialogs::ExtendedFilePickerElementIds;
using namespace ::com::sun::star::ui::dialogs::CommonFilePickerElementIds;

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

#define RES_NAME svt

// because the label of a listbox is
// a control itself (static text) we
// have defined a control id for this
// label which is the listbox control
// id + 100
#define LB_LABEL_OFFSET 100

#define FOLDERPICKER_TITLE            500
#define FOLDER_PICKER_DEF_DESCRIPTION 501

//------------------------------------------------------------
// we have to translate control ids to resource ids
//------------------------------------------------------------

struct _Entry
{
    sal_Int32 ctrlId;
    sal_Int16 resId;
};

_Entry CtrlIdToResIdTable[] = {
    { CHECKBOX_AUTOEXTENSION,                   STR_SVT_FILEPICKER_AUTO_EXTENSION },
    { CHECKBOX_PASSWORD,                        STR_SVT_FILEPICKER_PASSWORD },
    { CHECKBOX_FILTEROPTIONS,                   STR_SVT_FILEPICKER_FILTER_OPTIONS },
    { CHECKBOX_READONLY,                        STR_SVT_FILEPICKER_READONLY },
    { CHECKBOX_LINK,                            STR_SVT_FILEPICKER_INSERT_AS_LINK },
    { CHECKBOX_PREVIEW,                         STR_SVT_FILEPICKER_SHOW_PREVIEW },
    { PUSHBUTTON_PLAY,                          STR_SVT_FILEPICKER_PLAY },
    { LISTBOX_VERSION + LB_LABEL_OFFSET,        STR_SVT_FILEPICKER_VERSION },
    { LISTBOX_TEMPLATE + LB_LABEL_OFFSET,       STR_SVT_FILEPICKER_TEMPLATES },
    { LISTBOX_IMAGE_TEMPLATE + LB_LABEL_OFFSET, STR_SVT_FILEPICKER_IMAGE_TEMPLATE },
    { CHECKBOX_SELECTION,                       STR_SVT_FILEPICKER_SELECTION },
    { FOLDERPICKER_TITLE,                       STR_SVT_FOLDERPICKER_DEFAULT_TITLE },
    { FOLDER_PICKER_DEF_DESCRIPTION,            STR_SVT_FOLDERPICKER_DEFAULT_DESCRIPTION }
};

const sal_Int32 SIZE_TABLE = sizeof( CtrlIdToResIdTable ) / sizeof( _Entry );

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

sal_Int16 CtrlIdToResId( sal_Int32 aControlId )
{
    sal_Int16 aResId = -1;

    for ( sal_Int32 i = 0; i < SIZE_TABLE; i++ )
    {
        if ( CtrlIdToResIdTable[i].ctrlId == aControlId )
        {
            aResId = CtrlIdToResIdTable[i].resId;
            break;
        }
    }

    return aResId;
}

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

class CResourceProvider_Impl
{
public:

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

    CResourceProvider_Impl( )
    {
        m_ResMgr = CREATEVERSIONRESMGR( RES_NAME );
    }

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

    ~CResourceProvider_Impl( )
    {
        delete m_ResMgr;
    }

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

    OUString getResString( sal_Int16 aId )
    {
        String   aResString;
        OUString aResOUString;

        const ::vos::OGuard aGuard( Application::GetSolarMutex() );

        try
        {
            OSL_ASSERT( m_ResMgr );

            // translate the control id to a resource id
            sal_Int16 aResId = CtrlIdToResId( aId );

            if ( aResId > -1 )
            {
                aResString = String( ResId( aResId, m_ResMgr ) );
                aResOUString = OUString( aResString );
            }
        }
        catch(...)
        {
        }

        return aResOUString;
    }

public:
    ResMgr* m_ResMgr;
};

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

CResourceProvider::CResourceProvider( ) :
    m_pImpl( new CResourceProvider_Impl() )
{
}

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

CResourceProvider::~CResourceProvider( )
{
    delete m_pImpl;
}

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

OUString CResourceProvider::getResString( sal_Int32 aId )
{
   return m_pImpl->getResString( aId );
}<|endoftext|>


<commit_before>
#ifndef __MALLOC_ALLOC_HPP__
#define __MALLOC_ALLOC_HPP__

#include <stdlib.h>

struct malloc_alloc_t {
    // Standard constructor
    malloc_alloc_t() {}

    // We really don't need to take size here, but some super
    // allocators expect a constructor like this
    explicit malloc_alloc_t(size_t _size) {}

    void gc() {}

    void* malloc(size_t size) {
        void *ptr = ::malloc(size);
#ifdef VALGRIND
            // Zero out the buffer in debug mode so valgrind doesn't complain
            bzero(ptr, size);
#endif
        return ptr;
    }

    void free(void* ptr) {
        ::free(ptr);
    }
};

#endif // __MALLOC_ALLOC_HPP__

<commit_msg>Modified the generic malloc() allocator to also fill newly allocated memory with 0xBD.<commit_after>
#ifndef __MALLOC_ALLOC_HPP__
#define __MALLOC_ALLOC_HPP__

#include <stdlib.h>

struct malloc_alloc_t {
    // Standard constructor
    malloc_alloc_t() {}

    // We really don't need to take size here, but some super
    // allocators expect a constructor like this
    explicit malloc_alloc_t(size_t _size) {}

    void gc() {}

    void* malloc(size_t size) {
        void *ptr = ::malloc(size);
#if defined(VALGRIND) || !defined(NDEBUG)
            // Fill the buffer with garbage in debug mode so valgrind doesn't complain, and to help
            // catch uninitialized memory errors.
            memset(ptr, 0xBD, size);
#endif
        return ptr;
    }

    void free(void* ptr) {
        ::free(ptr);
    }
};

#endif // __MALLOC_ALLOC_HPP__

<|endoftext|>


<commit_before>#include <node.h>
#include "include/cef_base.h"
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "includes/cef_handler.h"
#include "includes/cef_sync_handler.h"
#include "appjs_window.h"

using namespace v8;
using namespace appjs;

ClientHandler::ClientHandler()
  : m_MainHwnd(NULL),
    m_BrowserHwnd(NULL) {
}

ClientHandler::~ClientHandler() {
}

Handle<Object> ClientHandler::GetV8WindowHandle(CefRefPtr<CefBrowser> browser) {
  return ClientHandler::GetWindow(browser)->GetV8Handle();
}

Handle<Object> ClientHandler::CreatedBrowser(CefRefPtr<CefBrowser> browser) {
  NativeWindow* window = ClientHandler::GetWindow(browser);
  window->SetBrowser(browser);
  return window->GetV8Handle();
}

void ClientHandler::OnAfterCreated(CefRefPtr<CefBrowser> browser) {
  REQUIRE_UI_THREAD();

  AutoLock lock_scope(this);

  if (!browser->IsPopup()) {
    // Set main browser of the application
    if (!m_Browser.get()) {
      m_Browser = browser;
      m_BrowserHwnd = browser->GetWindowHandle();
    }

    Handle<Object> handle = ClientHandler::CreatedBrowser(browser);
    Handle<Value> argv[1] = {String::New("create")};
    node::MakeCallback(handle,"emit", 1, argv);
  }
}

void ClientHandler::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context) {
  REQUIRE_UI_THREAD();
  if (!browser->IsPopup()) {
    context->Enter();
    CefRefPtr<CefV8Value> appjsObj = CefV8Value::CreateObject(NULL);
    CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction("send", new AppjsSyncHandler(browser));
    context->GetGlobal()->SetValue("appjs", appjsObj, V8_PROPERTY_ATTRIBUTE_NONE);
    appjsObj->SetValue("send", func, V8_PROPERTY_ATTRIBUTE_NONE);
    context->Exit();
  }
}

bool ClientHandler::DoClose(CefRefPtr<CefBrowser> browser) {
  REQUIRE_UI_THREAD();

  if (m_BrowserHwnd == browser->GetWindowHandle()) {
    // Since the main window contains the browser window, we need to close
    // the parent window instead of the browser window.
    m_Browser = NULL;
    CloseMainWindow();

    // Return true here so that we can skip closing the browser window
    // in this pass. (It will be destroyed due to the call to close
    // the parent above.)
  }

  // A popup browser window is not contained in another window, so we can let
  // these windows close by themselves.
  return false;
}

void ClientHandler::OnBeforeClose(CefRefPtr<CefBrowser> browser) {
  REQUIRE_UI_THREAD();

// There is a bug in CEF for Linux I think that there is no window object
// when the code reaches here.
#if not defined(__LINUX__)
  const int argc = 1;
  Handle<Object> handle = ClientHandler::GetV8WindowHandle(browser);
  Handle<Value> argv[1] = {String::New("close")};
  node::MakeCallback(handle,"emit",1,argv);
#endif

  if (m_BrowserHwnd == browser->GetWindowHandle()) {

    Local<Object> global = Context::GetCurrent()->Global();
    Local<Object> process = global->Get(String::NewSymbol("process"))->ToObject();
    Local<Object> emitter = Local<Object>::Cast(process->Get(String::NewSymbol("AppjsEmitter")));

    const int argc = 1;
    Handle<Value> argv[1] = {String::New("close")};
    node::MakeCallback(emitter,"emit",argc,argv);

    DoClose(browser);
  }
}

void ClientHandler::OnLoadEnd(CefRefPtr<CefBrowser> browser,
                         CefRefPtr<CefFrame> frame,
                         int httpStatusCode)
{
  REQUIRE_UI_THREAD();

  if (!browser->IsPopup()) {
    const int argc = 1;
    Handle<Object> handle = ClientHandler::GetV8WindowHandle(browser);
    Handle<Value> argv[argc] = {String::New("ready")};
    node::MakeCallback(handle,"emit",argc,argv);
  }
}

void ClientHandler::SetMainHwnd(CefWindowHandle& hwnd) {
  AutoLock lock_scope(this);

  m_MainHwnd = hwnd;
}
<commit_msg>revert change from "close" to "exit"<commit_after>#include <node.h>
#include "include/cef_base.h"
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "includes/cef_handler.h"
#include "includes/cef_sync_handler.h"
#include "appjs_window.h"

using namespace v8;
using namespace appjs;

ClientHandler::ClientHandler()
  : m_MainHwnd(NULL),
    m_BrowserHwnd(NULL) {
}

ClientHandler::~ClientHandler() {
}

Handle<Object> ClientHandler::GetV8WindowHandle(CefRefPtr<CefBrowser> browser) {
  return ClientHandler::GetWindow(browser)->GetV8Handle();
}

Handle<Object> ClientHandler::CreatedBrowser(CefRefPtr<CefBrowser> browser) {
  NativeWindow* window = ClientHandler::GetWindow(browser);
  window->SetBrowser(browser);
  return window->GetV8Handle();
}

void ClientHandler::OnAfterCreated(CefRefPtr<CefBrowser> browser) {
  REQUIRE_UI_THREAD();

  AutoLock lock_scope(this);

  if (!browser->IsPopup()) {
    // Set main browser of the application
    if (!m_Browser.get()) {
      m_Browser = browser;
      m_BrowserHwnd = browser->GetWindowHandle();
    }

    Handle<Object> handle = ClientHandler::CreatedBrowser(browser);
    Handle<Value> argv[1] = {String::New("create")};
    node::MakeCallback(handle,"emit", 1, argv);
  }
}

void ClientHandler::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context) {
  REQUIRE_UI_THREAD();
  if (!browser->IsPopup()) {
    context->Enter();
    CefRefPtr<CefV8Value> appjsObj = CefV8Value::CreateObject(NULL);
    CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction("send", new AppjsSyncHandler(browser));
    context->GetGlobal()->SetValue("appjs", appjsObj, V8_PROPERTY_ATTRIBUTE_NONE);
    appjsObj->SetValue("send", func, V8_PROPERTY_ATTRIBUTE_NONE);
    context->Exit();
  }
}

bool ClientHandler::DoClose(CefRefPtr<CefBrowser> browser) {
  REQUIRE_UI_THREAD();

  if (m_BrowserHwnd == browser->GetWindowHandle()) {
    // Since the main window contains the browser window, we need to close
    // the parent window instead of the browser window.
    m_Browser = NULL;
    CloseMainWindow();

    // Return true here so that we can skip closing the browser window
    // in this pass. (It will be destroyed due to the call to close
    // the parent above.)
  }

  // A popup browser window is not contained in another window, so we can let
  // these windows close by themselves.
  return false;
}

void ClientHandler::OnBeforeClose(CefRefPtr<CefBrowser> browser) {
  REQUIRE_UI_THREAD();

// There is a bug in CEF for Linux I think that there is no window object
// when the code reaches here.
#if not defined(__LINUX__)
  Handle<Object> handle = ClientHandler::GetV8WindowHandle(browser);
  Handle<Value> argv[1] = {String::New("close")};
  node::MakeCallback(handle,"emit",1,argv);
#endif

  if (m_BrowserHwnd == browser->GetWindowHandle()) {

    Local<Object> global = Context::GetCurrent()->Global();
    Local<Object> process = global->Get(String::NewSymbol("process"))->ToObject();
    Local<Object> emitter = Local<Object>::Cast(process->Get(String::NewSymbol("AppjsEmitter")));

    const int argc = 1;
    Handle<Value> argv[1] = {String::New("exit")};
    node::MakeCallback(emitter,"emit",argc,argv);

    DoClose(browser);
  }
}

void ClientHandler::OnLoadEnd(CefRefPtr<CefBrowser> browser,
                         CefRefPtr<CefFrame> frame,
                         int httpStatusCode)
{
  REQUIRE_UI_THREAD();

  if (!browser->IsPopup()) {
    const int argc = 1;
    Handle<Object> handle = ClientHandler::GetV8WindowHandle(browser);
    Handle<Value> argv[argc] = {String::New("ready")};
    node::MakeCallback(handle,"emit",argc,argv);
  }
}

void ClientHandler::SetMainHwnd(CefWindowHandle& hwnd) {
  AutoLock lock_scope(this);

  m_MainHwnd = hwnd;
}
<|endoftext|>


<commit_before>/* RTcmix  - Copyright (C) 2004  The RTcmix Development Team
   See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
   the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include <stdlib.h>
#include <string.h>
#include <rtcmix_types.h>
#include <PField.h>
#include <ugens.h>		// for warn, die

// Functions for creating signal conditioning wrapper PFields.
// -John Gibson, 11/25/04

extern int resetval;		// declared in src/rtcmix/minc_functions.c

// --------------------------------------------------------- local utilities ---
static Handle
_createPFieldHandle(PField *pfield)
{
	Handle handle = (Handle) malloc(sizeof(struct _handle));
	handle->type = PFieldType;
	handle->ptr = (void *) pfield;
	return handle;
}

// =============================================================================
// The remaining functions are public, callable from scripts.

extern "C" {
	Handle makefilter(const Arg args[], const int nargs);
}

// -------------------------------------------------------------- makefilter ---

enum {
	kSmoothFilter,
	kQuantizeFilter,
	kFitRangeFilter
};

static Handle
_makefilter_usage()
{
	die("makefilter",
		"\n   usage: filt = makefilter(pfield, \"fitrange\", min, max [, \"bipolar\"])"
		"\nOR"
		"\n   usage: filt = makefilter(pfield, \"quantize\", quantum)"
		"\nOR"
		"\n   usage: filt = makefilter(pfield, \"smooth\", lag)"
		"\n");
	return NULL;
}

Handle
makefilter(const Arg args[], const int nargs)
{
	if (nargs < 3)
		return _makefilter_usage();

	PField *innerpf = (PField *) args[0];
	if (innerpf == NULL)
		return _makefilter_usage();

	int type;
	if (args[1].isType(StringType)) {
		if (args[1] == "smooth" || args[1] == "lowpass")
			type = kSmoothFilter;
		else if (args[1] == "quantize")
			type = kQuantizeFilter;
		else if (args[1] == "fitrange")
			type = kFitRangeFilter;
		else {
			die("makefilter", "Unsupported filter type \"%s\".",
								(const char *) args[1]);
			return NULL;
		}
	}
	else
		return _makefilter_usage();

	PField *arg1pf = (PField *) args[2];
	if (arg1pf == NULL) {
		if (args[2].isType(DoubleType))
			arg1pf = new ConstPField((double) args[2]);
		else
			return _makefilter_usage();
	}

	PField *arg2pf = NULL;
	if (nargs > 3) {
		arg2pf = (PField *) args[3];
		if (arg2pf == NULL) {
			if (args[3].isType(DoubleType))
				arg2pf = new ConstPField((double) args[3]);
			else
				return _makefilter_usage();
		}
	}

	PField *filt = NULL;
	if (type == kSmoothFilter)
		filt = new SmoothPField(innerpf, resetval, arg1pf);
	else if (type == kQuantizeFilter)
		filt = new QuantizePField(innerpf, arg1pf);
	else if (type == kFitRangeFilter) {
		if (arg2pf) {
			if (nargs > 4 && args[4] == "bipolar")
				filt = new RangePField(innerpf, arg1pf, arg2pf, RangePField::BipolarSource);
			else
				filt = new RangePField(innerpf, arg1pf, arg2pf);
		}
		else
			return _makefilter_usage();
	}

	return _createPFieldHandle(filt);
}

<commit_msg>New constrain type<commit_after>/* RTcmix  - Copyright (C) 2004  The RTcmix Development Team
   See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
   the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include <stdlib.h>
#include <string.h>
#include <rtcmix_types.h>
#include <PField.h>
#include <ugens.h>		// for warn, die

// Functions for creating signal conditioning wrapper PFields.
// -John Gibson, 11/25/04

extern int resetval;		// declared in src/rtcmix/minc_functions.c

// --------------------------------------------------------- local utilities ---
static Handle
_createPFieldHandle(PField *pfield)
{
	Handle handle = (Handle) malloc(sizeof(struct _handle));
	handle->type = PFieldType;
	handle->ptr = (void *) pfield;
	return handle;
}

// =============================================================================
// The remaining functions are public, callable from scripts.

extern "C" {
	Handle makefilter(const Arg args[], const int nargs);
}

// -------------------------------------------------------------- makefilter ---

enum {
	kConstrainFilter,
	kFitRangeFilter,
	kQuantizeFilter,
	kSmoothFilter
};

static Handle
_makefilter_usage()
{
	die("makefilter",
		"\n   usage: filt = makefilter(pfield, \"constrain\", table, tightness)"
		"\nOR"
		"\n   usage: filt = makefilter(pfield, \"fitrange\", min, max [, \"bipolar\"])"
		"\nOR"
		"\n   usage: filt = makefilter(pfield, \"quantize\", quantum)"
		"\nOR"
		"\n   usage: filt = makefilter(pfield, \"smooth\", lag)"
		"\n");
	return NULL;
}

Handle
makefilter(const Arg args[], const int nargs)
{
	if (nargs < 3)
		return _makefilter_usage();

	PField *innerpf = (PField *) args[0];
	if (innerpf == NULL)
		return _makefilter_usage();

	int type;
	if (args[1].isType(StringType)) {
		if (args[1] == "constrain")
			type = kConstrainFilter;
		else if (args[1] == "fitrange")
			type = kFitRangeFilter;
		else if (args[1] == "quantize")
			type = kQuantizeFilter;
		else if (args[1] == "smooth" || args[1] == "lowpass")
			type = kSmoothFilter;
		else {
			die("makefilter", "Unsupported filter type \"%s\".",
								(const char *) args[1]);
			return NULL;
		}
	}
	else
		return _makefilter_usage();

	PField *arg1pf = (PField *) args[2];
	if (arg1pf == NULL) {
		if (args[2].isType(DoubleType))
			arg1pf = new ConstPField((double) args[2]);
		else
			return _makefilter_usage();
	}

	PField *arg2pf = NULL;
	if (nargs > 3) {
		arg2pf = (PField *) args[3];
		if (arg2pf == NULL) {
			if (args[3].isType(DoubleType))
				arg2pf = new ConstPField((double) args[3]);
			else
				return _makefilter_usage();
		}
	}

	PField *filt = NULL;
	if (type == kConstrainFilter) {
		const double *table = (double *) *arg1pf;
		const int len = arg1pf->values();
		if (table == NULL || len < 1)
			return _makefilter_usage();
		filt = new ConstrainPField(innerpf, table, len, arg2pf);
	}
	else if (type == kFitRangeFilter) {
		if (arg2pf) {
			if (nargs > 4 && args[4] == "bipolar")
				filt = new RangePField(innerpf, arg1pf, arg2pf, RangePField::BipolarSource);
			else
				filt = new RangePField(innerpf, arg1pf, arg2pf);
		}
		else
			return _makefilter_usage();
	}
	else if (type == kQuantizeFilter)
		filt = new QuantizePField(innerpf, arg1pf);
	else if (type == kSmoothFilter)
		filt = new SmoothPField(innerpf, resetval, arg1pf);

	return _createPFieldHandle(filt);
}

<|endoftext|>