<commit_before>/* This file is part of Ingen.
 * Copyright (C) 2007-2009 David Robillard <http://drobilla.net>
 *
 * Ingen is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * Ingen 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 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.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "raul/log.hpp"

#include "lv2/lv2plug.in/ns/ext/atom/atom.h"
#include "lv2/lv2plug.in/ns/ext/event/event.h"
#include "lv2/lv2plug.in/ns/ext/event/event-helpers.h"

#include "shared/LV2Atom.hpp"
#include "shared/LV2URIMap.hpp"

#include "NodeModel.hpp"
#include "PluginUI.hpp"
#include "PortModel.hpp"

using namespace std;
using namespace Raul;

namespace Ingen {
namespace Client {

SLV2UIHost PluginUI::ui_host = NULL;

static void
lv2_ui_write(LV2UI_Controller controller,
             uint32_t         port_index,
             uint32_t         buffer_size,
             uint32_t         format,
             const void*      buffer)
{
	PluginUI* const ui = (PluginUI*)controller;

	const NodeModel::Ports& ports = ui->node()->ports();
	if (port_index >= ports.size()) {
		error << "UI for " << ui->node()->plugin()->uri()
		      << " tried to write to non-existent port " << port_index << endl;
		return;
	}

	SharedPtr<PortModel> port = ports[port_index];

	const Shared::LV2URIMap& uris = *ui->world()->uris().get();

	// float (special case, always 0)
	if (format == 0) {
		assert(buffer_size == 4);
		if (*(float*)buffer == port->value().get_float())
			return; // do nothing (handle stupid plugin UIs that feed back)

		ui->world()->engine()->set_property(port->path(),
		                                    uris.ingen_value,
		                                    Atom(*(float*)buffer));

	} else if (format == uris.ui_Events.id) {
		LV2_Event_Buffer*  buf = (LV2_Event_Buffer*)buffer;
		LV2_Event_Iterator iter;
		uint8_t*           data;
		lv2_event_begin(&iter, buf);
		while (lv2_event_is_valid(&iter)) {
			LV2_Event* const ev = lv2_event_get(&iter, &data);
			std::pair<bool, uint16_t> midi_id =
			  uris.global_to_event(uris.midi_MidiEvent.id);
			if (midi_id.first && ev->type == midi_id.second) {
				// FIXME: bundle multiple events by writing an entire buffer here
				ui->world()->engine()->set_property(
					port->path(),
					uris.ingen_value,
					Atom("http://lv2plug.in/ns/ext/midi#MidiEvent", ev->size, data));
			} else {
				warn << "Unable to serialise UI event type " << ev->type
				     << ", event lost" << endl;
			}

			lv2_event_increment(&iter);
		}

	} else if (format == uris.atom_AtomTransfer.id) {
		LV2_Atom* buf = (LV2_Atom*)buffer;
		Raul::Atom val;
		Shared::LV2Atom::to_atom(uris, buf, val);
		ui->world()->engine()->set_property(port->path(), uris.ingen_value, val);

	} else {
		warn << "Unknown value format " << format
		     << " from LV2 UI " << ui->node()->plugin()->uri() << endl;
	}
}

PluginUI::PluginUI(Ingen::Shared::World* world,
                   SharedPtr<NodeModel>  node)
	: _world(world)
	, _node(node)
	, _instance(NULL)
{
}

PluginUI::~PluginUI()
{
	slv2_ui_instance_free(_instance);
}

SharedPtr<PluginUI>
PluginUI::create(Ingen::Shared::World* world,
                 SharedPtr<NodeModel>  node,
                 SLV2Plugin            plugin)
{
	if (!PluginUI::ui_host) {
		PluginUI::ui_host = slv2_ui_host_new(lv2_ui_write, NULL, NULL, NULL);
	}

	SLV2Value gtk_ui = slv2_value_new_uri(
		world->slv2_world(), "http://lv2plug.in/ns/extensions/ui#GtkUI");

	SLV2UI ui = slv2_plugin_get_default_ui(plugin, gtk_ui);

	slv2_value_free(gtk_ui);

	if (!ui) {
		return SharedPtr<PluginUI>();
	}

	SharedPtr<PluginUI> ret(new PluginUI(world, node));
	ret->_features = world->lv2_features()->lv2_features(world, node.get());

	SLV2UIInstance instance = slv2_ui_instance_new(
		plugin,
		ui,
		gtk_ui,
		ui_host,
		ret.get(),
		ret->_features->array());

	if (instance) {
		ret->_instance = instance;
	} else {
		error << "Failed to instantiate LV2 UI" << endl;
		ret.reset();
	}

	return ret;
}

LV2UI_Widget
PluginUI::get_widget()
{
	return (LV2UI_Widget*)slv2_ui_instance_get_widget(_instance);
}

void
PluginUI::port_event(uint32_t    port_index,
                     uint32_t    buffer_size,
                     uint32_t    format,
                     const void* buffer)
{
	slv2_ui_instance_port_event(
		_instance, port_index, buffer_size, format, buffer);
}

} // namespace Client
} // namespace Ingen
<commit_msg>Fix LV2 plugin UIs (broken in r3093).<commit_after>/* This file is part of Ingen.
 * Copyright (C) 2007-2009 David Robillard <http://drobilla.net>
 *
 * Ingen is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * Ingen 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 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.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "raul/log.hpp"

#include "lv2/lv2plug.in/ns/ext/atom/atom.h"
#include "lv2/lv2plug.in/ns/ext/event/event.h"
#include "lv2/lv2plug.in/ns/ext/event/event-helpers.h"

#include "shared/LV2Atom.hpp"
#include "shared/LV2URIMap.hpp"

#include "NodeModel.hpp"
#include "PluginUI.hpp"
#include "PortModel.hpp"

using namespace std;
using namespace Raul;

namespace Ingen {
namespace Client {

SLV2UIHost PluginUI::ui_host = NULL;

static void
lv2_ui_write(LV2UI_Controller controller,
             uint32_t         port_index,
             uint32_t         buffer_size,
             uint32_t         format,
             const void*      buffer)
{
	PluginUI* const ui = (PluginUI*)controller;

	const NodeModel::Ports& ports = ui->node()->ports();
	if (port_index >= ports.size()) {
		error << "UI for " << ui->node()->plugin()->uri()
		      << " tried to write to non-existent port " << port_index << endl;
		return;
	}

	SharedPtr<PortModel> port = ports[port_index];

	const Shared::LV2URIMap& uris = *ui->world()->uris().get();

	// float (special case, always 0)
	if (format == 0) {
		assert(buffer_size == 4);
		if (*(float*)buffer == port->value().get_float())
			return; // do nothing (handle stupid plugin UIs that feed back)

		ui->world()->engine()->set_property(port->path(),
		                                    uris.ingen_value,
		                                    Atom(*(float*)buffer));

	} else if (format == uris.ui_Events.id) {
		LV2_Event_Buffer*  buf = (LV2_Event_Buffer*)buffer;
		LV2_Event_Iterator iter;
		uint8_t*           data;
		lv2_event_begin(&iter, buf);
		while (lv2_event_is_valid(&iter)) {
			LV2_Event* const ev = lv2_event_get(&iter, &data);
			std::pair<bool, uint16_t> midi_id =
			  uris.global_to_event(uris.midi_MidiEvent.id);
			if (midi_id.first && ev->type == midi_id.second) {
				// FIXME: bundle multiple events by writing an entire buffer here
				ui->world()->engine()->set_property(
					port->path(),
					uris.ingen_value,
					Atom("http://lv2plug.in/ns/ext/midi#MidiEvent", ev->size, data));
			} else {
				warn << "Unable to serialise UI event type " << ev->type
				     << ", event lost" << endl;
			}

			lv2_event_increment(&iter);
		}

	} else if (format == uris.atom_AtomTransfer.id) {
		LV2_Atom* buf = (LV2_Atom*)buffer;
		Raul::Atom val;
		Shared::LV2Atom::to_atom(uris, buf, val);
		ui->world()->engine()->set_property(port->path(), uris.ingen_value, val);

	} else {
		warn << "Unknown value format " << format
		     << " from LV2 UI " << ui->node()->plugin()->uri() << endl;
	}
}

PluginUI::PluginUI(Ingen::Shared::World* world,
                   SharedPtr<NodeModel>  node)
	: _world(world)
	, _node(node)
	, _instance(NULL)
{
}

PluginUI::~PluginUI()
{
	slv2_ui_instance_free(_instance);
}

SharedPtr<PluginUI>
PluginUI::create(Ingen::Shared::World* world,
                 SharedPtr<NodeModel>  node,
                 SLV2Plugin            plugin)
{
	if (!PluginUI::ui_host) {
		PluginUI::ui_host = slv2_ui_host_new(lv2_ui_write, NULL, NULL, NULL);
	}

	SLV2Value gtk_ui = slv2_value_new_uri(
		world->slv2_world(), "http://lv2plug.in/ns/extensions/ui#GtkUI");

	SLV2UI ui = slv2_plugin_get_default_ui(plugin, gtk_ui);

	if (!ui) {
		slv2_value_free(gtk_ui);
		return SharedPtr<PluginUI>();
	}

	SharedPtr<PluginUI> ret(new PluginUI(world, node));
	ret->_features = world->lv2_features()->lv2_features(world, node.get());

	SLV2UIInstance instance = slv2_ui_instance_new(
		plugin,
		ui,
		gtk_ui,
		ui_host,
		ret.get(),
		ret->_features->array());

	slv2_value_free(gtk_ui);

	if (instance) {
		ret->_instance = instance;
	} else {
		error << "Failed to instantiate LV2 UI" << endl;
		ret.reset();
	}

	return ret;
}

LV2UI_Widget
PluginUI::get_widget()
{
	return (LV2UI_Widget*)slv2_ui_instance_get_widget(_instance);
}

void
PluginUI::port_event(uint32_t    port_index,
                     uint32_t    buffer_size,
                     uint32_t    format,
                     const void* buffer)
{
	slv2_ui_instance_port_event(
		_instance, port_index, buffer_size, format, buffer);
}

} // namespace Client
} // namespace Ingen
<|endoftext|>


<commit_before>#include "Renderer.hpp"

#include "Window.hpp"
#include <SDL2/SDL.h>
#include <SDL_image.h>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <iostream>

using std::unordered_map;
namespace fs=boost::filesystem;

Renderer::Renderer(Window* window)
    : m_renderer(nullptr),
      m_window(window),
      m_textures(),
      m_texture_dir(fs::path("resources")/"textures")
{
    m_renderer = SDL_CreateRenderer(window->m_window, -1, SDL_RENDERER_ACCELERATED);
    loadAllTextures();
}

Renderer::~Renderer()
{
    for (auto& entry : m_textures) {
        if (entry.second) {
            SDL_DestroyTexture(entry.second);
            entry.second = nullptr;
        }
    }
    if(m_renderer)
        SDL_DestroyRenderer(m_renderer);
    m_renderer = nullptr;
}

void Renderer::loadAllTextures()
{
    if (!fs::exists(m_texture_dir) || ! fs::is_directory(m_texture_dir)) {
        throw std::runtime_error("Invalid texture directory");
    }
    for (auto iter = fs::recursive_directory_iterator(m_texture_dir);
            iter != fs::recursive_directory_iterator(); iter++) {
        if (fs::is_regular_file(iter->path())) {
            loadTexture(iter->path());
        }
    }
}

void Renderer::loadTexture(const fs::path& path)
{
    SDL_Surface* surf = IMG_Load(path.c_str());
    if (!surf) {
        std::cerr << "Error loading texture " << path << std::endl;
        return;
    }
    SDL_Texture* tex  = SDL_CreateTextureFromSurface(m_renderer, surf);
    SDL_FreeSurface(surf);
    surf = nullptr;
    if (!tex) {
        std::cerr << "Error loading texture " << path << std::endl;
        return;
    }
    std::cout << "Loaded texture " << path.relative_path().c_str() << std::endl;
    m_textures[path.relative_path().c_str()] = tex;
}

void Renderer::renderScene()
{
    //SDL_Rect viewport;
    //viewport.x=200;
    //viewport.y=200;
    //viewport.w=900;
    //viewport.h=400;
    //SDL_RenderSetViewport(m_renderer, &viewport);
    //SDL_RenderCopy(m_renderer, m_textures["foo.png"], nullptr, nullptr);
}
<commit_msg>Texture path fixes<commit_after>#include "Renderer.hpp"

#include "Window.hpp"
#include <SDL2/SDL.h>
#include <SDL_image.h>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <iostream>

using std::unordered_map;
namespace fs=boost::filesystem;

Renderer::Renderer(Window* window)
    : m_renderer(nullptr),
      m_window(window),
      m_textures(),
      m_texture_dir(fs::path("resources")/"textures")
{
    m_renderer = SDL_CreateRenderer(window->m_window, -1, SDL_RENDERER_ACCELERATED);
    loadAllTextures();
}

Renderer::~Renderer()
{
    for (auto& entry : m_textures) {
        if (entry.second) {
            SDL_DestroyTexture(entry.second);
            entry.second = nullptr;
        }
    }
    if(m_renderer)
        SDL_DestroyRenderer(m_renderer);
    m_renderer = nullptr;
}

void Renderer::loadAllTextures()
{
    if (!fs::exists(m_texture_dir) || ! fs::is_directory(m_texture_dir)) {
        throw std::runtime_error("Invalid texture directory");
    }
    for (auto iter = fs::recursive_directory_iterator(m_texture_dir);
            iter != fs::recursive_directory_iterator(); iter++) {
        if (!fs::is_directory(iter->path())) {
            loadTexture(iter->path());
        }
    }
}

void Renderer::loadTexture(const fs::path& path)
{
    SDL_Surface* surf = IMG_Load(path.c_str());
    if (!surf) {
        std::cerr << "Error loading texture " << path << std::endl;
        return;
    }
    SDL_Texture* tex  = SDL_CreateTextureFromSurface(m_renderer, surf);
    SDL_FreeSurface(surf);
    surf = nullptr;
    if (!tex) {
        std::cerr << "Error loading texture " << path << std::endl;
        return;
    }
    string basepath = m_texture_dir.c_str();
    string name = path.parent_path().c_str();
    name.erase(0, basepath.length());
    if (name[0] == '/')
        name.erase(0, 1);
    name.append(path.stem().c_str());

    std::cout << "Loaded texture " << name << std::endl;
    m_textures[name] = tex;
}

void Renderer::renderScene()
{
    //SDL_Rect viewport;
    //viewport.x=200;
    //viewport.y=200;
    //viewport.w=900;
    //viewport.h=400;
    //SDL_RenderSetViewport(m_renderer, &viewport);
    SDL_RenderCopy(m_renderer, m_textures["foo"], nullptr, nullptr);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: invalidatetree.cxx,v $
 * $Revision: 1.23 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "cachecontroller.hxx"
#include "change.hxx"
#include "valuenode.hxx"
#include "updatehelper.hxx"
#include "treeactions.hxx"
#include "treeaccessor.hxx"
#include "tracer.hxx"
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/container/NoSuchElementException.hpp>
#include <vos/thread.hxx>

#ifndef INCLUDED_ALGORITHM
#include <algorithm>
#define INCLUDED_ALGORITHM
#endif

namespace configmgr
{

    using namespace com::sun::star::uno;
    using namespace configuration;
    namespace container = com::sun::star::container;
// -----------------------------------------------------------------------------
// ------------------------------- invalidateTree -------------------------------
// -----------------------------------------------------------------------------

namespace backend
{
// -----------------------------------------------------------------------------
std::auto_ptr<SubtreeChange> createDiffs(data::NodeAccess const& _aCachedNode,
                                            ISubtree const * _pLoadedSubtree,
                                            AbsolutePath const& _aAbsoluteSubtreePath)
{
    OSL_PRECOND(_aCachedNode.isValid(), "Need an existing node to create a diff");
    OSL_PRECOND(_pLoadedSubtree != 0, "Need a result node to create a diff");
    // Create a TreeChangeList with the right name, parentname and ConfigurationProperties
    std::auto_ptr<SubtreeChange> aNewChange(new SubtreeChange(_aAbsoluteSubtreePath.getLocalName().getName().toString(),
                                                                node::Attributes()) );

    if (!createUpdateFromDifference(*aNewChange, _aCachedNode, *_pLoadedSubtree))
        aNewChange.reset();

    return aNewChange;
}
// -----------------------------------------------------------------------------
#if 0
std::auto_ptr<ISubtree> TreeManager::loadNodeFromSession( AbsolutePath const& _aAbsoluteSubtreePath,
                                                     const vos::ORef < OOptions >& _xOptions,
                                                     sal_Int16 _nMinLevels)  CFG_UNO_THROW_ALL()
{
    TreeInfo* pInfo = this->requestTreeInfo(_xOptions,true /*create TreeInfo*/);

    CFG_TRACE_INFO_NI("cache manager: cache miss. going to load the node");
    rtl::Reference< OTreeLoader > xLoader = pInfo->getNewLoaderWithoutPending(_aAbsoluteSubtreePath, _nMinLevels, _xOptions, m_xBackend.get());

    OSL_ENSURE(xLoader.is(), "Did not receive a loader for retrieving the node");
    CFG_TRACE_INFO_NI("cache manager: cache miss. going to load the node");
    if (!xLoader.is())
        throw container::NoSuchElementException((::rtl::OUString::createFromAscii("Error while retrieving the node")), NULL);

    // now block for reading
    std::auto_ptr<ISubtree> pResponse;
    try
    {
        pResponse = xLoader->waitToResponse();
    }
    catch (uno::Exception& e)
    {
        pInfo->releaseLoader(xLoader);
        throw;
    }

    pInfo->releaseLoader(xLoader);

    return pResponse;
}
#endif
// -----------------------------------------------------------------------------

