<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
 *  Main authors:
 *     Christian Schulte <schulte@gecode.org>
 *
 *  Copyright:
 *     Christian Schulte, 2012
 *
 *  Last modified:
 *     $Date$ by $Author$
 *     $Revision$
 *
 *  This file is part of Gecode, the generic constraint
 *  development environment:
 *     http://www.gecode.org
 *
 *  Permission is hereby granted, free of charge, to any person obtaining
 *  a copy of this software and associated documentation files (the
 *  "Software"), to deal in the Software without restriction, including
 *  without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to
 *  permit persons to whom the Software is furnished to do so, subject to
 *  the following conditions:
 *
 *  The above copyright notice and this permission notice shall be
 *  included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

namespace Gecode {

  /**
   * \brief Tie-break limit function
   *
   * Here the value \a w is the worst and \b is the best merit value
   * found. The function must return the merit value that is considered
   * the limit for breaking ties.
   *
   * \ingroup TaskModelBranch
   */
  typedef double (*BranchTbl)(const Space& home, double w, double b);

  /**
   * \brief Variable branching information
   * \ingroup TaskModelBranch
   */
  class VarBranch {
  protected:
    /// Tie-breaking limit function
    BranchTbl _tbl;
    /// Random number generator
    Rnd _rnd;
    /// Decay information for AFC and activity
    double _decay;
    /// AFC information
    AFC _afc;
    /// Activity information
    Activity _act;
    /// Merit function (generic function pointer)
    VoidFunction _mf;
  public:
    /// Initialize with tie-break limit function \a t
    VarBranch(BranchTbl t);
    /// Initialize with random number generator \a r
    VarBranch(Rnd r);
    /// Initialize with decay factor \a d and tie-break limit function \a t
    VarBranch(double d, BranchTbl t);
    /// Initialize with AFC \a a and tie-break limit function \a t
    VarBranch(AFC a, BranchTbl t);
    /// Initialize with activity \a a and tie-break limit function \a t
    VarBranch(Activity a, BranchTbl t);
    /// Initialize with merit function \a f and tie-break limit function \a t
    VarBranch(void (*f)(void), BranchTbl t);
    /// Return tie-break limit function
    BranchTbl tbl(void) const;
    /// Return random number generator
    Rnd rnd(void) const;
    /// Return decay factor
    double decay(void) const;
    /// Return AFC
    AFC afc(void) const;
    /// Set AFC to \a a
    void afc(AFC a);
    /// Return activity
    Activity activity(void) const;
    /// Set activity to \a a
    void activity(Activity a);
    /// Return merit function
    VoidFunction merit(void) const;
  };

  // Variable branching
  forceinline
  VarBranch::VarBranch(BranchTbl t)
    : _tbl(t) {}

  forceinline
  VarBranch::VarBranch(double d, BranchTbl t)
    : _tbl(t), _decay(d) {}

  forceinline
  VarBranch::VarBranch(AFC a, BranchTbl t)
    : _tbl(t), _afc(a) {
    if (!_afc.initialized())
      throw UninitializedAFC("VarBranch::VarBranch");
  }

  forceinline
  VarBranch::VarBranch(Activity a, BranchTbl t)
    : _tbl(t), _act(a) {
    if (!_act.initialized())
      throw UninitializedActivity("VarBranch::VarBranch");
  }

  forceinline
  VarBranch::VarBranch(Rnd r)
    : _tbl(NULL), _rnd(r) {
    if (!_rnd.initialized())
      throw UninitializedRnd("VarBranch::VarBranch");
  }

  forceinline
  VarBranch::VarBranch(VoidFunction f, BranchTbl t)
    : _tbl(t), _mf(f) {}

  forceinline BranchTbl
  VarBranch::tbl(void) const {
    return _tbl;
  }

  inline Rnd
  VarBranch::rnd(void) const {
    return _rnd;
  }

  inline double
  VarBranch::decay(void) const {
    return _decay;
  }

  inline AFC
  VarBranch::afc(void) const {
    return _afc;
  }

  inline void
  VarBranch::afc(AFC a) {
    _afc=a;
  }

  inline Activity
  VarBranch::activity(void) const {
    return _act;
  }

  inline void
  VarBranch::activity(Activity a) {
    _act=a;
  }

  forceinline VoidFunction
  VarBranch::merit(void) const {
    return _mf;
  }

}

// STATISTICS: kernel-branch
<commit_msg>Always initialize decay<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
 *  Main authors:
 *     Christian Schulte <schulte@gecode.org>
 *
 *  Copyright:
 *     Christian Schulte, 2012
 *
 *  Last modified:
 *     $Date$ by $Author$
 *     $Revision$
 *
 *  This file is part of Gecode, the generic constraint
 *  development environment:
 *     http://www.gecode.org
 *
 *  Permission is hereby granted, free of charge, to any person obtaining
 *  a copy of this software and associated documentation files (the
 *  "Software"), to deal in the Software without restriction, including
 *  without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to
 *  permit persons to whom the Software is furnished to do so, subject to
 *  the following conditions:
 *
 *  The above copyright notice and this permission notice shall be
 *  included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

namespace Gecode {

  /**
   * \brief Tie-break limit function
   *
   * Here the value \a w is the worst and \b is the best merit value
   * found. The function must return the merit value that is considered
   * the limit for breaking ties.
   *
   * \ingroup TaskModelBranch
   */
  typedef double (*BranchTbl)(const Space& home, double w, double b);

  /**
   * \brief Variable branching information
   * \ingroup TaskModelBranch
   */
  class VarBranch {
  protected:
    /// Tie-breaking limit function
    BranchTbl _tbl;
    /// Random number generator
    Rnd _rnd;
    /// Decay information for AFC and activity
    double _decay;
    /// AFC information
    AFC _afc;
    /// Activity information
    Activity _act;
    /// Merit function (generic function pointer)
    VoidFunction _mf;
  public:
    /// Initialize with tie-break limit function \a t
    VarBranch(BranchTbl t);
    /// Initialize with random number generator \a r
    VarBranch(Rnd r);
    /// Initialize with decay factor \a d and tie-break limit function \a t
    VarBranch(double d, BranchTbl t);
    /// Initialize with AFC \a a and tie-break limit function \a t
    VarBranch(AFC a, BranchTbl t);
    /// Initialize with activity \a a and tie-break limit function \a t
    VarBranch(Activity a, BranchTbl t);
    /// Initialize with merit function \a f and tie-break limit function \a t
    VarBranch(void (*f)(void), BranchTbl t);
    /// Return tie-break limit function
    BranchTbl tbl(void) const;
    /// Return random number generator
    Rnd rnd(void) const;
    /// Return decay factor
    double decay(void) const;
    /// Return AFC
    AFC afc(void) const;
    /// Set AFC to \a a
    void afc(AFC a);
    /// Return activity
    Activity activity(void) const;
    /// Set activity to \a a
    void activity(Activity a);
    /// Return merit function
    VoidFunction merit(void) const;
  };

  // Variable branching
  forceinline
  VarBranch::VarBranch(BranchTbl t)
    : _tbl(t), _decay(1.0) {}

  forceinline
  VarBranch::VarBranch(double d, BranchTbl t)
    : _tbl(t), _decay(d) {}

  forceinline
  VarBranch::VarBranch(AFC a, BranchTbl t)
    : _tbl(t), _decay(1.0), _afc(a) {
    if (!_afc.initialized())
      throw UninitializedAFC("VarBranch::VarBranch");
  }

  forceinline
  VarBranch::VarBranch(Activity a, BranchTbl t)
    : _tbl(t), _decay(1.0), _act(a) {
    if (!_act.initialized())
      throw UninitializedActivity("VarBranch::VarBranch");
  }

  forceinline
  VarBranch::VarBranch(Rnd r)
    : _tbl(NULL), _decay(1.0), _rnd(r) {
    if (!_rnd.initialized())
      throw UninitializedRnd("VarBranch::VarBranch");
  }

  forceinline
  VarBranch::VarBranch(VoidFunction f, BranchTbl t)
    : _tbl(t), _decay(1.0), _mf(f) {}

  forceinline BranchTbl
  VarBranch::tbl(void) const {
    return _tbl;
  }

  inline Rnd
  VarBranch::rnd(void) const {
    return _rnd;
  }

  inline double
  VarBranch::decay(void) const {
    return _decay;
  }

  inline AFC
  VarBranch::afc(void) const {
    return _afc;
  }

  inline void
  VarBranch::afc(AFC a) {
    _afc=a;
  }

  inline Activity
  VarBranch::activity(void) const {
    return _act;
  }

  inline void
  VarBranch::activity(Activity a) {
    _act=a;
  }

  forceinline VoidFunction
  VarBranch::merit(void) const {
    return _mf;
  }

}

// STATISTICS: kernel-branch
<|endoftext|>


<commit_before>/******************************************************************************
This file is part of the lemmagen library. It gives support for lemmatization.
Copyright (C) 2011 Jernej Virag <jernej@virag.si>

The lemmagen 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
******************************************************************************/

/*
 *  This exports C interface for the lemmatizer
 */

#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include "../include/lemmagen.h"
#include "RdrLemmatizer.h"

#define HAS_MUTEX __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900)

// MSVC before 14 doesn't really handle C++11
#if HAS_MUTEX
	#include <mutex>
	static std::mutex mutex_lemmatizer;
#endif

static RdrLemmatizer *lemmatizer = nullptr;

#ifdef __cplusplus
extern "C"
{
#endif

	EXPORT_API int lem_load_language_library(const char *file_name)
	{
		#if HAS_MUTEX
		std::lock_guard<std::mutex> lock(mutex_lemmatizer);
		#endif

		struct stat buf;
		// Check if file exists first
		if (stat(file_name, &buf) != 0)
		{
			std::cerr << "[ERROR] Language file " << std::string(file_name) << " could not be found!" << std::endl;
			return STATUS_FILE_NOT_FOUND;
		}

		if (!(buf.st_mode & S_IFREG))
		{
			std::cerr << "[ERROR] Language file " << std::string(file_name) << " is not a file!" << std::endl;
			return STATUS_FILE_NOT_FOUND;
		}

		if (lemmatizer != nullptr)
		{
			delete lemmatizer;
		}

		try {
			lemmatizer = new RdrLemmatizer(file_name);
		} catch (std::ifstream::failure e) {
			return STATUS_FILE_NOT_FOUND;
		}

		return STATUS_OK;
	}

	EXPORT_API void lem_lemmatize_word(const char *input_word, char *output_word)
	{
		// TODO figure out fast locking for this to ensure thread safety
		// Lemmatization should be reentrant, but initialization isn't.
		if (lemmatizer == nullptr)
		{
			std::cerr << "[ERROR] Language file for lemmatizer has to be loaded first!" << std::endl;
			return;
		}

		if (output_word == nullptr) {
			std::cerr << "[ERROR] Output buffer is NULL!" << std::endl;
			return;
		}

		if (input_word == nullptr) {
			output_word[0] = '\0';
			return;
		}

		lemmatizer->Lemmatize(input_word, output_word);
	}

	EXPORT_API char *lem_lemmatize_word_alloc(const char *input_word)
	{
		if (lemmatizer == nullptr)
		{
			std::cerr << "[ERROR] Language file for lemmatizer has to be loaded first!" << std::endl;
			return nullptr;
		}

		if (input_word == nullptr) {
			char *return_val = (char *)malloc(sizeof(char));
			return_val[0] = '\0';
			return return_val;
		}

		char *output_word = lemmatizer->Lemmatize(input_word, nullptr);
		// Output word is allocated with "new" so we have to reallocate to change to
		// C-like malloc allocation
		char *return_val = (char *)malloc(sizeof(char) * strlen(output_word) + 1);
		strcpy(return_val, output_word);
		delete[] output_word;

		return return_val;
	}

	EXPORT_API void lem_unload_language_library(void) {
		#if HAS_MUTEX
		std::lock_guard<std::mutex> lock(mutex_lemmatizer);
		#endif

		if (lemmatizer != nullptr) {
			delete lemmatizer;
			lemmatizer = nullptr;
		}
	}

#ifdef __cplusplus
}
#endif
<commit_msg>fixed warning: catching polymorphic type by value<commit_after>/******************************************************************************
This file is part of the lemmagen library. It gives support for lemmatization.
Copyright (C) 2011 Jernej Virag <jernej@virag.si>

The lemmagen 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
******************************************************************************/

/*
 *  This exports C interface for the lemmatizer
 */

#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include "../include/lemmagen.h"
#include "RdrLemmatizer.h"

#define HAS_MUTEX __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900)

// MSVC before 14 doesn't really handle C++11
#if HAS_MUTEX
	#include <mutex>
	static std::mutex mutex_lemmatizer;
