<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/base/net_util.h"

#include <sys/types.h>

#include "base/eintr_wrapper.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "googleurl/src/gurl.h"
#include "net/base/escape.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"

#if !defined(OS_ANDROID)
#include <ifaddrs.h>
#endif

namespace net {

bool FileURLToFilePath(const GURL& url, FilePath* path) {
  *path = FilePath();
  std::string& file_path_str = const_cast<std::string&>(path->value());
  file_path_str.clear();

  if (!url.is_valid())
    return false;

  // Firefox seems to ignore the "host" of a file url if there is one. That is,
  // file://foo/bar.txt maps to /bar.txt.
  // TODO(dhg): This should probably take into account UNCs which could
  // include a hostname other than localhost or blank
  std::string old_path = url.path();

  if (old_path.empty())
    return false;

  // GURL stores strings as percent-encoded 8-bit, this will undo if possible.
  old_path = UnescapeURLComponent(old_path,
      UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS);

  // Collapse multiple path slashes into a single path slash.
  std::string new_path;
  do {
    new_path = old_path;
    ReplaceSubstringsAfterOffset(&new_path, 0, "//", "/");
    old_path.swap(new_path);
  } while (new_path != old_path);

  file_path_str.assign(old_path);

  return !file_path_str.empty();
}

bool GetNetworkList(NetworkInterfaceList* networks) {
#if defined(OS_ANDROID)
  // TODO: Android API doesn't support ifaddrs. This method was only used by
  // P2PMessage. Consider to implement it until really needed. The possible
  // approach is implementing the similar feature by
  // java.net.NetworkInterface through JNI.
  NOTIMPLEMENTED();
  return false;
#else
  // getifaddrs() may require IO operations.
  base::ThreadRestrictions::AssertIOAllowed();

  ifaddrs *ifaddr;
  if (getifaddrs(&ifaddr) < 0) {
    PLOG(ERROR) << "getifaddrs";
    return false;
  }

  for (ifaddrs *ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
    if (!ifa->ifa_addr)
      continue; // Interface has no IP addresses, so skip it.
    int family = ifa->ifa_addr->sa_family;
    if (family == AF_INET || family == AF_INET6) {
      IPEndPoint address;
      std::string name = ifa->ifa_name;
      if (address.FromSockAddr(ifa->ifa_addr,
                               sizeof(ifa->ifa_addr)) &&
          name.substr(0, 2) != "lo") {
        networks->push_back(NetworkInterface(name, address.address()));
      }
    }
  }

  freeifaddrs(ifaddr);

  return true;
#endif
}

}  // namespace net
<commit_msg>Cleanup GetNetworkList.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/base/net_util.h"

#include <sys/types.h>

#include "base/eintr_wrapper.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "googleurl/src/gurl.h"
#include "net/base/escape.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"

#if !defined(OS_ANDROID)
#include <ifaddrs.h>
#endif
#include <net/if.h>
#include <netinet/in.h>

namespace net {

bool FileURLToFilePath(const GURL& url, FilePath* path) {
  *path = FilePath();
  std::string& file_path_str = const_cast<std::string&>(path->value());
  file_path_str.clear();

  if (!url.is_valid())
    return false;

  // Firefox seems to ignore the "host" of a file url if there is one. That is,
  // file://foo/bar.txt maps to /bar.txt.
  // TODO(dhg): This should probably take into account UNCs which could
  // include a hostname other than localhost or blank
  std::string old_path = url.path();

  if (old_path.empty())
    return false;

  // GURL stores strings as percent-encoded 8-bit, this will undo if possible.
  old_path = UnescapeURLComponent(old_path,
      UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS);

  // Collapse multiple path slashes into a single path slash.
  std::string new_path;
  do {
    new_path = old_path;
    ReplaceSubstringsAfterOffset(&new_path, 0, "//", "/");
    old_path.swap(new_path);
  } while (new_path != old_path);

  file_path_str.assign(old_path);

  return !file_path_str.empty();
}

bool GetNetworkList(NetworkInterfaceList* networks) {
#if defined(OS_ANDROID)
  // TODO: Android API doesn't support ifaddrs. This method was only used by
  // P2PMessage. Consider to implement it until really needed. The possible
  // approach is implementing the similar feature by
  // java.net.NetworkInterface through JNI.
  NOTIMPLEMENTED();
  return false;
#else
  // getifaddrs() may require IO operations.
  base::ThreadRestrictions::AssertIOAllowed();

  ifaddrs *interfaces;
  if (getifaddrs(&interfaces) < 0) {
    PLOG(ERROR) << "getifaddrs";
    return false;
  }

  // Enumerate the addresses assigned to network interfaces which are up.
  for (ifaddrs *interface = interfaces;
       interface != NULL;
       interface = interface->ifa_next) {
    // Skip loopback interfaces, and ones which are down.
    if (!(IFF_UP & interface->ifa_flags))
      continue;
    if (IFF_LOOPBACK & interface->ifa_flags)
      continue;
    // Skip interfaces with no address configured.
    struct sockaddr* addr = interface->ifa_addr;
    if (!addr)
      continue;
    // Skip loopback addresses configured on non-loopback interfaces.
    int addr_size = 0;
    if (addr->sa_family == AF_INET6) {
      struct sockaddr_in6* addr_in6 =
          reinterpret_cast<struct sockaddr_in6*>(addr);
      struct in6_addr* sin6_addr = &addr_in6->sin6_addr;
      addr_size = sizeof(*addr_in6);
      if (IN6_IS_ADDR_LOOPBACK(sin6_addr))
        continue;
    } else if (addr->sa_family == AF_INET) {
      struct sockaddr_in* addr_in =
          reinterpret_cast<struct sockaddr_in*>(addr);
      addr_size = sizeof(*addr_in);
      if (addr_in->sin_addr.s_addr == INADDR_LOOPBACK)
        continue;
    } else {
      // Skip non-IP addresses.
      continue;
    }
    IPEndPoint address;
    std::string name = interface->ifa_name;
    if (address.FromSockAddr(addr, addr_size)) {
      networks->push_back(NetworkInterface(name, address.address()));
    }
  }

  freeifaddrs(interfaces);

  return true;
#endif
}

}  // namespace net
<|endoftext|>


<commit_before>#include <iostream>
#include "../include/baralho.h"
#include "../include/carta.h"
#include "../include/textura.h"

#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480

using namespace std;

int main(){
	// Janela principal
	SDL_Window* gWindow = NULL;

	// Renderizador principal
	SDL_Renderer* gRenderer = NULL;

	// Eventos
	SDL_Event event;

	// Responsavel pelo loop principal
	bool quit = false;

	// Cria a janela
	gWindow = SDL_CreateWindow("Freecell", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
	if(gWindow == NULL){
		cout << "Window could not be created. SDL Error: " << SDL_GetError() << endl;
	} else {
		// Cria o renderizador
		gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED);
		if(gRenderer == NULL) {
			cout << "Renderer could not be created. SDL Error: " << SDL_GetError() << endl;
		} else {
			// Inicializa a cor do renderizador
			SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);

			// Inicializa o carregamento de PNG
			int imgFlags = IMG_INIT_PNG;
			if(!(IMG_Init(imgFlags) & imgFlags)){
				cout << "SDL could not initialize image. SDL Error: " << IMG_GetError() << endl;
			}
		}
	}

	Baralho b = Baralho(52, gRenderer);
	Carta c = b.getCard();

	/*if(t == NULL){
		cout << "Failed to load texture." << endl;
	}*/

	// Loop  principal
	while(!quit){
		// Responsavel pelos eventos em espera
		while(SDL_PollEvent(&event) != 0){
			// Evento de saída
			if( event.type == SDL_QUIT)
				quit = true;
		}

		// Limpa a tela
		SDL_RenderClear(gRenderer);

		// Renderiza a carta
		c.renderCard();

		// Atualiza a tela
		SDL_RenderPresent(gRenderer);
	}

	// Destroi a janela
	SDL_DestroyRenderer(gRenderer);
	SDL_DestroyWindow(gWindow);
	gRenderer = NULL;
	gWindow = NULL;

	// Sai dos subsistemas
	IMG_Quit();
	SDL_Quit();

	return 0;
}
<commit_msg>SDL main requer esses argumentos<commit_after>#include <iostream>
#include "../include/baralho.h"
#include "../include/carta.h"
#include "../include/textura.h"

#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480

using namespace std;