class OInvalidateTreeThread: public vos::OThread
{
    typedef backend::ICachedDataProvider CacheManager;
    typedef rtl::Reference< CacheManager > CacheManagerRef;
    CacheManagerRef     m_rTreeManager;
    Name                m_aComponentName;
    RequestOptions      m_aOptions;

public:
    OInvalidateTreeThread(CacheManager* _rTreeManager,
                          Name const & _aComponentName,
                          const RequestOptions& _aOptions)
    : m_rTreeManager(_rTreeManager)
    , m_aComponentName(_aComponentName)
    , m_aOptions(_aOptions)
    {}

    ~OInvalidateTreeThread()
    {}

private:
    virtual void SAL_CALL onTerminated()
    {
        delete this;
    }

    virtual void SAL_CALL run();
};

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

void CacheController::invalidateComponent(ComponentRequest const & _aComponent) CFG_UNO_THROW_ALL(  )
{
    if (!this->m_bDisposing)
    {
        // start the InvalidateTreeThread only, if we are not at disposemode
        if (OInvalidateTreeThread *pThread =
            new OInvalidateTreeThread(this, _aComponent.getComponentName(), _aComponent.getOptions()))
        {
            pThread->create();
        }
        else
            OSL_ENSURE(false, "Could not create refresher thread");
    }

}

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

CacheLocation CacheController::refreshComponent(ComponentRequest const & _aRequest) CFG_UNO_THROW_ALL()
{
    if (m_bDisposing) return NULL;

    CacheRef aCache = this->getCacheAlways(_aRequest.getOptions());

    if (!aCache.is()) return NULL;

    // load the Node direct from the session, without using the cache
    ComponentRequest aForcedRequest(_aRequest);
    aForcedRequest.forceReload();

    ComponentResult aLoadedInstance = this->getComponentData(aForcedRequest,false);
    AbsolutePath aRequestPath = AbsolutePath::makeModulePath(_aRequest.getComponentName(), AbsolutePath::NoValidate());
    NodeInstance aNodeInstance(aLoadedInstance.mutableInstance().mutableData(),aRequestPath) ;
    NodeResult aLoadedNodeInstance(aNodeInstance) ;

    data::TreeAddress aResult = NULL;
    if (aLoadedNodeInstance.is())
    {
        Name aModuleName = aLoadedNodeInstance->root().getModuleName();

        bool bAcquired = aCache->acquireModule(aModuleName);
        aResult = CacheLocation( aCache->getTreeAddress(aModuleName) );

        if (bAcquired)
        try
    {
            std::auto_ptr<SubtreeChange> aTreeChanges;
            data::NodeAddress aRootAddress;

            {
                data::TreeAccessor aTreeAccess(aResult);
                data::NodeAccess aRootNode = aTreeAccess.getRootNode();

                aTreeChanges = createDiffs(aRootNode, aLoadedNodeInstance->data().get(), aLoadedNodeInstance->root().location());
                aRootAddress = aRootNode;
            }

            if (aTreeChanges.get() != NULL)
            {
        // change all Values... found in the Subtree in the CacheTree
        applyUpdateWithAdjustmentToTree(*aTreeChanges, aRootAddress);

                UpdateRequest anUpdateReq(  aTreeChanges.get(),
                                            aLoadedNodeInstance->root().location(),
                                            _aRequest.getOptions()
                                          );

                m_aNotifier.notifyChanged(anUpdateReq);
            }
        aCache->releaseModule(aModuleName);
        }
        catch (...)
        {
        aCache->releaseModule(aModuleName);
            throw;
        }
    }
    return aResult;
}

// -----------------------------------------------------------------------------
void OInvalidateTreeThread::run()
{
    try
    {
        UnoApiLock aLock;
        ComponentRequest aRequest(m_aComponentName, m_aOptions);
        m_rTreeManager->refreshComponent(aRequest);
    }
    catch(uno::Exception&)
    {
        // do nothing, only thread safe exception absorb
        CFG_TRACE_ERROR_NI("OInvalidateTreeThread::run: refreshing failed - ignoring the exception");
    }
}
// -----------------------------------------------------------------------------
    } // namespace backend

// -----------------------------------------------------------------------------
} // namespace configmgr

