<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007-2013, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/python.hpp"

#include "IECore/MessageHandler.h"
#include "IECore/NullMessageHandler.h"
#include "IECore/OStreamMessageHandler.h"
#include "IECore/CompoundMessageHandler.h"
#include "IECore/FilteredMessageHandler.h"
#include "IECore/LevelFilteredMessageHandler.h"
#include "IECorePython/MessageHandlerBinding.h"
#include "IECorePython/RefCountedBinding.h"
#include "IECorePython/Wrapper.h"
#include "IECorePython/ScopedGILLock.h"

using namespace boost::python;
using namespace IECore;

namespace IECorePython
{

class MessageHandlerWrap : public MessageHandler, public Wrapper<MessageHandler>
{
	public :

		MessageHandlerWrap( PyObject *self ) : Wrapper<MessageHandler>( self, this ) {}

		virtual void handle( MessageHandler::Level level, const std::string &context, const std::string &message )
		{
			ScopedGILLock gilLock;
			this->get_override( "handle" )( level, context, message );
		}

};

static void addHandler( CompoundMessageHandler &h, MessageHandlerPtr hh )
{
	h.handlers.insert( hh );
}

static void removeHandler( CompoundMessageHandler &h, MessageHandlerPtr hh )
{
	h.handlers.erase( hh );
}

static LevelFilteredMessageHandlerPtr levelFilteredMessageHandlerConstructor(MessageHandlerPtr handle, MessageHandler::Level level)
{
	return new LevelFilteredMessageHandler( handle, level );
}

void bindMessageHandler()
{

	def( "msg", (void (*)( MessageHandler::Level, const std::string &, const std::string &))&msg );

	object mh = RefCountedClass<MessageHandler, RefCounted, MessageHandlerWrap>( "MessageHandler" )
		.def( init<>() )
		.def( "handle", pure_virtual( &MessageHandler::handle ) )
		.def( "setDefaultHandler", &MessageHandler::setDefaultHandler )
		.staticmethod( "setDefaultHandler" )
		.def( "getDefaultHandler", &MessageHandler::getDefaultHandler, return_value_policy<CastToIntrusivePtr>() )
		.staticmethod( "getDefaultHandler" )
		.def( "currentHandler", &MessageHandler::currentHandler, return_value_policy<CastToIntrusivePtr>() )
		.staticmethod( "currentHandler" )
		.def( "output", (void (*)( MessageHandler::Level, const std::string &, const std::string &))&MessageHandler::output )
		.staticmethod( "output" )
		.def( "levelAsString", MessageHandler::levelAsString )
		.staticmethod( "levelAsString" )
		.def( "stringAsLevel", MessageHandler::stringAsLevel )
		.staticmethod( "stringAsLevel" )
	;

	RefCountedClass<NullMessageHandler, MessageHandler>( "NullMessageHandler" )
	.	def( init<>() )
	;

	RefCountedClass<OStreamMessageHandler, MessageHandler>( "OStreamMessageHandler" )
		.def( "cErrHandler", &OStreamMessageHandler::cErrHandler, return_value_policy<CastToIntrusivePtr>() )
		.staticmethod( "cErrHandler" )
		.def( "cOutHandler", &OStreamMessageHandler::cOutHandler, return_value_policy<CastToIntrusivePtr>() )
		.staticmethod( "cOutHandler" )
	;

	RefCountedClass<CompoundMessageHandler, MessageHandler>( "CompoundMessageHandler" )
		.def( init<>() )
		.def( "addHandler", &addHandler )
		.def( "removeHandler", &removeHandler )
	;

	RefCountedClass<FilteredMessageHandler, MessageHandler>( "FilteredMessageHandler" )
	;

	RefCountedClass<LevelFilteredMessageHandler, FilteredMessageHandler>( "LevelFilteredMessageHandler" )
		.def( "__init__", make_constructor( &levelFilteredMessageHandlerConstructor ) )
		.def( "setLevel", &LevelFilteredMessageHandler::setLevel )
		.def( "getLevel", &LevelFilteredMessageHandler::getLevel )
		.def( "defaultLevel", &LevelFilteredMessageHandler::defaultLevel ).staticmethod( "defaultLevel" )
	;

	scope mhS( mh );

	enum_<MessageHandler::Level>( "Level" )
		.value( "Error", MessageHandler::Error )
		.value( "Warning", MessageHandler::Warning )
		.value( "Info", MessageHandler::Info )
		.value( "Debug", MessageHandler::Debug )
		.value( "Invalid", MessageHandler::Invalid )
	;

	class_<MessageHandler::Scope, boost::noncopyable>( "_Scope", init<MessageHandler *>() )
	;

}

}
<commit_msg>MessageHandlerBinding : Use anonymous namespace as appropriate.<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007-2013, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/python.hpp"

#include "IECore/MessageHandler.h"
#include "IECore/NullMessageHandler.h"
#include "IECore/OStreamMessageHandler.h"
#include "IECore/CompoundMessageHandler.h"
#include "IECore/FilteredMessageHandler.h"
#include "IECore/LevelFilteredMessageHandler.h"
#include "IECorePython/MessageHandlerBinding.h"
#include "IECorePython/RefCountedBinding.h"
#include "IECorePython/Wrapper.h"
#include "IECorePython/ScopedGILLock.h"

using namespace boost::python;
using namespace IECore;
using namespace IECorePython;

namespace
{

class MessageHandlerWrap : public MessageHandler, public Wrapper<MessageHandler>
{
	public :

		MessageHandlerWrap( PyObject *self ) : Wrapper<MessageHandler>( self, this ) {}

		virtual void handle( MessageHandler::Level level, const std::string &context, const std::string &message )
		{
			ScopedGILLock gilLock;
			this->get_override( "handle" )( level, context, message );
		}

};

void addHandler( CompoundMessageHandler &h, MessageHandlerPtr hh )
{
	h.handlers.insert( hh );
}

void removeHandler( CompoundMessageHandler &h, MessageHandlerPtr hh )
{
	h.handlers.erase( hh );
}

LevelFilteredMessageHandlerPtr levelFilteredMessageHandlerConstructor(MessageHandlerPtr handle, MessageHandler::Level level)
{
	return new LevelFilteredMessageHandler( handle, level );
}

} // namespace

void IECorePython::bindMessageHandler()
{

	def( "msg", (void (*)( MessageHandler::Level, const std::string &, const std::string &))&msg );

	object mh = RefCountedClass<MessageHandler, RefCounted, MessageHandlerWrap>( "MessageHandler" )
		.def( init<>() )
		.def( "handle", pure_virtual( &MessageHandler::handle ) )
		.def( "setDefaultHandler", &MessageHandler::setDefaultHandler )
		.staticmethod( "setDefaultHandler" )
		.def( "getDefaultHandler", &MessageHandler::getDefaultHandler, return_value_policy<CastToIntrusivePtr>() )
		.staticmethod( "getDefaultHandler" )
		.def( "currentHandler", &MessageHandler::currentHandler, return_value_policy<CastToIntrusivePtr>() )
		.staticmethod( "currentHandler" )
		.def( "output", (void (*)( MessageHandler::Level, const std::string &, const std::string &))&MessageHandler::output )
		.staticmethod( "output" )
		.def( "levelAsString", MessageHandler::levelAsString )
		.staticmethod( "levelAsString" )
		.def( "stringAsLevel", MessageHandler::stringAsLevel )
		.staticmethod( "stringAsLevel" )
	;

	RefCountedClass<NullMessageHandler, MessageHandler>( "NullMessageHandler" )
	.	def( init<>() )
	;

	RefCountedClass<OStreamMessageHandler, MessageHandler>( "OStreamMessageHandler" )
		.def( "cErrHandler", &OStreamMessageHandler::cErrHandler, return_value_policy<CastToIntrusivePtr>() )
		.staticmethod( "cErrHandler" )
		.def( "cOutHandler", &OStreamMessageHandler::cOutHandler, return_value_policy<CastToIntrusivePtr>() )
		.staticmethod( "cOutHandler" )
	;

	RefCountedClass<CompoundMessageHandler, MessageHandler>( "CompoundMessageHandler" )
		.def( init<>() )
		.def( "addHandler", &addHandler )
		.def( "removeHandler", &removeHandler )
	;

	RefCountedClass<FilteredMessageHandler, MessageHandler>( "FilteredMessageHandler" )
	;

	RefCountedClass<LevelFilteredMessageHandler, FilteredMessageHandler>( "LevelFilteredMessageHandler" )
		.def( "__init__", make_constructor( &levelFilteredMessageHandlerConstructor ) )
		.def( "setLevel", &LevelFilteredMessageHandler::setLevel )
		.def( "getLevel", &LevelFilteredMessageHandler::getLevel )
		.def( "defaultLevel", &LevelFilteredMessageHandler::defaultLevel ).staticmethod( "defaultLevel" )
	;

	scope mhS( mh );

	enum_<MessageHandler::Level>( "Level" )
		.value( "Error", MessageHandler::Error )
		.value( "Warning", MessageHandler::Warning )
		.value( "Info", MessageHandler::Info )
		.value( "Debug", MessageHandler::Debug )
		.value( "Invalid", MessageHandler::Invalid )
	;

	class_<MessageHandler::Scope, boost::noncopyable>( "_Scope", init<MessageHandler *>() )
	;

}
<|endoftext|>