int main(int argv, char** args){
	// Janela principal
	SDL_Window* gWindow = NULL;

	// Renderizador principal
	SDL_Renderer* gRenderer = NULL;

	// Eventos
	SDL_Event event;

	// Responsavel pelo loop principal
	bool quit = false;

	// Cria a janela
	gWindow = SDL_CreateWindow("Freecell", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
	if(gWindow == NULL){
		cout << "Window could not be created. SDL Error: " << SDL_GetError() << endl;
	} else {
		// Cria o renderizador
		gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED);
		if(gRenderer == NULL) {
			cout << "Renderer could not be created. SDL Error: " << SDL_GetError() << endl;
		} else {
			// Inicializa a cor do renderizador
			SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);

			// Inicializa o carregamento de PNG
			int imgFlags = IMG_INIT_PNG;
			if(!(IMG_Init(imgFlags) & imgFlags)){
				cout << "SDL could not initialize image. SDL Error: " << IMG_GetError() << endl;
			}
		}
	}

	Baralho b = Baralho(52, gRenderer);
	Carta c = b.getCard();

	/*if(t == NULL){
		cout << "Failed to load texture." << endl;
	}*/

	// Loop  principal
	while(!quit){
		// Responsavel pelos eventos em espera
		while(SDL_PollEvent(&event) != 0){
			// Evento de saída
			if( event.type == SDL_QUIT)
				quit = true;
		}

		// Limpa a tela
		SDL_RenderClear(gRenderer);

		// Renderiza a carta
		c.renderCard();

		// Atualiza a tela
		SDL_RenderPresent(gRenderer);
	}

	// Destroi a janela
	SDL_DestroyRenderer(gRenderer);
	SDL_DestroyWindow(gWindow);
	gRenderer = NULL;
	gWindow = NULL;

	// Sai dos subsistemas
	IMG_Quit();
	SDL_Quit();

	return 0;
}
<|endoftext|>


<commit_before>/*
 * Configuration backend
 *
 * This file is part of softrig, a simple software defined radio transceiver.
 *
 * Copyright 2017-2019 Alexandru Csete OZ9AEC.
 *
 * 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <new>          // std::nothrow
#include <QDebug>
#include <QSettings>

#include "app_config.h"

#define CONFIG_VERSION  1

#define APP                "app"
#define APP_CFG_VER         APP"/config_version"

#define SDR_INPUT           "sdr_input"
#define SDR_INPUT_TYPE      SDR_INPUT"/type"
#define SDR_INPUT_FREQ      SDR_INPUT"/frequency"
#define SDR_INPUT_NCO       SDR_INPUT"/nco"
#define SDR_INPUT_LNB       SDR_INPUT"/transverter"
#define SDR_INPUT_RATE      SDR_INPUT"/sample_rate"
#define SDR_INPUT_DECIM     SDR_INPUT"/decimation"
#define SDR_INPUT_BW        SDR_INPUT"/bandwidth"
#define SDR_INPUT_CORR      SDR_INPUT"/frequency_correction"
#define SDR_INPUT_GAIN_MODE SDR_INPUT"/gain_mode"
#define SDR_INPUT_GAIN      SDR_INPUT"/gain"

AppConfig::AppConfig()
{
    settings = nullptr;
}

AppConfig::~AppConfig()
{
    close();
}

int AppConfig::load(const QString &filename)
{
    if (filename.isEmpty()) // FIXME: check that it is a correct path
        return APP_CONFIG_EINVAL;

    close();

    settings = new (std::nothrow) QSettings(filename, QSettings::IniFormat);
    if (!settings)
        return APP_CONFIG_EFILE;

    app_config.version = settings->value(APP_CFG_VER, CONFIG_VERSION).toUInt();
    readDeviceConf();

    return APP_CONFIG_OK;
}

void AppConfig::save(void)
{
    if (!settings)
        return;

    settings->setValue(APP_CFG_VER, app_config.version);
    saveDeviceConf();
    settings->sync();
}

void AppConfig::close(void)
{
    if (!settings)
        return;

    settings->sync();
    delete settings;
    settings = nullptr;
}

void AppConfig::readDeviceConf(void)
{
    device_config_t     *input = &app_config.input;

    input->type = settings->value(SDR_INPUT_TYPE, "").toString();
    input->frequency = settings->value(SDR_INPUT_FREQ, 0).toULongLong();
    input->nco = settings->value(SDR_INPUT_NCO, 0).toLongLong();
    input->transverter = settings->value(SDR_INPUT_LNB, 0).toLongLong();
    input->rate = settings->value(SDR_INPUT_RATE, 0).toUInt();
    input->decimation = settings->value(SDR_INPUT_DECIM, 1).toUInt();
    input->bandwidth = settings->value(SDR_INPUT_BW, 0).toUInt();
    input->freq_corr_ppb = settings->value(SDR_INPUT_CORR, 0).toInt();
    input->gain_mode = settings->value(SDR_INPUT_GAIN_MODE, 0).toInt();
    input->gain = settings->value(SDR_INPUT_GAIN, 50).toInt();
}

void AppConfig::saveDeviceConf(void)
{
    device_config_t     *input = &app_config.input;

    if (input->type.isEmpty())
        settings->remove(SDR_INPUT_TYPE);
    else
        settings->setValue(SDR_INPUT_TYPE, input->type);

    if (input->frequency)
        settings->setValue(SDR_INPUT_FREQ, input->frequency);
    else
        settings->remove(SDR_INPUT_FREQ);

    if (input->nco)
        settings->setValue(SDR_INPUT_NCO, input->nco);
    else
        settings->remove(SDR_INPUT_NCO);

    if (input->transverter)
        settings->setValue(SDR_INPUT_LNB, input->transverter);
    else
        settings->remove(SDR_INPUT_LNB);

    if (input->rate)
        settings->setValue(SDR_INPUT_RATE, input->rate);
    else
        settings->remove(SDR_INPUT_RATE);

    if (input->decimation < 2)
        settings->remove(SDR_INPUT_DECIM);
    else
        settings->setValue(SDR_INPUT_DECIM, input->decimation);

    if (input->bandwidth)
        settings->setValue(SDR_INPUT_BW, input->bandwidth);
    else
        settings->remove(SDR_INPUT_BW);

    if (input->freq_corr_ppb)
        settings->setValue(SDR_INPUT_CORR, input->freq_corr_ppb);
    else
        settings->remove(SDR_INPUT_CORR);

    if (input->gain_mode)
        settings->setValue(SDR_INPUT_GAIN_MODE, input->gain_mode);
    else
        settings->remove(SDR_INPUT_GAIN_MODE);

    if (input->gain)
        settings->setValue(SDR_INPUT_GAIN, input->gain);
    else
        settings->remove(SDR_INPUT_GAIN);
}

<commit_msg>Update default RF frequency<commit_after>/*
 * Configuration backend
 *
 * This file is part of softrig, a simple software defined radio transceiver.
 *
 * Copyright 2017-2019 Alexandru Csete OZ9AEC.
 *
 * 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <new>          // std::nothrow
#include <QDebug>
#include <QSettings>

#include "app_config.h"

#define CONFIG_VERSION  1

#define APP                "app"
#define APP_CFG_VER         APP"/config_version"

#define SDR_INPUT           "sdr_input"
#define SDR_INPUT_TYPE      SDR_INPUT"/type"
#define SDR_INPUT_FREQ      SDR_INPUT"/frequency"
#define SDR_INPUT_NCO       SDR_INPUT"/nco"
#define SDR_INPUT_LNB       SDR_INPUT"/transverter"
#define SDR_INPUT_RATE      SDR_INPUT"/sample_rate"
#define SDR_INPUT_DECIM     SDR_INPUT"/decimation"
#define SDR_INPUT_BW        SDR_INPUT"/bandwidth"
#define SDR_INPUT_CORR      SDR_INPUT"/frequency_correction"
#define SDR_INPUT_GAIN_MODE SDR_INPUT"/gain_mode"
#define SDR_INPUT_GAIN      SDR_INPUT"/gain"

AppConfig::AppConfig()
{
    settings = nullptr;
}

AppConfig::~AppConfig()
{
    close();
}

int AppConfig::load(const QString &filename)
{
    if (filename.isEmpty()) // FIXME: check that it is a correct path
        return APP_CONFIG_EINVAL;

    close();

    settings = new (std::nothrow) QSettings(filename, QSettings::IniFormat);
    if (!settings)
        return APP_CONFIG_EFILE;

    app_config.version = settings->value(APP_CFG_VER, CONFIG_VERSION).toUInt();
    readDeviceConf();

    return APP_CONFIG_OK;
}

void AppConfig::save(void)
{
    if (!settings)
        return;

    settings->setValue(APP_CFG_VER, app_config.version);
    saveDeviceConf();
    settings->sync();
}

void AppConfig::close(void)
{
    if (!settings)
        return;

    settings->sync();
    delete settings;
    settings = nullptr;
}

void AppConfig::readDeviceConf(void)
{
    device_config_t     *input = &app_config.input;

    input->type = settings->value(SDR_INPUT_TYPE, "").toString();
    input->frequency = settings->value(SDR_INPUT_FREQ, 145e6).toULongLong();
    input->nco = settings->value(SDR_INPUT_NCO, 0).toLongLong();
    input->transverter = settings->value(SDR_INPUT_LNB, 0).toLongLong();
    input->rate = settings->value(SDR_INPUT_RATE, 0).toUInt();
    input->decimation = settings->value(SDR_INPUT_DECIM, 1).toUInt();
    input->bandwidth = settings->value(SDR_INPUT_BW, 0).toUInt();
    input->freq_corr_ppb = settings->value(SDR_INPUT_CORR, 0).toInt();
    input->gain_mode = settings->value(SDR_INPUT_GAIN_MODE, 0).toInt();
    input->gain = settings->value(SDR_INPUT_GAIN, 50).toInt();
}

void AppConfig::saveDeviceConf(void)
{
    device_config_t     *input = &app_config.input;

    if (input->type.isEmpty())
        settings->remove(SDR_INPUT_TYPE);
    else
        settings->setValue(SDR_INPUT_TYPE, input->type);

    if (input->frequency)
        settings->setValue(SDR_INPUT_FREQ, input->frequency);
    else
        settings->remove(SDR_INPUT_FREQ);

    if (input->nco)
        settings->setValue(SDR_INPUT_NCO, input->nco);
    else
        settings->remove(SDR_INPUT_NCO);

    if (input->transverter)
        settings->setValue(SDR_INPUT_LNB, input->transverter);
    else
        settings->remove(SDR_INPUT_LNB);

    if (input->rate)
        settings->setValue(SDR_INPUT_RATE, input->rate);
    else
        settings->remove(SDR_INPUT_RATE);

    if (input->decimation < 2)
        settings->remove(SDR_INPUT_DECIM);
    else
        settings->setValue(SDR_INPUT_DECIM, input->decimation);

    if (input->bandwidth)
        settings->setValue(SDR_INPUT_BW, input->bandwidth);
    else
        settings->remove(SDR_INPUT_BW);

    if (input->freq_corr_ppb)
        settings->setValue(SDR_INPUT_CORR, input->freq_corr_ppb);
    else
        settings->remove(SDR_INPUT_CORR);

    if (input->gain_mode)
        settings->setValue(SDR_INPUT_GAIN_MODE, input->gain_mode);
    else
        settings->remove(SDR_INPUT_GAIN_MODE);

    if (input->gain)
        settings->setValue(SDR_INPUT_GAIN, input->gain);
    else
        settings->remove(SDR_INPUT_GAIN);
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: X11_clipboard.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 05:57:48 $
 *
 *  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
 *
 ************************************************************************/