<commit_msg>INTEGRATION: CWS sb88 (1.23.10); FILE MERGED 2008/06/10 13:04:49 sb 1.23.10.1: #157123# replace sole (exception handling) call to asynchronous CacheController::invalidateComponent with call to synchronous CacheController::refreshComponent, to avoid multi-threading issues<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: invalidatetree.cxx,v $
 * $Revision: 1.24 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "cachecontroller.hxx"
#include "change.hxx"
#include "valuenode.hxx"
#include "updatehelper.hxx"
#include "treeactions.hxx"
#include "treeaccessor.hxx"
#include "tracer.hxx"
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/container/NoSuchElementException.hpp>

#ifndef INCLUDED_ALGORITHM
#include <algorithm>
#define INCLUDED_ALGORITHM
#endif

namespace configmgr
{

    using namespace com::sun::star::uno;
    using namespace configuration;
    namespace container = com::sun::star::container;
// -----------------------------------------------------------------------------
// ------------------------------- invalidateTree -------------------------------
// -----------------------------------------------------------------------------

namespace backend
{
// -----------------------------------------------------------------------------
std::auto_ptr<SubtreeChange> createDiffs(data::NodeAccess const& _aCachedNode,
                                            ISubtree const * _pLoadedSubtree,
                                            AbsolutePath const& _aAbsoluteSubtreePath)
{
    OSL_PRECOND(_aCachedNode.isValid(), "Need an existing node to create a diff");
    OSL_PRECOND(_pLoadedSubtree != 0, "Need a result node to create a diff");
    // Create a TreeChangeList with the right name, parentname and ConfigurationProperties
    std::auto_ptr<SubtreeChange> aNewChange(new SubtreeChange(_aAbsoluteSubtreePath.getLocalName().getName().toString(),
                                                                node::Attributes()) );

    if (!createUpdateFromDifference(*aNewChange, _aCachedNode, *_pLoadedSubtree))
        aNewChange.reset();

    return aNewChange;
}
// -----------------------------------------------------------------------------
#if 0
std::auto_ptr<ISubtree> TreeManager::loadNodeFromSession( AbsolutePath const& _aAbsoluteSubtreePath,
                                                     const vos::ORef < OOptions >& _xOptions,
                                                     sal_Int16 _nMinLevels)  CFG_UNO_THROW_ALL()
{
    TreeInfo* pInfo = this->requestTreeInfo(_xOptions,true /*create TreeInfo*/);

    CFG_TRACE_INFO_NI("cache manager: cache miss. going to load the node");
    rtl::Reference< OTreeLoader > xLoader = pInfo->getNewLoaderWithoutPending(_aAbsoluteSubtreePath, _nMinLevels, _xOptions, m_xBackend.get());

    OSL_ENSURE(xLoader.is(), "Did not receive a loader for retrieving the node");
    CFG_TRACE_INFO_NI("cache manager: cache miss. going to load the node");
    if (!xLoader.is())
        throw container::NoSuchElementException((::rtl::OUString::createFromAscii("Error while retrieving the node")), NULL);

    // now block for reading
    std::auto_ptr<ISubtree> pResponse;
    try
    {
        pResponse = xLoader->waitToResponse();
    }
    catch (uno::Exception& e)
    {
        pInfo->releaseLoader(xLoader);
        throw;
    }

    pInfo->releaseLoader(xLoader);

    return pResponse;
}
#endif
// -----------------------------------------------------------------------------

CacheLocation CacheController::refreshComponent(ComponentRequest const & _aRequest) CFG_UNO_THROW_ALL()
{
    if (m_bDisposing) return NULL;

    CacheRef aCache = this->getCacheAlways(_aRequest.getOptions());

    if (!aCache.is()) return NULL;

    // load the Node direct from the session, without using the cache
    ComponentRequest aForcedRequest(_aRequest);
    aForcedRequest.forceReload();

    ComponentResult aLoadedInstance = this->getComponentData(aForcedRequest,false);
    AbsolutePath aRequestPath = AbsolutePath::makeModulePath(_aRequest.getComponentName(), AbsolutePath::NoValidate());
    NodeInstance aNodeInstance(aLoadedInstance.mutableInstance().mutableData(),aRequestPath) ;
    NodeResult aLoadedNodeInstance(aNodeInstance) ;

    data::TreeAddress aResult = NULL;
    if (aLoadedNodeInstance.is())
    {
        Name aModuleName = aLoadedNodeInstance->root().getModuleName();

        bool bAcquired = aCache->acquireModule(aModuleName);
        aResult = CacheLocation( aCache->getTreeAddress(aModuleName) );

        if (bAcquired)
        try
    {
            std::auto_ptr<SubtreeChange> aTreeChanges;
            data::NodeAddress aRootAddress;

            {
                data::TreeAccessor aTreeAccess(aResult);
                data::NodeAccess aRootNode = aTreeAccess.getRootNode();

                aTreeChanges = createDiffs(aRootNode, aLoadedNodeInstance->data().get(), aLoadedNodeInstance->root().location());
                aRootAddress = aRootNode;
            }

            if (aTreeChanges.get() != NULL)
            {
        // change all Values... found in the Subtree in the CacheTree
        applyUpdateWithAdjustmentToTree(*aTreeChanges, aRootAddress);

                UpdateRequest anUpdateReq(  aTreeChanges.get(),
                                            aLoadedNodeInstance->root().location(),
                                            _aRequest.getOptions()
                                          );

                m_aNotifier.notifyChanged(anUpdateReq);
            }
        aCache->releaseModule(aModuleName);
        }
        catch (...)
        {
        aCache->releaseModule(aModuleName);
            throw;
        }
    }
    return aResult;
}

// -----------------------------------------------------------------------------
    } // namespace backend

// -----------------------------------------------------------------------------
} // namespace configmgr

<|endoftext|>


<commit_before>#include "phOutput.h"
#include "phLinks.h"
#include "phAdjacent.h"
#include <PCU.h>