#endif

static RdrLemmatizer *lemmatizer = nullptr;

#ifdef __cplusplus
extern "C"
{
#endif

	EXPORT_API int lem_load_language_library(const char *file_name)
	{
		#if HAS_MUTEX
		std::lock_guard<std::mutex> lock(mutex_lemmatizer);
		#endif

		struct stat buf;
		// Check if file exists first
		if (stat(file_name, &buf) != 0)
		{
			std::cerr << "[ERROR] Language file " << std::string(file_name) << " could not be found!" << std::endl;
			return STATUS_FILE_NOT_FOUND;
		}

		if (!(buf.st_mode & S_IFREG))
		{
			std::cerr << "[ERROR] Language file " << std::string(file_name) << " is not a file!" << std::endl;
			return STATUS_FILE_NOT_FOUND;
		}

		if (lemmatizer != nullptr)
		{
			delete lemmatizer;
		}

		try {
			lemmatizer = new RdrLemmatizer(file_name);
		} catch (std::ifstream::failure& e) {
			return STATUS_FILE_NOT_FOUND;
		}

		return STATUS_OK;
	}

	EXPORT_API void lem_lemmatize_word(const char *input_word, char *output_word)
	{
		// TODO figure out fast locking for this to ensure thread safety
		// Lemmatization should be reentrant, but initialization isn't.
		if (lemmatizer == nullptr)
		{
			std::cerr << "[ERROR] Language file for lemmatizer has to be loaded first!" << std::endl;
			return;
		}

		if (output_word == nullptr) {
			std::cerr << "[ERROR] Output buffer is NULL!" << std::endl;
			return;
		}

		if (input_word == nullptr) {
			output_word[0] = '\0';
			return;
		}

		lemmatizer->Lemmatize(input_word, output_word);
	}

	EXPORT_API char *lem_lemmatize_word_alloc(const char *input_word)
	{
		if (lemmatizer == nullptr)
		{
			std::cerr << "[ERROR] Language file for lemmatizer has to be loaded first!" << std::endl;
			return nullptr;
		}

		if (input_word == nullptr) {
			char *return_val = (char *)malloc(sizeof(char));
			return_val[0] = '\0';
			return return_val;
		}

		char *output_word = lemmatizer->Lemmatize(input_word, nullptr);
		// Output word is allocated with "new" so we have to reallocate to change to
		// C-like malloc allocation
		char *return_val = (char *)malloc(sizeof(char) * strlen(output_word) + 1);
		strcpy(return_val, output_word);
		delete[] output_word;

		return return_val;
	}

	EXPORT_API void lem_unload_language_library(void) {
		#if HAS_MUTEX
		std::lock_guard<std::mutex> lock(mutex_lemmatizer);
		#endif

		if (lemmatizer != nullptr) {
			delete lemmatizer;
			lemmatizer = nullptr;
		}
	}

#ifdef __cplusplus
}
#endif
<|endoftext|>


<commit_before>#include "kclinfowidget.h"

#include "kclcode.h"
#include "kcldetect.h"
#include "kcldevicemodel.h"
#include "kclinputwidget.h"

#include <KIcon>
#include <KMessageBox>
#include <KPushButton>
#include <KSeparator>
#include <KLocale>
#include <KTabWidget>

#include <QGroupBox>
#include <QLabel>
#include <QProcess>
#include <QVBoxLayout>
#include <QStackedWidget>
#include <QComboBox>
#include <QTreeView>

KCLInfoWidget::KCLInfoWidget(QWidget *parent)
        : QWidget(parent)
{
    QVBoxLayout *layout = new QVBoxLayout;

    m_information = new QWidget;
    m_preview = new QWidget;
    KTabWidget *tab = new KTabWidget;
    tab->addTab(m_preview, KIcon("run-build-configure.png"), i18n("Preview"));
    tab->addTab(m_information, KIcon("run-build-file.png"), i18n("Information"));
    setupPreview();
    setupInformation();
    layout->addWidget(tab);
    setLayout(layout);
}

void KCLInfoWidget::setupPreview()
{
    QStackedWidget * widget = new QStackedWidget;
    QComboBox * combo = new QComboBox;

    foreach ( KCLInput * input, KCLDetect::inputList())
    {
        KCLInputWidget * w = new KCLInputWidget(input);
        combo->addItem(KCLCode::iconDevice(input->deviceType()),input->deviceName());
        widget->addWidget(w);
    }

    connect(combo,SIGNAL(currentIndexChanged(int)),widget,SLOT(setCurrentIndex(int)));
    combo->setCurrentIndex(combo->count()-1);
    QVBoxLayout * layout = new QVBoxLayout;
    layout->addWidget(combo);
    layout->addWidget(widget);
    m_preview->setLayout(layout);
}

void KCLInfoWidget::setupInformation()
{
    QVBoxLayout *layout = new QVBoxLayout;

    QLabel *info = new QLabel(i18n("Some Linux distributions forbid direct access \n to the input method used by KCL(evdev) as it can causes security-related issues\n"
                                    "If you are sure, you can allow direct access by clicking here."));

    KPushButton *buttonAuthorizate = new KPushButton(KIcon("dialog-password.png"), i18n("Set permissions"));
    KPushButton *buttonDetect = new KPushButton(KIcon("edit-find.png"), i18n("Detect devices"));

    connect(buttonAuthorizate, SIGNAL(clicked()), this, SLOT(setAuthorization()));
    connect(buttonDetect, SIGNAL(clicked()), this, SLOT(detectDevice()));

    QHBoxLayout *hlayout = new QHBoxLayout;
    hlayout->addWidget(info);
    hlayout->addStretch();
    hlayout->addWidget(buttonAuthorizate);
    hlayout->addWidget(buttonDetect);

    m_model = new KCLDeviceModel;
    m_treeView = new QTreeView;
    m_treeView->setModel(m_model);
    m_treeView->setIconSize(QSize(22, 22));
    layout->addLayout(hlayout);
    layout->addWidget(m_treeView);
    m_information->setLayout(layout);
}

void KCLInfoWidget::setAuthorization()
{
    //TODO: Find a better way to do that(either via HAL, PolicyKit, or use X11 libs instead of evdev.
    if (QProcess::execute("kdesudo chmod -R a+rwx /dev/input/*")) {
        KMessageBox::information(this, i18n("authorization success..."), i18n("success"));
    } else {
        KMessageBox::error(this, i18n("authorization failed..."), i18n("failed"));
    }
}

void KCLInfoWidget::detectDevice()
{
    m_model->clear();
    m_model->setupList();
}
<commit_msg>Give the model a parent, fixes a memory leak<commit_after>#include "kclinfowidget.h"

#include "kclcode.h"
#include "kcldetect.h"
#include "kcldevicemodel.h"
#include "kclinputwidget.h"

#include <KIcon>
#include <KMessageBox>
#include <KPushButton>
#include <KSeparator>
#include <KLocale>
#include <KTabWidget>

#include <QGroupBox>
#include <QLabel>
#include <QProcess>
#include <QVBoxLayout>
#include <QStackedWidget>
#include <QComboBox>
#include <QTreeView>

KCLInfoWidget::KCLInfoWidget(QWidget *parent)
        : QWidget(parent)
{
    QVBoxLayout *layout = new QVBoxLayout;

    m_information = new QWidget;
    m_preview = new QWidget;
    KTabWidget *tab = new KTabWidget;
    tab->addTab(m_preview, KIcon("run-build-configure.png"), i18n("Preview"));
    tab->addTab(m_information, KIcon("run-build-file.png"), i18n("Information"));
    setupPreview();
    setupInformation();
    layout->addWidget(tab);
    setLayout(layout);
}

void KCLInfoWidget::setupPreview()
{
    QStackedWidget * widget = new QStackedWidget;
    QComboBox * combo = new QComboBox;

    foreach ( KCLInput * input, KCLDetect::inputList())
    {
        KCLInputWidget * w = new KCLInputWidget(input);
        combo->addItem(KCLCode::iconDevice(input->deviceType()),input->deviceName());
        widget->addWidget(w);
    }

    connect(combo,SIGNAL(currentIndexChanged(int)),widget,SLOT(setCurrentIndex(int)));
    combo->setCurrentIndex(combo->count()-1);
    QVBoxLayout * layout = new QVBoxLayout;
    layout->addWidget(combo);
    layout->addWidget(widget);
    m_preview->setLayout(layout);
}

void KCLInfoWidget::setupInformation()
{
    QVBoxLayout *layout = new QVBoxLayout;

    QLabel *info = new QLabel(i18n("Some Linux distributions forbid direct access \n to the input method used by KCL(evdev) as it can causes security-related issues\n"
                                    "If you are sure, you can allow direct access by clicking here."));

    KPushButton *buttonAuthorizate = new KPushButton(KIcon("dialog-password.png"), i18n("Set permissions"));
    KPushButton *buttonDetect = new KPushButton(KIcon("edit-find.png"), i18n("Detect devices"));

    connect(buttonAuthorizate, SIGNAL(clicked()), this, SLOT(setAuthorization()));
    connect(buttonDetect, SIGNAL(clicked()), this, SLOT(detectDevice()));

    QHBoxLayout *hlayout = new QHBoxLayout;
    hlayout->addWidget(info);
    hlayout->addStretch();
    hlayout->addWidget(buttonAuthorizate);
    hlayout->addWidget(buttonDetect);

    m_model = new KCLDeviceModel(this);
    m_treeView = new QTreeView;
    m_treeView->setModel(m_model);
    m_treeView->setIconSize(QSize(22, 22));
    layout->addLayout(hlayout);
    layout->addWidget(m_treeView);
    m_information->setLayout(layout);
}

void KCLInfoWidget::setAuthorization()
{
    //TODO: Find a better way to do that(either via HAL, PolicyKit, or use X11 libs instead of evdev.
    if (QProcess::execute("kdesudo chmod -R a+rwx /dev/input/*")) {
        KMessageBox::information(this, i18n("authorization success..."), i18n("success"));
    } else {
        KMessageBox::error(this, i18n("authorization failed..."), i18n("failed"));
    }
}

void KCLInfoWidget::detectDevice()
{
    m_model->clear();
    m_model->setupList();
}
<|endoftext|>


<commit_before>/*++
Copyright (c) 2011 Microsoft Corporation

Module Name:

    iz3foci.cpp

Abstract:

   Implements a secondary solver using foci2.

Author:

    Ken McMillan (kenmcmil)

Revision History:

--*/

#include <sstream>
#include <iostream>
#include <assert.h>

#include "iz3hash.h"
#include "foci2.h"
#include "iz3foci.h"

using namespace stl_ext;

class iz3foci_impl : public iz3secondary {

  int frames;
  int *parents;
  foci2 *foci;
  foci2::symb select_op;
  foci2::symb store_op;
  foci2::symb mod_op;

public:
  iz3foci_impl(iz3mgr *mgr, int _frames, int *_parents) : iz3secondary(*mgr) {
    frames = _frames;
    parents = _parents;
    foci = 0;
  }

  typedef hash_map<ast,foci2::ast> AstToNode;
  AstToNode ast_to_node;                    // maps Z3 ast's to foci expressions

  typedef hash_map<foci2::ast,ast> NodeToAst;
  NodeToAst node_to_ast;                    // maps Z3 ast's to foci expressions

  // We only use this for FuncDeclToSymbol, which has no range destructor
  struct symb_hash {
    size_t operator()(const symb &s) const {
      return (size_t) s;
    }
  };

  typedef hash_map<symb,foci2::symb> FuncDeclToSymbol;
  FuncDeclToSymbol func_decl_to_symbol;     // maps Z3 func decls to symbols

  typedef hash_map<foci2::symb,symb> SymbolToFuncDecl;
  SymbolToFuncDecl symbol_to_func_decl;     // maps symbols to Z3 func decls

  int from_symb(symb func){
    std::string name = string_of_symbol(func);
    bool is_bool = is_bool_type(get_range_type(func));
    foci2::symb f;
    if(is_bool)
      f = foci->mk_pred(name);
    else
      f = foci->mk_func(name);
    symbol_to_func_decl[f] = func;
    func_decl_to_symbol[func] = f;
    return f;
  }

  // create a symbol corresponding to a DeBruijn index of a particular type
  // the type has to be encoded into the name because the same index can
  // occur with different types
  foci2::symb make_deBruijn_symbol(int index, type ty){
    std::ostringstream s;
    // s << "#" << index << "#" << type;
    return foci->mk_func(s.str());
  }