#include <X11/Xatom.h>
#include <X11_clipboard.hxx>
#include <X11_transferable.hxx>

#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_RENDERINGCAPABILITIES_HPP_
#include <com/sun/star/datatransfer/clipboard/RenderingCapabilities.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif

#ifndef _UNO_DISPATCHER_H_
#include <uno/dispatcher.h> // declaration of generic uno interface
#endif
#ifndef _UNO_MAPPING_HXX_
#include <uno/mapping.hxx> // mapping stuff
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif

#if OSL_DEBUG_LEVEL > 1
#include <stdio.h>
#endif

using namespace com::sun::star::datatransfer;
using namespace com::sun::star::datatransfer::clipboard;
using namespace com::sun::star::lang;
using namespace com::sun::star::uno;
using namespace com::sun::star::awt;
using namespace cppu;
using namespace osl;
using namespace rtl;
using namespace x11;

X11Clipboard::X11Clipboard( SelectionManager& rManager, Atom aSelection ) :
        ::cppu::WeakComponentImplHelper4<
    ::com::sun::star::datatransfer::clipboard::XClipboardEx,
    ::com::sun::star::datatransfer::clipboard::XClipboardNotifier,
    ::com::sun::star::lang::XServiceInfo,
    ::com::sun::star::lang::XInitialization
    >( rManager.getMutex() ),

        m_rSelectionManager( rManager ),
        m_xSelectionManager( & rManager ),
        m_aSelection( aSelection )
{
#if OSL_DEBUG_LEVEL > 1
    fprintf( stderr, "creating instance of X11Clipboard (this=%p)\n", this );
#endif

    if( m_aSelection != None )
    {
        m_rSelectionManager.registerHandler( m_aSelection, *this );
    }
    else
    {
        m_rSelectionManager.registerHandler( XA_PRIMARY, *this );
        m_rSelectionManager.registerHandler( m_rSelectionManager.getAtom( OUString::createFromAscii( "CLIPBOARD" ) ), *this );
    }
}

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

X11Clipboard::~X11Clipboard()
{
    MutexGuard aGuard( *Mutex::getGlobalMutex() );

#if OSL_DEBUG_LEVEL > 1
    fprintf( stderr, "shutting down instance of X11Clipboard (this=%p, Selecttion=\"%s\")\n", this, OUStringToOString( m_rSelectionManager.getString( m_aSelection ), RTL_TEXTENCODING_ISO_8859_1 ).getStr() );
#endif
    if( m_aSelection != None )
        m_rSelectionManager.deregisterHandler( m_aSelection );
    else
    {
        m_rSelectionManager.deregisterHandler( XA_PRIMARY );
        m_rSelectionManager.deregisterHandler( m_rSelectionManager.getAtom( OUString::createFromAscii( "CLIPBOARD" ) ) );
    }
}

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

void X11Clipboard::fireChangedContentsEvent()
{
    ClearableMutexGuard aGuard( m_rSelectionManager.getMutex() );
#if OSL_DEBUG_LEVEL > 1
    fprintf( stderr, "X11Clipboard::fireChangedContentsEvent for %s (%d listeners)\n",
             OUStringToOString( m_rSelectionManager.getString( m_aSelection ), RTL_TEXTENCODING_ISO_8859_1 ).getStr(), m_aListeners.size() );
#endif
    ::std::list< Reference< XClipboardListener > > listeners( m_aListeners );
    aGuard.clear();

    ClipboardEvent aEvent( static_cast<OWeakObject*>(this), m_aContents);
    while( listeners.begin() != listeners.end() )
    {
        if( listeners.front().is() )
            listeners.front()->changedContents(aEvent);
        listeners.pop_front();
    }
}

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

void X11Clipboard::clearContents()
{
    ClearableMutexGuard aGuard(m_rSelectionManager.getMutex());
    // protect against deletion during outside call
    Reference< XClipboard > xThis( static_cast<XClipboard*>(this));
    // copy member references on stack so they can be called
    // without having the mutex
    Reference< XClipboardOwner > xOwner( m_aOwner );
    Reference< XTransferable > xTrans( m_aContents );
    // clear members
    m_aOwner.clear();
    m_aContents.clear();

    // release the mutex
    aGuard.clear();

    // inform previous owner of lost ownership
    if ( xOwner.is() )
        xOwner->lostOwnership(xThis, m_aContents);
}

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

Reference< XTransferable > SAL_CALL X11Clipboard::getContents()
    throw(RuntimeException)
{
    MutexGuard aGuard(m_rSelectionManager.getMutex());

    if( ! m_aContents.is() )
        m_aContents = new X11Transferable( SelectionManager::get(), static_cast< OWeakObject* >(this), m_aSelection );
    return m_aContents;
}

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

void SAL_CALL X11Clipboard::setContents(
    const Reference< XTransferable >& xTrans,
    const Reference< XClipboardOwner >& xClipboardOwner )
    throw(RuntimeException)
{
    // remember old values for callbacks before setting the new ones.
    ClearableMutexGuard aGuard(m_rSelectionManager.getMutex());

    Reference< XClipboardOwner > oldOwner( m_aOwner );
    m_aOwner = xClipboardOwner;

    Reference< XTransferable > oldContents( m_aContents );
    m_aContents = xTrans;

    aGuard.clear();

    // for now request ownership for both selections
    if( m_aSelection != None )
        m_rSelectionManager.requestOwnership( m_aSelection );
    else
    {
        m_rSelectionManager.requestOwnership( XA_PRIMARY );
        m_rSelectionManager.requestOwnership( m_rSelectionManager.getAtom( OUString::createFromAscii( "CLIPBOARD" ) ) );
    }

    // notify old owner on loss of ownership
    if( oldOwner.is() )
        oldOwner->lostOwnership(static_cast < XClipboard * > (this), oldContents);

    // notify all listeners on content changes
    fireChangedContentsEvent();
}

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

OUString SAL_CALL X11Clipboard::getName()
    throw(RuntimeException)
{
    return m_rSelectionManager.getString( m_aSelection );
}

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

sal_Int8 SAL_CALL X11Clipboard::getRenderingCapabilities()
    throw(RuntimeException)
{
    return RenderingCapabilities::Delayed;
}

// ------------------------------------------------------------------------
void SAL_CALL X11Clipboard::addClipboardListener( const Reference< XClipboardListener >& listener )
    throw(RuntimeException)
{
    MutexGuard aGuard( m_rSelectionManager.getMutex() );
    m_aListeners.push_back( listener );
}

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

void SAL_CALL X11Clipboard::removeClipboardListener( const Reference< XClipboardListener >& listener )
    throw(RuntimeException)
{
    MutexGuard aGuard( m_rSelectionManager.getMutex() );
    m_aListeners.remove( listener );
}

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

Reference< XTransferable > X11Clipboard::getTransferable()
{
    return getContents();
}

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

void X11Clipboard::clearTransferable()
{
    clearContents();
}

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

void X11Clipboard::fireContentsChanged()
{
    fireChangedContentsEvent();
}

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

Reference< XInterface > X11Clipboard::getReference() throw()
{
    return Reference< XInterface >( static_cast< OWeakObject* >(this) );
}

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

OUString SAL_CALL X11Clipboard::getImplementationName(  )
    throw(RuntimeException)
{
    return OUString::createFromAscii(X11_CLIPBOARD_IMPLEMENTATION_NAME);
}

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