namespace ph {

static void getCounts(Output& o)
{
  for (int i = 0; i < 4; ++i)
    o.nGlobalEntities[i] = apf::countOwned(o.mesh, i);
  PCU_Add_Ints(o.nGlobalEntities, 4);
  o.nOwnedNodes = apf::countOwned(o.mesh, 0);
  o.nOverlapNodes = o.mesh->count(0);
  o.nGlobalNodes = o.nGlobalEntities[0];
}

static void getCoordinates(Output& o)
{
  apf::Mesh* m = o.mesh;
  int n = m->count(0);
  double* x = new double[n * 3];
  apf::MeshEntity* v;
  int i = 0;
  apf::MeshIterator* it = m->begin(0);
  while ((v = m->iterate(it))) {
    apf::Vector3 p;
    m->getPoint(v, 0, p);
    for (int j = 0; j < 3; ++j)
      x[j * n + i] = p[j]; /* FORTRAN indexing */
    ++i;
  }
  m->end(it);
  assert(i == n);
  o.arrays.coordinates = x;
}

/* so apparently old phParAdapt just used EN_id,
   and the id generator from pumi would do things
   like this. I guess PHASTA is ok with a unique
   number for each copy, regardless of part boundary
   sharing... */
static void getGlobal(Output& o)
{
  apf::Mesh* m = o.mesh;
  int n = m->count(0);
  int self = PCU_Comm_Self();
  int peers = PCU_Comm_Peers();
  int id = self + 1;
  o.arrays.globalNodeNumbers = new int[n];
  for (int i = 0; i < n; ++i) {
    o.arrays.globalNodeNumbers[i] = id;
    id += peers;
  }
}

static void getLinks(Output& o, apf::Numbering* n)
{
  Links links;
  getVertexLinks(o.mesh, links);
  size_t size;
  encodeLinks(n, links, size, o.arrays.ilwork);
  o.nlwork = size;
}

static void getInterior(Output& o, apf::Numbering* n)
{
  apf::Mesh* m = o.mesh;
  Blocks& bs = o.blocks.interior;
  int*** ien = new int**[bs.getSize()];
  for (int i = 0; i < bs.getSize(); ++i) {
    ien[i] = new int*[bs.nElements[i]];
    int t = bs.keys[i].elementType;
    int nv = bs.keys[i].nElementVertices;
    apf::MeshEntity* e;
    int j = 0;
    apf::MeshIterator* it = m->begin(m->getDimension());
    while ((e = m->iterate(it))) {
      if (getPhastaType(m, e) != t)
        continue;
      ien[i][j] = new int[nv];
      apf::Downward v;
      getVertices(m, e, v);
      for (int k = 0; k < nv; ++k)
        ien[i][j][k] = apf::getNumber(n, v[k], 0, 0);
      ++j;
    }
    m->end(it);
  }
  o.arrays.ien = ien;
}

static void getBoundary(Output& o, BCs& bcs, apf::Numbering* n)
{
  apf::Mesh* m = o.mesh;
  ModelBounds modelFaces;
  int nbc = countNaturalBCs(*o.in);
  Blocks& bs = o.blocks.boundary;
  int*** ienb = new int**[bs.getSize()];
  int*** ibcb = new int**[bs.getSize()];
  double*** bcb = new double**[bs.getSize()];
  apf::NewArray<int> js(bs.getSize());
  for (int i = 0; i < bs.getSize(); ++i) {
    ienb[i] = new int*[bs.nElements[i]];
    ibcb[i] = new int*[bs.nElements[i]];
    bcb[i] = new double*[bs.nElements[i]];
    js[i] = 0;
  }
  gmi_model* gm = m->getModel();
  gmi_ent* gf;
  gmi_iter* git = gmi_begin(gm, m->getDimension() - 1);
  while ((gf = gmi_next(gm, git))) {
    apf::ModelEntity* mf = (apf::ModelEntity*)gf;
    int* ibcbMaster = new int[2]();
    double* bcbMaster = new double[nbc]();
    applyNaturalBCs(gm, gf, bcs, bcbMaster, ibcbMaster);
    apf::MeshEntity* f;
    apf::MeshIterator* it = m->begin(m->getDimension() - 1);
    while ((f = m->iterate(it))) {
      if (m->toModel(f) != mf)
        continue;
      BlockKey k;
      apf::MeshEntity* e = m->getUpward(f, 0);
      getBoundaryBlockKey(m, e, f, k);
      assert(bs.keyToIndex.count(k));
      int i = bs.keyToIndex[k];
      int j = js[i];
      int nv = k.nElementVertices;
      apf::Downward v;
      getBoundaryVertices(m, e, f, v);
      ienb[i][j] = new int[nv];
      for (int k = 0; k < nv; ++k)
        ienb[i][j][k] = apf::getNumber(n, v[k], 0, 0);
      bcb[i][j] = new double[nbc]();
      for (int k = 0; k < nbc; ++k)
        bcb[i][j][k] = bcbMaster[k];
      ibcb[i][j] = new int[2](); /* <- parens initialize to zero */
      for (int k = 0; k < 2; ++k)
        ibcb[i][j][k] = ibcbMaster[k];
      ++js[i];
    }
    delete [] ibcbMaster;
    delete [] bcbMaster;
    m->end(it);
  }
  gmi_end(gm, git);
  for (int i = 0; i < bs.getSize(); ++i)
    assert(js[i] == bs.nElements[i]);
  o.arrays.ienb = ienb;
  o.arrays.ibcb = ibcb;
  o.arrays.bcb = bcb;
}

static void getBoundaryElements(Output& o)
{
  Blocks& bs = o.blocks.boundary;
  int n = 0;
  for (int i = 0; i < bs.getSize(); ++i)
    n += bs.nElements[i];
  o.nBoundaryElements = n;
}

static void getMaxElementNodes(Output& o)
{
  int n = 0;
  Blocks& ibs = o.blocks.interior;
  for (int i = 0; i < ibs.getSize(); ++i)
    n = std::max(n, ibs.keys[i].nElementVertices);
  Blocks& bbs = o.blocks.boundary;
  for (int i = 0; i < bbs.getSize(); ++i)
    n = std::max(n, bbs.keys[i].nElementVertices);
  o.nMaxElementNodes = n;
}

static apf::MeshEntity* getPeriodicMaster(apf::Mesh* m, apf::MeshEntity* e)
{
  if ( ! m->hasMatching())
    return e;
  apf::Matches matches;
  m->getMatches(e, matches);
  if (!matches.getSize())
    return e;
  apf::MeshEntity* master = e;
  int self = PCU_Comm_Self();
  for (size_t i = 0; i < matches.getSize(); ++i)
    if ((matches[i].peer == self)&&(matches[i].entity < master))
      master = matches[i].entity;
  return master;
}

static void getPeriodicMasters(Output& o, apf::Numbering* n)
{
  apf::Mesh* m = o.mesh;
  int* iper = new int[m->count(0)];
  apf::MeshIterator* it = m->begin(0);
  apf::MeshEntity* e;
  int i = 0;
  while ((e = m->iterate(it))) {
    apf::MeshEntity* master = getPeriodicMaster(m, e);
    if (master == e)
      iper[i] = 0;
    else
      iper[i] = apf::getNumber(n, master, 0, 0) + 1;
    ++i;
  }
  m->end(it);
  o.arrays.iper = iper;
}

static void getEssentialBCsOn(BCs& bcs, Output& o, gmi_ent* ge)
{
  Input& in = *o.in;
  apf::Mesh* m = o.mesh;
  int ibcMaster = 0;
  int nec = countEssentialBCs(in);
  double* bcMaster = new double[nec]();
  gmi_model* gm = m->getModel();
  bool did = applyEssentialBCs(gm, ge, bcs, bcMaster, &ibcMaster);
  if (did) {
    apf::MeshEntity* v;
    apf::MeshIterator* it = m->begin(0);
    int i = 0;
    int& ei = o.nEssentialBCNodes;
    while ((v = m->iterate(it))) {
      if (m->toModel(v) == (apf::ModelEntity*)ge) {
        o.arrays.nbc[i] = ei + 1;
        o.arrays.ibc[ei] = ibcMaster;
        double* bc_ei = new double[nec]();
        for (int j = 0; j < nec; ++j)
          bc_ei[j] = bcMaster[j];
        o.arrays.bc[ei] = bc_ei;
        ++ei;
      }
      ++i;
    }
    m->end(it);
  }
  delete [] bcMaster;
}

static void getEssentialBCs(BCs& bcs, Output& o)
{
  apf::Mesh* m = o.mesh;
  int nv = m->count(0);
  o.arrays.nbc = new int[nv];
  for (int i = 0; i < nv; ++i)
    o.arrays.nbc[i] = -1;
  o.arrays.ibc = new int[nv]();
  o.arrays.bc = new double*[nv];
  o.nEssentialBCNodes = 0;
  gmi_model* gm = m->getModel();
  for (int d = 3; d >= 0; --d) {
    gmi_iter* it = gmi_begin(gm, d);
    gmi_ent* ge;
    while ((ge = gmi_next(gm, it)))
      getEssentialBCsOn(bcs, o, ge);
    gmi_end(gm, it);
  }
}

static void getInitialConditions(BCs& bcs, Output& o)
{
  Input& in = *o.in;
  apf::Mesh* m = o.mesh;
  apf::MeshEntity* v;
  apf::NewArray<double> s(in.ensa_dof);
  apf::Field* f = m->findField("solution");
  apf::MeshIterator* it = m->begin(0);
  gmi_model* gm = m->getModel();
  while ((v = m->iterate(it))) {
    gmi_ent* ge = (gmi_ent*)m->toModel(v);
    apf::getComponents(f, v, 0, &s[0]);
/* unfortunately, there is no way to know which
   components this overwrites without creating
   bad coupling between pieces of code, so we
   call this for every vertex even though it
   only depends on classification */
    applySolutionBCs(gm, ge, bcs, &s[0]);
    apf::setComponents(f, v, 0, &s[0]);
  }
  m->end(it);
}

Output::~Output()
{
  delete [] arrays.coordinates;
  delete [] arrays.ilwork;
  delete [] arrays.iper;
  delete [] arrays.globalNodeNumbers;
  Blocks& ibs = blocks.interior;
  for (int i = 0; i < ibs.getSize(); ++i) {
    for (int j = 0; j < ibs.nElements[i]; ++j)
      delete [] arrays.ien[i][j];
    delete [] arrays.ien[i];
  }
  delete [] arrays.ien;
  Blocks& bbs = blocks.boundary;
  for (int i = 0; i < bbs.getSize(); ++i) {
    for (int j = 0; j < bbs.nElements[i]; ++j) {
      delete [] arrays.ienb[i][j];
      delete [] arrays.ibcb[i][j];
      delete [] arrays.bcb[i][j];
    }
    delete [] arrays.ienb[i];
    delete [] arrays.ibcb[i];
    delete [] arrays.bcb[i];
  }
  delete [] arrays.ienb;
  delete [] arrays.ibcb;
  delete [] arrays.bcb;
  delete [] arrays.nbc;
  delete [] arrays.ibc;
  for (int i = 0; i < nEssentialBCNodes; ++i)
    delete [] arrays.bc[i];
  delete [] arrays.bc;
}

void generateOutput(Input& in, BCs& bcs, apf::Mesh* mesh, Output& o)
{
  double t0 = MPI_Wtime();
  o.in = ∈
  o.mesh = mesh;
  getCounts(o);
  getCoordinates(o);
  getGlobal(o);
  getAllBlocks(o.mesh, o.blocks);
  apf::Numbering* n = apf::numberOverlapNodes(mesh, "ph_local");
  getLinks(o, n);
  getInterior(o, n);
  getBoundary(o, bcs, n);
  getPeriodicMasters(o, n);
  apf::destroyNumbering(n);
  getBoundaryElements(o);
  getMaxElementNodes(o);
  getEssentialBCs(bcs, o);
  getInitialConditions(bcs, o);
  double t1 = MPI_Wtime();
  if (!PCU_Comm_Self())
    printf("generated output structs in %f seconds\n",t1 - t0);
}

}
<commit_msg>in nbc, none is 0, not -1<commit_after>#include "phOutput.h"
#include "phLinks.h"
#include "phAdjacent.h"
#include <PCU.h>