<commit_before>/*
 *
 *    Copyright (c) 2021 Project CHIP Authors
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
#include "MdnsImpl.h"
#include "lib/mdns/platform/Mdns.h"

namespace chip {
namespace Mdns {

namespace test {
namespace {
static constexpr size_t kMaxExpectedCalls = 10;
size_t numExpectedCalls                   = 0;
ExpectedCall expectedCalls[kMaxExpectedCalls];
bool foundCall[kMaxExpectedCalls] = {};
} // namespace

CHIP_ERROR AddExpectedCall(const ExpectedCall & call)
{
    if (!call.IsValid())
    {
        return CHIP_ERROR_INVALID_ARGUMENT;
    }
    if (numExpectedCalls >= kMaxExpectedCalls)
    {
        return CHIP_ERROR_NO_MEMORY;
    }
    expectedCalls[numExpectedCalls++] = call;
    return CHIP_NO_ERROR;
}

void Reset()
{
    numExpectedCalls = 0;
    for (auto & found : foundCall)
    {
        found = false;
    }
}

CHIP_ERROR CheckExpected(CallType type, const MdnsService * service)
{
    for (size_t i = 0; i < test::numExpectedCalls; ++i)
    {
        if (test::foundCall[i])
        {
            continue;
        }
        if (test::expectedCalls[i].CheckMatch(type, service))
        {
            return CHIP_NO_ERROR;
        }
    }
    ChipLogError(Discovery, "Unexpected event of type %d", static_cast<int>(type));
    ChipLogProgress(Discovery, "mName = %s", service->mName);
    ChipLogProgress(Discovery, "mHostName = %s", service->mHostName);
    ChipLogProgress(Discovery, "mType = %s", service->mType);
    ChipLogProgress(Discovery, "mProtocol = %d", static_cast<int>(service->mProtocol));
    ChipLogProgress(Discovery, "num subtypes = %lu", static_cast<unsigned long>(service->mSubTypeSize));
    for (size_t i = 0; i < service->mSubTypeSize; ++i)
    {
        ChipLogProgress(Discovery, "\t%s", service->mSubTypes[i]);
    }
    ChipLogProgress(Discovery, "num text entries = %lu", static_cast<unsigned long>(service->mTextEntrySize));
    for (size_t i = 0; i < service->mSubTypeSize; ++i)
    {
        ChipLogProgress(Discovery, "\t%s", service->mTextEntries[i].mKey);
    }
    ChipLogProgress(Discovery, "\nExpected:");
    for (size_t i = 0; i < test::numExpectedCalls; ++i)
    {
        ChipLogProgress(Discovery, "Call %lu", static_cast<unsigned long>(i));
        test::expectedCalls[i].PrintForDebugging();
    }
    return CHIP_ERROR_UNEXPECTED_EVENT;
}

} // namespace test

CHIP_ERROR ChipMdnsInit(MdnsAsyncReturnCallback initCallback, MdnsAsyncReturnCallback errorCallback, void * context)
{
    return CHIP_NO_ERROR;
}

CHIP_ERROR ChipMdnsShutdown()
{
    return CHIP_NO_ERROR;
}

CHIP_ERROR ChipMdnsPublishService(const MdnsService * service)
{
    return test::CheckExpected(test::CallType::kStart, service);
}

CHIP_ERROR ChipMdnsStopPublish()
{
    return CHIP_ERROR_NOT_IMPLEMENTED;
}

CHIP_ERROR ChipMdnsStopPublishService(const MdnsService * service)
{
    return test::CheckExpected(test::CallType::kStart, service);
}

CHIP_ERROR ChipMdnsBrowse(const char * type, MdnsServiceProtocol protocol, chip::Inet::IPAddressType addressType,
                          chip::Inet::InterfaceId interface, MdnsBrowseCallback callback, void * context)
{
    return CHIP_ERROR_NOT_IMPLEMENTED;
}

CHIP_ERROR ChipMdnsResolve(MdnsService * browseResult, chip::Inet::InterfaceId interface, MdnsResolveCallback callback,
                           void * context)

{
    return CHIP_ERROR_NOT_IMPLEMENTED;
}

void GetMdnsTimeout(timeval & timeout) {}
void HandleMdnsTimeout() {}

} // namespace Mdns
} // namespace chip
<commit_msg>Fix wrong loop condition in fake MdnsImpl (#9905)<commit_after>/*
 *
 *    Copyright (c) 2021 Project CHIP Authors
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
#include "MdnsImpl.h"
#include "lib/mdns/platform/Mdns.h"

namespace chip {
namespace Mdns {

namespace test {
namespace {
static constexpr size_t kMaxExpectedCalls = 10;
size_t numExpectedCalls                   = 0;
ExpectedCall expectedCalls[kMaxExpectedCalls];
bool foundCall[kMaxExpectedCalls] = {};
} // namespace

CHIP_ERROR AddExpectedCall(const ExpectedCall & call)
{
    if (!call.IsValid())
    {
        return CHIP_ERROR_INVALID_ARGUMENT;
    }
    if (numExpectedCalls >= kMaxExpectedCalls)
    {
        return CHIP_ERROR_NO_MEMORY;
    }
    expectedCalls[numExpectedCalls++] = call;
    return CHIP_NO_ERROR;
}

void Reset()
{
    numExpectedCalls = 0;
    for (auto & found : foundCall)
    {
        found = false;
    }
}

CHIP_ERROR CheckExpected(CallType type, const MdnsService * service)
{
    for (size_t i = 0; i < test::numExpectedCalls; ++i)
    {
        if (test::foundCall[i])
        {
            continue;
        }
        if (test::expectedCalls[i].CheckMatch(type, service))
        {
            return CHIP_NO_ERROR;
        }
    }
    ChipLogError(Discovery, "Unexpected event of type %d", static_cast<int>(type));
    ChipLogProgress(Discovery, "mName = %s", service->mName);
    ChipLogProgress(Discovery, "mHostName = %s", service->mHostName);
    ChipLogProgress(Discovery, "mType = %s", service->mType);
    ChipLogProgress(Discovery, "mProtocol = %d", static_cast<int>(service->mProtocol));
    ChipLogProgress(Discovery, "num subtypes = %lu", static_cast<unsigned long>(service->mSubTypeSize));
    for (size_t i = 0; i < service->mSubTypeSize; ++i)
    {
        ChipLogProgress(Discovery, "\t%s", service->mSubTypes[i]);
    }
    ChipLogProgress(Discovery, "num text entries = %lu", static_cast<unsigned long>(service->mTextEntrySize));
    for (size_t i = 0; i < service->mTextEntrySize; ++i)
    {
        ChipLogProgress(Discovery, "\t%s", service->mTextEntries[i].mKey);
    }
    ChipLogProgress(Discovery, "\nExpected:");
    for (size_t i = 0; i < test::numExpectedCalls; ++i)
    {
        ChipLogProgress(Discovery, "Call %lu", static_cast<unsigned long>(i));
        test::expectedCalls[i].PrintForDebugging();
    }
    return CHIP_ERROR_UNEXPECTED_EVENT;
}

} // namespace test

CHIP_ERROR ChipMdnsInit(MdnsAsyncReturnCallback initCallback, MdnsAsyncReturnCallback errorCallback, void * context)
{
    return CHIP_NO_ERROR;
}

CHIP_ERROR ChipMdnsShutdown()
{
    return CHIP_NO_ERROR;
}

CHIP_ERROR ChipMdnsPublishService(const MdnsService * service)
{
    return test::CheckExpected(test::CallType::kStart, service);
}

CHIP_ERROR ChipMdnsStopPublish()
{
    return CHIP_ERROR_NOT_IMPLEMENTED;
}

CHIP_ERROR ChipMdnsStopPublishService(const MdnsService * service)
{
    return test::CheckExpected(test::CallType::kStart, service);
}

CHIP_ERROR ChipMdnsBrowse(const char * type, MdnsServiceProtocol protocol, chip::Inet::IPAddressType addressType,
                          chip::Inet::InterfaceId interface, MdnsBrowseCallback callback, void * context)
{
    return CHIP_ERROR_NOT_IMPLEMENTED;
}

CHIP_ERROR ChipMdnsResolve(MdnsService * browseResult, chip::Inet::InterfaceId interface, MdnsResolveCallback callback,
                           void * context)

{
    return CHIP_ERROR_NOT_IMPLEMENTED;
}

void GetMdnsTimeout(timeval & timeout) {}
void HandleMdnsTimeout() {}

} // namespace Mdns
} // namespace chip
<|endoftext|>


<commit_before>/*  -*- mode: C++; c-file-style: "gnu" -*-
 *
 *  This file is part of KMail, the KDE mail client.
 *
 *  Copyright (c) 2002-2003 Carsten Pfeiffer <pfeiffer@kde.org>
 *  Copyright (c) 2003      Zack Rusin <zack@kde.org>
 *
 *  KMail is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU General Public License, version 2, as
 *  published by the Free Software Foundation.
 *
 *  KMail 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
 *  General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *  In addition, as a special exception, the copyright holders give
 *  permission to link the code of this program with any edition of
 *  the Qt library by Trolltech AS, Norway (or with modified versions
 *  of Qt that use the same license as Qt), and distribute linked
 *  combinations including the two.  You must obey the GNU General
 *  Public License in all respects for all of the code used other than
 *  Qt.  If you modify this file, you may extend this exception to
 *  your version of the file, but you are not obligated to do so.  If
 *  you do not wish to do so, delete this exception statement from
 *  your version.
 */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "mailsourceviewer.h"

#include <kapplication.h>
#include <kwin.h>

#include <qregexp.h>
#include <qaccel.h>

namespace KMail {

int MailSourceHighlighter::highlightParagraph( const QString& text, int ) {
  QRegExp regexp( "^([\\w-]+:\\s)" );
  if( regexp.search( text ) != -1 ) {
    QFont font = textEdit()->currentFont();
    font.setBold( true );
    setFormat( 0, regexp.matchedLength(), font );
  }
  return 0;
}

MailSourceViewer::MailSourceViewer( QWidget *parent, const char *name )
  : KTextBrowser( parent, name ), mSourceHighLighter( 0 )
{
  setWFlags( WDestructiveClose );
  QAccel *accel = new QAccel( this, "browser close-accel" );
  accel->connectItem( accel->insertItem( Qt::Key_Escape ), this , SLOT( close() ));
  setWordWrap( KTextBrowser::NoWrap );
  KWin::setIcons(winId(), kapp->icon(), kapp->miniIcon());
}

MailSourceViewer::~MailSourceViewer()
{
   if ( mSourceHighLighter != 0 )
      delete mSourceHighLighter;
}

void MailSourceViewer::setText( const QString& text )
{
   if ( text.length() > 500000 ) {
     setTextFormat( Qt::LogText );
   } else {
     setTextFormat( Qt::PlainText );
     mSourceHighLighter = new MailSourceHighlighter( this );
   }
   KTextBrowser::setText( text );
}

}
<commit_msg>- Remove the superfluous 'if ( pointer != 0 )'. - Don't leak MailSourceHighlighter if setText is called multiple times. - Fix indentation.<commit_after>/*  -*- mode: C++; c-file-style: "gnu" -*-
 *
 *  This file is part of KMail, the KDE mail client.
 *
 *  Copyright (c) 2002-2003 Carsten Pfeiffer <pfeiffer@kde.org>
 *  Copyright (c) 2003      Zack Rusin <zack@kde.org>
 *
 *  KMail is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU General Public License, version 2, as
 *  published by the Free Software Foundation.
 *
 *  KMail 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
 *  General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *  In addition, as a special exception, the copyright holders give
 *  permission to link the code of this program with any edition of
 *  the Qt library by Trolltech AS, Norway (or with modified versions
 *  of Qt that use the same license as Qt), and distribute linked
 *  combinations including the two.  You must obey the GNU General
 *  Public License in all respects for all of the code used other than
 *  Qt.  If you modify this file, you may extend this exception to
 *  your version of the file, but you are not obligated to do so.  If
 *  you do not wish to do so, delete this exception statement from
 *  your version.
 */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "mailsourceviewer.h"