sal_Bool SAL_CALL X11Clipboard::supportsService( const OUString& ServiceName )
    throw(RuntimeException)
{
    Sequence < OUString > SupportedServicesNames = X11Clipboard_getSupportedServiceNames();

    for ( sal_Int32 n = SupportedServicesNames.getLength(); n--; )
        if (SupportedServicesNames[n].compareTo(ServiceName) == 0)
            return sal_True;

    return sal_False;
}

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

void SAL_CALL X11Clipboard::initialize( const Sequence< Any >& ) throw( ::com::sun::star::uno::Exception )
{
}

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

Sequence< OUString > SAL_CALL X11Clipboard::getSupportedServiceNames(    )
    throw(RuntimeException)
{
    return X11Clipboard_getSupportedServiceNames();
}

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

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

#include <X11/Xatom.h>
#include <X11_clipboard.hxx>
#include <X11_transferable.hxx>

#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_RENDERINGCAPABILITIES_HPP_
#include <com/sun/star/datatransfer/clipboard/RenderingCapabilities.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif

#ifndef _UNO_DISPATCHER_H_
#include <uno/dispatcher.h> // declaration of generic uno interface
#endif
#ifndef _UNO_MAPPING_HXX_
#include <uno/mapping.hxx> // mapping stuff
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif

#if OSL_DEBUG_LEVEL > 1
#include <stdio.h>
#endif

using namespace com::sun::star::datatransfer;
using namespace com::sun::star::datatransfer::clipboard;
using namespace com::sun::star::lang;
using namespace com::sun::star::uno;
using namespace com::sun::star::awt;
using namespace cppu;
using namespace osl;
using namespace rtl;
using namespace x11;

X11Clipboard::X11Clipboard( SelectionManager& rManager, Atom aSelection ) :
        ::cppu::WeakComponentImplHelper4<
    ::com::sun::star::datatransfer::clipboard::XClipboardEx,
    ::com::sun::star::datatransfer::clipboard::XClipboardNotifier,
    ::com::sun::star::lang::XServiceInfo,
    ::com::sun::star::lang::XInitialization
    >( rManager.getMutex() ),

        m_rSelectionManager( rManager ),
        m_xSelectionManager( & rManager ),
        m_aSelection( aSelection )
{
#if OSL_DEBUG_LEVEL > 1
    fprintf( stderr, "creating instance of X11Clipboard (this=%p)\n", this );
#endif

    if( m_aSelection != None )
    {
        m_rSelectionManager.registerHandler( m_aSelection, *this );
    }
    else
    {
        m_rSelectionManager.registerHandler( XA_PRIMARY, *this );
        m_rSelectionManager.registerHandler( m_rSelectionManager.getAtom( OUString::createFromAscii( "CLIPBOARD" ) ), *this );
    }
}

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

X11Clipboard::~X11Clipboard()
{
    MutexGuard aGuard( *Mutex::getGlobalMutex() );

#if OSL_DEBUG_LEVEL > 1
    fprintf( stderr, "shutting down instance of X11Clipboard (this=%p, Selecttion=\"%s\")\n", this, OUStringToOString( m_rSelectionManager.getString( m_aSelection ), RTL_TEXTENCODING_ISO_8859_1 ).getStr() );
#endif
    if( m_aSelection != None )
        m_rSelectionManager.deregisterHandler( m_aSelection );
    else
    {
        m_rSelectionManager.deregisterHandler( XA_PRIMARY );
        m_rSelectionManager.deregisterHandler( m_rSelectionManager.getAtom( OUString::createFromAscii( "CLIPBOARD" ) ) );
    }
}

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

void X11Clipboard::fireChangedContentsEvent()
{
    ClearableMutexGuard aGuard( m_rSelectionManager.getMutex() );
#if OSL_DEBUG_LEVEL > 1
    fprintf( stderr, "X11Clipboard::fireChangedContentsEvent for %s (%d listeners)\n",
             OUStringToOString( m_rSelectionManager.getString( m_aSelection ), RTL_TEXTENCODING_ISO_8859_1 ).getStr(), m_aListeners.size() );
#endif
    ::std::list< Reference< XClipboardListener > > listeners( m_aListeners );
    aGuard.clear();

    ClipboardEvent aEvent( static_cast<OWeakObject*>(this), m_aContents);
    while( listeners.begin() != listeners.end() )
    {
        if( listeners.front().is() )
            listeners.front()->changedContents(aEvent);
        listeners.pop_front();
    }
}

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

void X11Clipboard::clearContents()
{
    ClearableMutexGuard aGuard(m_rSelectionManager.getMutex());
    // protect against deletion during outside call
    Reference< XClipboard > xThis( static_cast<XClipboard*>(this));
    // copy member references on stack so they can be called
    // without having the mutex
    Reference< XClipboardOwner > xOwner( m_aOwner );
    Reference< XTransferable > xTrans( m_aContents );
    // clear members
    m_aOwner.clear();
    m_aContents.clear();

    // release the mutex
    aGuard.clear();

    // inform previous owner of lost ownership
    if ( xOwner.is() )
        xOwner->lostOwnership(xThis, m_aContents);
}

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

Reference< XTransferable > SAL_CALL X11Clipboard::getContents()
    throw(RuntimeException)
{
    MutexGuard aGuard(m_rSelectionManager.getMutex());

    if( ! m_aContents.is() )
        m_aContents = new X11Transferable( SelectionManager::get(), static_cast< OWeakObject* >(this), m_aSelection );
    return m_aContents;
}

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

void SAL_CALL X11Clipboard::setContents(
    const Reference< XTransferable >& xTrans,
    const Reference< XClipboardOwner >& xClipboardOwner )
    throw(RuntimeException)
{
    // remember old values for callbacks before setting the new ones.
    ClearableMutexGuard aGuard(m_rSelectionManager.getMutex());

    Reference< XClipboardOwner > oldOwner( m_aOwner );
    m_aOwner = xClipboardOwner;

    Reference< XTransferable > oldContents( m_aContents );
    m_aContents = xTrans;

    aGuard.clear();

    // for now request ownership for both selections
    if( m_aSelection != None )
        m_rSelectionManager.requestOwnership( m_aSelection );
    else
    {
        m_rSelectionManager.requestOwnership( XA_PRIMARY );
        m_rSelectionManager.requestOwnership( m_rSelectionManager.getAtom( OUString::createFromAscii( "CLIPBOARD" ) ) );
    }

    // notify old owner on loss of ownership
    if( oldOwner.is() )
        oldOwner->lostOwnership(static_cast < XClipboard * > (this), oldContents);

    // notify all listeners on content changes
    fireChangedContentsEvent();
}

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

OUString SAL_CALL X11Clipboard::getName()
    throw(RuntimeException)
{
    return m_rSelectionManager.getString( m_aSelection );
}

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

sal_Int8 SAL_CALL X11Clipboard::getRenderingCapabilities()
    throw(RuntimeException)
{
    return RenderingCapabilities::Delayed;
}

// ------------------------------------------------------------------------
void SAL_CALL X11Clipboard::addClipboardListener( const Reference< XClipboardListener >& listener )
    throw(RuntimeException)
{
    MutexGuard aGuard( m_rSelectionManager.getMutex() );
    m_aListeners.push_back( listener );
}

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

void SAL_CALL X11Clipboard::removeClipboardListener( const Reference< XClipboardListener >& listener )
    throw(RuntimeException)
{
    MutexGuard aGuard( m_rSelectionManager.getMutex() );
    m_aListeners.remove( listener );
}

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

Reference< XTransferable > X11Clipboard::getTransferable()
{
    return getContents();
}

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

void X11Clipboard::clearTransferable()
{
    clearContents();
}

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

void X11Clipboard::fireContentsChanged()
{
    fireChangedContentsEvent();
}

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

Reference< XInterface > X11Clipboard::getReference() throw()
{
    return Reference< XInterface >( static_cast< OWeakObject* >(this) );
}

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

OUString SAL_CALL X11Clipboard::getImplementationName(  )
    throw(RuntimeException)
{
    return OUString::createFromAscii(X11_CLIPBOARD_IMPLEMENTATION_NAME);
}

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

sal_Bool SAL_CALL X11Clipboard::supportsService( const OUString& ServiceName )
    throw(RuntimeException)
{
    Sequence < OUString > SupportedServicesNames = X11Clipboard_getSupportedServiceNames();

    for ( sal_Int32 n = SupportedServicesNames.getLength(); n--; )
        if (SupportedServicesNames[n].compareTo(ServiceName) == 0)
            return sal_True;

    return sal_False;
}

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

void SAL_CALL X11Clipboard::initialize( const Sequence< Any >& ) throw( ::com::sun::star::uno::Exception )
{
}

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