  int from_Z3_ast(ast t){
    std::pair<ast,foci2::ast> foo(t,0);
    std::pair<AstToNode::iterator, bool> bar = ast_to_node.insert(foo);
    int &res = bar.first->second;
    if(!bar.second) return res;
    int nargs = num_args(t);
    std::vector<foci2::ast> args(nargs);
    for(int i = 0; i < nargs; i++)
      args[i] = from_Z3_ast(arg(t,i));

    switch(op(t)){
      case True:
	res = foci->mk_true(); break;
      case False:
	res = foci->mk_false(); break;
      case And:
	res = foci->mk_op(foci2::And,args); break;
      case Or:
	res = foci->mk_op(foci2::Or,args); break;
      case Not:
	res = foci->mk_op(foci2::Not,args[0]); break;
      case Iff:
	res = foci->mk_op(foci2::Iff,args); break;
      case OP_OEQ: // bit of a mystery, this one...
	if(args[0] == args[1]) res = foci->mk_true();
	else res = foci->mk_op(foci2::Iff,args);
	break;
      case Ite:
	if(is_bool_type(get_type(t)))
	  res = foci->mk_op(foci2::And,foci->mk_op(foci2::Or,foci->mk_op(foci2::Not,args[0]),args[1]),foci->mk_op(foci2::Or,args[0],args[2]));
	else
	  res = foci->mk_op(foci2::Ite,args);
	break;
      case Equal:
	res = foci->mk_op(foci2::Equal,args); break;
      case Implies:
	args[0] = foci->mk_op(foci2::Not,args[0]); res = foci->mk_op(foci2::Or,args); break;
      case Xor:
	res = foci->mk_op(foci2::Not,foci->mk_op(foci2::Iff,args)); break;
      case Leq:
	res = foci->mk_op(foci2::Leq,args); break;
      case Geq:
	std::swap(args[0],args[1]); res = foci->mk_op(foci2::Leq,args); break;
      case Gt:
	res = foci->mk_op(foci2::Not,foci->mk_op(foci2::Leq,args)); break;
      case Lt:
	std::swap(args[0],args[1]); res = foci->mk_op(foci2::Not,foci->mk_op(foci2::Leq,args)); break;
      case Plus:
	res = foci->mk_op(foci2::Plus,args); break;
      case Sub:
	args[1] = foci->mk_op(foci2::Times,foci->mk_int("-1"),args[1]); res = foci->mk_op(foci2::Plus,args); break;
      case Uminus:
	res = foci->mk_op(foci2::Times,foci->mk_int("-1"),args[0]); break;
      case Times:
	res = foci->mk_op(foci2::Times,args); break;
      case Idiv:
	res = foci->mk_op(foci2::Div,args); break;
      case Mod:
	res = foci->mk_app(mod_op,args); break;
      case Select:
	res = foci->mk_app(select_op,args); break;
      case Store:
	res = foci->mk_app(store_op,args); break;
      case Distinct:
	res = foci->mk_op(foci2::Distinct,args); break;
      case Uninterpreted: {
	symb func = sym(t);
	FuncDeclToSymbol::iterator it = func_decl_to_symbol.find(func);
	foci2::symb f = (it == func_decl_to_symbol.end()) ? from_symb(func) : it->second;
	if(foci->get_symb(f).substr(0,3) == "lbl" && args.size()==1) // HACK to handle Z3 labels
	  res = args[0];
	else if(foci->get_symb(f).substr(0,3) == "lbl" && args.size()==0) // HACK to handle Z3 labels
	  res = foci->mk_true();
	else res = foci->mk_app(f,args);
	break;
      }
      case Numeral: {
	std::string s = string_of_numeral(t);
	res = foci->mk_int(s);
	break;
      }
      case Forall:
      case Exists: {
	bool is_forall = op(t) == Forall;
	foci2::ops qop = is_forall ? foci2::Forall : foci2::Exists;
	int bvs = get_quantifier_num_bound(t);
	std::vector<int> foci_bvs(bvs);
	for(int i = 0; i < bvs; i++){
	  std::string name = get_quantifier_bound_name(t,i);
	  //Z3_string name = Z3_get_symbol_string(ctx,sym);
	  // type ty = get_quantifier_bound_type(t,i);
	  foci2::symb f = foci->mk_func(name);
	  foci2::ast v = foci->mk_app(f,std::vector<foci2::ast>());
	  foci_bvs[i] = v;
	}
	foci2::ast body = from_Z3_ast(get_quantifier_body(t));
	foci_bvs.push_back(body);
	res = foci->mk_op(qop,foci_bvs);
	node_to_ast[res] = t; // desperate
	break;
      }
      case Variable: {  // a deBruijn index
        int index = get_variable_index_value(t);
	type ty = get_type(t);
        foci2::symb symbol = make_deBruijn_symbol(index,ty);
        res = foci->mk_app(symbol,std::vector<foci2::ast>());
	break;
      }
      default:
	{
	  std::cerr << "iZ3: unsupported Z3 operator in expression\n ";
	  print_expr(std::cerr,t);
	  std::cerr << "\n";
	  assert(0 && "iZ3: unsupported Z3 operator");
	}
    }
    return res;
  }

  // convert an expr to Z3 ast
  ast to_Z3_ast(foci2::ast i){
    std::pair<foci2::ast,ast> foo(i,ast());
    std::pair<NodeToAst::iterator,bool> bar = node_to_ast.insert(foo);
    if(!bar.second) return bar.first->second;
    ast &res = bar.first->second;

    if(i < 0){
      res = mk_not(to_Z3_ast(-i));
      return res;
    }

    // get the arguments
    unsigned n = foci->get_num_args(i);
    std::vector<ast> args(n);
    for(unsigned j = 0; j < n; j++)
      args[j] = to_Z3_ast(foci->get_arg(i,j));

    // handle operators
    foci2::ops o;
    foci2::symb f;
    std::string nval;
    if(foci->get_true(i))
      res = mk_true();
    else if(foci->get_false(i))
      res = mk_false();
    else if(foci->get_op(i,o)){
      switch(o){
      case foci2::And:
	res = make(And,args); break;
      case foci2::Or:
	res = make(Or,args); break;
      case foci2::Not:
	res = mk_not(args[0]); break;
      case foci2::Iff:
	res = make(Iff,args[0],args[1]); break;
      case foci2::Ite:
	res = make(Ite,args[0],args[1],args[2]); break;
      case foci2::Equal:
	res = make(Equal,args[0],args[1]); break;
      case foci2::Plus:
	res = make(Plus,args); break;
      case foci2::Times:
	res = make(Times,args); break;
      case foci2::Div:
	res = make(Idiv,args[0],args[1]); break;
      case foci2::Leq:
	res = make(Leq,args[0],args[1]); break;
      case foci2::Distinct:
	res = make(Distinct,args);
	break;
      case foci2::Tsym:
	res = mk_true();
	break;
      case foci2::Fsym:
	res = mk_false();
	break;
      case foci2::Forall:
      case foci2::Exists:
	{
	  int nargs = n;
	  std::vector<ast> bounds(nargs-1);
	  for(int i = 0; i < nargs-1; i++)
	    bounds[i] = args[i];
	  opr oz = o == foci2::Forall ? Forall : Exists;
	  res = make_quant(oz,bounds,args[nargs-1]);
	}
	break;
      default:
	assert("unknown built-in op");
      }
    }
    else if(foci->get_int(i,nval)){
      res = make_int(nval);
    }
    else if(foci->get_func(i,f)){
      if(f == select_op){
	assert(n == 2);
	res = make(Select,args[0],args[1]);
      }
      else if(f == store_op){
	assert(n == 3);
	res = make(Store,args[0],args[1],args[2]);
      }
      else if(f == mod_op){
	assert(n == 2);
	res = make(Mod,args[0],args[1]);
      }
      else {
	std::pair<int,symb> foo(f,(symb)0);
	std::pair<SymbolToFuncDecl::iterator,bool> bar = symbol_to_func_decl.insert(foo);
	symb &func_decl = bar.first->second;
        if(bar.second){
          std::cout << "unknown function symbol:\n";
          foci->show_ast(i);
          assert(0);
        }
	res = make(func_decl,args);
      }
    }
    else {
      std::cerr << "iZ3: unknown FOCI expression kind\n";
      assert(0 && "iZ3: unknown FOCI expression kind");
    }
    return res;
  }

  int interpolate(const std::vector<ast> &cnsts, std::vector<ast> &itps){
    assert((int)cnsts.size() == frames);
    std::string lia("lia");
#ifdef _FOCI2
    foci = foci2::create(lia);
#else
    foci = 0;
#endif
    if(!foci){
      std::cerr << "iZ3: cannot find foci lia solver.\n";
      assert(0);
    }
    select_op = foci->mk_func("select");
    store_op = foci->mk_func("store");
    mod_op = foci->mk_func("mod");
    std::vector<foci2::ast> foci_cnsts(frames), foci_itps(frames-1), foci_parents;
    if(parents)
      foci_parents.resize(frames);
    for(int i = 0; i < frames; i++){
      foci_cnsts[i] = from_Z3_ast(cnsts[i]);
      if(parents)
	foci_parents[i] = parents[i];
    }
    int res = foci->interpolate(foci_cnsts, foci_itps, foci_parents);
    if(res == 0){
      assert((int)foci_itps.size() == frames-1);
      itps.resize(frames-1);
      for(int i = 0; i < frames-1; i++){
        // foci->show_ast(foci_itps[i]);
	itps[i] = to_Z3_ast(foci_itps[i]);
      }
    }
    ast_to_node.clear();
    node_to_ast.clear();
    func_decl_to_symbol.clear();
    symbol_to_func_decl.clear();
    delete foci;
    return res;
  }

};

iz3secondary *iz3foci::create(iz3mgr *mgr, int num, int *parents){
  return new iz3foci_impl(mgr,num,parents);
}
<commit_msg>Wstring-conversion<commit_after>/*++
Copyright (c) 2011 Microsoft Corporation

Module Name:

    iz3foci.cpp

Abstract:

   Implements a secondary solver using foci2.

Author:

    Ken McMillan (kenmcmil)

Revision History:

--*/

#include <sstream>
#include <iostream>
#include <assert.h>

#include "iz3hash.h"
#include "foci2.h"
#include "iz3foci.h"

using namespace stl_ext;

class iz3foci_impl : public iz3secondary {

  int frames;
  int *parents;
  foci2 *foci;
  foci2::symb select_op;
  foci2::symb store_op;
  foci2::symb mod_op;

public:
  iz3foci_impl(iz3mgr *mgr, int _frames, int *_parents) : iz3secondary(*mgr) {
    frames = _frames;
    parents = _parents;
    foci = 0;
  }

  typedef hash_map<ast,foci2::ast> AstToNode;
  AstToNode ast_to_node;                    // maps Z3 ast's to foci expressions

  typedef hash_map<foci2::ast,ast> NodeToAst;
  NodeToAst node_to_ast;                    // maps Z3 ast's to foci expressions

  // We only use this for FuncDeclToSymbol, which has no range destructor
  struct symb_hash {
    size_t operator()(const symb &s) const {
      return (size_t) s;
    }
  };

  typedef hash_map<symb,foci2::symb> FuncDeclToSymbol;
  FuncDeclToSymbol func_decl_to_symbol;     // maps Z3 func decls to symbols

  typedef hash_map<foci2::symb,symb> SymbolToFuncDecl;
  SymbolToFuncDecl symbol_to_func_decl;     // maps symbols to Z3 func decls

  int from_symb(symb func){
    std::string name = string_of_symbol(func);
    bool is_bool = is_bool_type(get_range_type(func));
    foci2::symb f;
    if(is_bool)
      f = foci->mk_pred(name);
    else
      f = foci->mk_func(name);
    symbol_to_func_decl[f] = func;
    func_decl_to_symbol[func] = f;
    return f;
  }

  // create a symbol corresponding to a DeBruijn index of a particular type
  // the type has to be encoded into the name because the same index can
  // occur with different types
  foci2::symb make_deBruijn_symbol(int index, type ty){
    std::ostringstream s;
    // s << "#" << index << "#" << type;
    return foci->mk_func(s.str());
  }