#include <kapplication.h>
#include <kwin.h>

#include <qregexp.h>
#include <qaccel.h>

namespace KMail {

int MailSourceHighlighter::highlightParagraph( const QString& text, int ) {
  QRegExp regexp( "^([\\w-]+:\\s)" );
  if( regexp.search( text ) != -1 ) {
    QFont font = textEdit()->currentFont();
    font.setBold( true );
    setFormat( 0, regexp.matchedLength(), font );
  }
  return 0;
}

MailSourceViewer::MailSourceViewer( QWidget *parent, const char *name )
  : KTextBrowser( parent, name ), mSourceHighLighter( 0 )
{
  setWFlags( WDestructiveClose );
  QAccel *accel = new QAccel( this, "browser close-accel" );
  accel->connectItem( accel->insertItem( Qt::Key_Escape ), this , SLOT( close() ));
  setWordWrap( KTextBrowser::NoWrap );
  KWin::setIcons(winId(), kapp->icon(), kapp->miniIcon());
}

MailSourceViewer::~MailSourceViewer()
{
  delete mSourceHighLighter; mSourceHighLighter = 0;
}

void MailSourceViewer::setText( const QString& text )
{
  delete mSourceHighLighter; mSourceHighLighter = 0;
  if ( text.length() > 500000 ) {
    setTextFormat( Qt::LogText );
  } else {
    setTextFormat( Qt::PlainText );
    mSourceHighLighter = new MailSourceHighlighter( this );
  }
  KTextBrowser::setText( text );
}

}
<|endoftext|>


<commit_before>
#include "ksp_plugin/planetarium.hpp"

#include <algorithm>
#include <vector>

#include "geometry/point.hpp"
#include "quantities/elementary_functions.hpp"

namespace principia {
namespace ksp_plugin {
namespace internal_planetarium {

using geometry::Position;
using geometry::RP2Line;
using geometry::Sign;
using geometry::Velocity;
using quantities::Pow;
using quantities::Sin;
using quantities::Sqrt;
using quantities::Tan;
using quantities::Time;

Planetarium::Parameters::Parameters(double const sphere_radius_multiplier,
                                    Angle const& angular_resolution,
                                    Angle const& field_of_view)
    : sphere_radius_multiplier_(sphere_radius_multiplier),
      sin²_angular_resolution_(Pow<2>(Sin(angular_resolution))),
      tan_angular_resolution_(Tan(angular_resolution)),
      tan_field_of_view_(Tan(field_of_view)) {}

Planetarium::Planetarium(
    Parameters const& parameters,
    Perspective<Navigation, Camera> const& perspective,
    not_null<Ephemeris<Barycentric> const*> const ephemeris,
    not_null<NavigationFrame const*> const plotting_frame)
    : parameters_(parameters),
      perspective_(perspective),
      ephemeris_(ephemeris),
      plotting_frame_(plotting_frame) {}

RP2Lines<Length, Camera> Planetarium::PlotMethod0(
    DiscreteTrajectory<Barycentric>::Iterator const& begin,
    DiscreteTrajectory<Barycentric>::Iterator const& end,
    Instant const& now,
    bool const reverse) const {
  auto const plottable_begin =
      begin.trajectory()->LowerBound(plotting_frame_->t_min());
  auto const plottable_end =
      begin.trajectory()->LowerBound(plotting_frame_->t_max());
  auto const plottable_spheres = ComputePlottableSpheres(now);
  auto const plottable_segments = ComputePlottableSegments(plottable_spheres,
                                                           plottable_begin,
                                                           plottable_end);

  auto const field_of_view_radius² =
      perspective_.focal() * perspective_.focal() *
      parameters_.tan_field_of_view_ * parameters_.tan_field_of_view_;
  std::experimental::optional<Position<Navigation>> previous_position;
  RP2Lines<Length, Camera> rp2_lines;
  for (auto const& plottable_segment : plottable_segments) {
    // Apply the projection to the current plottable segment.
    auto const rp2_first = perspective_(plottable_segment.first);
    auto const rp2_second = perspective_(plottable_segment.second);

    // If the segment is entirely outside the field of view, ignore it.
    Length const x1 = rp2_first.x();
    Length const y1 = rp2_first.y();
    Length const x2 = rp2_second.x();
    Length const y2 = rp2_second.y();
    if (x1 * x1 + y1 * y1 > field_of_view_radius² &&
        x2 * x2 + y2 * y2 > field_of_view_radius²) {
      continue;
    }

    // Create a new ℝP² line when two segments are not consecutive.  Don't
    // compare ℝP² points for equality, that's expensive.
    bool const are_consecutive =
        previous_position == plottable_segment.first;
    previous_position = plottable_segment.second;

    if (are_consecutive) {
      rp2_lines.back().push_back(rp2_second);
    } else {
      RP2Line<Length, Camera> const rp2_line = {rp2_first, rp2_second};
      rp2_lines.push_back(rp2_line);
    }
  }
  return rp2_lines;
}

RP2Lines<Length, Camera> Planetarium::PlotMethod1(
    DiscreteTrajectory<Barycentric>::Iterator const& begin,
    DiscreteTrajectory<Barycentric>::Iterator const& end,
    Instant const& now,
    bool const reverse) const {
  Length const focal_plane_tolerance =
      perspective_.focal() * parameters_.tan_angular_resolution_;
  auto const focal_plane_tolerance² =
      focal_plane_tolerance * focal_plane_tolerance;

  auto const rp2_lines = PlotMethod0(begin, end, now, reverse);

  int skipped = 0;
  int total = 0;
  RP2Lines<Length, Camera> new_rp2_lines;
  for (auto const& rp2_line : rp2_lines) {
    RP2Line<Length, Camera> new_rp2_line;
    std::experimental::optional<RP2Point<Length, Camera>> start_rp2_point;
    for (int i = 0; i < rp2_line.size(); ++i) {
      RP2Point<Length, Camera> const& rp2_point = rp2_line[i];
      if (i == 0) {
        new_rp2_line.push_back(rp2_point);
        start_rp2_point = rp2_point;
      } else if (Pow<2>(rp2_point.x() - start_rp2_point->x()) +
                 Pow<2>(rp2_point.y() - start_rp2_point->y()) >
                     focal_plane_tolerance²) {
        // TODO(phl): This creates a segment if the tolerance is exceeded.  It
        // should probably create a segment that stays just below the tolerance.
        new_rp2_line.push_back(rp2_point);
        start_rp2_point = rp2_point;
      } else if (i == rp2_line.size() - 1) {
        new_rp2_line.push_back(rp2_point);
      } else {
        ++skipped;
      }
      ++total;
    }
    new_rp2_lines.push_back(std::move(new_rp2_line));
  }
  LOG(INFO) << "PlotMethod1 skipped " << skipped << " points out of " << total
            << ", emitting " << total - skipped << " points";
  return new_rp2_lines;
}

RP2Lines<Length, Camera> Planetarium::PlotMethod2(
    DiscreteTrajectory<Barycentric>::Iterator const& begin,
    DiscreteTrajectory<Barycentric>::Iterator const& end,
    Instant const& now,
    bool const reverse) const {
  RP2Lines<Length, Camera> lines;
  if (begin == end) {
    return lines;
  }
  auto last = end;
  --last;

  double const tan²_angular_resolution =
      Pow<2>(parameters_.tan_angular_resolution_);
  auto const plottable_spheres = ComputePlottableSpheres(now);
  auto const& trajectory = *begin.trajectory();
  auto const begin_time = std::max(begin.time(), plotting_frame_->t_min());
  auto const last_time = std::min(last.time(), plotting_frame_->t_max());
  auto const final_time = reverse ? begin_time : last_time;
  auto previous_time = reverse ? last_time : begin_time;
  Sign const direction = reverse ? Sign(-1) : Sign(1);
  if (direction * (final_time - previous_time) <= Time{}) {
    return lines;
  }
  RigidMotion<Barycentric, Navigation> to_plotting_frame_at_t =
      plotting_frame_->ToThisFrameAtTime(previous_time);
  DegreesOfFreedom<Navigation> const initial_degrees_of_freedom =
      to_plotting_frame_at_t(
          trajectory.EvaluateDegreesOfFreedom(previous_time));
  Position<Navigation> previous_position =
      initial_degrees_of_freedom.position();
  Velocity<Navigation> previous_velocity =
      initial_degrees_of_freedom.velocity();
  Time Δt = final_time - previous_time;

  Instant t;
  double estimated_tan²_error;
  std::experimental::optional<DegreesOfFreedom<Barycentric>>
      degrees_of_freedom_in_barycentric;
  Position<Navigation> position;

  std::experimental::optional<Position<Navigation>> last_endpoint;

  int steps_accepted = 0;
  int steps_attempted = 0;

  goto estimate_tan²_error;

  while (steps_accepted < 10'000 &&
         direction * (previous_time - final_time) < Time{}) {
    do {
      // One square root because we have squared errors, another one because the
      // errors are quadratic in time (in other words, two square roots because
      // the squared errors are quartic in time).
      // A safety factor prevents catastrophic retries.
      Δt *= 0.9 * Sqrt(Sqrt(tan²_angular_resolution / estimated_tan²_error));
    estimate_tan²_error:
      t = previous_time + Δt;
      if (direction * (t - final_time) > Time{}) {
        t = final_time;
        Δt = t - previous_time;
      }
      Position<Navigation> const extrapolated_position =
          previous_position + previous_velocity * Δt;
      to_plotting_frame_at_t = plotting_frame_->ToThisFrameAtTime(t);
      degrees_of_freedom_in_barycentric =
          trajectory.EvaluateDegreesOfFreedom(t);
      position = to_plotting_frame_at_t.rigid_transformation()(
                     degrees_of_freedom_in_barycentric->position());

      // The quadratic term of the error between the linear interpolation and
      // the actual function is maximized halfway through the segment, so it is
      // 1/2 (Δt/2)² f″(t-Δt) = (1/2 Δt² f″(t-Δt)) / 4; the squared error is
      // thus (1/2 Δt² f″(t-Δt))² / 16.
      estimated_tan²_error =
          perspective_.Tan²AngularDistance(extrapolated_position, position) /
          16;
      ++steps_attempted;
    } while (estimated_tan²_error > tan²_angular_resolution);
    ++steps_accepted;

    // TODO(egg): also limit to field of view.
    auto const segment_behind_focal_plane =
        perspective_.SegmentBehindFocalPlane(
            Segment<Navigation>(previous_position, position));

    previous_time = t;
    previous_position = position;
    previous_velocity =
        to_plotting_frame_at_t(*degrees_of_freedom_in_barycentric).velocity();

    if (!segment_behind_focal_plane) {
      continue;
    }

    auto const visible_segments = perspective_.VisibleSegments(
                                      *segment_behind_focal_plane,
                                      plottable_spheres);
    for (auto const& segment : visible_segments) {
      if (last_endpoint != segment.first) {
        lines.emplace_back();
        lines.back().push_back(perspective_(segment.first));
      }
      lines.back().push_back(perspective_(segment.second));
      last_endpoint = segment.second;
    }
  }
  LOG(INFO) << "PlotMethod2 took " << steps_accepted << " steps, attempted "
            << steps_attempted << " steps";
  return lines;
}

std::vector<Sphere<Navigation>> Planetarium::ComputePlottableSpheres(
    Instant const& now) const {
  RigidMotion<Barycentric, Navigation> const rigid_motion_at_now =
      plotting_frame_->ToThisFrameAtTime(now);
  std::vector<Sphere<Navigation>> plottable_spheres;

  auto const& bodies = ephemeris_->bodies();
  for (auto const body : bodies) {
    auto const trajectory = ephemeris_->trajectory(body);
    Length const mean_radius = body->mean_radius();
    Position<Barycentric> const centre_in_barycentric =
        trajectory->EvaluatePosition(now);
    Sphere<Navigation> plottable_sphere(
        rigid_motion_at_now.rigid_transformation()(centre_in_barycentric),
        parameters_.sphere_radius_multiplier_ * mean_radius);
    // If the sphere is seen under an angle that is very small it doesn't
    // participate in hiding.
    if (perspective_.SphereSin²HalfAngle(plottable_sphere) >
        parameters_.sin²_angular_resolution_) {
      plottable_spheres.emplace_back(std::move(plottable_sphere));
    }
  }
  return plottable_spheres;
}

Segments<Navigation> Planetarium::ComputePlottableSegments(
    const std::vector<Sphere<Navigation>>& plottable_spheres,
    DiscreteTrajectory<Barycentric>::Iterator const& begin,
    DiscreteTrajectory<Barycentric>::Iterator const& end) const {
  Segments<Navigation> all_segments;
  if (begin == end) {
    return all_segments;
  }
  auto it1 = begin;
  Instant t1 = it1.time();
  RigidMotion<Barycentric, Navigation> rigid_motion_at_t1 =
      plotting_frame_->ToThisFrameAtTime(t1);
  Position<Navigation> p1 =
      rigid_motion_at_t1(it1.degrees_of_freedom()).position();

  auto it2 = it1;
  while (++it2 != end) {
    // Processing one segment of the trajectory.
    Instant const t2 = it2.time();

    // Transform the degrees of freedom to the plotting frame.
    RigidMotion<Barycentric, Navigation> const rigid_motion_at_t2 =
        plotting_frame_->ToThisFrameAtTime(t2);
    Position<Navigation> const p2 =
        rigid_motion_at_t2(it2.degrees_of_freedom()).position();

    // Find the part of the segment that is behind the focal plane.  We don't
    // care about things that are in front of the focal plane.
    const Segment<Navigation> segment = {p1, p2};
    auto const segment_behind_focal_plane =
        perspective_.SegmentBehindFocalPlane(segment);
    if (segment_behind_focal_plane) {
      // Find the part(s) of the segment that are not hidden by spheres.  These
      // are the ones we want to plot.
      auto segments = perspective_.VisibleSegments(*segment_behind_focal_plane,
                                                   plottable_spheres);
      std::move(segments.begin(),
                segments.end(),
                std::back_inserter(all_segments));
    }

    it1 = it2;
    t1 = t2;
    rigid_motion_at_t1 = rigid_motion_at_t2;
    p1 = p2;
  }

  return all_segments;
}

}  // namespace internal_planetarium
}  // namespace ksp_plugin
}  // namespace principia
<commit_msg>after pleroy's review<commit_after>
#include "ksp_plugin/planetarium.hpp"