Sequence< OUString > SAL_CALL X11Clipboard::getSupportedServiceNames(    )
    throw(RuntimeException)
{
    return X11Clipboard_getSupportedServiceNames();
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: shellextensions.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 16:40:46 $
 *
 *  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
 *
 ************************************************************************/

/*
    Windows shell extensions need to be approved in order to be used by the
    Windows shell for clarification read the following section from the
    Microsoft Developers Network Library (MSDN) see
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/programmersguide/shell_int/shell_int_extending/extensionhandlers/shell_ext.asp

    <MSDN>
    Shell extension handlers run in the Shell process. Because it is a system process,
    the administrator of a Windows NT system can limit Shell extension handlers to
    those on an approved list by setting the EnforceShellExtensionSecurity value of the
    HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer key to 1
    (one).
    To place a Shell extension handler on the approved list, create a REG_SZ value whose
    name is the string form of the handler's GUID under
    HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved.

    The Shell does not use the value that is assigned to the GUID, but it should be set to
    make inspecting the registry easier.

    Your setup application can add values to the Approved key only if the person installing
    the application has sufficient privileges. If the attempt to add an extension handler
    fails, you should inform the user that administrative privileges are required to fully
    install the application. If the handler is essential to the application, you should fail
    the setup and notify the user to contact an administrator.

    While there is no need to add values to the Approved key on Windows 95 or Windows 98
    systems, there is no harm in doing so. The system will simply ignore them. However, there
    is no guarantee that the key will exist on these systems. Your setup program must be able
    to handle this case.
    </MSDN>

    We add the following entries to the respective registry key
    "{C52AF81D-F7A0-4AAB-8E87-F80A60CCD396}"="OpenOffice.org Column Handler"
    "{087B3AE3-E237-4467-B8DB-5A38AB959AC9}"="OpenOffice.org Infotip Handler"
    "{63542C48-9552-494A-84F7-73AA6A7C99C1}"="OpenOffice.org Property Sheet Handler"
    "{3B092F0C-7696-40E3-A80F-68D74DA84210}"="OpenOffice.org Thumbnail Viewer"

    These shell extensions are implemented in the 'shell' project. We ignore registration
    failures because of insufficient privileges. The reason is: On systems which restrict the
    use of shell extensions by applying the aforementioned policy probably only people with
    sufficient privileges are allowed to install applications anyway. On systems where the
    use of shell extensions is not restricted registration failures because of insufficient
    prviliges have no negative effect because the shell extensions will work anyhow.
*/

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#include <malloc.h>

#ifdef UNICODE
#define _UNICODE
#endif
#include <tchar.h>

struct RegistryEntry
{
    TCHAR* Key;
    TCHAR* Value;
};

RegistryEntry ColumnHandler = { TEXT("{C52AF81D-F7A0-4AAB-8E87-F80A60CCD396}"), TEXT("OpenOffice.org Column Handler") };
RegistryEntry InfotipHandler = { TEXT("{087B3AE3-E237-4467-B8DB-5A38AB959AC9}"), TEXT("OpenOffice.org Infotip Handler") };
RegistryEntry PropHandler = { TEXT("{63542C48-9552-494A-84F7-73AA6A7C99C1}"), TEXT("OpenOffice.org Property Sheet Handler") };
RegistryEntry ThumbViewer = { TEXT("{3B092F0C-7696-40E3-A80F-68D74DA84210}"), TEXT("OpenOffice.org Thumbnail Viewer") };

/*
    Called during installation when the module "Windows Explorer Extensions" is
    selected.
*/
extern "C" UINT __stdcall InstallExecSequenceEntry(MSIHANDLE handle)
{
    //MessageBox(NULL, TEXT("InstallExecSequenceEntry"), TEXT("Pythonmsi"), MB_OK | MB_ICONINFORMATION);
    HKEY hKey;
    if (RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved"), &hKey) == ERROR_SUCCESS)
    {
        RegSetValueEx(hKey, ColumnHandler.Key, 0, REG_SZ, reinterpret_cast<const BYTE*>(ColumnHandler.Value), _tcslen(ColumnHandler.Value) + 1);
        RegSetValueEx(hKey, InfotipHandler.Key, 0, REG_SZ, reinterpret_cast<const BYTE*>(InfotipHandler.Value), _tcslen(InfotipHandler.Value) + 1);
        RegSetValueEx(hKey, PropHandler.Key, 0, REG_SZ, reinterpret_cast<const BYTE*>(PropHandler.Value), _tcslen(PropHandler.Value) + 1);
        RegSetValueEx(hKey, ThumbViewer.Key, 0, REG_SZ, reinterpret_cast<const BYTE*>(ThumbViewer.Value), _tcslen(ThumbViewer.Value) + 1);

        RegCloseKey(hKey);
    }
    return ERROR_SUCCESS;
}

/*
    Called during deinstallation when the module "Windows Explorer Extensions" has
    been installed.
*/
extern "C" UINT __stdcall DeinstallExecSequenceEntry(MSIHANDLE handle)
{
    //MessageBox(NULL, TEXT("DeinstallExecSequenceEntry"), TEXT("Pythonmsi"), MB_OK | MB_ICONINFORMATION);
    HKEY hKey;
    if (RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved"), &hKey) == ERROR_SUCCESS)
    {
        RegDeleteValue(hKey, ColumnHandler.Key);
        RegDeleteValue(hKey, InfotipHandler.Key);
        RegDeleteValue(hKey, PropHandler.Key);
        RegDeleteValue(hKey, ThumbViewer.Key);

        RegCloseKey(hKey);
    }
    return ERROR_SUCCESS;
}
<commit_msg>INTEGRATION: CWS warnings01 (1.4.18); FILE MERGED 2006/01/31 13:35:35 sb 1.4.18.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: shellextensions.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 03:42:06 $
 *
 *  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
 *
 ************************************************************************/

/*
    Windows shell extensions need to be approved in order to be used by the
    Windows shell for clarification read the following section from the
    Microsoft Developers Network Library (MSDN) see
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/programmersguide/shell_int/shell_int_extending/extensionhandlers/shell_ext.asp

    <MSDN>
    Shell extension handlers run in the Shell process. Because it is a system process,
    the administrator of a Windows NT system can limit Shell extension handlers to
    those on an approved list by setting the EnforceShellExtensionSecurity value of the
    HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer key to 1
    (one).
    To place a Shell extension handler on the approved list, create a REG_SZ value whose
    name is the string form of the handler's GUID under
    HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved.

    The Shell does not use the value that is assigned to the GUID, but it should be set to
    make inspecting the registry easier.

    Your setup application can add values to the Approved key only if the person installing
    the application has sufficient privileges. If the attempt to add an extension handler
    fails, you should inform the user that administrative privileges are required to fully
    install the application. If the handler is essential to the application, you should fail
    the setup and notify the user to contact an administrator.

    While there is no need to add values to the Approved key on Windows 95 or Windows 98
    systems, there is no harm in doing so. The system will simply ignore them. However, there
    is no guarantee that the key will exist on these systems. Your setup program must be able
    to handle this case.
    </MSDN>

    We add the following entries to the respective registry key
    "{C52AF81D-F7A0-4AAB-8E87-F80A60CCD396}"="OpenOffice.org Column Handler"
    "{087B3AE3-E237-4467-B8DB-5A38AB959AC9}"="OpenOffice.org Infotip Handler"
    "{63542C48-9552-494A-84F7-73AA6A7C99C1}"="OpenOffice.org Property Sheet Handler"
    "{3B092F0C-7696-40E3-A80F-68D74DA84210}"="OpenOffice.org Thumbnail Viewer"

    These shell extensions are implemented in the 'shell' project. We ignore registration
    failures because of insufficient privileges. The reason is: On systems which restrict the
    use of shell extensions by applying the aforementioned policy probably only people with
    sufficient privileges are allowed to install applications anyway. On systems where the
    use of shell extensions is not restricted registration failures because of insufficient
    prviliges have no negative effect because the shell extensions will work anyhow.
*/

#pragma warning(push, 1) /* disable warnings within system headers */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#pragma warning(pop)

#include <malloc.h>

#ifdef UNICODE
#define _UNICODE
#endif
#include <tchar.h>

struct RegistryEntry
{
    TCHAR* Key;
    TCHAR* Value;
};

RegistryEntry ColumnHandler = { TEXT("{C52AF81D-F7A0-4AAB-8E87-F80A60CCD396}"), TEXT("OpenOffice.org Column Handler") };
RegistryEntry InfotipHandler = { TEXT("{087B3AE3-E237-4467-B8DB-5A38AB959AC9}"), TEXT("OpenOffice.org Infotip Handler") };
RegistryEntry PropHandler = { TEXT("{63542C48-9552-494A-84F7-73AA6A7C99C1}"), TEXT("OpenOffice.org Property Sheet Handler") };
RegistryEntry ThumbViewer = { TEXT("{3B092F0C-7696-40E3-A80F-68D74DA84210}"), TEXT("OpenOffice.org Thumbnail Viewer") };

/*
    Called during installation when the module "Windows Explorer Extensions" is
    selected.
*/
extern "C" UINT __stdcall InstallExecSequenceEntry(MSIHANDLE)
{
    //MessageBox(NULL, TEXT("InstallExecSequenceEntry"), TEXT("Pythonmsi"), MB_OK | MB_ICONINFORMATION);
    HKEY hKey;
    if (RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved"), &hKey) == ERROR_SUCCESS)
    {
        RegSetValueEx(hKey, ColumnHandler.Key, 0, REG_SZ, reinterpret_cast<const BYTE*>(ColumnHandler.Value), _tcslen(ColumnHandler.Value) + 1);
        RegSetValueEx(hKey, InfotipHandler.Key, 0, REG_SZ, reinterpret_cast<const BYTE*>(InfotipHandler.Value), _tcslen(InfotipHandler.Value) + 1);
        RegSetValueEx(hKey, PropHandler.Key, 0, REG_SZ, reinterpret_cast<const BYTE*>(PropHandler.Value), _tcslen(PropHandler.Value) + 1);
        RegSetValueEx(hKey, ThumbViewer.Key, 0, REG_SZ, reinterpret_cast<const BYTE*>(ThumbViewer.Value), _tcslen(ThumbViewer.Value) + 1);

        RegCloseKey(hKey);
    }
    return ERROR_SUCCESS;
}

/*
    Called during deinstallation when the module "Windows Explorer Extensions" has
    been installed.
*/
extern "C" UINT __stdcall DeinstallExecSequenceEntry(MSIHANDLE)
{
    //MessageBox(NULL, TEXT("DeinstallExecSequenceEntry"), TEXT("Pythonmsi"), MB_OK | MB_ICONINFORMATION);
    HKEY hKey;
    if (RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved"), &hKey) == ERROR_SUCCESS)
    {
        RegDeleteValue(hKey, ColumnHandler.Key);
        RegDeleteValue(hKey, InfotipHandler.Key);
        RegDeleteValue(hKey, PropHandler.Key);
        RegDeleteValue(hKey, ThumbViewer.Key);

        RegCloseKey(hKey);
    }
    return ERROR_SUCCESS;
}
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2020)

#ifndef DUNE_GDT_OPERATORS_BILINEAR_FORM_HH
#define DUNE_GDT_OPERATORS_BILINEAR_FORM_HH

#include <dune/xt/common/parallel/threadstorage.hh>
#include <dune/xt/common/timedlogging.hh>
#include <dune/xt/la/type_traits.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/grid/walker.hh>
#include <dune/xt/functions/grid-function.hh>

#include <dune/gdt/local/assembler/bilinear-form-accumulators.hh>
#include <dune/gdt/local/bilinear-forms/interfaces.hh>

namespace Dune {
namespace GDT {

template <class GridView,
          size_t source_range_dim = 1,
          size_t source_range_dim_cols = 1,
          class SourceRangeField = double,
          class Result = double,
          size_t range_range_dim = source_range_dim,
          size_t range_range_dim_cols = source_range_dim_cols,
          class RangeRangeField = SourceRangeField>
class BilinearForm
  : public XT::Grid::ElementAndIntersectionFunctor<GridView>
  , XT::Common::ThreadResultPropagator<BilinearForm<GridView,
                                                    source_range_dim,
                                                    source_range_dim_cols,
                                                    SourceRangeField,
                                                    Result,
                                                    range_range_dim,
                                                    range_range_dim_cols,
                                                    RangeRangeField>,
                                       Result>
  , public XT::Common::WithLogger<BilinearForm<GridView,
                                               source_range_dim,
                                               source_range_dim_cols,
                                               SourceRangeField,
                                               Result,
                                               range_range_dim,
                                               range_range_dim_cols,
                                               RangeRangeField>>
{
  static_assert(XT::Grid::is_view<GridView>::value, "");

  using ThisType = BilinearForm;
  using BaseType = XT::Grid::ElementAndIntersectionFunctor<GridView>;
  using Propagator = XT::Common::ThreadResultPropagator<BilinearForm<GridView,
                                                                     source_range_dim,
                                                                     source_range_dim_cols,
                                                                     SourceRangeField,
                                                                     Result,
                                                                     range_range_dim,
                                                                     range_range_dim_cols,
                                                                     RangeRangeField>,
                                                        Result>;
  friend Propagator;

  using Logger = XT::Common::WithLogger<BilinearForm<GridView,
                                                     source_range_dim,
                                                     source_range_dim_cols,
                                                     SourceRangeField,
                                                     Result,
                                                     range_range_dim,
                                                     range_range_dim_cols,
                                                     RangeRangeField>>;

public:
  using GV = GridView;
  using typename BaseType::E;
  using typename BaseType::GridViewType;
  using typename BaseType::I;
  using ResultType = Result;

  static const constexpr size_t s_r = source_range_dim;
  static const constexpr size_t s_rC = source_range_dim_cols;
  using SR = SourceRangeField;
  using SourceType = XT::Functions::GridFunctionInterface<E, s_r, s_rC, SR>;

  static const constexpr size_t r_r = range_range_dim;
  static const constexpr size_t r_rC = range_range_dim_cols;
  using RR = RangeRangeField;
  using RangeType = XT::Functions::GridFunctionInterface<E, r_r, r_rC, RR>;

  using ElementFilterType = XT::Grid::ElementFilter<GV>;
  using IntersectionFilterType = XT::Grid::IntersectionFilter<GV>;

  BilinearForm(GridViewType grd_vw,
               XT::Functions::GridFunction<E, s_r, s_rC, SR> src,
               XT::Functions::GridFunction<E, r_r, r_rC, RR> rng,
               const std::string& logging_prefix = "")
    : BaseType()
    , Propagator(this)
    , Logger(logging_prefix.empty() ? "gdt" : "gdt.bilinearform",
             logging_prefix.empty() ? "BilinearForm" : logging_prefix,
             /*logging_disabled=*/logging_prefix.empty())
    , grid_view_(grd_vw)
    , source_(src)
    , range_(rng)
    , local_source_(source_.local_function())
    , local_range_(range_.local_function())
    , bilinear_form_value_(1, 1, 0.)
    , result_(0)
  {
    LOG__(Logger, info) << Logger::logging_id << "(grid_view=" << &grd_vw << ", src=" << &src << ", rng=" << &rng << ")"
                        << std::endl;
  }

  BilinearForm(const ThisType& other)
    : BaseType(other)
    , Propagator(other)
    , Logger(other)
    , grid_view_(other.grid_view_)
    , source_(other.source_)
    , range_(other.range_)
    , local_source_(source_.local_function())
    , local_range_(range_.local_function())
    , bilinear_form_value_(other.bilinear_form_value_)
    , result_(other.result_)
  {
    for (auto& element_data : other.element_data_) {
      const auto& local_bilinear_form = *std::get<0>(element_data);
      auto& param = std::get<1>(element_data);
      const auto& filter = *std::get<2>(element_data);
      this->append(local_bilinear_form, param, filter);
    }
  } // BilinearForm(...)

  BaseType* copy() override final
  {
    return Propagator::copy_imp();
  }

  const GridViewType& grid_view() const
  {
    return grid_view_;
  }

  const SourceType& source() const
  {
    return source_;
  }

  const RangeType& range() const
  {
    return range_;
  }

  ThisType&
  append(const LocalElementBilinearFormInterface<E, s_r, s_rC, SR, Result, r_r, r_rC, RR>& local_bilinear_form,
         const XT::Common::Parameter& param = {},
         const ElementFilterType& filter = XT::Grid::ApplyOn::AllElements<GV>())
  {
    LOG__(Logger, info) << Logger::logging_id << ".append(local_bilinear_form=" << &local_bilinear_form
                        << ", param=" << param << ", filter=" << &filter << ")" << std::endl;
    element_data_.emplace_back(local_bilinear_form.copy(), param, std::unique_ptr<ElementFilterType>(filter.copy()));
    return *this;
  }

  ThisType&
  operator+=(const LocalElementBilinearFormInterface<E, s_r, s_rC, SR, Result, r_r, r_rC, RR>& local_bilinear_form)
  {
    this->append(local_bilinear_form);
    return *this;
  }

  ThisType& operator+=(std::tuple<const LocalElementBilinearFormInterface<E, s_r, s_rC, SR, Result, r_r, r_rC, RR>&,
                                  const XT::Common::Parameter&> local_bilinear_form__param)
  {
    this->append(std::get<0>(local_bilinear_form__param), std::get<1>(local_bilinear_form__param));
    return *this;
  }

  ThisType& operator+=(std::tuple<const LocalElementBilinearFormInterface<E, s_r, s_rC, SR, Result, r_r, r_rC, RR>&,
                                  const ElementFilterType&> local_bilinear_form__filter)
  {
    this->append(std::get<0>(local_bilinear_form__filter), {}, std::get<1>(local_bilinear_form__filter));
    return *this;
  }

  ThisType& operator+=(std::tuple<const LocalElementBilinearFormInterface<E, s_r, s_rC, SR, Result, r_r, r_rC, RR>&,
                                  const XT::Common::Parameter&,
                                  const ElementFilterType&> local_bilinear_form__param__filter)
  {
    this->append(std::get<0>(local_bilinear_form__param__filter),
                 std::get<1>(local_bilinear_form__param__filter),
                 std::get<2>(local_bilinear_form__param__filter));
    return *this;
  }

  void prepare() override final
  {
    result_ = 0;
  }

  Result compute_locally(const E& element)
  {
    Result ret = 0;
    local_source_->bind(element);
    local_range_->bind(element);
    DUNE_THROW_IF(local_source_->size() != 1,
                  Exceptions::bilinear_form_error,
                  "local_source_->size() = " << local_source_->size());
    DUNE_THROW_IF(
        local_range_->size() != 1, Exceptions::bilinear_form_error, "local_range_->size() = " << local_range_->size());
    for (auto& element_data : element_data) {
      const auto& local_bilinear_form = *std::get<0>(element_data);
      auto& param = std::get<1>(element_data);
      const auto& filter = *std::get<2>(element_data);
      if (filter.contains(this->grid_view_, element)) {
        local_bilinear_form.apply2(*local_source_, *local_range_, bilinear_form_value_, param);
        assert(bilinear_form_value_.rows() >= 1);
        assert(bilinear_form_value_.cols() >= 1);
        ret += bilinear_form_value_[0][0];
      }
    }
    return ret;
  }

  void apply_local(const E& element) override final
  {
    result_ += compute_locally(element);
  }

  void apply_local(const I& /*intersection*/, const E& /*inside_element*/, const E& /*outside_element*/) override final
  {}

  void finalize() override final
  {
    Propagator::finalize_imp();
  }

  const ResultType& result() const
  {
    return result_;
  }

  Result apply2(const bool use_tbb = false)
  {
    this->prepare();
    XT::Grid::Walker<GV> walker(this->grid_view_);
    walker.append(*this);
    walker.walk(use_tbb);
    return this->result_;
  }

protected:
  void set_result(Result res)
  {
    result_ = res;
  }

  const GridViewType grid_view_;
  XT::Functions::GridFunction<E, s_r, s_rC, SR> source_;
  XT::Functions::GridFunction<E, r_r, r_rC, RR> range_;
  std::unique_ptr<typename SourceType::LocalFunctionType> local_source_;
  std::unique_ptr<typename RangeType::LocalFunctionType> local_range_;
  DynamicMatrix<Result> bilinear_form_value_;
  ResultType result_;
  std::list<std::tuple<std::unique_ptr<LocalElementBilinearFormInterface<E, s_r, s_rC, SR, ResultType, r_r, r_rC, RR>>,
                       XT::Common::Parameter,
                       std::unique_ptr<ElementFilterType>>>
      element_data_;
}; // class BilinearForm

template <class GV, size_t s_r, size_t s_rC, class SR, size_t r_r, size_t r_rC, class RR>
std::enable_if_t<XT::Grid::is_view<GV>::value, BilinearForm<GV, s_r, s_rC, SR, double, r_r, r_rC, RR>>
make_bilinear_form(GV grid_view,
                   const XT::Functions::GridFunctionInterface<XT::Grid::extract_entity_t<GV>, s_r, s_rC, SR>& source,
                   const XT::Functions::GridFunctionInterface<XT::Grid::extract_entity_t<GV>, r_r, r_rC, RR>& range,
                   const std::string& logging_prefix = "")
{
  return BilinearForm<GV, s_r, s_rC, SR, double, r_r, r_rC, RR>(grid_view, source, range, logging_prefix);
}

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_OPERATORS_BILINEAR_FORM_HH
<commit_msg>[operators.bilinear-form] fix fix<commit_after>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2020)

#ifndef DUNE_GDT_OPERATORS_BILINEAR_FORM_HH
#define DUNE_GDT_OPERATORS_BILINEAR_FORM_HH

#include <dune/xt/common/parallel/threadstorage.hh>
#include <dune/xt/common/timedlogging.hh>
#include <dune/xt/la/type_traits.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/grid/walker.hh>
#include <dune/xt/functions/grid-function.hh>

#include <dune/gdt/local/assembler/bilinear-form-accumulators.hh>
#include <dune/gdt/local/bilinear-forms/interfaces.hh>

namespace Dune {
namespace GDT {

template <class GridView,
          size_t source_range_dim = 1,
          size_t source_range_dim_cols = 1,
          class SourceRangeField = double,
          class Result = double,
          size_t range_range_dim = source_range_dim,
          size_t range_range_dim_cols = source_range_dim_cols,
          class RangeRangeField = SourceRangeField>
class BilinearForm
  : public XT::Grid::ElementAndIntersectionFunctor<GridView>
  , XT::Common::ThreadResultPropagator<BilinearForm<GridView,
                                                    source_range_dim,
                                                    source_range_dim_cols,
                                                    SourceRangeField,
                                                    Result,
                                                    range_range_dim,
                                                    range_range_dim_cols,
                                                    RangeRangeField>,
                                       Result>
  , public XT::Common::WithLogger<BilinearForm<GridView,
                                               source_range_dim,
                                               source_range_dim_cols,
                                               SourceRangeField,
                                               Result,
                                               range_range_dim,
                                               range_range_dim_cols,
                                               RangeRangeField>>
{
  static_assert(XT::Grid::is_view<GridView>::value, "");

  using ThisType = BilinearForm;
  using BaseType = XT::Grid::ElementAndIntersectionFunctor<GridView>;
  using Propagator = XT::Common::ThreadResultPropagator<BilinearForm<GridView,
                                                                     source_range_dim,
                                                                     source_range_dim_cols,
                                                                     SourceRangeField,
                                                                     Result,
                                                                     range_range_dim,
                                                                     range_range_dim_cols,
                                                                     RangeRangeField>,
                                                        Result>;
  friend Propagator;

  using Logger = XT::Common::WithLogger<BilinearForm<GridView,
                                                     source_range_dim,
                                                     source_range_dim_cols,
                                                     SourceRangeField,
                                                     Result,
                                                     range_range_dim,
                                                     range_range_dim_cols,
                                                     RangeRangeField>>;

public:
  using GV = GridView;
  using typename BaseType::E;
  using typename BaseType::GridViewType;
  using typename BaseType::I;
  using ResultType = Result;

  static const constexpr size_t s_r = source_range_dim;
  static const constexpr size_t s_rC = source_range_dim_cols;
  using SR = SourceRangeField;
  using SourceType = XT::Functions::GridFunctionInterface<E, s_r, s_rC, SR>;

  static const constexpr size_t r_r = range_range_dim;
  static const constexpr size_t r_rC = range_range_dim_cols;
  using RR = RangeRangeField;
  using RangeType = XT::Functions::GridFunctionInterface<E, r_r, r_rC, RR>;

  using ElementFilterType = XT::Grid::ElementFilter<GV>;
  using IntersectionFilterType = XT::Grid::IntersectionFilter<GV>;

  BilinearForm(GridViewType grd_vw,
               XT::Functions::GridFunction<E, s_r, s_rC, SR> src,
               XT::Functions::GridFunction<E, r_r, r_rC, RR> rng,
               const std::string& logging_prefix = "")
    : BaseType()
    , Propagator(this)
    , Logger(logging_prefix.empty() ? "gdt" : "gdt.bilinearform",
             logging_prefix.empty() ? "BilinearForm" : logging_prefix,
             /*logging_disabled=*/logging_prefix.empty())
    , grid_view_(grd_vw)
    , source_(src)
    , range_(rng)
    , local_source_(source_.local_function())
    , local_range_(range_.local_function())
    , bilinear_form_value_(1, 1, 0.)
    , result_(0)
  {
    LOG__(Logger, info) << Logger::logging_id << "(grid_view=" << &grd_vw << ", src=" << &src << ", rng=" << &rng << ")"
                        << std::endl;
  }

  BilinearForm(const ThisType& other)
    : BaseType(other)
    , Propagator(other)
    , Logger(other)
    , grid_view_(other.grid_view_)
    , source_(other.source_)
    , range_(other.range_)
    , local_source_(source_.local_function())
    , local_range_(range_.local_function())
    , bilinear_form_value_(other.bilinear_form_value_)
    , result_(other.result_)
  {
    for (auto& element_data : other.element_data_) {
      const auto& local_bilinear_form = *std::get<0>(element_data);
      auto& param = std::get<1>(element_data);
      const auto& filter = *std::get<2>(element_data);
      this->append(local_bilinear_form, param, filter);
    }
  } // BilinearForm(...)

  BaseType* copy() override final
  {
    return Propagator::copy_imp();
  }

  const GridViewType& grid_view() const
  {
    return grid_view_;
  }

  const SourceType& source() const
  {
    return source_;
  }

  const RangeType& range() const
  {
    return range_;
  }

  ThisType&
  append(const LocalElementBilinearFormInterface<E, s_r, s_rC, SR, Result, r_r, r_rC, RR>& local_bilinear_form,
         const XT::Common::Parameter& param = {},
         const ElementFilterType& filter = XT::Grid::ApplyOn::AllElements<GV>())
  {
    LOG__(Logger, info) << Logger::logging_id << ".append(local_bilinear_form=" << &local_bilinear_form
                        << ", param=" << param << ", filter=" << &filter << ")" << std::endl;
    element_data_.emplace_back(local_bilinear_form.copy(), param, std::unique_ptr<ElementFilterType>(filter.copy()));
    return *this;
  }

  ThisType&
  operator+=(const LocalElementBilinearFormInterface<E, s_r, s_rC, SR, Result, r_r, r_rC, RR>& local_bilinear_form)
  {
    this->append(local_bilinear_form);
    return *this;
  }

  ThisType& operator+=(std::tuple<const LocalElementBilinearFormInterface<E, s_r, s_rC, SR, Result, r_r, r_rC, RR>&,
                                  const XT::Common::Parameter&> local_bilinear_form__param)
  {
    this->append(std::get<0>(local_bilinear_form__param), std::get<1>(local_bilinear_form__param));
    return *this;
  }

  ThisType& operator+=(std::tuple<const LocalElementBilinearFormInterface<E, s_r, s_rC, SR, Result, r_r, r_rC, RR>&,
                                  const ElementFilterType&> local_bilinear_form__filter)
  {
    this->append(std::get<0>(local_bilinear_form__filter), {}, std::get<1>(local_bilinear_form__filter));
    return *this;
  }

  ThisType& operator+=(std::tuple<const LocalElementBilinearFormInterface<E, s_r, s_rC, SR, Result, r_r, r_rC, RR>&,
                                  const XT::Common::Parameter&,
                                  const ElementFilterType&> local_bilinear_form__param__filter)
  {
    this->append(std::get<0>(local_bilinear_form__param__filter),
                 std::get<1>(local_bilinear_form__param__filter),
                 std::get<2>(local_bilinear_form__param__filter));
    return *this;
  }

  void prepare() override final
  {
    result_ = 0;
  }

  Result compute_locally(const E& element)
  {
    Result ret = 0;
    local_source_->bind(element);
    local_range_->bind(element);
    DUNE_THROW_IF(local_source_->size() != 1,
                  Exceptions::bilinear_form_error,
                  "local_source_->size() = " << local_source_->size());
    DUNE_THROW_IF(
        local_range_->size() != 1, Exceptions::bilinear_form_error, "local_range_->size() = " << local_range_->size());
    for (auto& element_data : element_data_) {
      const auto& local_bilinear_form = *std::get<0>(element_data);
      auto& param = std::get<1>(element_data);
      const auto& filter = *std::get<2>(element_data);
      if (filter.contains(this->grid_view_, element)) {
        local_bilinear_form.apply2(*local_source_, *local_range_, bilinear_form_value_, param);
        assert(bilinear_form_value_.rows() >= 1);
        assert(bilinear_form_value_.cols() >= 1);
        ret += bilinear_form_value_[0][0];
      }
    }
    return ret;
  }

  void apply_local(const E& element) override final
  {
    result_ += compute_locally(element);
  }

  void apply_local(const I& /*intersection*/, const E& /*inside_element*/, const E& /*outside_element*/) override final
  {}

  void finalize() override final
  {
    Propagator::finalize_imp();
  }

  const ResultType& result() const
  {
    return result_;
  }

  Result apply2(const bool use_tbb = false)
  {
    this->prepare();
    XT::Grid::Walker<GV> walker(this->grid_view_);
    walker.append(*this);
    walker.walk(use_tbb);
    return this->result_;
  }

protected:
  void set_result(Result res)
  {
    result_ = res;
  }

  const GridViewType grid_view_;
  XT::Functions::GridFunction<E, s_r, s_rC, SR> source_;
  XT::Functions::GridFunction<E, r_r, r_rC, RR> range_;
  std::unique_ptr<typename SourceType::LocalFunctionType> local_source_;
  std::unique_ptr<typename RangeType::LocalFunctionType> local_range_;
  DynamicMatrix<Result> bilinear_form_value_;
  ResultType result_;
  std::list<std::tuple<std::unique_ptr<LocalElementBilinearFormInterface<E, s_r, s_rC, SR, ResultType, r_r, r_rC, RR>>,
                       XT::Common::Parameter,
                       std::unique_ptr<ElementFilterType>>>
      element_data_;
}; // class BilinearForm

template <class GV, size_t s_r, size_t s_rC, class SR, size_t r_r, size_t r_rC, class RR>
std::enable_if_t<XT::Grid::is_view<GV>::value, BilinearForm<GV, s_r, s_rC, SR, double, r_r, r_rC, RR>>
make_bilinear_form(GV grid_view,
                   const XT::Functions::GridFunctionInterface<XT::Grid::extract_entity_t<GV>, s_r, s_rC, SR>& source,
                   const XT::Functions::GridFunctionInterface<XT::Grid::extract_entity_t<GV>, r_r, r_rC, RR>& range,
                   const std::string& logging_prefix = "")
{
  return BilinearForm<GV, s_r, s_rC, SR, double, r_r, r_rC, RR>(grid_view, source, range, logging_prefix);
}

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_OPERATORS_BILINEAR_FORM_HH
<|endoftext|>


<commit_before>#include "cube.h"
#include <vector>
#include <sstream>
#include <regex>
#include <map>

Cube::Cube()
{
    CornerOrientation cornerOrientation;
    CornerPermutation cornerPermutation;
    EdgeOrientation edgeOrientation;
    EdgePermutation edgePermutation;
    coState = cornerOrientation.array_to_index(vector<int>{ 0, 0, 0, 0, 0, 0, 0, 0 });
    cpState = cornerPermutation.array_to_index(vector<int>{ 0, 1, 2, 3, 4, 5, 6, 7 });
    eoState = edgeOrientation.array_to_index(vector<int>{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
    epState1 = edgePermutation.array_to_index(vector<int>{ 0, 1, 2, 3, 4, 5 });
    epState2 = edgePermutation.array_to_index(vector<int>{ 6, 7, 8, 9, 10, 11, 12 });

    cornerOrientation.buildTransitionTable();
    coTransition = cornerOrientation.getTransitionTable();

    cornerPermutation.buildTransitionTable();
    cpTransition = cornerPermutation.getTransitionTable();

    edgeOrientation.buildTransitionTable();
    eoTransition = edgeOrientation.getTransitionTable();

    edgePermutation.buildTransitionTable();
    epTransition = edgePermutation.getTransitionTable();
}

Cube::Cube(string scramble) : Cube()
{
    map<char, int> moveNames{{'U', 0}, {'D', 1}, {'R', 2}, {'L', 3}, {'F', 4}, {'B', 5}};
    map<char, int> repeatNames{{'\'', 3}, {'2', 2}};

    smatch sm;
    regex r("([UDRLFB][2']?)");
    regex_iterator<string::iterator> it(scramble.begin(), scramble.end(), r);
    regex_iterator<string::iterator> end;

    while (it != end)
    {
        string match = it->str();
        int move = moveNames[match[0]];
        int repeats = 1;
        if (match.size() > 1)
            repeats = repeatNames[match[1]];

        for (int i = 0; i < repeats; i++)
            apply_move(move);

        ++it;
    }
}

void Cube::apply_move(int move)
{
    coState = coTransition[coState][move];
    cpState = cpTransition[cpState][move];
    eoState = eoTransition[eoState][move];
    epState1 = epTransition[epState1][move];
    epState2 = epTransition[epState2][move];
}

bool Cube::is_solved()
{
    return cpState == 0 && coState == 0 && eoState == 0 && epState1 == 0 && epState2 == 366288;
}
<commit_msg>there are only 12 edge pieces, not 13<commit_after>#include "cube.h"
#include <vector>
#include <sstream>
#include <regex>
#include <map>

Cube::Cube()
{
    CornerOrientation cornerOrientation;
    CornerPermutation cornerPermutation;
    EdgeOrientation edgeOrientation;
    EdgePermutation edgePermutation;
    coState = cornerOrientation.array_to_index(vector<int>{ 0, 0, 0, 0, 0, 0, 0, 0 });
    cpState = cornerPermutation.array_to_index(vector<int>{ 0, 1, 2, 3, 4, 5, 6, 7 });
    eoState = edgeOrientation.array_to_index(vector<int>{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
    epState1 = edgePermutation.array_to_index(vector<int>{ 0, 1, 2, 3, 4, 5 });
    epState2 = edgePermutation.array_to_index(vector<int>{ 6, 7, 8, 9, 10, 11 });

    cornerOrientation.buildTransitionTable();
    coTransition = cornerOrientation.getTransitionTable();

    cornerPermutation.buildTransitionTable();
    cpTransition = cornerPermutation.getTransitionTable();

    edgeOrientation.buildTransitionTable();
    eoTransition = edgeOrientation.getTransitionTable();

    edgePermutation.buildTransitionTable();
    epTransition = edgePermutation.getTransitionTable();
}

Cube::Cube(string scramble) : Cube()
{
    map<char, int> moveNames{{'U', 0}, {'D', 1}, {'R', 2}, {'L', 3}, {'F', 4}, {'B', 5}};
    map<char, int> repeatNames{{'\'', 3}, {'2', 2}};

    smatch sm;
    regex r("([UDRLFB][2']?)");
    regex_iterator<string::iterator> it(scramble.begin(), scramble.end(), r);
    regex_iterator<string::iterator> end;

    while (it != end)
    {
        string match = it->str();
        int move = moveNames[match[0]];
        int repeats = 1;
        if (match.size() > 1)
            repeats = repeatNames[match[1]];

        for (int i = 0; i < repeats; i++)
            apply_move(move);

        ++it;
    }
}

void Cube::apply_move(int move)
{
    coState = coTransition[coState][move];
    cpState = cpTransition[cpState][move];
    eoState = eoTransition[eoState][move];
    epState1 = epTransition[epState1][move];
    epState2 = epTransition[epState2][move];
}

bool Cube::is_solved()
{
    return cpState == 0 && coState == 0 && eoState == 0 && epState1 == 0 && epState2 == 366288;
}
<|endoftext|>


<commit_before><commit_msg>coverity#1268025 Uninitialized scalar field<commit_after><|endoftext|>