  int from_Z3_ast(ast t){
    std::pair<ast,foci2::ast> foo(t,0);
    std::pair<AstToNode::iterator, bool> bar = ast_to_node.insert(foo);
    int &res = bar.first->second;
    if(!bar.second) return res;
    int nargs = num_args(t);
    std::vector<foci2::ast> args(nargs);
    for(int i = 0; i < nargs; i++)
      args[i] = from_Z3_ast(arg(t,i));

    switch(op(t)){
      case True:
	res = foci->mk_true(); break;
      case False:
	res = foci->mk_false(); break;
      case And:
	res = foci->mk_op(foci2::And,args); break;
      case Or:
	res = foci->mk_op(foci2::Or,args); break;
      case Not:
	res = foci->mk_op(foci2::Not,args[0]); break;
      case Iff:
	res = foci->mk_op(foci2::Iff,args); break;
      case OP_OEQ: // bit of a mystery, this one...
	if(args[0] == args[1]) res = foci->mk_true();
	else res = foci->mk_op(foci2::Iff,args);
	break;
      case Ite:
	if(is_bool_type(get_type(t)))
	  res = foci->mk_op(foci2::And,foci->mk_op(foci2::Or,foci->mk_op(foci2::Not,args[0]),args[1]),foci->mk_op(foci2::Or,args[0],args[2]));
	else
	  res = foci->mk_op(foci2::Ite,args);
	break;
      case Equal:
	res = foci->mk_op(foci2::Equal,args); break;
      case Implies:
	args[0] = foci->mk_op(foci2::Not,args[0]); res = foci->mk_op(foci2::Or,args); break;
      case Xor:
	res = foci->mk_op(foci2::Not,foci->mk_op(foci2::Iff,args)); break;
      case Leq:
	res = foci->mk_op(foci2::Leq,args); break;
      case Geq:
	std::swap(args[0],args[1]); res = foci->mk_op(foci2::Leq,args); break;
      case Gt:
	res = foci->mk_op(foci2::Not,foci->mk_op(foci2::Leq,args)); break;
      case Lt:
	std::swap(args[0],args[1]); res = foci->mk_op(foci2::Not,foci->mk_op(foci2::Leq,args)); break;
      case Plus:
	res = foci->mk_op(foci2::Plus,args); break;
      case Sub:
	args[1] = foci->mk_op(foci2::Times,foci->mk_int("-1"),args[1]); res = foci->mk_op(foci2::Plus,args); break;
      case Uminus:
	res = foci->mk_op(foci2::Times,foci->mk_int("-1"),args[0]); break;
      case Times:
	res = foci->mk_op(foci2::Times,args); break;
      case Idiv:
	res = foci->mk_op(foci2::Div,args); break;
      case Mod:
	res = foci->mk_app(mod_op,args); break;
      case Select:
	res = foci->mk_app(select_op,args); break;
      case Store:
	res = foci->mk_app(store_op,args); break;
      case Distinct:
	res = foci->mk_op(foci2::Distinct,args); break;
      case Uninterpreted: {
	symb func = sym(t);
	FuncDeclToSymbol::iterator it = func_decl_to_symbol.find(func);
	foci2::symb f = (it == func_decl_to_symbol.end()) ? from_symb(func) : it->second;
	if(foci->get_symb(f).substr(0,3) == "lbl" && args.size()==1) // HACK to handle Z3 labels
	  res = args[0];
	else if(foci->get_symb(f).substr(0,3) == "lbl" && args.size()==0) // HACK to handle Z3 labels
	  res = foci->mk_true();
	else res = foci->mk_app(f,args);
	break;
      }
      case Numeral: {
	std::string s = string_of_numeral(t);
	res = foci->mk_int(s);
	break;
      }
      case Forall:
      case Exists: {
	bool is_forall = op(t) == Forall;
	foci2::ops qop = is_forall ? foci2::Forall : foci2::Exists;
	int bvs = get_quantifier_num_bound(t);
	std::vector<int> foci_bvs(bvs);
	for(int i = 0; i < bvs; i++){
	  std::string name = get_quantifier_bound_name(t,i);
	  //Z3_string name = Z3_get_symbol_string(ctx,sym);
	  // type ty = get_quantifier_bound_type(t,i);
	  foci2::symb f = foci->mk_func(name);
	  foci2::ast v = foci->mk_app(f,std::vector<foci2::ast>());
	  foci_bvs[i] = v;
	}
	foci2::ast body = from_Z3_ast(get_quantifier_body(t));
	foci_bvs.push_back(body);
	res = foci->mk_op(qop,foci_bvs);
	node_to_ast[res] = t; // desperate
	break;
      }
      case Variable: {  // a deBruijn index
        int index = get_variable_index_value(t);
	type ty = get_type(t);
        foci2::symb symbol = make_deBruijn_symbol(index,ty);
        res = foci->mk_app(symbol,std::vector<foci2::ast>());
	break;
      }
      default:
	{
	  std::cerr << "iZ3: unsupported Z3 operator in expression\n ";
	  print_expr(std::cerr,t);
	  std::cerr << "\n";
	  assert(0 && "iZ3: unsupported Z3 operator");
	}
    }
    return res;
  }

  // convert an expr to Z3 ast
  ast to_Z3_ast(foci2::ast i){
    std::pair<foci2::ast,ast> foo(i,ast());
    std::pair<NodeToAst::iterator,bool> bar = node_to_ast.insert(foo);
    if(!bar.second) return bar.first->second;
    ast &res = bar.first->second;

    if(i < 0){
      res = mk_not(to_Z3_ast(-i));
      return res;
    }

    // get the arguments
    unsigned n = foci->get_num_args(i);
    std::vector<ast> args(n);
    for(unsigned j = 0; j < n; j++)
      args[j] = to_Z3_ast(foci->get_arg(i,j));

    // handle operators
    foci2::ops o;
    foci2::symb f;
    std::string nval;
    if(foci->get_true(i))
      res = mk_true();
    else if(foci->get_false(i))
      res = mk_false();
    else if(foci->get_op(i,o)){
      switch(o){
      case foci2::And:
	res = make(And,args); break;
      case foci2::Or:
	res = make(Or,args); break;
      case foci2::Not:
	res = mk_not(args[0]); break;
      case foci2::Iff:
	res = make(Iff,args[0],args[1]); break;
      case foci2::Ite:
	res = make(Ite,args[0],args[1],args[2]); break;
      case foci2::Equal:
	res = make(Equal,args[0],args[1]); break;
      case foci2::Plus:
	res = make(Plus,args); break;
      case foci2::Times:
	res = make(Times,args); break;
      case foci2::Div:
	res = make(Idiv,args[0],args[1]); break;
      case foci2::Leq:
	res = make(Leq,args[0],args[1]); break;
      case foci2::Distinct:
	res = make(Distinct,args);
	break;
      case foci2::Tsym:
	res = mk_true();
	break;
      case foci2::Fsym:
	res = mk_false();
	break;
      case foci2::Forall:
      case foci2::Exists:
	{
	  int nargs = n;
	  std::vector<ast> bounds(nargs-1);
	  for(int i = 0; i < nargs-1; i++)
	    bounds[i] = args[i];
	  opr oz = o == foci2::Forall ? Forall : Exists;
	  res = make_quant(oz,bounds,args[nargs-1]);
	}
	break;
      default:
	assert(false && "unknown built-in op");
      }
    }
    else if(foci->get_int(i,nval)){
      res = make_int(nval);
    }
    else if(foci->get_func(i,f)){
      if(f == select_op){
	assert(n == 2);
	res = make(Select,args[0],args[1]);
      }
      else if(f == store_op){
	assert(n == 3);
	res = make(Store,args[0],args[1],args[2]);
      }
      else if(f == mod_op){
	assert(n == 2);
	res = make(Mod,args[0],args[1]);
      }
      else {
	std::pair<int,symb> foo(f,(symb)0);
	std::pair<SymbolToFuncDecl::iterator,bool> bar = symbol_to_func_decl.insert(foo);
	symb &func_decl = bar.first->second;
        if(bar.second){
          std::cout << "unknown function symbol:\n";
          foci->show_ast(i);
          assert(0);
        }
	res = make(func_decl,args);
      }
    }
    else {
      std::cerr << "iZ3: unknown FOCI expression kind\n";
      assert(0 && "iZ3: unknown FOCI expression kind");
    }
    return res;
  }

  int interpolate(const std::vector<ast> &cnsts, std::vector<ast> &itps){
    assert((int)cnsts.size() == frames);
    std::string lia("lia");
#ifdef _FOCI2
    foci = foci2::create(lia);
#else
    foci = 0;
#endif
    if(!foci){
      std::cerr << "iZ3: cannot find foci lia solver.\n";
      assert(0);
    }
    select_op = foci->mk_func("select");
    store_op = foci->mk_func("store");
    mod_op = foci->mk_func("mod");
    std::vector<foci2::ast> foci_cnsts(frames), foci_itps(frames-1), foci_parents;
    if(parents)
      foci_parents.resize(frames);
    for(int i = 0; i < frames; i++){
      foci_cnsts[i] = from_Z3_ast(cnsts[i]);
      if(parents)
	foci_parents[i] = parents[i];
    }
    int res = foci->interpolate(foci_cnsts, foci_itps, foci_parents);
    if(res == 0){
      assert((int)foci_itps.size() == frames-1);
      itps.resize(frames-1);
      for(int i = 0; i < frames-1; i++){
        // foci->show_ast(foci_itps[i]);
	itps[i] = to_Z3_ast(foci_itps[i]);
      }
    }
    ast_to_node.clear();
    node_to_ast.clear();
    func_decl_to_symbol.clear();
    symbol_to_func_decl.clear();
    delete foci;
    return res;
  }

};

iz3secondary *iz3foci::create(iz3mgr *mgr, int num, int *parents){
  return new iz3foci_impl(mgr,num,parents);
}
<|endoftext|>


<commit_before>/*
 * File:  strings.cpp
 * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
 */

#include "common/sedna.h"

#include "tr/strings/utf8.h"
#include "tr/pstr/pstr.h"
#include "tr/pstr/pstr_long.h"
#include "tr/executor/fo/casting_operations.h"
#include "common/errdbg/d_printf.h"

CharsetHandler *charset_handler = NULL;

#define T_STR_MEMBUF_SIZE 100

void str_buf_base::move_to_mem_buf()
{
	if (m_flags & f_text_in_buf)
		return;
	if (m_buf_size <= m_len)
	{
		if (m_buf_size > 0)
			free(m_buf);
		m_buf_size = m_len + 1;
		if (m_buf_size < T_STR_MEMBUF_SIZE)
			m_buf_size = T_STR_MEMBUF_SIZE;
		m_buf = (char*)malloc(m_buf_size);
	}
	if (m_len == 0)
	{
		m_buf[0] = 0;
		return;
	}
	switch (m_ttype)
	{
	case text_mem:
		strcpy(m_buf, m_str_ptr.get());
		m_flags |= f_text_in_buf;
		m_ttype = text_mem;
		return;
	case text_estr:
		estr_copy_to_buffer(m_buf, m_ptr, m_len);
		m_buf[m_len] = 0;
		m_flags |= f_text_in_buf;
		m_ttype = text_mem;
		return;
	case text_doc:
		if (m_len < PSTRMAXSIZE)
			estr_copy_to_buffer(m_buf, m_ptr, m_len);
		else
			pstr_long_copy_to_buffer(m_buf, m_ptr, m_len);
		m_buf[m_len] = 0;
		m_flags |= f_text_in_buf;
		m_ttype = text_mem;
		return;
	}
	throw USER_EXCEPTION2(SE1003, "Impossible case in str_buf_base::move_to_mem_buf()");
}

//pre: text is not in estr buf
void str_buf_base::move_to_estr()
{
	U_ASSERT(!mem_only());
	if (m_flags & f_text_in_buf)
	{
		m_ptr = m_estr.append_mstr(m_buf);
		m_flags |= f_text_in_estr_buf;
		return;
	}
	switch (m_ttype)
	{
	case text_mem:
		m_ptr = m_estr.append_mstr(m_str_ptr.get());
		m_ttype = text_estr;
		m_flags |= f_text_in_estr_buf;
		return;
	case text_estr:
		m_ptr = m_estr.append_estr(m_ptr, m_len);
		m_flags |= f_text_in_estr_buf;
		return;
	case text_doc:
		if (m_len < PSTRMAXSIZE)
			m_ptr = m_estr.append_estr(m_ptr, m_len);
		else
			m_ptr = m_estr.append_pstr_long(m_ptr);
		m_ttype = text_estr;
		m_flags |= f_text_in_estr_buf;
		return;
	}
	throw USER_EXCEPTION2(SE1003, "Impossible case in op_str_buf::move_to_estr()");
}

void str_buf_base::clear()
{
	m_len = 0;
	if (m_flags & f_text_in_estr_buf)
		clear_estr_buf();
	m_flags = 0;
	m_ttype = text_mem;
}