#include <algorithm>
#include <vector>

#include "geometry/point.hpp"
#include "quantities/elementary_functions.hpp"

namespace principia {
namespace ksp_plugin {
namespace internal_planetarium {

using geometry::Position;
using geometry::RP2Line;
using geometry::Sign;
using geometry::Velocity;
using quantities::Pow;
using quantities::Sin;
using quantities::Sqrt;
using quantities::Tan;
using quantities::Time;

namespace {
constexpr int max_plot_method_2_steps = 10'000;
}  // namespace

Planetarium::Parameters::Parameters(double const sphere_radius_multiplier,
                                    Angle const& angular_resolution,
                                    Angle const& field_of_view)
    : sphere_radius_multiplier_(sphere_radius_multiplier),
      sin²_angular_resolution_(Pow<2>(Sin(angular_resolution))),
      tan_angular_resolution_(Tan(angular_resolution)),
      tan_field_of_view_(Tan(field_of_view)) {}

Planetarium::Planetarium(
    Parameters const& parameters,
    Perspective<Navigation, Camera> const& perspective,
    not_null<Ephemeris<Barycentric> const*> const ephemeris,
    not_null<NavigationFrame const*> const plotting_frame)
    : parameters_(parameters),
      perspective_(perspective),
      ephemeris_(ephemeris),
      plotting_frame_(plotting_frame) {}

RP2Lines<Length, Camera> Planetarium::PlotMethod0(
    DiscreteTrajectory<Barycentric>::Iterator const& begin,
    DiscreteTrajectory<Barycentric>::Iterator const& end,
    Instant const& now,
    bool const /*reverse*/) const {
  auto const plottable_begin =
      begin.trajectory()->LowerBound(plotting_frame_->t_min());
  auto const plottable_end =
      begin.trajectory()->LowerBound(plotting_frame_->t_max());
  auto const plottable_spheres = ComputePlottableSpheres(now);
  auto const plottable_segments = ComputePlottableSegments(plottable_spheres,
                                                           plottable_begin,
                                                           plottable_end);

  auto const field_of_view_radius² =
      perspective_.focal() * perspective_.focal() *
      parameters_.tan_field_of_view_ * parameters_.tan_field_of_view_;
  std::experimental::optional<Position<Navigation>> previous_position;
  RP2Lines<Length, Camera> rp2_lines;
  for (auto const& plottable_segment : plottable_segments) {
    // Apply the projection to the current plottable segment.
    auto const rp2_first = perspective_(plottable_segment.first);
    auto const rp2_second = perspective_(plottable_segment.second);

    // If the segment is entirely outside the field of view, ignore it.
    Length const x1 = rp2_first.x();
    Length const y1 = rp2_first.y();
    Length const x2 = rp2_second.x();
    Length const y2 = rp2_second.y();
    if (x1 * x1 + y1 * y1 > field_of_view_radius² &&
        x2 * x2 + y2 * y2 > field_of_view_radius²) {
      continue;
    }

    // Create a new ℝP² line when two segments are not consecutive.  Don't
    // compare ℝP² points for equality, that's expensive.
    bool const are_consecutive =
        previous_position == plottable_segment.first;
    previous_position = plottable_segment.second;

    if (are_consecutive) {
      rp2_lines.back().push_back(rp2_second);
    } else {
      RP2Line<Length, Camera> const rp2_line = {rp2_first, rp2_second};
      rp2_lines.push_back(rp2_line);
    }
  }
  return rp2_lines;
}

RP2Lines<Length, Camera> Planetarium::PlotMethod1(
    DiscreteTrajectory<Barycentric>::Iterator const& begin,
    DiscreteTrajectory<Barycentric>::Iterator const& end,
    Instant const& now,
    bool const reverse) const {
  Length const focal_plane_tolerance =
      perspective_.focal() * parameters_.tan_angular_resolution_;
  auto const focal_plane_tolerance² =
      focal_plane_tolerance * focal_plane_tolerance;

  auto const rp2_lines = PlotMethod0(begin, end, now, reverse);

  int skipped = 0;
  int total = 0;
  RP2Lines<Length, Camera> new_rp2_lines;
  for (auto const& rp2_line : rp2_lines) {
    RP2Line<Length, Camera> new_rp2_line;
    std::experimental::optional<RP2Point<Length, Camera>> start_rp2_point;
    for (int i = 0; i < rp2_line.size(); ++i) {
      RP2Point<Length, Camera> const& rp2_point = rp2_line[i];
      if (i == 0) {
        new_rp2_line.push_back(rp2_point);
        start_rp2_point = rp2_point;
      } else if (Pow<2>(rp2_point.x() - start_rp2_point->x()) +
                 Pow<2>(rp2_point.y() - start_rp2_point->y()) >
                     focal_plane_tolerance²) {
        // TODO(phl): This creates a segment if the tolerance is exceeded.  It
        // should probably create a segment that stays just below the tolerance.
        new_rp2_line.push_back(rp2_point);
        start_rp2_point = rp2_point;
      } else if (i == rp2_line.size() - 1) {
        new_rp2_line.push_back(rp2_point);
      } else {
        ++skipped;
      }
      ++total;
    }
    new_rp2_lines.push_back(std::move(new_rp2_line));
  }
  LOG(INFO) << "PlotMethod1 skipped " << skipped << " points out of " << total
            << ", emitting " << total - skipped << " points";
  return new_rp2_lines;
}

RP2Lines<Length, Camera> Planetarium::PlotMethod2(
    DiscreteTrajectory<Barycentric>::Iterator const& begin,
    DiscreteTrajectory<Barycentric>::Iterator const& end,
    Instant const& now,
    bool const reverse) const {
  RP2Lines<Length, Camera> lines;
  if (begin == end) {
    return lines;
  }
  auto last = end;
  --last;

  double const tan²_angular_resolution =
      Pow<2>(parameters_.tan_angular_resolution_);
  auto const plottable_spheres = ComputePlottableSpheres(now);
  auto const& trajectory = *begin.trajectory();
  auto const begin_time = std::max(begin.time(), plotting_frame_->t_min());
  auto const last_time = std::min(last.time(), plotting_frame_->t_max());
  auto const final_time = reverse ? begin_time : last_time;
  auto previous_time = reverse ? last_time : begin_time;
  Sign const direction = reverse ? Sign(-1) : Sign(1);
  if (direction * (final_time - previous_time) <= Time{}) {
    return lines;
  }
  RigidMotion<Barycentric, Navigation> to_plotting_frame_at_t =
      plotting_frame_->ToThisFrameAtTime(previous_time);
  DegreesOfFreedom<Navigation> const initial_degrees_of_freedom =
      to_plotting_frame_at_t(
          trajectory.EvaluateDegreesOfFreedom(previous_time));
  Position<Navigation> previous_position =
      initial_degrees_of_freedom.position();
  Velocity<Navigation> previous_velocity =
      initial_degrees_of_freedom.velocity();
  Time Δt = final_time - previous_time;

  Instant t;
  double estimated_tan²_error;
  std::experimental::optional<DegreesOfFreedom<Barycentric>>
      degrees_of_freedom_in_barycentric;
  Position<Navigation> position;

  std::experimental::optional<Position<Navigation>> last_endpoint;

  int steps_accepted = 0;
  int steps_attempted = 0;

  goto estimate_tan²_error;

  while (steps_accepted < max_plot_method_2_steps &&
         direction * (previous_time - final_time) < Time{}) {
    do {
      // One square root because we have squared errors, another one because the
      // errors are quadratic in time (in other words, two square roots because
      // the squared errors are quartic in time).
      // A safety factor prevents catastrophic retries.
      Δt *= 0.9 * Sqrt(Sqrt(tan²_angular_resolution / estimated_tan²_error));
    estimate_tan²_error:
      t = previous_time + Δt;
      if (direction * (t - final_time) > Time{}) {
        t = final_time;
        Δt = t - previous_time;
      }
      Position<Navigation> const extrapolated_position =
          previous_position + previous_velocity * Δt;
      to_plotting_frame_at_t = plotting_frame_->ToThisFrameAtTime(t);
      degrees_of_freedom_in_barycentric =
          trajectory.EvaluateDegreesOfFreedom(t);
      position = to_plotting_frame_at_t.rigid_transformation()(
                     degrees_of_freedom_in_barycentric->position());

      // The quadratic term of the error between the linear interpolation and
      // the actual function is maximized halfway through the segment, so it is
      // 1/2 (Δt/2)² f″(t-Δt) = (1/2 Δt² f″(t-Δt)) / 4; the squared error is
      // thus (1/2 Δt² f″(t-Δt))² / 16.
      estimated_tan²_error =
          perspective_.Tan²AngularDistance(extrapolated_position, position) /
          16;
      ++steps_attempted;
    } while (estimated_tan²_error > tan²_angular_resolution);
    ++steps_accepted;

    // TODO(egg): also limit to field of view.
    auto const segment_behind_focal_plane =
        perspective_.SegmentBehindFocalPlane(
            Segment<Navigation>(previous_position, position));

    previous_time = t;
    previous_position = position;
    previous_velocity =
        to_plotting_frame_at_t(*degrees_of_freedom_in_barycentric).velocity();

    if (!segment_behind_focal_plane) {
      continue;
    }

    auto const visible_segments = perspective_.VisibleSegments(
                                      *segment_behind_focal_plane,
                                      plottable_spheres);
    for (auto const& segment : visible_segments) {
      if (last_endpoint != segment.first) {
        lines.emplace_back();
        lines.back().push_back(perspective_(segment.first));
      }
      lines.back().push_back(perspective_(segment.second));
      last_endpoint = segment.second;
    }
  }
  LOG(INFO) << "PlotMethod2 took " << steps_accepted << " steps, attempted "
            << steps_attempted << " steps";
  return lines;
}

std::vector<Sphere<Navigation>> Planetarium::ComputePlottableSpheres(
    Instant const& now) const {
  RigidMotion<Barycentric, Navigation> const rigid_motion_at_now =
      plotting_frame_->ToThisFrameAtTime(now);
  std::vector<Sphere<Navigation>> plottable_spheres;

  auto const& bodies = ephemeris_->bodies();
  for (auto const body : bodies) {
    auto const trajectory = ephemeris_->trajectory(body);
    Length const mean_radius = body->mean_radius();
    Position<Barycentric> const centre_in_barycentric =
        trajectory->EvaluatePosition(now);
    Sphere<Navigation> plottable_sphere(
        rigid_motion_at_now.rigid_transformation()(centre_in_barycentric),
        parameters_.sphere_radius_multiplier_ * mean_radius);
    // If the sphere is seen under an angle that is very small it doesn't
    // participate in hiding.
    if (perspective_.SphereSin²HalfAngle(plottable_sphere) >
        parameters_.sin²_angular_resolution_) {
      plottable_spheres.emplace_back(std::move(plottable_sphere));
    }
  }
  return plottable_spheres;
}

Segments<Navigation> Planetarium::ComputePlottableSegments(
    const std::vector<Sphere<Navigation>>& plottable_spheres,
    DiscreteTrajectory<Barycentric>::Iterator const& begin,
    DiscreteTrajectory<Barycentric>::Iterator const& end) const {
  Segments<Navigation> all_segments;
  if (begin == end) {
    return all_segments;
  }
  auto it1 = begin;
  Instant t1 = it1.time();
  RigidMotion<Barycentric, Navigation> rigid_motion_at_t1 =
      plotting_frame_->ToThisFrameAtTime(t1);
  Position<Navigation> p1 =
      rigid_motion_at_t1(it1.degrees_of_freedom()).position();

  auto it2 = it1;
  while (++it2 != end) {
    // Processing one segment of the trajectory.
    Instant const t2 = it2.time();

    // Transform the degrees of freedom to the plotting frame.
    RigidMotion<Barycentric, Navigation> const rigid_motion_at_t2 =
        plotting_frame_->ToThisFrameAtTime(t2);
    Position<Navigation> const p2 =
        rigid_motion_at_t2(it2.degrees_of_freedom()).position();

    // Find the part of the segment that is behind the focal plane.  We don't
    // care about things that are in front of the focal plane.
    const Segment<Navigation> segment = {p1, p2};
    auto const segment_behind_focal_plane =
        perspective_.SegmentBehindFocalPlane(segment);
    if (segment_behind_focal_plane) {
      // Find the part(s) of the segment that are not hidden by spheres.  These
      // are the ones we want to plot.
      auto segments = perspective_.VisibleSegments(*segment_behind_focal_plane,
                                                   plottable_spheres);
      std::move(segments.begin(),
                segments.end(),
                std::back_inserter(all_segments));
    }

    it1 = it2;
    t1 = t2;
    rigid_motion_at_t1 = rigid_motion_at_t2;
    p1 = p2;
  }

  return all_segments;
}

}  // namespace internal_planetarium
}  // namespace ksp_plugin
}  // namespace principia
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 University of Szeged. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``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 UNIVERSITY OF SZEGED 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 "config.h"
#include "NumberOfCores.h"