namespace ph {

static void getCounts(Output& o)
{
  for (int i = 0; i < 4; ++i)
    o.nGlobalEntities[i] = apf::countOwned(o.mesh, i);
  PCU_Add_Ints(o.nGlobalEntities, 4);
  o.nOwnedNodes = apf::countOwned(o.mesh, 0);
  o.nOverlapNodes = o.mesh->count(0);
  o.nGlobalNodes = o.nGlobalEntities[0];
}

static void getCoordinates(Output& o)
{
  apf::Mesh* m = o.mesh;
  int n = m->count(0);
  double* x = new double[n * 3];
  apf::MeshEntity* v;
  int i = 0;
  apf::MeshIterator* it = m->begin(0);
  while ((v = m->iterate(it))) {
    apf::Vector3 p;
    m->getPoint(v, 0, p);
    for (int j = 0; j < 3; ++j)
      x[j * n + i] = p[j]; /* FORTRAN indexing */
    ++i;
  }
  m->end(it);
  assert(i == n);
  o.arrays.coordinates = x;
}

/* so apparently old phParAdapt just used EN_id,
   and the id generator from pumi would do things
   like this. I guess PHASTA is ok with a unique
   number for each copy, regardless of part boundary
   sharing... */
static void getGlobal(Output& o)
{
  apf::Mesh* m = o.mesh;
  int n = m->count(0);
  int self = PCU_Comm_Self();
  int peers = PCU_Comm_Peers();
  int id = self + 1;
  o.arrays.globalNodeNumbers = new int[n];
  for (int i = 0; i < n; ++i) {
    o.arrays.globalNodeNumbers[i] = id;
    id += peers;
  }
}

static void getLinks(Output& o, apf::Numbering* n)
{
  Links links;
  getVertexLinks(o.mesh, links);
  size_t size;
  encodeLinks(n, links, size, o.arrays.ilwork);
  o.nlwork = size;
}

static void getInterior(Output& o, apf::Numbering* n)
{
  apf::Mesh* m = o.mesh;
  Blocks& bs = o.blocks.interior;
  int*** ien = new int**[bs.getSize()];
  for (int i = 0; i < bs.getSize(); ++i) {
    ien[i] = new int*[bs.nElements[i]];
    int t = bs.keys[i].elementType;
    int nv = bs.keys[i].nElementVertices;
    apf::MeshEntity* e;
    int j = 0;
    apf::MeshIterator* it = m->begin(m->getDimension());
    while ((e = m->iterate(it))) {
      if (getPhastaType(m, e) != t)
        continue;
      ien[i][j] = new int[nv];
      apf::Downward v;
      getVertices(m, e, v);
      for (int k = 0; k < nv; ++k)
        ien[i][j][k] = apf::getNumber(n, v[k], 0, 0);
      ++j;
    }
    m->end(it);
  }
  o.arrays.ien = ien;
}

static void getBoundary(Output& o, BCs& bcs, apf::Numbering* n)
{
  apf::Mesh* m = o.mesh;
  ModelBounds modelFaces;
  int nbc = countNaturalBCs(*o.in);
  Blocks& bs = o.blocks.boundary;
  int*** ienb = new int**[bs.getSize()];
  int*** ibcb = new int**[bs.getSize()];
  double*** bcb = new double**[bs.getSize()];
  apf::NewArray<int> js(bs.getSize());
  for (int i = 0; i < bs.getSize(); ++i) {
    ienb[i] = new int*[bs.nElements[i]];
    ibcb[i] = new int*[bs.nElements[i]];
    bcb[i] = new double*[bs.nElements[i]];
    js[i] = 0;
  }
  gmi_model* gm = m->getModel();
  gmi_ent* gf;
  gmi_iter* git = gmi_begin(gm, m->getDimension() - 1);
  while ((gf = gmi_next(gm, git))) {
    apf::ModelEntity* mf = (apf::ModelEntity*)gf;
    int* ibcbMaster = new int[2]();
    double* bcbMaster = new double[nbc]();
    applyNaturalBCs(gm, gf, bcs, bcbMaster, ibcbMaster);
    apf::MeshEntity* f;
    apf::MeshIterator* it = m->begin(m->getDimension() - 1);
    while ((f = m->iterate(it))) {
      if (m->toModel(f) != mf)
        continue;
      BlockKey k;
      apf::MeshEntity* e = m->getUpward(f, 0);
      getBoundaryBlockKey(m, e, f, k);
      assert(bs.keyToIndex.count(k));
      int i = bs.keyToIndex[k];
      int j = js[i];
      int nv = k.nElementVertices;
      apf::Downward v;
      getBoundaryVertices(m, e, f, v);
      ienb[i][j] = new int[nv];
      for (int k = 0; k < nv; ++k)
        ienb[i][j][k] = apf::getNumber(n, v[k], 0, 0);
      bcb[i][j] = new double[nbc]();
      for (int k = 0; k < nbc; ++k)
        bcb[i][j][k] = bcbMaster[k];
      ibcb[i][j] = new int[2](); /* <- parens initialize to zero */
      for (int k = 0; k < 2; ++k)
        ibcb[i][j][k] = ibcbMaster[k];
      ++js[i];
    }
    delete [] ibcbMaster;
    delete [] bcbMaster;
    m->end(it);
  }
  gmi_end(gm, git);
  for (int i = 0; i < bs.getSize(); ++i)
    assert(js[i] == bs.nElements[i]);
  o.arrays.ienb = ienb;
  o.arrays.ibcb = ibcb;
  o.arrays.bcb = bcb;
}

static void getBoundaryElements(Output& o)
{
  Blocks& bs = o.blocks.boundary;
  int n = 0;
  for (int i = 0; i < bs.getSize(); ++i)
    n += bs.nElements[i];
  o.nBoundaryElements = n;
}

static void getMaxElementNodes(Output& o)
{
  int n = 0;
  Blocks& ibs = o.blocks.interior;
  for (int i = 0; i < ibs.getSize(); ++i)
    n = std::max(n, ibs.keys[i].nElementVertices);
  Blocks& bbs = o.blocks.boundary;
  for (int i = 0; i < bbs.getSize(); ++i)
    n = std::max(n, bbs.keys[i].nElementVertices);
  o.nMaxElementNodes = n;
}

static apf::MeshEntity* getPeriodicMaster(apf::Mesh* m, apf::MeshEntity* e)
{
  if ( ! m->hasMatching())
    return e;
  apf::Matches matches;
  m->getMatches(e, matches);
  if (!matches.getSize())
    return e;
  apf::MeshEntity* master = e;
  int self = PCU_Comm_Self();
  for (size_t i = 0; i < matches.getSize(); ++i)
    if ((matches[i].peer == self)&&(matches[i].entity < master))
      master = matches[i].entity;
  return master;
}

static void getPeriodicMasters(Output& o, apf::Numbering* n)
{
  apf::Mesh* m = o.mesh;
  int* iper = new int[m->count(0)];
  apf::MeshIterator* it = m->begin(0);
  apf::MeshEntity* e;
  int i = 0;
  while ((e = m->iterate(it))) {
    apf::MeshEntity* master = getPeriodicMaster(m, e);
    if (master == e)
      iper[i] = 0;
    else
      iper[i] = apf::getNumber(n, master, 0, 0) + 1;
    ++i;
  }
  m->end(it);
  o.arrays.iper = iper;
}

static void getEssentialBCsOn(BCs& bcs, Output& o, gmi_ent* ge)
{
  Input& in = *o.in;
  apf::Mesh* m = o.mesh;
  int ibcMaster = 0;
  int nec = countEssentialBCs(in);
  double* bcMaster = new double[nec]();
  gmi_model* gm = m->getModel();
  bool did = applyEssentialBCs(gm, ge, bcs, bcMaster, &ibcMaster);
  if (did) {
    apf::MeshEntity* v;
    apf::MeshIterator* it = m->begin(0);
    int i = 0;
    int& ei = o.nEssentialBCNodes;
    while ((v = m->iterate(it))) {
      if (m->toModel(v) == (apf::ModelEntity*)ge) {
        o.arrays.nbc[i] = ei + 1;
        o.arrays.ibc[ei] = ibcMaster;
        double* bc_ei = new double[nec]();
        for (int j = 0; j < nec; ++j)
          bc_ei[j] = bcMaster[j];
        o.arrays.bc[ei] = bc_ei;
        ++ei;
      }
      ++i;
    }
    m->end(it);
  }
  delete [] bcMaster;
}

static void getEssentialBCs(BCs& bcs, Output& o)
{
  apf::Mesh* m = o.mesh;
  int nv = m->count(0);
  o.arrays.nbc = new int[nv];
  for (int i = 0; i < nv; ++i)
    o.arrays.nbc[i] = 0;
  o.arrays.ibc = new int[nv]();
  o.arrays.bc = new double*[nv];
  o.nEssentialBCNodes = 0;
  gmi_model* gm = m->getModel();
  for (int d = 3; d >= 0; --d) {
    gmi_iter* it = gmi_begin(gm, d);
    gmi_ent* ge;
    while ((ge = gmi_next(gm, it)))
      getEssentialBCsOn(bcs, o, ge);
    gmi_end(gm, it);
  }
}

static void getInitialConditions(BCs& bcs, Output& o)
{
  Input& in = *o.in;
  apf::Mesh* m = o.mesh;
  apf::MeshEntity* v;
  apf::NewArray<double> s(in.ensa_dof);
  apf::Field* f = m->findField("solution");
  apf::MeshIterator* it = m->begin(0);
  gmi_model* gm = m->getModel();
  while ((v = m->iterate(it))) {
    gmi_ent* ge = (gmi_ent*)m->toModel(v);
    apf::getComponents(f, v, 0, &s[0]);
/* unfortunately, there is no way to know which
   components this overwrites without creating
   bad coupling between pieces of code, so we
   call this for every vertex even though it
   only depends on classification */
    applySolutionBCs(gm, ge, bcs, &s[0]);
    apf::setComponents(f, v, 0, &s[0]);
  }
  m->end(it);
}

Output::~Output()
{
  delete [] arrays.coordinates;
  delete [] arrays.ilwork;
  delete [] arrays.iper;
  delete [] arrays.globalNodeNumbers;
  Blocks& ibs = blocks.interior;
  for (int i = 0; i < ibs.getSize(); ++i) {
    for (int j = 0; j < ibs.nElements[i]; ++j)
      delete [] arrays.ien[i][j];
    delete [] arrays.ien[i];
  }
  delete [] arrays.ien;
  Blocks& bbs = blocks.boundary;
  for (int i = 0; i < bbs.getSize(); ++i) {
    for (int j = 0; j < bbs.nElements[i]; ++j) {
      delete [] arrays.ienb[i][j];
      delete [] arrays.ibcb[i][j];
      delete [] arrays.bcb[i][j];
    }
    delete [] arrays.ienb[i];
    delete [] arrays.ibcb[i];
    delete [] arrays.bcb[i];
  }
  delete [] arrays.ienb;
  delete [] arrays.ibcb;
  delete [] arrays.bcb;
  delete [] arrays.nbc;
  delete [] arrays.ibc;
  for (int i = 0; i < nEssentialBCNodes; ++i)
    delete [] arrays.bc[i];
  delete [] arrays.bc;
}

void generateOutput(Input& in, BCs& bcs, apf::Mesh* mesh, Output& o)
{
  double t0 = MPI_Wtime();
  o.in = ∈
  o.mesh = mesh;
  getCounts(o);
  getCoordinates(o);
  getGlobal(o);
  getAllBlocks(o.mesh, o.blocks);
  apf::Numbering* n = apf::numberOverlapNodes(mesh, "ph_local");
  getLinks(o, n);
  getInterior(o, n);
  getBoundary(o, bcs, n);
  getPeriodicMasters(o, n);
  apf::destroyNumbering(n);
  getBoundaryElements(o);
  getMaxElementNodes(o);
  getEssentialBCs(bcs, o);
  getInitialConditions(bcs, o);
  double t1 = MPI_Wtime();
  if (!PCU_Comm_Self())
    printf("generated output structs in %f seconds\n",t1 - t0);
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: Boolean.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 07:17:59 $
 *
 *  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 _CONNECTIVITY_JAVA_LANG_BOOLEAN_HXX_
#define _CONNECTIVITY_JAVA_LANG_BOOLEAN_HXX_

#ifndef _CONNECTIVITY_JAVA_LANG_OBJECT_HXX_
#include "java/lang/Object.hxx"
#endif
//**************************************************************
//************ Class: java.lang.Boolean
//**************************************************************
namespace connectivity
{
    class java_lang_Boolean : public java_lang_Object
    {
    protected:
    // statische Daten fuer die Klasse
        static jclass theClass;
        // der Destruktor um den Object-Counter zu aktualisieren
        static void saveClassRef( jclass pClass );
    public:
        static jclass getMyClass();
        virtual ~java_lang_Boolean();
        // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
        java_lang_Boolean( JNIEnv * pEnv, jobject myObj ) : java_lang_Object( pEnv, myObj ){}

        java_lang_Boolean( sal_Bool _par0 );
    };
}

#endif // _CONNECTIVITY_JAVA_LANG_BOOLEAN_HXX_

<commit_msg>INTEGRATION: CWS changefileheader (1.2.372); FILE MERGED 2008/04/01 10:53:34 thb 1.2.372.2: #i85898# Stripping all external header guards 2008/03/28 15:24:26 rt 1.2.372.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: Boolean.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_JAVA_LANG_BOOLEAN_HXX_
#define _CONNECTIVITY_JAVA_LANG_BOOLEAN_HXX_

#include "java/lang/Object.hxx"
//**************************************************************
//************ Class: java.lang.Boolean
//**************************************************************
namespace connectivity
{
    class java_lang_Boolean : public java_lang_Object
    {
    protected:
    // statische Daten fuer die Klasse
        static jclass theClass;
        // der Destruktor um den Object-Counter zu aktualisieren
        static void saveClassRef( jclass pClass );
    public:
        static jclass getMyClass();
        virtual ~java_lang_Boolean();
        // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
        java_lang_Boolean( JNIEnv * pEnv, jobject myObj ) : java_lang_Object( pEnv, myObj ){}

        java_lang_Boolean( sal_Bool _par0 );
    };
}

#endif // _CONNECTIVITY_JAVA_LANG_BOOLEAN_HXX_

<|endoftext|>


<commit_before>/*
qgvdial is a cross platform Google Voice Dialer
Copyright (C) 2009-2012  Yuvraaj Kelkar

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

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

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Contact: yuvraaj@gmail.com
*/

#include "TpAccountUtility.h"
#include "TpHeaders.h"
#include "Singletons.h"

#define ofdTA "org.freedesktop.Telepathy.Account"
#define cnAIC "com.nokia.Account.Interface.Compat"

TpPhoneIntegration::TpPhoneIntegration(QObject *parent /*= NULL*/)
: IPhoneIntegration(parent)
, m_acMgrInitInProgress(false)
, m_EnableAfteracMgrInit(false)
{
}//TpPhoneIntegration::TpPhoneIntegration

void
TpPhoneIntegration::phoneIntegrationChanged(bool enable /* = false*/)
{
    if (!acMgr.isNull ()) {
        Q_WARN("Account manager is valid!!");
        return;
    }

    m_EnableAfteracMgrInit = enable;
    acMgr = AccountManager::create();

    Tp::PendingOperation *op = acMgr->becomeReady ();
    connect(op, SIGNAL(finished(Tp::PendingOperation*)),
            this, SLOT(onAcMgrReady(Tp::PendingOperation*)));
}//TpPhoneIntegration::integrateChanged

void
TpPhoneIntegration::onAcMgrReady(Tp::PendingOperation * /*operation*/)
{
    if (acMgr->isReady()) {
        Q_DEBUG("Account manager is ready");

        if (m_EnableAfteracMgrInit) {
            QStringList props = acMgr->supportedAccountProperties ();
            Q_DEBUG(QString("Supported properties = [%1]").arg(props.join(", ")));

            enablePhoneIntegration ();
        } else {
            disablePhoneIntegration ();
        }
    } else {
        Q_WARN("Account manager is not getting ready");
    }
}//TpPhoneIntegration::onAcMgrReady

void
TpPhoneIntegration::enablePhoneIntegration()
{
    CacheDatabase &dbMain = Singletons::getRef().getDBMain();
    QString user, pass;
    bool rv;

    rv = dbMain.getUserPass (user, pass);
    if (!rv) {
        Q_WARN("Failed to get user pass");
        return;
    }
    user.replace('@', '_');
    user.replace('.', '_');

    QVariantMap connectionParametersMap;
    connectionParametersMap.insert("account", user);

    QList<QVariant> presenceDetails;
    uint presenceType(2); //Available = 2
    presenceDetails << presenceType;
    presenceDetails << "online";
    presenceDetails << "Available";

    QVariantMap accountPropertiesMap;
    // Looks like this is not required... (?)
    //"org.freedesktop.Telepathy.Account.AutomaticPresence" = simple presence
    //accountPropertiesMap.insert(ofdTA ".AutomaticPresence",
    //                            QVariant::fromValue(presence));
    //"org.freedesktop.Telepathy.Account.RequestedPresence" = simple presence
    //accountPropertiesMap.insert(ofdTA ".RequestedPresence",
    //                            QVariant::fromValue(presence));

    // "org.freedesktop.Telepathy.Account.Enabled" = true
    accountPropertiesMap.insert(ofdTA ".Enabled", true);
    // "org.freedesktop.Telepathy.Account.ConnectAutomatically" = true
    accountPropertiesMap.insert(ofdTA ".ConnectAutomatically", true);
#if defined(MEEGO_HARMATTAN)
    // "com.nokia.Account.Interface.Compat.Profile" = "qgvtp"
    accountPropertiesMap.insert(cnAIC ".Profile", "qgvtp");
#endif

    QStringList valuesList;
    valuesList.append("TEL");
#if defined(MEEGO_HARMATTAN)
    // "com.nokia.Account.Interface.Compat.SecondaryVCardFields" = a("TEL")
    accountPropertiesMap.insert(cnAIC ".SecondaryVCardFields", valuesList);
#endif

    Tp::PendingAccount *pa =
    acMgr->createAccount ("qgvtp", "qgv", user, connectionParametersMap,
                          accountPropertiesMap);
    rv = connect(pa, SIGNAL(finished(Tp::PendingOperation*)),
                 this, SLOT(onAccountCreated(Tp::PendingOperation*)));
    Q_ASSERT(rv);
    if (!rv) {
        Q_WARN("Failed to connect account creation signal");
    }
}//TpPhoneIntegration::enablePhoneIntegration

void
TpPhoneIntegration::onAccountCreated(Tp::PendingOperation *op)
{
    Tp::PendingAccount *pa = (Tp::PendingAccount *) op;

    if (pa->isError ()) {
        Q_WARN("Failed to create account");
        return;
    }

    AccountPtr ac = pa->account();

    QString acPath = ac->objectPath ();
    Q_DEBUG(QString("Account with path %1 is created").arg(acPath));

    Tp::Presence p(ConnectionPresenceTypeAvailable, "online", "Available");
    op = ac->setRequestedPresence(p);
    connect(op, SIGNAL(finished(Tp::PendingOperation*)),
            this, SLOT(onAccountOnline(Tp::PendingOperation*)));
}//TpPhoneIntegration::onAccountCreated

void
TpPhoneIntegration::disablePhoneIntegration()
{
    QList<AccountPtr> allAc = acMgr->allAccounts ();
    foreach (AccountPtr ac, allAc) {
        QString acPath = ac->objectPath ();
        if (acPath.contains ("qgvtp/qgv/qgvtp")) {
            Q_DEBUG(QString("Removing account %1").arg (acPath));
            Tp::PendingOperation *op = ac->remove ();
            connect(op, SIGNAL(finished(Tp::PendingOperation*)),
                    this, SLOT(onAccountRemoved(Tp::PendingOperation*)));
        }
    }

    acMgr.reset ();
    IPhoneIntegration::phoneIntegrationChanged (false);
}//TpPhoneIntegration::disablePhoneIntegration

void
TpPhoneIntegration::onAccountOnline(Tp::PendingOperation *op)
{
    if (op->isError()) {
        Q_WARN("Account could not be made online");
        disablePhoneIntegration();
    } else {
        Q_DEBUG("Account is now online");
        IPhoneIntegration::phoneIntegrationChanged (true);
    }

    acMgr.reset ();
}//TpPhoneIntegration::onAccountOnline

void
TpPhoneIntegration::onAccountRemoved(Tp::PendingOperation * /*operation*/)
{
    Q_DEBUG("Account removed");

    bool oldVal = m_integrationEnabled;
    m_integrationEnabled = false;
    if (oldVal != m_integrationEnabled) {
        emit enableChanged(m_integrationEnabled);
    }
}//TpPhoneIntegration::onAccountRemoved

bool
TpPhoneIntegration::isEnabled()
{
    return m_integrationEnabled;
}//TpPhoneIntegration::isEnabled
<commit_msg>fix account removal<commit_after>/*
qgvdial is a cross platform Google Voice Dialer
Copyright (C) 2009-2012  Yuvraaj Kelkar

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

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

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Contact: yuvraaj@gmail.com
*/

#include "TpAccountUtility.h"
#include "TpHeaders.h"
#include "Singletons.h"

#define ofdTA "org.freedesktop.Telepathy.Account"
#define cnAIC "com.nokia.Account.Interface.Compat"

TpPhoneIntegration::TpPhoneIntegration(QObject *parent /*= NULL*/)
: IPhoneIntegration(parent)
, m_acMgrInitInProgress(false)
, m_EnableAfteracMgrInit(false)
{
}//TpPhoneIntegration::TpPhoneIntegration

void
TpPhoneIntegration::phoneIntegrationChanged(bool enable /* = false*/)
{
    if (!acMgr.isNull ()) {
        Q_WARN("Account manager is valid!!");
        return;
    }

    m_EnableAfteracMgrInit = enable;
    acMgr = AccountManager::create();

    Tp::PendingOperation *op = acMgr->becomeReady ();
    connect(op, SIGNAL(finished(Tp::PendingOperation*)),
            this, SLOT(onAcMgrReady(Tp::PendingOperation*)));
}//TpPhoneIntegration::integrateChanged

void
TpPhoneIntegration::onAcMgrReady(Tp::PendingOperation * /*operation*/)
{
    if (acMgr->isReady()) {
        Q_DEBUG("Account manager is ready");

        if (m_EnableAfteracMgrInit) {
            QStringList props = acMgr->supportedAccountProperties ();
            Q_DEBUG(QString("Supported properties = [%1]").arg(props.join(", ")));

            enablePhoneIntegration ();
        } else {
            disablePhoneIntegration ();
        }
    } else {
        Q_WARN("Account manager is not getting ready");
    }
}//TpPhoneIntegration::onAcMgrReady

void
TpPhoneIntegration::enablePhoneIntegration()
{
    CacheDatabase &dbMain = Singletons::getRef().getDBMain();
    QString user, pass;
    bool rv;

    rv = dbMain.getUserPass (user, pass);
    if (!rv) {
        Q_WARN("Failed to get user pass");
        return;
    }
    user.replace('@', '_');
    user.replace('.', '_');

    QVariantMap connectionParametersMap;
    connectionParametersMap.insert("account", user);

    QList<QVariant> presenceDetails;
    uint presenceType(2); //Available = 2
    presenceDetails << presenceType;
    presenceDetails << "online";
    presenceDetails << "Available";

    QVariantMap accountPropertiesMap;
    // Looks like this is not required... (?)
    //"org.freedesktop.Telepathy.Account.AutomaticPresence" = simple presence
    //accountPropertiesMap.insert(ofdTA ".AutomaticPresence",
    //                            QVariant::fromValue(presence));
    //"org.freedesktop.Telepathy.Account.RequestedPresence" = simple presence
    //accountPropertiesMap.insert(ofdTA ".RequestedPresence",
    //                            QVariant::fromValue(presence));

    // "org.freedesktop.Telepathy.Account.Enabled" = true
    accountPropertiesMap.insert(ofdTA ".Enabled", true);
    // "org.freedesktop.Telepathy.Account.ConnectAutomatically" = true
    accountPropertiesMap.insert(ofdTA ".ConnectAutomatically", true);
#if defined(MEEGO_HARMATTAN)
    // "com.nokia.Account.Interface.Compat.Profile" = "qgvtp"
    accountPropertiesMap.insert(cnAIC ".Profile", "qgvtp");
#endif

    QStringList valuesList;
    valuesList.append("TEL");
#if defined(MEEGO_HARMATTAN)
    // "com.nokia.Account.Interface.Compat.SecondaryVCardFields" = a("TEL")
    accountPropertiesMap.insert(cnAIC ".SecondaryVCardFields", valuesList);
#endif

    Tp::PendingAccount *pa =
    acMgr->createAccount ("qgvtp", "qgv", user, connectionParametersMap,
                          accountPropertiesMap);
    rv = connect(pa, SIGNAL(finished(Tp::PendingOperation*)),
                 this, SLOT(onAccountCreated(Tp::PendingOperation*)));
    Q_ASSERT(rv);
    if (!rv) {
        Q_WARN("Failed to connect account creation signal");
    }
}//TpPhoneIntegration::enablePhoneIntegration

void
TpPhoneIntegration::onAccountCreated(Tp::PendingOperation *op)
{
    Tp::PendingAccount *pa = (Tp::PendingAccount *) op;

    if (pa->isError ()) {
        Q_WARN("Failed to create account");
        return;
    }

    AccountPtr ac = pa->account();

    QString acPath = ac->objectPath ();
    Q_DEBUG(QString("Account with path %1 is created").arg(acPath));

    Tp::Presence p(ConnectionPresenceTypeAvailable, "online", "Available");
    op = ac->setRequestedPresence(p);
    connect(op, SIGNAL(finished(Tp::PendingOperation*)),
            this, SLOT(onAccountOnline(Tp::PendingOperation*)));
}//TpPhoneIntegration::onAccountCreated

void
TpPhoneIntegration::disablePhoneIntegration()
{
    QList<AccountPtr> allAc = acMgr->allAccounts ();
    foreach (AccountPtr ac, allAc) {
        QString acPath = ac->objectPath ();
        if (acPath.contains ("qgvtp/qgv/")) {
            Q_DEBUG(QString("Removing account %1").arg (acPath));
            Tp::PendingOperation *op = ac->remove ();
            connect(op, SIGNAL(finished(Tp::PendingOperation*)),
                    this, SLOT(onAccountRemoved(Tp::PendingOperation*)));
        }
    }

    acMgr.reset ();
    IPhoneIntegration::phoneIntegrationChanged (false);
}//TpPhoneIntegration::disablePhoneIntegration

void
TpPhoneIntegration::onAccountOnline(Tp::PendingOperation *op)
{
    if (op->isError()) {
        Q_WARN("Account could not be made online");
        disablePhoneIntegration();
    } else {
        Q_DEBUG("Account is now online");
        IPhoneIntegration::phoneIntegrationChanged (true);
    }

    acMgr.reset ();
}//TpPhoneIntegration::onAccountOnline

void
TpPhoneIntegration::onAccountRemoved(Tp::PendingOperation * /*operation*/)
{
    Q_DEBUG("Account removed");

    bool oldVal = m_integrationEnabled;
    m_integrationEnabled = false;
    if (oldVal != m_integrationEnabled) {
        emit enableChanged(m_integrationEnabled);
    }
}//TpPhoneIntegration::onAccountRemoved

bool
TpPhoneIntegration::isEnabled()
{
    return m_integrationEnabled;
}//TpPhoneIntegration::isEnabled
<|endoftext|>


<commit_before>// Copyright © 2017 Dmitriy Khaustov
//
// 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.
//
// Author: Dmitriy Khaustov aka xDimon
// Contacts: khaustov.dm@gmail.com
// File created on: 2017.03.31

// WsFrame.cpp

#include "WsFrame.hpp"

#include "../../utils/literals.hpp"

size_t WsFrame::calcHeaderSize(const char data[2])
{
	uint8_t prelen = (data[1] >> 0) & 0x7F_u8;
	uint8_t masked = (data[1] >> 7) & 0x01_u8;

	return 2												// Стартовые байты
		+ ((prelen <= 125) ? 0 : (prelen == 126) ? 2 : 8)	// Байты расширенной длины
		+ ((!masked) ? 0 : 4);								// Байты маски
}

WsFrame::WsFrame(const char *begin, const char *end)
{
	auto s = begin;

	_finaly = static_cast<bool>((s[0] >> 7) & 0x01);
	_opcode = static_cast<Opcode>((s[0] >> 0) & 0x0F);
	_masked = static_cast<bool>((s[1] >> 7) & 0x01);

	uint8_t prelen = (s[1] >> 0) & 0x7F_u8;
	if ((s + 2) > end)
	{
		throw std::runtime_error("Not anough data");
	}
	s += 2;

	if (prelen < 126)
	{
		_length = prelen;
	}
	else if (prelen == 126)
	{
		if ((s + 2) > end)
		{
			throw std::runtime_error("Not anough data");
		}
		_length = 0;
		_length = (_length << 8) | *s++;
		_length = (_length << 8) | *s++;
	}
	else if (prelen == 127)
	{
		if ((s + 8) > end)
		{
			throw std::runtime_error("Not anough data");
		}
		_length = 0;
		_length = (_length << 8) | *s++;
		_length = (_length << 8) | *s++;
		_length = (_length << 8) | *s++;
		_length = (_length << 8) | *s++;
		_length = (_length << 8) | *s++;
		_length = (_length << 8) | *s++;
		_length = (_length << 8) | *s++;
		_length = (_length << 8) | *s++;
	}

	if (_masked)
	{
		if ((s + 4) > end)
		{
			throw std::runtime_error("Not anough data");
		}
		_mask[0] = static_cast<uint8_t>(*s++);
		_mask[1] = static_cast<uint8_t>(*s++);
		_mask[2] = static_cast<uint8_t>(*s++);
		_mask[3] = static_cast<uint8_t>(*s++);
	}
	else
	{
		_mask[0] =
		_mask[1] =
		_mask[2] =
		_mask[3] = 0;
	}
}

void WsFrame::applyMask()
{
	if (!_masked)
	{
		return;
	}
	int i = 0;
	size_t remain = dataLen();
	for (auto &b : _data)
	{
		b ^= _mask[i++];
		if (!--remain) break;
		if (i == 4)
		{
			i = 0;
		}
	}
}

void WsFrame::send(std::shared_ptr<Writer> writer, Opcode code, const char *data, size_t size)
{
	bool masked = false;
	uint8_t byte;

	byte = (1_u8 << 7) | static_cast<uint8_t>(code);
	writer->write(&byte, sizeof(byte));

	byte = static_cast<uint8_t>((size > 65535) ? 127 : (size > 125) ? 126 : size);
	if (masked)
	{
		byte |= (1_u8 << 7);
	}
	writer->write(&byte, sizeof(byte));

	if (size > 125)
	{
		uint16_t size16 = static_cast<uint16_t>(size);
		writer->write(&size16, sizeof(size16));
	}
	else if (size > 65535)
	{
		uint64_t size64 = static_cast<uint64_t>(size);
		writer->write(&size64, sizeof(size64));
	}

	if (!masked)
	{
		writer->write(data, size);
		return;
	}

	union {
		uint32_t i;
		uint8_t b[4];
	} mask;

	mask.i = static_cast<uint32_t>(std::rand());

	for (size_t i = 0; i < sizeof(mask.b); i++)
	{
		writer->write(&mask.b[i], 1);
	}

	int i = 0;
	while (size--)
	{
		byte = static_cast<uint8_t>(*data++) ^ mask.b[i++];

		writer->write(&byte, sizeof(byte));

		if (i == 4)
		{
			i = 0;
		}
	}
}
<commit_msg>Improve WsFrame for performance<commit_after>// Copyright © 2017 Dmitriy Khaustov
//
// 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.
//
// Author: Dmitriy Khaustov aka xDimon
// Contacts: khaustov.dm@gmail.com
// File created on: 2017.03.31

// WsFrame.cpp

#include <cstring>
#include "WsFrame.hpp"

#include "../../utils/literals.hpp"

size_t WsFrame::calcHeaderSize(const char data[2])
{
	uint8_t prelen = (data[1] >> 0) & 0x7F_u8;
	uint8_t masked = (data[1] >> 7) & 0x01_u8;

	return 2												// Стартовые байты
		+ ((prelen <= 125) ? 0 : (prelen == 126) ? 2 : 8)	// Байты расширенной длины
		+ ((!masked) ? 0 : 4);								// Байты маски
}

WsFrame::WsFrame(const char *begin, const char *end)
{
	auto s = begin;

	_finaly = static_cast<bool>((s[0] >> 7) & 0x01);
	_opcode = static_cast<Opcode>((s[0] >> 0) & 0x0F);
	_masked = static_cast<bool>((s[1] >> 7) & 0x01);

	uint8_t prelen = (s[1] >> 0) & 0x7F_u8;
	if ((s + 2) > end)
	{
		throw std::runtime_error("Not anough data");
	}
	s += 2;

	if (prelen < 126)
	{
		_length = prelen;
	}
	else if (prelen == 126)
	{
		if ((s + 2) > end)
		{
			throw std::runtime_error("Not anough data");
		}
		uint16_t length;
		memcpy(&length, s, sizeof(length));
		s += sizeof(length);
		_length = be16toh(length);
	}
	else if (prelen == 127)
	{
		if ((s + 8) > end)
		{
			throw std::runtime_error("Not anough data");
		}
		uint64_t length;
		memcpy(&length, s, sizeof(length));
		s += sizeof(length);
		_length = be64toh(length);
	}

	if (_masked)
	{
		if ((s + 4) > end)
		{
			throw std::runtime_error("Not anough data");
		}
		_mask[0] = static_cast<uint8_t>(*s++);
		_mask[1] = static_cast<uint8_t>(*s++);
		_mask[2] = static_cast<uint8_t>(*s++);
		_mask[3] = static_cast<uint8_t>(*s++);
	}
	else
	{
		_mask[0] =
		_mask[1] =
		_mask[2] =
		_mask[3] = 0;
	}
}

void WsFrame::applyMask()
{
	if (!_masked)
	{
		return;
	}
	int i = 0;
	size_t remain = dataLen();
	for (auto &b : _data)
	{
		b ^= _mask[i++];
		if (!--remain) break;
		if (i == 4)
		{
			i = 0;
		}
	}
}

void WsFrame::send(std::shared_ptr<Writer> writer, Opcode code, const char *data, size_t size)
{
	bool masked = false;
	uint8_t byte;

	byte = (1_u8 << 7) | static_cast<uint8_t>(code);
	writer->write(&byte, sizeof(byte));

	byte = static_cast<uint8_t>((size > 65535) ? 127 : (size > 125) ? 126 : size);
	if (masked)
	{
		byte |= (1_u8 << 7);
	}
	writer->write(&byte, sizeof(byte));

	if (size > 65535)
	{
		uint64_t size64 = htobe64(static_cast<uint64_t>(size));
		writer->write(&size64, sizeof(size64));
	}
	else if (size > 125)
	{
		uint16_t size16 = htobe16(static_cast<uint16_t>(size));
		writer->write(&size16, sizeof(size16));
	}

	if (!masked)
	{
		writer->write(data, size);
		return;
	}

	union {
		uint32_t i;
		uint8_t b[4];
	} mask;

	mask.i = static_cast<uint32_t>(std::rand());

	for (size_t i = 0; i < sizeof(mask.b); i++)
	{
		writer->write(&mask.b[i], 1);
	}

	int i = 0;
	while (size--)
	{
		byte = static_cast<uint8_t>(*data++) ^ mask.b[i++];

		writer->write(&byte, sizeof(byte));

		if (i == 4)
		{
			i = 0;
		}
	}
}
<|endoftext|>


<commit_before>// -------------------------------------------------------------------------
//    @FileName         :    NFVector2.h
//    @Author           :    LvSheng.Huang
//    @Date             :    2016-09-27
//    @Module           :    NFVector2
//
// -------------------------------------------------------------------------

#ifndef NF_VETOR2_H
#define NF_VETOR2_H

#include <iostream>
#include <string>
#include <vector>
#include "NFComm/NFPluginModule/NFPlatform.h"

class NFLine;
class NFBox;
class NFPlane;
class NFVector3;

class NFVector2
{
private:
	float x, y;
	void InitData()
	{
		x = 0.0f;
		y = 0.0f;
	}

public:
	// construction
	NFVector2()
	{
		InitData();
	}

	NFVector2(float x, float y)
	{
		this->x = x;
		this->y = y;
	}

	NFVector2(float coordinate[2])
	{
		this->x = coordinate[0];
		this->y = coordinate[1];
	}

	NFVector2(double coordinate[2])
	{
		this->x = coordinate[0];
		this->y = coordinate[1];
	}

	NFVector2(const NFVector2& v)
	{
		this->x = v.x;
		this->y = v.x;
	}

	bool operator<(const NFVector2& v) const
	{
		return this->Length() < v.Length();
	}

	bool operator>(const NFVector2& v) const
	{
		return this->Length() > v.Length();
	}

	NFVector2& operator= (const NFVector2& v)
	{
		this->x = v.x;
		this->y = v.x;

		return *this;
	}

	bool operator== (const NFVector2& v) const
	{
		return std::abs(this->x - v.x) < 0.001f && std::abs(this->y - v.y) < 0.001f;
	}

	bool operator!= (const NFVector2& v) const
	{
		return std::abs(this->x - v.x) >= 0.001f || std::abs(this->y - v.y) >= 0.001f;
	}
	//----------------------------------------------------------------------------
	// Arithmetic Operations
	NFVector2 operator+ (const NFVector2& v) const
	{
		NFVector2 xV;

		xV.x = this->x + v.x;
		xV.y = this->y + v.y;
		return xV;
	}

	NFVector2 operator- (const NFVector2& v) const
	{
		NFVector2 xV;

		xV.x = this->x - v.x;
		xV.y = this->y - v.y;
		return xV;
	}

	NFVector2 operator- () const
	{
		return NFVector2(-x, -y);
	}

	NFVector2 operator* (float s) const
	{
		return NFVector2(x * s, y * s);
	}

	NFVector2 operator/ (float s) const
	{
		if (std::abs(s) > 0.001f)
		{
			return NFVector2(x / s, y / s);
		}

		return Zero();
	}

	//----------------------------------------------------------------------------
	// Arithmetic Updates
	NFVector2& operator+= (const NFVector2& v)
	{
		x += v.x;
		y += v.y;
		return *this;
	}

	NFVector2& operator-= (const NFVector2 v)
	{
		x -= v.x;
		y -= v.y;
		return *this;
	}

	NFVector2& operator*= (float s)
	{
		x *= s;
		y *= s;
		return *this;
	}

	NFVector2 operator/= (float s)
	{
		//if (std::abs(s) > 0.001f)
		{
			return NFVector2(x / s, y / s);
		}

		//return Zero();
	}

	float X() const
	{
		return this->x;
	}

	float Y() const
	{
		return this->y;
	}

	void SetX(float x)
	{
		this->x = x;
	}

	void SetY(float y)
	{
		this->y = y;
	}

	bool IsZero() const
	{
		return x < 0.001f && y < 0.001f;
	}

	//----------------------------------------------------------------------------
	inline float SquaredMagnitude() const
	{
		return x*x + y*y;
	}

	//----------------------------------------------------------------------------
	inline float SquaredLength() const
	{
		return SquaredMagnitude();
	}

	//----------------------------------------------------------------------------
	inline float Magnitude() const
	{
		return sqrtf(x*x + y*y);
	}

	//----------------------------------------------------------------------------
	inline float Length() const
	{
		return Magnitude();
	}

	//----------------------------------------------------------------------------
	inline NFVector2 Direction() const
	{
		if (this->IsZero())
		{
			return Zero();
		}

		float lenSquared = SquaredMagnitude();
		float invSqrt = 1.0f / sqrtf(lenSquared);
		return NFVector2(x * invSqrt, y * invSqrt);
	}

	//----------------------------------------------------------------------------
	inline NFVector2 Normalized() const
	{
		return Direction();
	}

	//----------------------------------------------------------------------------
	float Distance(const NFVector2& v) const
	{
		NFVector2 vX = *this - v;
		return vX.Length();
	}

	bool FromString(const std::string& value)
	{
		std::vector<std::string> values;
		Split(value, values, ",");
		if (values.size() != 2)
		{
			return false;
		}
		x = lexical_cast<float>(values.at(0));
		y = lexical_cast<float>(values.at(1));

		return true;
	}

	std::string ToString() const
	{
		return lexical_cast<std::string>(x) + "," + lexical_cast<std::string>(this->y);
	}

	// Special values.
	inline static const NFVector2& Zero()
	{
		static NFVector2 v(0, 0);
		return v;
	}

	inline static const NFVector2& One()
	{
		static NFVector2 v(1, 1);
		return v;
	}

	inline static const NFVector2& UnitX()
	{
		static NFVector2 v(1, 0);
		return v;
	}

	inline static const NFVector2& UnitY()
	{
		static NFVector2 v(0, 1);
		return v;
	}

	bool Split(const std::string& str, std::vector<std::string>& result, std::string delim)
	{
		if (str.empty())
		{
			return false;
		}

		std::string tmp;
		size_t pos_begin = str.find_first_not_of(delim);
		size_t pos = 0;
		while (pos_begin != std::string::npos)
		{
			pos = str.find(delim, pos_begin);
			if (pos != std::string::npos)
			{
				tmp = str.substr(pos_begin, pos - pos_begin);
				pos_begin = pos + delim.length();
			}
			else
			{
				tmp = str.substr(pos_begin);
				pos_begin = pos;
			}

			if (!tmp.empty())
			{
				result.push_back(tmp);
				tmp.clear();
			}
		}
		return true;
	}
};

#endif<commit_msg>fixed for NFVector2<commit_after>// -------------------------------------------------------------------------
//    @FileName         :    NFVector2.h
//    @Author           :    LvSheng.Huang
//    @Date             :    2016-09-27
//    @Module           :    NFVector2
//
// -------------------------------------------------------------------------

#ifndef NF_VETOR2_H
#define NF_VETOR2_H

#include <iostream>
#include <string>
#include <vector>
#include "NFComm/NFPluginModule/NFPlatform.h"

class NFLine;
class NFBox;
class NFPlane;
class NFVector3;

class NFVector2
{
private:
	float x, y;
	void InitData()
	{
		x = 0.0f;
		y = 0.0f;
	}

public:
	// construction
	NFVector2()
	{
		InitData();
	}

	NFVector2(float x, float y)
	{
		this->x = x;
		this->y = y;
	}

	NFVector2(float coordinate[2])
	{
		this->x = coordinate[0];
		this->y = coordinate[1];
	}

	NFVector2(double coordinate[2])
	{
		this->x = coordinate[0];
		this->y = coordinate[1];
	}

	NFVector2(const NFVector2& v)
	{
		this->x = v.x;
		this->y = v.y;
	}

	bool operator<(const NFVector2& v) const
	{
		return this->Length() < v.Length();
	}

	bool operator>(const NFVector2& v) const
	{
		return this->Length() > v.Length();
	}

	NFVector2& operator= (const NFVector2& v)
	{
		this->x = v.x;
		this->y = v.y;

		return *this;
	}

	bool operator== (const NFVector2& v) const
	{
		return std::abs(this->x - v.x) < 0.001f && std::abs(this->y - v.y) < 0.001f;
	}

	bool operator!= (const NFVector2& v) const
	{
		return std::abs(this->x - v.x) >= 0.001f || std::abs(this->y - v.y) >= 0.001f;
	}
	//----------------------------------------------------------------------------
	// Arithmetic Operations
	NFVector2 operator+ (const NFVector2& v) const
	{
		NFVector2 xV;

		xV.x = this->x + v.x;
		xV.y = this->y + v.y;
		return xV;
	}

	NFVector2 operator- (const NFVector2& v) const
	{
		NFVector2 xV;

		xV.x = this->x - v.x;
		xV.y = this->y - v.y;
		return xV;
	}

	NFVector2 operator- () const
	{
		return NFVector2(-x, -y);
	}

	NFVector2 operator* (float s) const
	{
		return NFVector2(x * s, y * s);
	}

	NFVector2 operator/ (float s) const
	{
		if (std::abs(s) > 0.001f)
		{
			return NFVector2(x / s, y / s);
		}

		return Zero();
	}

	//----------------------------------------------------------------------------
	// Arithmetic Updates
	NFVector2& operator+= (const NFVector2& v)
	{
		x += v.x;
		y += v.y;
		return *this;
	}

	NFVector2& operator-= (const NFVector2 v)
	{
		x -= v.x;
		y -= v.y;
		return *this;
	}

	NFVector2& operator*= (float s)
	{
		x *= s;
		y *= s;
		return *this;
	}

	NFVector2 operator/= (float s)
	{
		//if (std::abs(s) > 0.001f)
		{
			return NFVector2(x / s, y / s);
		}

		//return Zero();
	}

	float X() const
	{
		return this->x;
	}

	float Y() const
	{
		return this->y;
	}

	void SetX(float x)
	{
		this->x = x;
	}

	void SetY(float y)
	{
		this->y = y;
	}

	bool IsZero() const
	{
		return x < 0.001f && y < 0.001f;
	}

	//----------------------------------------------------------------------------
	inline float SquaredMagnitude() const
	{
		return x*x + y*y;
	}

	//----------------------------------------------------------------------------
	inline float SquaredLength() const
	{
		return SquaredMagnitude();
	}

	//----------------------------------------------------------------------------
	inline float Magnitude() const
	{
		return sqrtf(x*x + y*y);
	}

	//----------------------------------------------------------------------------
	inline float Length() const
	{
		return Magnitude();
	}

	//----------------------------------------------------------------------------
	inline NFVector2 Direction() const
	{
		if (this->IsZero())
		{
			return Zero();
		}

		float lenSquared = SquaredMagnitude();
		float invSqrt = 1.0f / sqrtf(lenSquared);
		return NFVector2(x * invSqrt, y * invSqrt);
	}

	//----------------------------------------------------------------------------
	inline NFVector2 Normalized() const
	{
		return Direction();
	}

	//----------------------------------------------------------------------------
	float Distance(const NFVector2& v) const
	{
		NFVector2 vX = *this - v;
		return vX.Length();
	}

	bool FromString(const std::string& value)
	{
		std::vector<std::string> values;
		Split(value, values, ",");
		if (values.size() != 2)
		{
			return false;
		}
		x = lexical_cast<float>(values.at(0));
		y = lexical_cast<float>(values.at(1));

		return true;
	}

	std::string ToString() const
	{
		return lexical_cast<std::string>(x) + "," + lexical_cast<std::string>(this->y);
	}

	// Special values.
	inline static const NFVector2& Zero()
	{
		static NFVector2 v(0, 0);
		return v;
	}

	inline static const NFVector2& One()
	{
		static NFVector2 v(1, 1);
		return v;
	}

	inline static const NFVector2& UnitX()
	{
		static NFVector2 v(1, 0);
		return v;
	}

	inline static const NFVector2& UnitY()
	{
		static NFVector2 v(0, 1);
		return v;
	}

	bool Split(const std::string& str, std::vector<std::string>& result, std::string delim)
	{
		if (str.empty())
		{
			return false;
		}

		std::string tmp;
		size_t pos_begin = str.find_first_not_of(delim);
		size_t pos = 0;
		while (pos_begin != std::string::npos)
		{
			pos = str.find(delim, pos_begin);
			if (pos != std::string::npos)
			{
				tmp = str.substr(pos_begin, pos - pos_begin);
				pos_begin = pos + delim.length();
			}
			else
			{
				tmp = str.substr(pos_begin);
				pos_begin = pos;
			}

			if (!tmp.empty())
			{
				result.push_back(tmp);
				tmp.clear();
			}
		}
		return true;
	}
};

#endif<|endoftext|>