void str_buf_base::append(const tuple_cell &tc)
{
	if (m_len == 0)
	{
		m_flags = 0;
		if (tc.is_light_atomic())
		{
			m_str_ptr = tc.get_str_ptr();
			m_len = tc.get_strlen_mem();
			m_flags = 0;
			m_ttype = text_mem;
		}
		else
		{
			m_len = tc.get_strlen_vmm();
			m_ptr = tc.get_str_vmm();
			if (tc.get_type() == tc_heavy_atomic_estr)
				m_ttype = text_estr;
			else
				m_ttype = text_doc;
		}
	}
	else
	{
		if (tc.is_light_atomic())
		{
			append(tc.get_str_mem());
		}
		else
		{
			const int add_len = tc.get_strlen_vmm();
			const int new_len = m_len + add_len;

			if (new_len < T_STR_MEMBUF_SIZE || mem_only())
			{
				if (m_buf_size == 0)
				{
					m_buf_size = T_STR_MEMBUF_SIZE;
					while (m_buf_size <= new_len)
						m_buf_size *= 2;
					m_buf = (char *)malloc(m_buf_size);
				}
				else if (m_buf_size <= new_len)
				{
					while (m_buf_size <= new_len)
						m_buf_size *= 2;
					m_buf = (char*)realloc(m_buf, m_buf_size);
				}
				move_to_mem_buf();
				if (m_flags & f_text_in_estr_buf)
				{
					m_flags = f_text_in_buf; //clear f_text_in_estr_buf
					clear_estr_buf();
				}
				tc.copy_string(m_buf + m_len);
				m_buf[new_len] = 0;
				m_len = new_len;
			}
			else
			{
				if (!(m_flags & f_text_in_estr_buf))
					move_to_estr();
				m_flags = f_text_in_estr_buf; //clear f_text_in_buf
				m_estr.append(tc);
				m_len = new_len;
			}
		}
	}
}

void str_buf_base::append(const char *str, int add_len)
{
	const int new_len = m_len + add_len;
	if (new_len < T_STR_MEMBUF_SIZE || mem_only())
	{
		if (m_buf_size == 0)
		{
			m_buf_size = T_STR_MEMBUF_SIZE;
			while (m_buf_size <= new_len)
				m_buf_size *= 2;
			U_ASSERT(m_buf == NULL);
			m_buf = (char *)malloc(m_buf_size);
		}
		else if (m_buf_size <= new_len)
		{
			while (m_buf_size <= new_len)
				m_buf_size *= 2;
			m_buf = (char*)realloc(m_buf, m_buf_size);
		}
		if (m_len > 0)
		{
			move_to_mem_buf();
			if (m_flags & f_text_in_estr_buf)
				clear_estr_buf();
		}
		m_flags = f_text_in_buf; //clear f_text_in_estr_buf
		m_ttype = text_mem;
		strncpy(m_buf + m_len, str, add_len);
		m_len = new_len;
		U_ASSERT(m_len < m_buf_size);
		m_buf[m_len] = 0;
	}
	else
	{
		char *str_copy = (char*)malloc(add_len); //FIXME (what if NULL)
		memcpy(str_copy, str, add_len);
		//TODO: add a flag/another func that avoids copying str & use it where possible
		if (!(m_flags & f_text_in_estr_buf))
			move_to_estr();
		m_estr.append_mstr(str_copy, add_len);
		m_len = new_len;
		m_ttype = text_estr;
		m_flags = f_text_in_estr_buf; //clear f_text_in_buf
		free(str_copy); //FIXME: check that no exceptions can be thrown above
	}
}

void str_buf_base::append(const char *str)
{
	const int add_len = strlen(str);
	this->append(str, add_len);
}

char * str_buf_base::c_str()
{
	if (m_flags & f_text_in_buf)
		return m_buf;
	if (m_ttype == text_mem)
		return m_str_ptr.get();
	move_to_mem_buf();
	return m_buf;
}
char * str_buf_base::get_str()
{
	U_ASSERT(mem_only());
	move_to_mem_buf();
	char *res = m_buf;

	m_buf = NULL;
	m_buf_size = 0;
	U_ASSERT(!(m_flags & f_text_in_estr_buf));
	m_flags = 0;
	m_ptr = XNULL;
	m_len = 0;
	m_ttype = text_mem;

	return res;
}

str_buf_base::~str_buf_base()
{
	if (m_buf_size > 0)
		free(m_buf);
}

stmt_str_buf_impl stmt_str_buf::buf_impl;
bool stmt_str_buf::used = false;

void feed_tuple_cell(string_consumer_fn fn, void *p, const tuple_cell& tc)
{
	tuple_cell cell = cast(tc, xs_string);

	switch (tc.get_type())
	{
	case tc_light_atomic_var_size:
		fn(tc.get_str_mem(), tc.get_strlen_mem(), p);
		return;
	case tc_heavy_atomic_estr:
	case tc_heavy_atomic_pstr_short:
		estr_feed(fn, p, tc.get_str_vmm(), tc.get_strlen_vmm());
		return;
	case tc_heavy_atomic_pstr_long:
		pstr_long_feed2(tc.get_str_vmm(), fn, p);
		return;
	}
}

void print_tuple_cell_dummy(se_ostream& crmout,const tuple_cell& tc)
{
	    feed_tuple_cell(writextext_cb, &crmout, tc);
}

CollationHandler *CollationManager::get_collation_handler(const char *uri)
{
    if (strcmp(uri, "http://www.w3.org/2005/xpath-functions/collation/codepoint") == 0)
        return utf8_charset_handler.get_unicode_codepoint_collation();
    else
        return NULL;
}

CollationHandler *CollationManager::get_default_collation_handler()
{
    return utf8_charset_handler.get_unicode_codepoint_collation();
}

<commit_msg>str_buf fix<commit_after>/*
 * File:  strings.cpp
 * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
 */

#include "common/sedna.h"

#include "tr/strings/utf8.h"
#include "tr/pstr/pstr.h"
#include "tr/pstr/pstr_long.h"
#include "tr/executor/fo/casting_operations.h"
#include "common/errdbg/d_printf.h"

CharsetHandler *charset_handler = NULL;

#define T_STR_MEMBUF_SIZE 100

void str_buf_base::move_to_mem_buf()
{
	if (m_flags & f_text_in_buf)
		return;
	if (m_buf_size <= m_len)
	{
		if (m_buf_size > 0)
			free(m_buf);
		m_buf_size = m_len + 1;
		if (m_buf_size < T_STR_MEMBUF_SIZE)
			m_buf_size = T_STR_MEMBUF_SIZE;
		m_buf = (char*)malloc(m_buf_size);
	}
	if (m_len == 0)
	{
		m_buf[0] = 0;
		return;
	}
	switch (m_ttype)
	{
	case text_mem:
		strcpy(m_buf, m_str_ptr.get());
		m_flags |= f_text_in_buf;
		m_ttype = text_mem;
		return;
	case text_estr:
		estr_copy_to_buffer(m_buf, m_ptr, m_len);
		m_buf[m_len] = 0;
		m_flags |= f_text_in_buf;
		m_ttype = text_mem;
		return;
	case text_doc:
		if (m_len < PSTRMAXSIZE)
			estr_copy_to_buffer(m_buf, m_ptr, m_len);
		else
			pstr_long_copy_to_buffer(m_buf, m_ptr, m_len);
		m_buf[m_len] = 0;
		m_flags |= f_text_in_buf;
		m_ttype = text_mem;
		return;
	}
	throw USER_EXCEPTION2(SE1003, "Impossible case in str_buf_base::move_to_mem_buf()");
}

//pre: text is not in estr buf
//post: m_ttype == text_estr
void str_buf_base::move_to_estr()
{
	U_ASSERT(!mem_only());
	if (m_flags & f_text_in_buf)
	{
		m_ptr = m_estr.append_mstr(m_buf);
		m_ttype = text_estr;
		m_flags |= f_text_in_estr_buf;
		return;
	}
	switch (m_ttype)
	{
	case text_mem:
		m_ptr = m_estr.append_mstr(m_str_ptr.get());
		m_ttype = text_estr;
		m_flags |= f_text_in_estr_buf;
		return;
	case text_estr:
		m_ptr = m_estr.append_estr(m_ptr, m_len);
		m_flags |= f_text_in_estr_buf;
		return;
	case text_doc:
		if (m_len < PSTRMAXSIZE)
			m_ptr = m_estr.append_estr(m_ptr, m_len);
		else
			m_ptr = m_estr.append_pstr_long(m_ptr);
		m_ttype = text_estr;
		m_flags |= f_text_in_estr_buf;
		return;
	}
	throw USER_EXCEPTION2(SE1003, "Impossible case in op_str_buf::move_to_estr()");
}

void str_buf_base::clear()
{
	m_len = 0;
	if (m_flags & f_text_in_estr_buf)
		clear_estr_buf();
	m_flags = 0;
	m_ttype = text_mem;
}

void str_buf_base::append(const tuple_cell &tc)
{
	if (m_len == 0)
	{
		m_flags = 0;
		if (tc.is_light_atomic())
		{
			m_str_ptr = tc.get_str_ptr();
			m_len = tc.get_strlen_mem();
			m_flags = 0;
			m_ttype = text_mem;
		}
		else
		{
			m_len = tc.get_strlen_vmm();
			m_ptr = tc.get_str_vmm();
			if (tc.get_type() == tc_heavy_atomic_estr)
				m_ttype = text_estr;
			else
				m_ttype = text_doc;
		}
	}
	else
	{
		if (tc.is_light_atomic())
		{
			append(tc.get_str_mem());
		}
		else
		{
			const int add_len = tc.get_strlen_vmm();
			const int new_len = m_len + add_len;

			if (new_len < T_STR_MEMBUF_SIZE || mem_only())
			{
				if (m_buf_size == 0)
				{
					m_buf_size = T_STR_MEMBUF_SIZE;
					while (m_buf_size <= new_len)
						m_buf_size *= 2;
					m_buf = (char *)malloc(m_buf_size);
				}
				else if (m_buf_size <= new_len)
				{
					while (m_buf_size <= new_len)
						m_buf_size *= 2;
					m_buf = (char*)realloc(m_buf, m_buf_size);
				}
				move_to_mem_buf();
				if (m_flags & f_text_in_estr_buf)
				{
					m_flags = f_text_in_buf; //clear f_text_in_estr_buf
					clear_estr_buf();
				}
				tc.copy_string(m_buf + m_len);
				m_buf[new_len] = 0;
				m_len = new_len;
			}
			else
			{
				if (!(m_flags & f_text_in_estr_buf))
					move_to_estr();
				m_flags = f_text_in_estr_buf; //clear f_text_in_buf
				m_estr.append(tc);
				m_len = new_len;
			}
		}
	}
}

void str_buf_base::append(const char *str, int add_len)
{
	const int new_len = m_len + add_len;
	if (new_len < T_STR_MEMBUF_SIZE || mem_only())
	{
		if (m_buf_size == 0)
		{
			m_buf_size = T_STR_MEMBUF_SIZE;
			while (m_buf_size <= new_len)
				m_buf_size *= 2;
			U_ASSERT(m_buf == NULL);
			m_buf = (char *)malloc(m_buf_size);
		}
		else if (m_buf_size <= new_len)
		{
			while (m_buf_size <= new_len)
				m_buf_size *= 2;
			m_buf = (char*)realloc(m_buf, m_buf_size);
		}
		if (m_len > 0)
		{
			move_to_mem_buf();
			if (m_flags & f_text_in_estr_buf)
				clear_estr_buf();
		}
		m_flags = f_text_in_buf; //clear f_text_in_estr_buf
		m_ttype = text_mem;
		strncpy(m_buf + m_len, str, add_len);
		m_len = new_len;
		U_ASSERT(m_len < m_buf_size);
		m_buf[m_len] = 0;
	}
	else
	{
		char *str_copy = (char*)malloc(add_len); //FIXME (what if NULL)
		memcpy(str_copy, str, add_len);
		//TODO: add a flag/another func that avoids copying str & use it where possible
		if (!(m_flags & f_text_in_estr_buf))
			move_to_estr();
		m_estr.append_mstr(str_copy, add_len);
		m_len = new_len;
		m_flags = f_text_in_estr_buf; //clear f_text_in_buf
		free(str_copy); //FIXME: check that no exceptions can be thrown above
	}
}

void str_buf_base::append(const char *str)
{
	const int add_len = strlen(str);
	this->append(str, add_len);
}

char * str_buf_base::c_str()
{
	if (m_flags & f_text_in_buf)
		return m_buf;
	if (m_ttype == text_mem)
		return m_str_ptr.get();
	move_to_mem_buf();
	return m_buf;
}
char * str_buf_base::get_str()
{
	U_ASSERT(mem_only());
	move_to_mem_buf();
	char *res = m_buf;

	m_buf = NULL;
	m_buf_size = 0;
	U_ASSERT(!(m_flags & f_text_in_estr_buf));
	m_flags = 0;
	m_ptr = XNULL;
	m_len = 0;
	m_ttype = text_mem;

	return res;
}