#if OS(DARWIN) || OS(OPENBSD) || OS(NETBSD) || OS(FREEBSD)
#include <sys/param.h>
// sys/types.h must come before sys/sysctl.h because the latter uses
// data types defined in the former. See sysctl(3) and style(9).
#include <sys/types.h>
#include <sys/sysctl.h>
#elif OS(LINUX) || OS(SOLARIS)
#include <unistd.h>
#elif OS(WINDOWS)
#include "wtf/UnusedParam.h"
#if OS(WINDOWS)
#include <windows.h>
#endif
#endif

namespace WTF {

int numberOfProcessorCores()
{
    const int defaultIfUnavailable = 1;
    static int s_numberOfCores = -1;

    if (s_numberOfCores > 0)
        return s_numberOfCores;

#if OS(DARWIN) || OS(OPENBSD) || OS(NETBSD) || OS(FREEBSD)
    unsigned result;
    size_t length = sizeof(result);
    int name[] = {
            CTL_HW,
            HW_NCPU
    };
    int sysctlResult = sysctl(name, sizeof(name) / sizeof(int), &result, &length, 0, 0);

    s_numberOfCores = sysctlResult < 0 ? defaultIfUnavailable : result;
#elif OS(LINUX) || OS(SOLARIS)
    long sysconfResult = sysconf(_SC_NPROCESSORS_ONLN);

    s_numberOfCores = sysconfResult < 0 ? defaultIfUnavailable : static_cast<int>(sysconfResult);
#elif OS(WINDOWS)
    UNUSED_PARAM(defaultIfUnavailable);
    SYSTEM_INFO sysInfo;
    GetSystemInfo(&sysInfo);

    s_numberOfCores = sysInfo.dwNumberOfProcessors;
#else
    s_numberOfCores = defaultIfUnavailable;
#endif
    return s_numberOfCores;
}

}
<commit_msg>wtf: Simplify OS(WINDOWS) check.<commit_after>/*
 * Copyright (C) 2012 University of Szeged. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``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 UNIVERSITY OF SZEGED 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 "config.h"
#include "NumberOfCores.h"

#if OS(DARWIN) || OS(OPENBSD) || OS(NETBSD) || OS(FREEBSD)
#include <sys/param.h>
// sys/types.h must come before sys/sysctl.h because the latter uses
// data types defined in the former. See sysctl(3) and style(9).
#include <sys/types.h>
#include <sys/sysctl.h>
#elif OS(LINUX) || OS(SOLARIS)
#include <unistd.h>
#elif OS(WINDOWS)
#include "wtf/UnusedParam.h"
#include <windows.h>
#endif

namespace WTF {

int numberOfProcessorCores()
{
    const int defaultIfUnavailable = 1;
    static int s_numberOfCores = -1;

    if (s_numberOfCores > 0)
        return s_numberOfCores;

#if OS(DARWIN) || OS(OPENBSD) || OS(NETBSD) || OS(FREEBSD)
    unsigned result;
    size_t length = sizeof(result);
    int name[] = {
            CTL_HW,
            HW_NCPU
    };
    int sysctlResult = sysctl(name, sizeof(name) / sizeof(int), &result, &length, 0, 0);

    s_numberOfCores = sysctlResult < 0 ? defaultIfUnavailable : result;
#elif OS(LINUX) || OS(SOLARIS)
    long sysconfResult = sysconf(_SC_NPROCESSORS_ONLN);

    s_numberOfCores = sysconfResult < 0 ? defaultIfUnavailable : static_cast<int>(sysconfResult);
#elif OS(WINDOWS)
    UNUSED_PARAM(defaultIfUnavailable);
    SYSTEM_INFO sysInfo;
    GetSystemInfo(&sysInfo);

    s_numberOfCores = sysInfo.dwNumberOfProcessors;
#else
    s_numberOfCores = defaultIfUnavailable;
#endif
    return s_numberOfCores;
}

}
<|endoftext|>


<commit_before>

#include "luiRoot.h"
#include "shader.h"

bool LUIRoot::_use_glsl_130 = false;

LUIRoot::LUIRoot(float width, float height) : _requested_focus(NULL) {

  if (lui_cat.is_spam()) {
    lui_cat.spam() << "Constructing new LUIRoot ..\n";
  }
  _root = new LUIObject(NULL, 0.0f, 0.0f, width, height);
  _root->set_root(this);

  _sprites_rendered = 0;
  _frame_count = 0;
  _render_index = 0;

  // Create vertex chunks
  // CPT(GeomVertexFormat) format = GeomVertexFormat::get_v3c4t2();

  PT(GeomVertexArrayFormat) array_format = new GeomVertexArrayFormat();
  array_format->add_column(InternalName::make("vertex"), 3, Geom::NT_stdfloat, Geom::C_point);
  array_format->add_column(InternalName::make("color"), 4, Geom::NT_uint8, Geom::C_color);
  array_format->add_column(InternalName::make("texcoord"), 2, Geom::NT_stdfloat, Geom::C_texcoord);
  array_format->add_column(InternalName::make("texindex"), 1, Geom::NT_uint16, Geom::C_other);

  _sprite_vertex_pointer = NULL;

  PT(GeomVertexFormat) unregistered_format = new GeomVertexFormat();
  unregistered_format->add_array(array_format);

  CPT(GeomVertexFormat) format = GeomVertexFormat::register_format(unregistered_format);

  _index_buffer_size = 1000000;

  _vertex_data = new GeomVertexData("VertexPool", format, Geom::UH_dynamic);
  _vertex_data->reserve_num_rows(_index_buffer_size);

  _triangles = new GeomTriangles(Geom::UH_dynamic);
  _triangles->set_index_type(GeomEnums::NT_uint32);
  _triangles->make_indexed();

  _geom = new Geom(_vertex_data);
  _geom->add_primitive(_triangles);
  _geom->set_bounds(new OmniBoundingVolume());

  _triangle_index_buffer = new LUITriangleIndex[_index_buffer_size];
}

void LUIRoot::prepare_render() {

  if (lui_cat.is_spam()) {
    lui_cat.spam() << "\nPreparing sprite render" << endl;
  }

  PT(GeomVertexArrayDataHandle) array_data_handle = _vertex_data->modify_array(0)->modify_handle();
  _sprite_vertex_pointer = array_data_handle->get_write_pointer();

  _min_rendered_vertex = 999999999;
  _max_rendered_vertex = 0;
  _render_index = 0;
  _frame_count += 1;

  // prepare the geom triangle
  _sprites_rendered = 0;

  _triangles->clear_vertices();
  _triangles->make_indexed();
  _triangles->set_index_type(GeomEnums::NT_uint32);

  // Update lui elements graph
  _root->update_downstream();
  _root->update_dimensions_upstream();
  // for (int i = 0; i < 20; ++i)
    _root->update_upstream();
  _root->update_clip_bounds();

  // Render normal elements
  _root->render_recursive(false, false);

  // Render topmost elements
  int sprites_before = _sprites_rendered;
  _root->render_recursive(true, false);
  int sprites_topmost = _sprites_rendered - sprites_before;

  if (_sprites_rendered > 0) {
    _triangles->modify_vertices()->unclean_set_num_rows(_sprites_rendered * 2 * 3);

    memcpy(_triangles->modify_vertices()->modify_handle()->get_write_pointer(), _triangle_index_buffer, _sprites_rendered * sizeof(LUITriangleIndex) * 2);

    nassertv(_min_rendered_vertex < _max_rendered_vertex);
    _triangles->set_minmax(_min_rendered_vertex, _max_rendered_vertex, NULL, NULL);
  }

  if (lui_cat.is_spam()) {
    lui_cat.spam() << "Rendered " << _triangles->get_num_vertices() << " vertices (" << _sprites_rendered << " Sprites)" << endl;
    lui_cat.spam() << sprites_topmost << " sprites rendered topmost vs " << sprites_before << " normal" << endl;
  }
}

LUIRoot::~LUIRoot() {
  if (lui_cat.is_spam()) {
    lui_cat.spam() << "Destructed LUIRoot\n";
  }

  // Remove all children first
  _root->remove_all_children();
  _sprites.clear();
  _textures.clear();
}

PT(Shader) LUIRoot::create_object_shader() {
  if (_use_glsl_130) {
    return Shader::make(Shader::SL_GLSL,
      // Vertex
      "#version 130\n"
      "uniform mat4 p3d_ModelViewProjectionMatrix;\n"
      "in vec4 p3d_Vertex;\n"
      "in uint texindex;\n"
      "in vec4 color;\n"
      "in vec2 p3d_MultiTexCoord0;\n"
      "out vec2 texcoord;\n"
      "flat out uint vtx_texindex;\n"
      "out vec4 color_scale;\n"
      "void main() {\n"
      "  texcoord = p3d_MultiTexCoord0;\n"
      "  color_scale = color;\n"
      "  vtx_texindex = texindex;\n"
      "  gl_Position = p3d_ModelViewProjectionMatrix * p3d_Vertex;\n"
      "}\n"
      ,
      // Fragment
      "#version 130\n"
      "in vec2 texcoord;\n"
      "flat in uint vtx_texindex;\n"
      "in vec4 color_scale;\n"
      "uniform sampler2D lui_texture_0;\n"
      "uniform sampler2D lui_texture_1;\n"
      "uniform sampler2D lui_texture_2;\n"
      "uniform sampler2D lui_texture_3;\n"
      "uniform sampler2D lui_texture_4;\n"
      "uniform sampler2D lui_texture_5;\n"
      "uniform sampler2D lui_texture_6;\n"
      "uniform sampler2D lui_texture_7;\n"
      "out vec4 color;\n"
      "void main() {\n"
      "  vec4 texcolor = vec4(0,0,0,1);\n"
      "  switch(vtx_texindex) {\n"
      "    case 0u: texcolor = texture(lui_texture_0, texcoord); break;\n"
      "    case 1u: texcolor = texture(lui_texture_1, texcoord); break;\n"
      "    case 2u: texcolor = texture(lui_texture_2, texcoord); break;\n"
      "    case 3u: texcolor = texture(lui_texture_3, texcoord); break;\n"
      "    case 4u: texcolor = texture(lui_texture_4, texcoord); break;\n"
      "    case 5u: texcolor = texture(lui_texture_5, texcoord); break;\n"
      "    case 6u: texcolor = texture(lui_texture_6, texcoord); break;\n"
      "    case 7u: texcolor = texture(lui_texture_7, texcoord); break;\n"
      "  }\n"
      "  color = vec4(texcolor * color_scale);\n"
      "}\n"
      );
  } else {
    return Shader::make(Shader::SL_GLSL,
      // Vertex
      "#version 100\n"
      "uniform mat4 p3d_ModelViewProjectionMatrix;\n"
      "attribute vec4 p3d_Vertex;\n"
      "attribute float texindex;\n"
      "attribute vec4 color;\n"
      "attribute vec2 p3d_MultiTexCoord0;\n"
      "varying vec2 texcoord;\n"
      "varying float vtx_texindex;\n"
      "varying vec4 color_scale;\n"
      "void main() {\n"
      "  texcoord = p3d_MultiTexCoord0;\n"
      "  color_scale = color;\n"
      "  vtx_texindex = texindex;\n"
      "  gl_Position = p3d_ModelViewProjectionMatrix * p3d_Vertex;\n"
      "}\n"
      ,
      // Fragment
      "#version 100\n"
      "precision mediump float;\n"
      "varying vec2 texcoord;\n"
      "varying float vtx_texindex;\n"
      "varying vec4 color_scale;\n"
      "uniform sampler2D lui_texture_0;\n"
      "uniform sampler2D lui_texture_1;\n"
      "uniform sampler2D lui_texture_2;\n"
      "uniform sampler2D lui_texture_3;\n"
      "uniform sampler2D lui_texture_4;\n"
      "uniform sampler2D lui_texture_5;\n"
      "uniform sampler2D lui_texture_6;\n"
      "uniform sampler2D lui_texture_7;\n"
      "void main() {\n"
      "  vec4 texcolor = vec4(0.0, 0.0, 0.0, 1.0);\n"
      // OpenGL ES doesn't have ints unfortunately
      "  #define DO_SWITCH(n) if (vtx_texindex > (n ## .0 - 0.5) && vtx_texindex < (n ## .0 + 0.5)) texcolor = texture2D(lui_texture_ ## n, texcoord);\n"
      "  DO_SWITCH(0)\n"
      "  DO_SWITCH(1)\n"
      "  DO_SWITCH(2)\n"
      "  DO_SWITCH(3)\n"
      "  DO_SWITCH(4)\n"
      "  DO_SWITCH(5)\n"
      "  DO_SWITCH(6)\n"
      "  DO_SWITCH(7)\n"
      "  gl_FragColor = vec4(texcolor * color_scale);\n"
      "}\n"
      );
  }
}
<commit_msg>Fix shader on GLES<commit_after>

#include "luiRoot.h"
#include "shader.h"

bool LUIRoot::_use_glsl_130 = false;

LUIRoot::LUIRoot(float width, float height) : _requested_focus(NULL) {

  if (lui_cat.is_spam()) {
    lui_cat.spam() << "Constructing new LUIRoot ..\n";
  }
  _root = new LUIObject(NULL, 0.0f, 0.0f, width, height);
  _root->set_root(this);

  _sprites_rendered = 0;
  _frame_count = 0;
  _render_index = 0;

  // Create vertex chunks
  // CPT(GeomVertexFormat) format = GeomVertexFormat::get_v3c4t2();

  PT(GeomVertexArrayFormat) array_format = new GeomVertexArrayFormat();
  array_format->add_column(InternalName::make("vertex"), 3, Geom::NT_stdfloat, Geom::C_point);
  array_format->add_column(InternalName::make("color"), 4, Geom::NT_uint8, Geom::C_color);
  array_format->add_column(InternalName::make("texcoord"), 2, Geom::NT_stdfloat, Geom::C_texcoord);
  array_format->add_column(InternalName::make("texindex"), 1, Geom::NT_uint16, Geom::C_other);

  _sprite_vertex_pointer = NULL;

  PT(GeomVertexFormat) unregistered_format = new GeomVertexFormat();
  unregistered_format->add_array(array_format);

  CPT(GeomVertexFormat) format = GeomVertexFormat::register_format(unregistered_format);

  _index_buffer_size = 1000000;

  _vertex_data = new GeomVertexData("VertexPool", format, Geom::UH_dynamic);
  _vertex_data->reserve_num_rows(_index_buffer_size);

  _triangles = new GeomTriangles(Geom::UH_dynamic);
  _triangles->set_index_type(GeomEnums::NT_uint32);
  _triangles->make_indexed();

  _geom = new Geom(_vertex_data);
  _geom->add_primitive(_triangles);
  _geom->set_bounds(new OmniBoundingVolume());

  _triangle_index_buffer = new LUITriangleIndex[_index_buffer_size];
}

void LUIRoot::prepare_render() {

  if (lui_cat.is_spam()) {
    lui_cat.spam() << "\nPreparing sprite render" << endl;
  }

  PT(GeomVertexArrayDataHandle) array_data_handle = _vertex_data->modify_array(0)->modify_handle();
  _sprite_vertex_pointer = array_data_handle->get_write_pointer();

  _min_rendered_vertex = 999999999;
  _max_rendered_vertex = 0;
  _render_index = 0;
  _frame_count += 1;

  // prepare the geom triangle
  _sprites_rendered = 0;

  _triangles->clear_vertices();
  _triangles->make_indexed();
  _triangles->set_index_type(GeomEnums::NT_uint32);

  // Update lui elements graph
  _root->update_downstream();
  _root->update_dimensions_upstream();
  // for (int i = 0; i < 20; ++i)
    _root->update_upstream();
  _root->update_clip_bounds();

  // Render normal elements
  _root->render_recursive(false, false);

  // Render topmost elements
  int sprites_before = _sprites_rendered;
  _root->render_recursive(true, false);
  int sprites_topmost = _sprites_rendered - sprites_before;

  if (_sprites_rendered > 0) {
    _triangles->modify_vertices()->unclean_set_num_rows(_sprites_rendered * 2 * 3);

    memcpy(_triangles->modify_vertices()->modify_handle()->get_write_pointer(), _triangle_index_buffer, _sprites_rendered * sizeof(LUITriangleIndex) * 2);

    nassertv(_min_rendered_vertex < _max_rendered_vertex);
    _triangles->set_minmax(_min_rendered_vertex, _max_rendered_vertex, NULL, NULL);
  }

  if (lui_cat.is_spam()) {
    lui_cat.spam() << "Rendered " << _triangles->get_num_vertices() << " vertices (" << _sprites_rendered << " Sprites)" << endl;
    lui_cat.spam() << sprites_topmost << " sprites rendered topmost vs " << sprites_before << " normal" << endl;
  }
}

LUIRoot::~LUIRoot() {
  if (lui_cat.is_spam()) {
    lui_cat.spam() << "Destructed LUIRoot\n";
  }

  // Remove all children first
  _root->remove_all_children();
  _sprites.clear();
  _textures.clear();
}

PT(Shader) LUIRoot::create_object_shader() {
  if (_use_glsl_130) {
    return Shader::make(Shader::SL_GLSL,
      // Vertex
      "#version 130\n"
      "uniform mat4 p3d_ModelViewProjectionMatrix;\n"
      "in vec4 p3d_Vertex;\n"
      "in uint texindex;\n"
      "in vec4 color;\n"
      "in vec2 p3d_MultiTexCoord0;\n"
      "out vec2 texcoord;\n"
      "flat out uint vtx_texindex;\n"
      "out vec4 color_scale;\n"
      "void main() {\n"
      "  texcoord = p3d_MultiTexCoord0;\n"
      "  color_scale = color;\n"
      "  vtx_texindex = texindex;\n"
      "  gl_Position = p3d_ModelViewProjectionMatrix * p3d_Vertex;\n"
      "}\n"
      ,
      // Fragment
      "#version 130\n"
      "in vec2 texcoord;\n"
      "flat in uint vtx_texindex;\n"
      "in vec4 color_scale;\n"
      "uniform sampler2D lui_texture_0;\n"
      "uniform sampler2D lui_texture_1;\n"
      "uniform sampler2D lui_texture_2;\n"
      "uniform sampler2D lui_texture_3;\n"
      "uniform sampler2D lui_texture_4;\n"
      "uniform sampler2D lui_texture_5;\n"
      "uniform sampler2D lui_texture_6;\n"
      "uniform sampler2D lui_texture_7;\n"
      "out vec4 color;\n"
      "void main() {\n"
      "  vec4 texcolor = vec4(0,0,0,1);\n"
      "  switch(vtx_texindex) {\n"
      "    case 0u: texcolor = texture(lui_texture_0, texcoord); break;\n"
      "    case 1u: texcolor = texture(lui_texture_1, texcoord); break;\n"
      "    case 2u: texcolor = texture(lui_texture_2, texcoord); break;\n"
      "    case 3u: texcolor = texture(lui_texture_3, texcoord); break;\n"
      "    case 4u: texcolor = texture(lui_texture_4, texcoord); break;\n"
      "    case 5u: texcolor = texture(lui_texture_5, texcoord); break;\n"
      "    case 6u: texcolor = texture(lui_texture_6, texcoord); break;\n"
      "    case 7u: texcolor = texture(lui_texture_7, texcoord); break;\n"
      "  }\n"
      "  color = vec4(texcolor * color_scale);\n"
      "}\n"
      );
  } else {
    return Shader::make(Shader::SL_GLSL,
      // Vertex
      "#version 100\n"
      "uniform mat4 p3d_ModelViewProjectionMatrix;\n"
      "attribute vec4 p3d_Vertex;\n"
      "attribute float texindex;\n"
      "attribute vec4 color;\n"
      "attribute vec2 p3d_MultiTexCoord0;\n"
      "varying vec2 texcoord;\n"
      "varying float vtx_texindex;\n"
      "varying vec4 color_scale;\n"
      "void main() {\n"
      "  texcoord = p3d_MultiTexCoord0;\n"
      "  color_scale = color;\n"
      "  vtx_texindex = texindex;\n"
      "  gl_Position = p3d_ModelViewProjectionMatrix * p3d_Vertex;\n"
      "}\n"
      ,
      // Fragment
      "#version 100\n"
      "precision mediump float;\n"
      "varying vec2 texcoord;\n"
      "varying float vtx_texindex;\n"
      "varying vec4 color_scale;\n"
      "uniform sampler2D lui_texture_0;\n"
      "uniform sampler2D lui_texture_1;\n"
      "uniform sampler2D lui_texture_2;\n"
      "uniform sampler2D lui_texture_3;\n"
      "uniform sampler2D lui_texture_4;\n"
      "uniform sampler2D lui_texture_5;\n"
      "uniform sampler2D lui_texture_6;\n"
      "uniform sampler2D lui_texture_7;\n"
      "void main() {\n"
      "  vec4 texcolor = vec4(0.1, 0.0, 0.0, 1.0);\n"

      // We can't even properly use defines with the GLES compiler .. that sucks
      "  if (vtx_texindex > -0.5 && vtx_texindex < 0.5) texcolor = texture2D(lui_texture_0, texcoord); \n"
      "  if (vtx_texindex >  0.5 && vtx_texindex < 1.5) texcolor = texture2D(lui_texture_1, texcoord); \n"
      "  if (vtx_texindex >  1.5 && vtx_texindex < 2.5) texcolor = texture2D(lui_texture_2, texcoord); \n"
      "  if (vtx_texindex >  2.5 && vtx_texindex < 3.5) texcolor = texture2D(lui_texture_3, texcoord); \n"
      "  if (vtx_texindex >  3.5 && vtx_texindex < 4.5) texcolor = texture2D(lui_texture_4, texcoord); \n"
      "  if (vtx_texindex >  4.5 && vtx_texindex < 5.5) texcolor = texture2D(lui_texture_5, texcoord); \n"
      "  if (vtx_texindex >  5.5 && vtx_texindex < 6.5) texcolor = texture2D(lui_texture_6, texcoord); \n"
      "  if (vtx_texindex >  6.5 && vtx_texindex < 7.5) texcolor = texture2D(lui_texture_7, texcoord); \n"

      "  gl_FragColor = vec4(texcolor * color_scale);\n"
      "}\n"
      );
  }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: GraphicViewShell.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 05:06:21 $
 *
 *  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
 *
 ************************************************************************/