str_buf_base::~str_buf_base()
{
	if (m_buf_size > 0)
		free(m_buf);
}

stmt_str_buf_impl stmt_str_buf::buf_impl;
bool stmt_str_buf::used = false;

void feed_tuple_cell(string_consumer_fn fn, void *p, const tuple_cell& tc)
{
	tuple_cell cell = cast(tc, xs_string);

	switch (tc.get_type())
	{
	case tc_light_atomic_var_size:
		fn(tc.get_str_mem(), tc.get_strlen_mem(), p);
		return;
	case tc_heavy_atomic_estr:
	case tc_heavy_atomic_pstr_short:
		estr_feed(fn, p, tc.get_str_vmm(), tc.get_strlen_vmm());
		return;
	case tc_heavy_atomic_pstr_long:
		pstr_long_feed2(tc.get_str_vmm(), fn, p);
		return;
	}
}

void print_tuple_cell_dummy(se_ostream& crmout,const tuple_cell& tc)
{
	    feed_tuple_cell(writextext_cb, &crmout, tc);
}

CollationHandler *CollationManager::get_collation_handler(const char *uri)
{
    if (strcmp(uri, "http://www.w3.org/2005/xpath-functions/collation/codepoint") == 0)
        return utf8_charset_handler.get_unicode_codepoint_collation();
    else
        return NULL;
}

CollationHandler *CollationManager::get_default_collation_handler()
{
    return utf8_charset_handler.get_unicode_codepoint_collation();
}

<|endoftext|>


<commit_before>#pragma once

#include "config.hpp"

#if not WITH_XKB
#error "X xkb extension is disabled..."
#endif

#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wkeyword-macro"
#endif
#define explicit mask_cxx_explicit_keyword
#include <xcb/xkb.h>
#include <xpp/proto/xkb.hpp>
#undef explicit
#if defined(__clang__)
#pragma clang diagnostic pop
#endif

#include "common.hpp"

POLYBAR_NS

// fwd
class connection;

namespace evt {
  using xkb_new_keyboard_notify = xpp::xkb::event::new_keyboard_notify<connection&>;
  using xkb_map_notify = xpp::xkb::event::map_notify<connection&>;
  using xkb_state_notify = xpp::xkb::event::state_notify<connection&>;
  using xkb_controls_notify = xpp::xkb::event::controls_notify<connection&>;
  using xkb_indicator_state_notify = xpp::xkb::event::indicator_state_notify<connection&>;
  using xkb_indicator_map_notify = xpp::xkb::event::indicator_map_notify<connection&>;
  using xkb_names_notify = xpp::xkb::event::names_notify<connection&>;
  using xkb_compat_map_notify = xpp::xkb::event::compat_map_notify<connection&>;
  using xkb_bell_notify = xpp::xkb::event::bell_notify<connection&>;
  using xkb_action_message = xpp::xkb::event::action_message<connection&>;
  using xkb_access_x_notify = xpp::xkb::event::access_x_notify<connection&>;
  using xkb_extension_device_notify = xpp::xkb::event::extension_device_notify<connection&>;
}

class keyboard {
 public:
  struct indicator {
    enum class type { NONE = 0U, CAPS_LOCK, NUM_LOCK };
    xcb_atom_t atom{};
    uint8_t mask{0};
    string name;
    bool enabled{false};
  };

  struct layout {
    string group_name;
    vector<string> symbols;
  };

  explicit keyboard(vector<layout>&& layouts_, map<indicator::type, indicator>&& indicators_)
      : layouts(forward<decltype(layouts)>(layouts_)), indicators(forward<decltype(indicators)>(indicators_)) {}

  const indicator& get(const indicator::type& i) const;
  void set(uint32_t indicator_state);
  bool on(const indicator::type&) const;

  const string group_name(size_t index = 0) const;
  const string layout_name(size_t index = 0) const;
  const string indicator_name(const indicator::type&) const;

 private:
  vector<layout> layouts;
  map<indicator::type, indicator> indicators;
};

namespace xkb_util {
  static constexpr const char* LAYOUT_SYMBOL_BLACKLIST{";group;inet;pc;"};

  string parse_layout_symbol(string&& name);
  vector<keyboard::layout> get_layouts(connection& conn, xcb_xkb_device_spec_t device);
  map<keyboard::indicator::type, keyboard::indicator> get_indicators(connection& conn, xcb_xkb_device_spec_t device);
}

POLYBAR_NS_END
<commit_msg>fix(cmake): Add legacy pragma<commit_after>#pragma once

#include "config.hpp"

#if not WITH_XKB
#error "X xkb extension is disabled..."
#endif

#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunknown-pragmas"
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#pragma clang diagnostic ignored "-Wkeyword-macro"
#endif
#define explicit mask_cxx_explicit_keyword
#include <xcb/xkb.h>
#include <xpp/proto/xkb.hpp>
#undef explicit
#if defined(__clang__)
#pragma clang diagnostic pop
#endif

#include "common.hpp"

POLYBAR_NS

// fwd
class connection;

namespace evt {
  using xkb_new_keyboard_notify = xpp::xkb::event::new_keyboard_notify<connection&>;
  using xkb_map_notify = xpp::xkb::event::map_notify<connection&>;
  using xkb_state_notify = xpp::xkb::event::state_notify<connection&>;
  using xkb_controls_notify = xpp::xkb::event::controls_notify<connection&>;
  using xkb_indicator_state_notify = xpp::xkb::event::indicator_state_notify<connection&>;
  using xkb_indicator_map_notify = xpp::xkb::event::indicator_map_notify<connection&>;
  using xkb_names_notify = xpp::xkb::event::names_notify<connection&>;
  using xkb_compat_map_notify = xpp::xkb::event::compat_map_notify<connection&>;
  using xkb_bell_notify = xpp::xkb::event::bell_notify<connection&>;
  using xkb_action_message = xpp::xkb::event::action_message<connection&>;
  using xkb_access_x_notify = xpp::xkb::event::access_x_notify<connection&>;
  using xkb_extension_device_notify = xpp::xkb::event::extension_device_notify<connection&>;
}

class keyboard {
 public:
  struct indicator {
    enum class type { NONE = 0U, CAPS_LOCK, NUM_LOCK };
    xcb_atom_t atom{};
    uint8_t mask{0};
    string name;
    bool enabled{false};
  };

  struct layout {
    string group_name;
    vector<string> symbols;
  };

  explicit keyboard(vector<layout>&& layouts_, map<indicator::type, indicator>&& indicators_)
      : layouts(forward<decltype(layouts)>(layouts_)), indicators(forward<decltype(indicators)>(indicators_)) {}

  const indicator& get(const indicator::type& i) const;
  void set(uint32_t indicator_state);
  bool on(const indicator::type&) const;

  const string group_name(size_t index = 0) const;
  const string layout_name(size_t index = 0) const;
  const string indicator_name(const indicator::type&) const;

 private:
  vector<layout> layouts;
  map<indicator::type, indicator> indicators;
};

namespace xkb_util {
  static constexpr const char* LAYOUT_SYMBOL_BLACKLIST{";group;inet;pc;"};

  string parse_layout_symbol(string&& name);
  vector<keyboard::layout> get_layouts(connection& conn, xcb_xkb_device_spec_t device);
  map<keyboard::indicator::type, keyboard::indicator> get_indicators(connection& conn, xcb_xkb_device_spec_t device);
}

POLYBAR_NS_END
<|endoftext|>


<commit_before>/* pilotAddress.cc			KPilot
**
** Copyright (C) 1998-2001 by Dan Pilone
**
** This is a C++ wrapper for the pilot's address database structures.
*/

/*
** This program 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.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
** MA 02139, USA.
*/

/*
** Bug reports and questions can be sent to adridg@cs.kun.nl
*/

static const char *pilotadress_id="$Id$";

#include "options.h"

#include <stdlib.h>
#include <assert.h>

#ifndef _KPILOT_PILOTADDRESS_H
#include "pilotAddress.h"
#endif

const int PilotAddress::APP_BUFFER_SIZE = 0xffff;

PilotAddress::PilotAddress(struct AddressAppInfo &appInfo,
			   PilotRecord* rec)
      : PilotAppCategory(rec), fAppInfo(appInfo), fAddressInfo()
    {
    unpack_Address(&fAddressInfo, (unsigned char*)rec->getData(), rec->getLen());
    (void)pilotadress_id;
    }

PilotAddress::PilotAddress(struct AddressAppInfo &appInfo) :
      PilotAppCategory(), fAppInfo(appInfo)
    {
    reset();
    }

PilotAddress::PilotAddress(const PilotAddress &copyFrom) :
      PilotAppCategory(copyFrom), fAppInfo(copyFrom.fAppInfo),
      fAddressInfo()
    {
    _copyAddressInfo(copyFrom.fAddressInfo);
    }

PilotAddress& PilotAddress::operator=( const PilotAddress &copyFrom )
    {
    PilotAppCategory::operator=(copyFrom);
    _copyAddressInfo(copyFrom.fAddressInfo);
    return *this;
    }

void PilotAddress::_copyAddressInfo(const struct Address &copyFrom)
    {
    fAddressInfo.showPhone = copyFrom.showPhone;
    for (int labelLp=0;labelLp < 5;labelLp++)
	fAddressInfo.phoneLabel[labelLp] =
	    copyFrom.phoneLabel[labelLp];
    for (int entryLp=0;entryLp < 19;entryLp++)
	{
	if (copyFrom.entry[entryLp])
	    fAddressInfo.entry[entryLp] =
		qstrdup(copyFrom.entry[entryLp]);
	else
	    fAddressInfo.entry[entryLp] = 0L;
	}
    return *this;
    }

PilotAddress::~PilotAddress()
    {
    free_Address(&fAddressInfo);
    }

QString PilotAddress::_typeToStr(EPhoneType type) const
    {
    QString s;
    switch(type)
	{
	case eWork : s = "Work"; break;
	case eHome : s = "Home"; break;
	case eFax : s = "Fax"; break;
	case eOther : s = "Other"; break;
	case ePager : s = "Pager"; break;
	case eMobile : s = "Mobile"; break;
	case eEmail : s = "E-mail"; break;
	case eMain :
	default : s = "Main"; break;
	}
    return s;
    }

bool PilotAddress::setCategory(const char *label)
    {
    for (int catId;catId < 16;catId++)
	{
	QString aCat = fAppInfo.category.name[catId];
	if (label == aCat)
	    {
	    setCat(catId);
	    return true;
	    }
	else
	    // if empty, then no more labels; add it
	    if (aCat.isEmpty())
		{
		qstrncpy(fAppInfo.category.name[catId], label, 16);
		setCat(catId);
		return true;
		}
	}
    // if got here, the category slots were full
    return false;
    }

int PilotAddress::_getNextEmptyPhoneSlot() const
    {
    for (int phoneSlot = entryPhone1;phoneSlot <= entryPhone5;phoneSlot++)
	{
	QString phoneField = getField(phoneSlot);
	if (phoneField.isEmpty())
	    return phoneSlot;
	}
    return entryCustom4;
    }

void PilotAddress::setPhoneField(EPhoneType type, const char *field,
				 bool overflowCustom)
    {
    // first look to see if the type is already assigned to a fieldSlot
    QString fieldStr(field);
    QString typeStr(_typeToStr(type));
    int appPhoneLabelNum = _getAppPhoneLabelNum(typeStr);
    int fieldSlot = _findPhoneFieldSlot(appPhoneLabelNum);
    if (fieldSlot == -1)
	fieldSlot = _getNextEmptyPhoneSlot();

    // store the overflow phone
    if (fieldSlot == entryCustom4)
	{
	if (!fieldStr.isEmpty() && overflowCustom)
	    {
	    QString custom4Field = getField(entryCustom4);
	    custom4Field += typeStr + " " + fieldStr;
	    setField(entryCustom4, custom4Field.latin1());
	    }
	}
    else // phone field 1 - 5; straight forward storage
	{
	setField(fieldSlot, field);
	int labelIndex = fieldSlot - entryPhone1;
	fAddressInfo.phoneLabel[labelIndex] = appPhoneLabelNum;
	}
    }

int PilotAddress::_findPhoneFieldSlot(int appTypeNum) const
    {
    for (int index=0;index < 5;index++)
	if (fAddressInfo.phoneLabel[index] == appTypeNum)
	    return index+entryPhone1;
    return -1;
    }