#ifndef SD_GRAPHIC_VIEW_SHELL_HXX
#define SD_GRAPHIC_VIEW_SHELL_HXX

#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif

class Window;

namespace sd {

/** View shell of the Draw application.

This class is an example of how not to do it: specialization by
    inheritance.  A graphic view shell is similar to a draw view shell
    but lacks some of its features.  Thus is should be at most a base
    class of DrawViewShell.  There even is special case code in
    ViewShell that turns off some of the features for GraphicViewShell
    instances.

*/
class GraphicViewShell
    : public DrawViewShell
{
public:
    TYPEINFO();

    SFX_DECL_VIEWFACTORY(GraphicViewShell);
    SFX_DECL_INTERFACE(SD_IF_SDGRAPHICVIEWSHELL);

    GraphicViewShell (
        SfxViewFrame* pFrame,
        ::Window* pParentWindow,
        const DrawViewShell& rShell);

    /** Create a new view shell for the Draw application.
        @param rViewShellBase
            The new object will be stacked on this view shell base.
        @param pFrameView
            The frame view that makes it possible to pass information from
            one view shell to the next.
    */
    GraphicViewShell (
        SfxViewFrame* pFrame,
        ViewShellBase& rViewShellBase,
        ::Window* pParentWindow,
        FrameView* pFrameView = NULL);

    virtual ~GraphicViewShell (void);

    /** This method is overloaded in order to have the layer mode allways
        active.
    */
    virtual void ChangeEditMode (EditMode eMode, bool bIsLayerModeActive);

protected:
    void Construct (void);
    virtual void ArrangeGUIElements (void);

private:
    DECL_LINK(TabBarSplitHandler, TabBar*);
};

} // end of namespace sd

#endif
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.4.314); FILE MERGED 2006/11/27 13:48:06 cl 1.4.314.2: #i69285# warning free code changes for sd project 2006/11/22 12:42:01 cl 1.4.314.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: GraphicViewShell.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 17:34:31 $
 *
 *  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
 *
 ************************************************************************/

#ifndef SD_GRAPHIC_VIEW_SHELL_HXX
#define SD_GRAPHIC_VIEW_SHELL_HXX

#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif

class Window;

namespace sd {

/** View shell of the Draw application.

This class is an example of how not to do it: specialization by
    inheritance.  A graphic view shell is similar to a draw view shell
    but lacks some of its features.  Thus is should be at most a base
    class of DrawViewShell.  There even is special case code in
    ViewShell that turns off some of the features for GraphicViewShell
    instances.

*/
class GraphicViewShell
    : public DrawViewShell
{
public:
    TYPEINFO();

    SFX_DECL_VIEWFACTORY(GraphicViewShell);
    SFX_DECL_INTERFACE(SD_IF_SDGRAPHICVIEWSHELL)

    GraphicViewShell (
        SfxViewFrame* pFrame,
        ::Window* pParentWindow,
        const DrawViewShell& rShell);

    /** Create a new view shell for the Draw application.
        @param rViewShellBase
            The new object will be stacked on this view shell base.
        @param pFrameView
            The frame view that makes it possible to pass information from
            one view shell to the next.
    */
    GraphicViewShell (
        SfxViewFrame* pFrame,
        ViewShellBase& rViewShellBase,
        ::Window* pParentWindow,
        FrameView* pFrameView = NULL);

    virtual ~GraphicViewShell (void);

    /** This method is overloaded in order to have the layer mode allways
        active.
    */
    virtual void ChangeEditMode (EditMode eMode, bool bIsLayerModeActive);

protected:
    void ConstructGraphicViewShell (void);
    virtual void ArrangeGUIElements (void);

private:
    DECL_LINK(TabBarSplitHandler, TabBar*);
};

} // end of namespace sd