const char *PilotAddress::getPhoneField(EPhoneType type,
					bool checkCustom4) const
    {
    // given the type, need to find which slot is associated with it
    QString typeToStr(_typeToStr(type));
    int appTypeNum = _getAppPhoneLabelNum(typeToStr);
    int fieldSlot = _findPhoneFieldSlot(appTypeNum);
    if (fieldSlot != -1)
	return getField(fieldSlot);

    // look through custom 4 for the field
    if (!checkCustom4)
	return 0L;

    // look for the phone type str
    QString customField(getField(entryCustom4));
    int foundField = customField.find(typeToStr);
    if (foundField == -1)
	return 0L;

    // parse out the next token
    int startPos = foundField+typeToStr.length()+1;
    int endPos = customField.find(' ', startPos);
    if (endPos == -1)
	endPos = customField.length();
    QString field = customField.mid(startPos, endPos);
    field = field.simplifyWhiteSpace();

    // return the token
    return field.latin1();
    }

int PilotAddress::_getAppPhoneLabelNum(const QString &phoneType) const
    {
    for (int index=0;index < 8;index++)
	if (phoneType == fAppInfo.phoneLabels[index])
	    return index;
    qDebug("PilotAddress::getAppPhoneLabelNum can't find index for phoneType = %s", phoneType.latin1());
    assert(0);
    return -1;
    }

void
PilotAddress::setField(int field, const char* text)
    {
    // This will have either been created with unpack_Address, and/or will
    // be released with free_Address, so use malloc/free here:
    if(fAddressInfo.entry[field])
	{
	free(fAddressInfo.entry[field]);
	}
    if (text)
      {
	fAddressInfo.entry[field] = (char*)malloc(strlen(text) + 1);
	strcpy(fAddressInfo.entry[field], text);
      }
    else
      fAddressInfo.entry[field] = 0L;
    }

void*
PilotAddress::pack(void *buf, int *len)
    {
    int i;
    i = pack_Address(&fAddressInfo, (unsigned char*)buf, *len);
    *len = i;
    return buf;
    }

// $Log$
// Revision 1.13  2001/04/02 21:56:22  stern
// Fixed bugs in getPhoneField and setPhoneField methods
//
// Revision 1.12  2001/03/29 21:40:55  stern
// Added APP_BUFFER_SIZE to pilotAddress
//
// Revision 1.11  2001/03/19 23:12:39  stern
// Made changes necessary for upcoming abbrowser conduit.
//
// Mainly, I added two public methods to PilotAddress that allow for easier
// setting and getting of phone fields.
//
// I also have added some documentation throughout as I have tried to figure
// out how everything works.
//
// Revision 1.10  2001/03/09 09:46:15  adridg
// Large-scale #include cleanup
//
// Revision 1.9  2001/02/08 08:13:44  habenich
// exchanged the common identifier "id" with source unique <sourcename>_id for --enable-final build
//
// Revision 1.8  2001/02/05 20:58:48  adridg
// Fixed copyright headers for source releases. No code changed
//
<commit_msg>A void function must not return anything. Also there was an uninitialize variable being used.<commit_after>/* pilotAddress.cc			KPilot
**
** Copyright (C) 1998-2001 by Dan Pilone
**
** This is a C++ wrapper for the pilot's address database structures.
*/

/*
** This program 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.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
** MA 02139, USA.
*/

/*
** Bug reports and questions can be sent to adridg@cs.kun.nl
*/

static const char *pilotadress_id="$Id$";

#include "options.h"

#include <stdlib.h>
#include <assert.h>

#ifndef _KPILOT_PILOTADDRESS_H
#include "pilotAddress.h"
#endif

const int PilotAddress::APP_BUFFER_SIZE = 0xffff;

PilotAddress::PilotAddress(struct AddressAppInfo &appInfo,
			   PilotRecord* rec)
      : PilotAppCategory(rec), fAppInfo(appInfo), fAddressInfo()
    {
    unpack_Address(&fAddressInfo, (unsigned char*)rec->getData(), rec->getLen());
    (void)pilotadress_id;
    }

PilotAddress::PilotAddress(struct AddressAppInfo &appInfo) :
      PilotAppCategory(), fAppInfo(appInfo)
    {
    reset();
    }

PilotAddress::PilotAddress(const PilotAddress &copyFrom) :
      PilotAppCategory(copyFrom), fAppInfo(copyFrom.fAppInfo),
      fAddressInfo()
    {
    _copyAddressInfo(copyFrom.fAddressInfo);
    }

PilotAddress& PilotAddress::operator=( const PilotAddress &copyFrom )
    {
    PilotAppCategory::operator=(copyFrom);
    _copyAddressInfo(copyFrom.fAddressInfo);
    return *this;
    }

void PilotAddress::_copyAddressInfo(const struct Address &copyFrom)
    {
    fAddressInfo.showPhone = copyFrom.showPhone;
    for (int labelLp=0;labelLp < 5;labelLp++)
	fAddressInfo.phoneLabel[labelLp] =
	    copyFrom.phoneLabel[labelLp];
    for (int entryLp=0;entryLp < 19;entryLp++)
	{
	if (copyFrom.entry[entryLp])
	    fAddressInfo.entry[entryLp] =
		qstrdup(copyFrom.entry[entryLp]);
	else
	    fAddressInfo.entry[entryLp] = 0L;
	}
    return;
    }

PilotAddress::~PilotAddress()
    {
    free_Address(&fAddressInfo);
    }

QString PilotAddress::_typeToStr(EPhoneType type) const
    {
    QString s;
    switch(type)
	{
	case eWork : s = "Work"; break;
	case eHome : s = "Home"; break;
	case eFax : s = "Fax"; break;
	case eOther : s = "Other"; break;
	case ePager : s = "Pager"; break;
	case eMobile : s = "Mobile"; break;
	case eEmail : s = "E-mail"; break;
	case eMain :
	default : s = "Main"; break;
	}
    return s;
    }

bool PilotAddress::setCategory(const char *label)
    {
    for (int catId=0;catId < 16;catId++)
	{
	QString aCat = fAppInfo.category.name[catId];
	if (label == aCat)
	    {
	    setCat(catId);
	    return true;
	    }
	else
	    // if empty, then no more labels; add it
	    if (aCat.isEmpty())
		{
		qstrncpy(fAppInfo.category.name[catId], label, 16);
		setCat(catId);
		return true;
		}
	}
    // if got here, the category slots were full
    return false;
    }

int PilotAddress::_getNextEmptyPhoneSlot() const
    {
    for (int phoneSlot = entryPhone1;phoneSlot <= entryPhone5;phoneSlot++)
	{
	QString phoneField = getField(phoneSlot);
	if (phoneField.isEmpty())
	    return phoneSlot;
	}
    return entryCustom4;
    }

void PilotAddress::setPhoneField(EPhoneType type, const char *field,
				 bool overflowCustom)
    {
    // first look to see if the type is already assigned to a fieldSlot
    QString fieldStr(field);
    QString typeStr(_typeToStr(type));
    int appPhoneLabelNum = _getAppPhoneLabelNum(typeStr);
    int fieldSlot = _findPhoneFieldSlot(appPhoneLabelNum);
    if (fieldSlot == -1)
	fieldSlot = _getNextEmptyPhoneSlot();

    // store the overflow phone
    if (fieldSlot == entryCustom4)
	{
	if (!fieldStr.isEmpty() && overflowCustom)
	    {
	    QString custom4Field = getField(entryCustom4);
	    custom4Field += typeStr + " " + fieldStr;
	    setField(entryCustom4, custom4Field.latin1());
	    }
	}
    else // phone field 1 - 5; straight forward storage
	{
	setField(fieldSlot, field);
	int labelIndex = fieldSlot - entryPhone1;
	fAddressInfo.phoneLabel[labelIndex] = appPhoneLabelNum;
	}
    }

int PilotAddress::_findPhoneFieldSlot(int appTypeNum) const
    {
    for (int index=0;index < 5;index++)
	if (fAddressInfo.phoneLabel[index] == appTypeNum)
	    return index+entryPhone1;
    return -1;
    }

const char *PilotAddress::getPhoneField(EPhoneType type,
					bool checkCustom4) const
    {
    // given the type, need to find which slot is associated with it
    QString typeToStr(_typeToStr(type));
    int appTypeNum = _getAppPhoneLabelNum(typeToStr);
    int fieldSlot = _findPhoneFieldSlot(appTypeNum);
    if (fieldSlot != -1)
	return getField(fieldSlot);

    // look through custom 4 for the field
    if (!checkCustom4)
	return 0L;

    // look for the phone type str
    QString customField(getField(entryCustom4));
    int foundField = customField.find(typeToStr);
    if (foundField == -1)
	return 0L;

    // parse out the next token
    int startPos = foundField+typeToStr.length()+1;
    int endPos = customField.find(' ', startPos);
    if (endPos == -1)
	endPos = customField.length();
    QString field = customField.mid(startPos, endPos);
    field = field.simplifyWhiteSpace();

    // return the token
    return field.latin1();
    }

int PilotAddress::_getAppPhoneLabelNum(const QString &phoneType) const
    {
    for (int index=0;index < 8;index++)
	if (phoneType == fAppInfo.phoneLabels[index])
	    return index;
    qDebug("PilotAddress::getAppPhoneLabelNum can't find index for phoneType = %s", phoneType.latin1());
    assert(0);
    return -1;
    }

void
PilotAddress::setField(int field, const char* text)
    {
    // This will have either been created with unpack_Address, and/or will
    // be released with free_Address, so use malloc/free here:
    if(fAddressInfo.entry[field])
	{
	free(fAddressInfo.entry[field]);
	}
    if (text)
      {
	fAddressInfo.entry[field] = (char*)malloc(strlen(text) + 1);
	strcpy(fAddressInfo.entry[field], text);
      }
    else
      fAddressInfo.entry[field] = 0L;
    }

void*
PilotAddress::pack(void *buf, int *len)
    {
    int i;
    i = pack_Address(&fAddressInfo, (unsigned char*)buf, *len);
    *len = i;
    return buf;
    }

// $Log$
// Revision 1.14  2001/04/04 21:20:32  stern
// Added support for category information and copy constructors
//
// Revision 1.13  2001/04/02 21:56:22  stern
// Fixed bugs in getPhoneField and setPhoneField methods
//
// Revision 1.12  2001/03/29 21:40:55  stern
// Added APP_BUFFER_SIZE to pilotAddress
//
// Revision 1.11  2001/03/19 23:12:39  stern
// Made changes necessary for upcoming abbrowser conduit.
//
// Mainly, I added two public methods to PilotAddress that allow for easier
// setting and getting of phone fields.
//
// I also have added some documentation throughout as I have tried to figure
// out how everything works.
//
// Revision 1.10  2001/03/09 09:46:15  adridg
// Large-scale #include cleanup
//
// Revision 1.9  2001/02/08 08:13:44  habenich
// exchanged the common identifier "id" with source unique <sourcename>_id for --enable-final build
//
// Revision 1.8  2001/02/05 20:58:48  adridg
// Fixed copyright headers for source releases. No code changed
//
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/kernel/terminate.C $                                      */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2012,2018                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

#include <kernel/hbdescriptor.H>
#include <kernel/hbterminatetypes.H>
#include <kernel/terminate.H>
#ifndef BOOTLOADER
#include <stdint.h>
#include <kernel/console.H>
#include <kernel/ipc.H>

#include <builtins.h>
#include <kernel/kernel_reasoncodes.H>
#endif // BOOTLOADER

extern "C" void p8_force_attn() NO_RETURN;

#ifndef BOOTLOADER
/* Instance of the TI Data Area */
HB_TI_DataArea kernel_TIDataArea;

/* Instance of the HB descriptor struct */
HB_Descriptor kernel_hbDescriptor =
{
    &kernel_TIDataArea,
    &KernelIpc::ipc_data_area,
    0
};
#endif // BOOTLOADER

void terminateExecuteTI()
{
    // Call the function that actually executes the TI code.
    p8_force_attn();
}

#ifndef BOOTLOADER
void termWritePlid(uint16_t i_source, uint32_t plid)
{
    kernel_TIDataArea.type = TI_WITH_PLID;
    kernel_TIDataArea.source = i_source;
    kernel_TIDataArea.plid = plid;
}
#endif // BOOTLOADER

void termWriteSRC(uint16_t i_source, uint16_t i_reasoncode,uint64_t i_failAddr,
                  uint32_t i_error_data)
{
    // Update the TI structure with the type of TI, who called,
    // and extra error data (if applicable, otherwise 0)
    kernel_TIDataArea.type = TI_WITH_SRC;
    kernel_TIDataArea.source = i_source;
    kernel_TIDataArea.error_data = i_error_data;

    // Update TID data area with the SRC info we have avail
    kernel_TIDataArea.src.ID = 0xBC;
    kernel_TIDataArea.src.subsystem = 0x8A;
    kernel_TIDataArea.src.reasoncode = i_reasoncode;
    kernel_TIDataArea.src.moduleID = 0;
    kernel_TIDataArea.src.iType = TI_WITH_SRC;
    kernel_TIDataArea.src.iSource = i_source;

    // Update User Data with address of fail location
    kernel_TIDataArea.src.word6 = i_failAddr;
}

void termModifySRC(uint8_t i_moduleID, uint32_t i_word7, uint32_t i_word8)
{
    // Update module ID
    kernel_TIDataArea.src.moduleID = i_moduleID;

    // Update User Data with anything supplied for word7 or word8
    kernel_TIDataArea.src.word7 = i_word7;
    kernel_TIDataArea.src.word8 = i_word8;
}

#ifndef BOOTLOADER
void termSetHbDump(void)
{
    // Set indicator flag for doing HB dump
    kernel_TIDataArea.hbDumpFlag = 1;

    return;
}
#endif // BOOTLOADER
<commit_msg>Set HB Dump Flag in TI Data on any TI with SRC<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/kernel/terminate.C $                                      */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2012,2018                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

#include <kernel/hbdescriptor.H>
#include <kernel/hbterminatetypes.H>
#include <kernel/terminate.H>
#ifndef BOOTLOADER
#include <stdint.h>
#include <kernel/console.H>
#include <kernel/ipc.H>

#include <builtins.h>
#include <kernel/kernel_reasoncodes.H>
#endif // BOOTLOADER

extern "C" void p8_force_attn() NO_RETURN;

#ifndef BOOTLOADER
/* Instance of the TI Data Area */
HB_TI_DataArea kernel_TIDataArea;

/* Instance of the HB descriptor struct */
HB_Descriptor kernel_hbDescriptor =
{
    &kernel_TIDataArea,
    &KernelIpc::ipc_data_area,
    0
};
#endif // BOOTLOADER

void terminateExecuteTI()
{
    // Call the function that actually executes the TI code.
    p8_force_attn();
}

#ifndef BOOTLOADER
void termWritePlid(uint16_t i_source, uint32_t plid)
{
    kernel_TIDataArea.type = TI_WITH_PLID;
    kernel_TIDataArea.source = i_source;
    kernel_TIDataArea.plid = plid;
}
#endif // BOOTLOADER

void termWriteSRC(uint16_t i_source, uint16_t i_reasoncode,uint64_t i_failAddr,
                  uint32_t i_error_data)
{
    // Update the TI structure with the type of TI, who called,
    // and indicator flag for doing HB dump
    // and extra error data (if applicable, otherwise 0)
    kernel_TIDataArea.type = TI_WITH_SRC;
    kernel_TIDataArea.source = i_source;
    kernel_TIDataArea.hbDumpFlag = 1;
    kernel_TIDataArea.error_data = i_error_data;

    // Update TID data area with the SRC info we have avail
    kernel_TIDataArea.src.ID = 0xBC;
    kernel_TIDataArea.src.subsystem = 0x8A;
    kernel_TIDataArea.src.reasoncode = i_reasoncode;
    kernel_TIDataArea.src.moduleID = 0;
    kernel_TIDataArea.src.iType = TI_WITH_SRC;
    kernel_TIDataArea.src.iSource = i_source;

    // Update User Data with address of fail location
    kernel_TIDataArea.src.word6 = i_failAddr;
}

void termModifySRC(uint8_t i_moduleID, uint32_t i_word7, uint32_t i_word8)
{
    // Update module ID
    kernel_TIDataArea.src.moduleID = i_moduleID;

    // Update User Data with anything supplied for word7 or word8
    kernel_TIDataArea.src.word7 = i_word7;
    kernel_TIDataArea.src.word8 = i_word8;
}

#ifndef BOOTLOADER
void termSetHbDump(void)
{
    // Set indicator flag for doing HB dump
    kernel_TIDataArea.hbDumpFlag = 1;

    return;
}
#endif // BOOTLOADER
<|endoftext|>


<commit_before>/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You 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.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee++ Internals -- Catch
 *
 * @sa catch.hpp
 *
 * @author Christopher Alfeld <calfeld@qualys.com>
 */

#include <ironbee/types.h>  // ib_status_t, ib_status_to_string()
#include <ironbee/engine.h> // ib_log_*
#include <ironbee/util.h> // ib_util_log_*

#include <ironbeepp/catch.hpp>

#include <ironbeepp/engine.hpp>
#include <ironbeepp/exception.hpp>

using namespace std;

namespace IronBee {

ib_status_t convert_exception(
    ib_engine_t* engine,
    bool         logging
)
{
    ib_status_t status = IB_OK;
    try {
        throw;
    }
    catch (declined)         { status = IB_DECLINED;  }
    catch (eunknown)         { status = IB_EUNKNOWN;  }
    catch (enotimpl)         { status = IB_ENOTIMPL;  }
    catch (eincompat)        { status = IB_EINCOMPAT; }
    catch (ealloc)           { status = IB_EALLOC;    }
    catch (einval)           { status = IB_EINVAL;    }
    catch (enoent)           { status = IB_ENOENT;    }
    catch (etrunc)           { status = IB_ETRUNC;    }
    catch (etimedout)        { status = IB_ETIMEDOUT; }
    catch (eagain)           { status = IB_EAGAIN;    }
    catch (eother)           { status = IB_EOTHER;    }
    catch (ebadval)          { status = IB_EBADVAL;   }
    catch (eexist)           { status = IB_EEXIST;    }
    catch (invalid_argument) { status = IB_EINVAL;    }
    catch (bad_alloc)        { status = IB_EALLOC;    }
    catch (...)              { status = IB_EUNKNOWN;  }

    if (logging) {
        try {
            throw;
        }
        catch (const error& e) {
            string message;
            int level = 1;

            message = string(ib_status_to_string(status)) + ":";
            if (boost::get_error_info<errinfo_what>(e)) {
                message += *boost::get_error_info<errinfo_what>(e);
            }
            else {
                message +=
                    "IronBee++ Exception but no explanation provided.  "
                    "Please report as bug.";
            }

            if (boost::get_error_info<errinfo_level>(e)) {
                level = *boost::get_error_info<errinfo_level>(e);
            }

            if (engine) {
                ib_log_level_t ib_level = static_cast<ib_log_level_t>(level);
                ib_log(engine, ib_level, "%s", message.c_str());
                ib_log_debug(engine, "%s", diagnostic_information(e).c_str() );
            } else {
                ib_util_log_error("%s", message.c_str());
                ib_util_log_debug("%s", diagnostic_information(e).c_str());
            }
        }
        catch (const exception& e) {
            string message;
            if (status == IB_EINVAL) {
                message = "Invalid argument: ";
            }
            else {
                message = "Unknown exception thrown: ";
            }
            message += e.what();

            if (engine) {
                ib_log_error(engine,  "%s", message.c_str());
            } else {
                ib_util_log_error("%s", message.c_str());
            }
        }
        catch (const boost::exception& e) {
            string message;
            int level = 1;

            message = "Unknown boost::exception thrown: ";
            if (boost::get_error_info<boost::throw_function>(e)) {
                message += *boost::get_error_info<boost::throw_function>(e);
            }
            else {
                message += "No information provided.  Please report as bug.";
            }

            if (boost::get_error_info<errinfo_level>(e)) {
                level = *boost::get_error_info<errinfo_level>(e);
            }

            if (engine) {
                ib_log_level_t ib_level = static_cast<ib_log_level_t>(level);
                ib_log(engine, ib_level, "%s", message.c_str());
                ib_log_debug(engine, "%s",
                    diagnostic_information(e).c_str()
                );
            } else {
                ib_util_log_error("%s", message.c_str());
                ib_util_log_debug("%s", diagnostic_information(e).c_str());
            }
        }
        catch(...) {
            if (engine) {
                ib_log_error(engine,  "%s",
                    "Completely unknown exception thrown.  "
                    "Please report as bug."
                );
            } else {
                ib_util_log_error("%s",
                    "Completely unknown exception thrown.  "
                    "Please report as bug."
                );
            }
        }
    }

    return status;
}

ib_status_t convert_exception(
    Engine engine,
    bool   logging
)
{
    return convert_exception(engine.ib(), logging);
}

} // IronBee
<commit_msg>IronBee++/catch: Fix bug where boost exception were transalted as std exceptions.<commit_after>/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You 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.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee++ Internals -- Catch
 *
 * @sa catch.hpp
 *
 * @author Christopher Alfeld <calfeld@qualys.com>
 */

#include <ironbee/types.h>  // ib_status_t, ib_status_to_string()
#include <ironbee/engine.h> // ib_log_*
#include <ironbee/util.h> // ib_util_log_*

#include <ironbeepp/catch.hpp>

#include <ironbeepp/engine.hpp>
#include <ironbeepp/exception.hpp>

using namespace std;

namespace IronBee {

ib_status_t convert_exception(
    ib_engine_t* engine,
    bool         logging
)
{
    ib_status_t status = IB_OK;
    try {
        throw;
    }
    catch (declined)         { status = IB_DECLINED;  }
    catch (eunknown)         { status = IB_EUNKNOWN;  }
    catch (enotimpl)         { status = IB_ENOTIMPL;  }
    catch (eincompat)        { status = IB_EINCOMPAT; }
    catch (ealloc)           { status = IB_EALLOC;    }
    catch (einval)           { status = IB_EINVAL;    }
    catch (enoent)           { status = IB_ENOENT;    }
    catch (etrunc)           { status = IB_ETRUNC;    }
    catch (etimedout)        { status = IB_ETIMEDOUT; }
    catch (eagain)           { status = IB_EAGAIN;    }
    catch (eother)           { status = IB_EOTHER;    }
    catch (ebadval)          { status = IB_EBADVAL;   }
    catch (eexist)           { status = IB_EEXIST;    }
    catch (invalid_argument) { status = IB_EINVAL;    }
    catch (bad_alloc)        { status = IB_EALLOC;    }
    catch (...)              { status = IB_EUNKNOWN;  }

    if (logging) {
        try {
            throw;
        }
        catch (const error& e) {
            string message;
            int level = 1;

            message = string(ib_status_to_string(status)) + ":";
            if (boost::get_error_info<errinfo_what>(e)) {
                message += *boost::get_error_info<errinfo_what>(e);
            }
            else {
                message +=
                    "IronBee++ Exception but no explanation provided.  "
                    "Please report as bug.";
            }

            if (boost::get_error_info<errinfo_level>(e)) {
                level = *boost::get_error_info<errinfo_level>(e);
            }

            if (engine) {
                ib_log_level_t ib_level = static_cast<ib_log_level_t>(level);
                ib_log(engine, ib_level, "%s", message.c_str());
                ib_log_debug(engine, "%s", diagnostic_information(e).c_str() );
            } else {
                ib_util_log_error("%s", message.c_str());
                ib_util_log_debug("%s", diagnostic_information(e).c_str());
            }
        }
        catch (const boost::exception& e) {
            string message;
            int level = 1;

            message = "Unknown boost::exception thrown: ";
            if (boost::get_error_info<boost::throw_function>(e)) {
                message += *boost::get_error_info<boost::throw_function>(e);
            }
            else {
                message += "No information provided.  Please report as bug.";
            }

            if (boost::get_error_info<errinfo_level>(e)) {
                level = *boost::get_error_info<errinfo_level>(e);
            }

            if (engine) {
                ib_log_level_t ib_level = static_cast<ib_log_level_t>(level);
                ib_log(engine, ib_level, "%s", message.c_str());
                ib_log_debug(engine, "%s",
                    diagnostic_information(e).c_str()
                );
            } else {
                ib_util_log_error("%s", message.c_str());
                ib_util_log_debug("%s", diagnostic_information(e).c_str());
            }
        }
        catch (const exception& e) {
            string message;
            if (status == IB_EINVAL) {
                message = "Invalid argument: ";
            }
            else {
                message = "Unknown exception thrown: ";
            }
            message += e.what();

            if (engine) {
                ib_log_error(engine,  "%s", message.c_str());
            } else {
                ib_util_log_error("%s", message.c_str());
            }
        }
        catch(...) {
            if (engine) {
                ib_log_error(engine,  "%s",
                    "Completely unknown exception thrown.  "
                    "Please report as bug."
                );
            } else {
                ib_util_log_error("%s",
                    "Completely unknown exception thrown.  "
                    "Please report as bug."
                );
            }
        }
    }

    return status;
}

ib_status_t convert_exception(
    Engine engine,
    bool   logging
)
{
    return convert_exception(engine.ib(), logging);
}

} // IronBee
<|endoftext|>