#endif
<|endoftext|>


<commit_before>#include <CoreAudio/CoreAudio.h>
#include "StudioLink.h"
#include "EnumBuiltinDevices.h"

#define PRECONDITION_RETURN(a, b) if(!(a)) { return (b); }

bool EnumBuiltinDevices_osx(const STUDIO_LINK_DEVICE_TYPE deviceType, STUDIO_LINK_DEVICE_LIST* devices)
{
    PRECONDITION_RETURN(deviceType != INVALID_DEVICE_TYPE, false);
    PRECONDITION_RETURN(devices != 0, false);

    bool result = false;

    AudioObjectPropertyScope scope = kAudioObjectPropertyScopeGlobal;
    if(deviceType == MICROPHONE)
    {
        scope = kAudioObjectPropertyScopeInput;
    }
    else
    {
        scope = kAudioObjectPropertyScopeOutput;
    }

    AudioObjectPropertyAddress propertyAddress = {
        kAudioHardwarePropertyDevices,
        scope,
        kAudioObjectPropertyElementMaster
    };

    UInt32 dataSize = 0;
    OSStatus status = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject,
                                                     &propertyAddress,
                                                     0, NULL, &dataSize);
    if(kAudioHardwareNoError == status)
    {
        size_t deviceIdCount = dataSize / sizeof(AudioDeviceID);
        AudioDeviceID deviceIds[deviceIdCount];
        status = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &dataSize, deviceIds);
        if(kAudioHardwareNoError == status)
        {
            size_t foundDevices = 0;
            for(UInt32 i = 0; (i < deviceIdCount) && (foundDevices < deviceIdCount); i++)
            {
                dataSize = 0;
                propertyAddress.mScope = scope,
                propertyAddress.mSelector = kAudioDevicePropertyStreams;
                status = AudioObjectGetPropertyDataSize(deviceIds[i],
                                                        &propertyAddress,
                                                        0,
                                                        0,
                                                        &dataSize);
                if(kAudioHardwareNoError == status)
                {
                    const size_t streamIdCount = dataSize / sizeof(AudioStreamID);
                    if(streamIdCount > 0)
                    {
                        AudioStreamID streamIds[streamIdCount];
                        status = AudioObjectGetPropertyData(deviceIds[i],
                                                            &propertyAddress,
                                                            0,
                                                            0,
                                                            &dataSize,
                                                            &streamIds);
                        if(kAudioHardwareNoError == status)
                        {
                        // FIXME: handle multiple streams
                            AudioStreamID streamId = streamIds[0];
                            AudioStreamBasicDescription description = {0};
                            dataSize = sizeof(AudioStreamBasicDescription);
                            propertyAddress.mSelector = kAudioStreamPropertyVirtualFormat;
                            status = AudioObjectGetPropertyData(streamId,
                                                                &propertyAddress,
                                                                0,
                                                                0,
                                                                &dataSize,
                                                                &description);
                            if(kAudioHardwareNoError == status)
                            {
                                devices->devices[foundDevices].sampleRate = static_cast<double>(description.mSampleRate);
                                devices->devices[foundDevices].channelCount = static_cast<uint32_t>(description.mChannelsPerFrame);

                                CFStringRef deviceName = 0;
                                dataSize = sizeof(deviceName);
                                propertyAddress.mSelector = kAudioDevicePropertyDeviceNameCFString;
                                status = AudioObjectGetPropertyData(deviceIds[i],
                                                                    &propertyAddress,
                                                                    0, NULL, &dataSize, &deviceName);
                                if(kAudioHardwareNoError == status)
                                {
                                    memset(devices->devices[foundDevices].name, 0, STUDIO_LINK_DEVICE_NAME_LENGTH * sizeof(char));
                                    strcpy(devices->devices[foundDevices].name, CFStringGetCStringPtr(deviceName, kCFStringEncodingUTF8));
                                    CFRelease(deviceName);
                                }
                            }

                            foundDevices++;
                        }
                    }
                }
            }

            devices->deviceCount = foundDevices;
        }
    }

    if(devices->deviceCount > 0)
    {
        result = true;
    }

    return result;
}

<commit_msg>fixed crash on empty device name<commit_after>#include <CoreAudio/CoreAudio.h>
#include "StudioLink.h"
#include "EnumBuiltinDevices.h"

#define PRECONDITION_RETURN(a, b) if(!(a)) { return (b); }

bool EnumBuiltinDevices_osx(const STUDIO_LINK_DEVICE_TYPE deviceType, STUDIO_LINK_DEVICE_LIST* devices)
{
    PRECONDITION_RETURN(deviceType != INVALID_DEVICE_TYPE, false);
    PRECONDITION_RETURN(devices != 0, false);

    bool result = false;

    AudioObjectPropertyScope scope = kAudioObjectPropertyScopeGlobal;
    if(deviceType == MICROPHONE)
    {
        scope = kAudioObjectPropertyScopeInput;
    }
    else
    {
        scope = kAudioObjectPropertyScopeOutput;
    }

    AudioObjectPropertyAddress propertyAddress = {
        kAudioHardwarePropertyDevices,
        scope,
        kAudioObjectPropertyElementMaster
    };

    UInt32 dataSize = 0;
    OSStatus status = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject,
                                                     &propertyAddress,
                                                     0, NULL, &dataSize);
    if(kAudioHardwareNoError == status)
    {
        size_t deviceIdCount = dataSize / sizeof(AudioDeviceID);
        AudioDeviceID deviceIds[deviceIdCount];
        status = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &dataSize, deviceIds);
        if(kAudioHardwareNoError == status)
        {
            size_t foundDevices = 0;
            for(UInt32 i = 0; (i < deviceIdCount) && (foundDevices < deviceIdCount); i++)
            {
                dataSize = 0;
                propertyAddress.mScope = scope,
                propertyAddress.mSelector = kAudioDevicePropertyStreams;
                status = AudioObjectGetPropertyDataSize(deviceIds[i],
                                                        &propertyAddress,
                                                        0,
                                                        0,
                                                        &dataSize);
                if(kAudioHardwareNoError == status)
                {
                    const size_t streamIdCount = dataSize / sizeof(AudioStreamID);
                    if(streamIdCount > 0)
                    {
                        AudioStreamID streamIds[streamIdCount];
                        status = AudioObjectGetPropertyData(deviceIds[i],
                                                            &propertyAddress,
                                                            0,
                                                            0,
                                                            &dataSize,
                                                            &streamIds);
                        if(kAudioHardwareNoError == status)
                        {
                        // FIXME: handle multiple streams
                            AudioStreamID streamId = streamIds[0];
                            AudioStreamBasicDescription description = {0};
                            dataSize = sizeof(AudioStreamBasicDescription);
                            propertyAddress.mSelector = kAudioStreamPropertyVirtualFormat;
                            status = AudioObjectGetPropertyData(streamId,
                                                                &propertyAddress,
                                                                0,
                                                                0,
                                                                &dataSize,
                                                                &description);
                            if(kAudioHardwareNoError == status)
                            {
                                CFStringRef deviceName = 0;
                                dataSize = sizeof(deviceName);
                                propertyAddress.mSelector = kAudioDevicePropertyDeviceNameCFString;
                                status = AudioObjectGetPropertyData(deviceIds[i],
                                                                    &propertyAddress,
                                                                    0, NULL, &dataSize, &deviceName);
                                if(kAudioHardwareNoError == status)
                                {
                                    if(CFStringGetLength(deviceName) > 0)
                                    {
                                        memset(devices->devices[foundDevices].name, 0, STUDIO_LINK_DEVICE_NAME_LENGTH * sizeof(char));
                                        strcpy(devices->devices[foundDevices].name, CFStringGetCStringPtr(deviceName, kCFStringEncodingUTF8));

                                        devices->devices[foundDevices].sampleRate = static_cast<double>(description.mSampleRate);
                                        devices->devices[foundDevices].channelCount = static_cast<uint32_t>(description.mChannelsPerFrame);

                                        foundDevices++;
                                    }

                                    CFRelease(deviceName);
                                }
                            }

                        }
                    }
                }
            }

            devices->deviceCount = foundDevices;
        }
    }

    if(devices->deviceCount > 0)
    {
        result = true;
    }

    return result;
}

<|endoftext|>