<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.7  2003/12/17 00:18:37  cargilld
 * Update to memory management so that the static memory manager (one used to call Initialize) is only for static data.
 *
 * Revision 1.6  2003/05/18 14:02:06  knoaman
 * Memory manager implementation: pass per instance manager.
 *
 * Revision 1.5  2003/05/16 00:03:10  knoaman
 * Partial implementation of the configurable memory manager.
 *
 * Revision 1.4  2003/05/15 18:42:54  knoaman
 * Partial implementation of the configurable memory manager.
 *
 * Revision 1.3  2002/11/04 15:17:00  tng
 * C++ Namespace Support.
 *
 * Revision 1.2  2002/03/18 19:29:53  knoaman
 * Change constant names to eliminate possible conflict with user defined ones.
 *
 * Revision 1.1.1.1  2002/02/01 22:22:29  peiyongz
 * sane_include
 *
 * Revision 1.3  2001/06/07 20:55:36  tng
 * Fix no newline at the end warning.  By Pei Yong Zhang.
 *
 * Revision 1.2  2001/05/11 13:26:43  tng
 * Copyright update.
 *
 * Revision 1.1  2001/03/02 19:22:48  knoaman
 * Schema: Regular expression handling part I
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/regx/OpFactory.hpp>
#include <xercesc/util/regx/Op.hpp>
#include <xercesc/util/PlatformUtils.hpp>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  OpFactory: Constructors and Destructor
// ---------------------------------------------------------------------------
OpFactory::OpFactory(MemoryManager* const manager) :
    fOpVector(0)
    , fMemoryManager(manager)
{
    fOpVector = new (fMemoryManager) RefVectorOf<Op>(16, true, fMemoryManager);
}

OpFactory::~OpFactory() {

	delete fOpVector;
	fOpVector = 0;
}

// ---------------------------------------------------------------------------
//  OpFactory - Factory methods
// ---------------------------------------------------------------------------
Op* OpFactory::createDotOp() {

	Op* tmpOp = new (fMemoryManager) Op(Op::O_DOT, fMemoryManager);
	fOpVector->addElement(tmpOp);
	return tmpOp;
}

CharOp* OpFactory::createCharOp(int data) {

	CharOp* tmpOp = new (fMemoryManager) CharOp(Op::O_CHAR, data, fMemoryManager);

	fOpVector->addElement(tmpOp);
	return tmpOp;
}

CharOp* OpFactory::createAnchorOp(int data) {

	CharOp* tmpOp = new (fMemoryManager) CharOp(Op::O_ANCHOR, data, fMemoryManager);

	fOpVector->addElement(tmpOp);
	return tmpOp;
}

CharOp* OpFactory::createCaptureOp(int number, const Op* const next) {

	CharOp* tmpOp = new (fMemoryManager) CharOp(Op::O_CAPTURE, number, fMemoryManager);

	tmpOp->setNextOp(next);
	fOpVector->addElement(tmpOp);
	return tmpOp;
}

UnionOp* OpFactory::createUnionOp(int size) {

	UnionOp* tmpOp = new (fMemoryManager) UnionOp(Op::O_UNION, size, fMemoryManager);

	fOpVector->addElement(tmpOp);
	return tmpOp;
}

ChildOp* OpFactory::createClosureOp(int id) {

	ModifierOp* tmpOp = new (fMemoryManager) ModifierOp(Op::O_CLOSURE, id, -1, fMemoryManager);

	fOpVector->addElement(tmpOp);
	return tmpOp;
}

ChildOp* OpFactory::createNonGreedyClosureOp() {

	ChildOp* tmpOp = new (fMemoryManager) ChildOp(Op::O_NONGREEDYCLOSURE, fMemoryManager);

	fOpVector->addElement(tmpOp);
	return tmpOp;
}

ChildOp* OpFactory::createQuestionOp(bool nonGreedy) {

	ChildOp* tmpOp = new (fMemoryManager)  ChildOp(nonGreedy ? Op::O_NONGREEDYQUESTION :
											 Op::O_QUESTION, fMemoryManager);

	fOpVector->addElement(tmpOp);
	return tmpOp;
}

RangeOp* OpFactory::createRangeOp(const Token* const token) {

	RangeOp* tmpOp = new (fMemoryManager)  RangeOp(Op::O_RANGE, token, fMemoryManager);

	fOpVector->addElement(tmpOp);
	return tmpOp;
}

ChildOp* OpFactory::createLookOp(const short type, const Op* const next,
						         const Op* const branch) {

	ChildOp* tmpOp = new (fMemoryManager) ChildOp(type, fMemoryManager);

	tmpOp->setNextOp(next);
	tmpOp->setChild(branch);
	fOpVector->addElement(tmpOp);
	return tmpOp;
}

CharOp* OpFactory::createBackReferenceOp(int refNo) {

	CharOp* tmpOp = new (fMemoryManager) CharOp(Op::O_BACKREFERENCE, refNo, fMemoryManager);

	fOpVector->addElement(tmpOp);
	return tmpOp;
}

StringOp* OpFactory::createStringOp(const XMLCh* const literal) {

	StringOp* tmpOp = new (fMemoryManager) StringOp(Op::O_STRING, literal, fMemoryManager);

	fOpVector->addElement(tmpOp);
	return tmpOp;
}

ChildOp* OpFactory::createIndependentOp(const Op* const next,
							            const Op* const branch) {

	ChildOp* tmpOp = new (fMemoryManager) ChildOp(Op::O_INDEPENDENT, fMemoryManager);

	tmpOp->setNextOp(next);
	tmpOp->setChild(branch);
	fOpVector->addElement(tmpOp);
	return tmpOp;
}

ModifierOp* OpFactory::createModifierOp(const Op* const next,
                                        const Op* const branch,
                                        const int add, const int mask) {

	ModifierOp* tmpOp = new (fMemoryManager) ModifierOp(Op::O_MODIFIER, add, mask, fMemoryManager);

	tmpOp->setNextOp(next);
	tmpOp->setChild(branch);
	return tmpOp;
}

ConditionOp* OpFactory::createConditionOp(const Op* const next, const int ref,
								          const Op* const conditionFlow,
								          const Op* const yesFlow,
								          const Op* const noFlow) {

	ConditionOp* tmpOp = new (fMemoryManager) ConditionOp(Op::O_CONDITION, ref, conditionFlow,
										 yesFlow, noFlow, fMemoryManager);

	tmpOp->setNextOp(next);
	return tmpOp;
}

XERCES_CPP_NAMESPACE_END

/**
  * End of file OpFactory.cpp
  */
<commit_msg>Fixed warning with gcc 3.3<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.8  2004/02/16 10:11:28  amassari
 * Fixed warning with gcc 3.3
 *
 * Revision 1.7  2003/12/17 00:18:37  cargilld
 * Update to memory management so that the static memory manager (one used to call Initialize) is only for static data.
 *
 * Revision 1.6  2003/05/18 14:02:06  knoaman
 * Memory manager implementation: pass per instance manager.
 *
 * Revision 1.5  2003/05/16 00:03:10  knoaman
 * Partial implementation of the configurable memory manager.
 *
 * Revision 1.4  2003/05/15 18:42:54  knoaman
 * Partial implementation of the configurable memory manager.
 *
 * Revision 1.3  2002/11/04 15:17:00  tng
 * C++ Namespace Support.
 *
 * Revision 1.2  2002/03/18 19:29:53  knoaman
 * Change constant names to eliminate possible conflict with user defined ones.
 *
 * Revision 1.1.1.1  2002/02/01 22:22:29  peiyongz
 * sane_include
 *
 * Revision 1.3  2001/06/07 20:55:36  tng
 * Fix no newline at the end warning.  By Pei Yong Zhang.
 *
 * Revision 1.2  2001/05/11 13:26:43  tng
 * Copyright update.
 *
 * Revision 1.1  2001/03/02 19:22:48  knoaman
 * Schema: Regular expression handling part I
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/regx/Op.hpp>
#include <xercesc/util/regx/OpFactory.hpp>
#include <xercesc/util/PlatformUtils.hpp>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  OpFactory: Constructors and Destructor
// ---------------------------------------------------------------------------
OpFactory::OpFactory(MemoryManager* const manager) :
    fOpVector(0)
    , fMemoryManager(manager)
{
    fOpVector = new (fMemoryManager) RefVectorOf<Op>(16, true, fMemoryManager);
}

OpFactory::~OpFactory() {

	delete fOpVector;
	fOpVector = 0;
}

// ---------------------------------------------------------------------------
//  OpFactory - Factory methods
// ---------------------------------------------------------------------------
Op* OpFactory::createDotOp() {

	Op* tmpOp = new (fMemoryManager) Op(Op::O_DOT, fMemoryManager);
	fOpVector->addElement(tmpOp);
	return tmpOp;
}

CharOp* OpFactory::createCharOp(int data) {

	CharOp* tmpOp = new (fMemoryManager) CharOp(Op::O_CHAR, data, fMemoryManager);

	fOpVector->addElement(tmpOp);
	return tmpOp;
}

CharOp* OpFactory::createAnchorOp(int data) {

	CharOp* tmpOp = new (fMemoryManager) CharOp(Op::O_ANCHOR, data, fMemoryManager);

	fOpVector->addElement(tmpOp);
	return tmpOp;
}

CharOp* OpFactory::createCaptureOp(int number, const Op* const next) {

	CharOp* tmpOp = new (fMemoryManager) CharOp(Op::O_CAPTURE, number, fMemoryManager);

	tmpOp->setNextOp(next);
	fOpVector->addElement(tmpOp);
	return tmpOp;
}

UnionOp* OpFactory::createUnionOp(int size) {

	UnionOp* tmpOp = new (fMemoryManager) UnionOp(Op::O_UNION, size, fMemoryManager);

	fOpVector->addElement(tmpOp);
	return tmpOp;
}

ChildOp* OpFactory::createClosureOp(int id) {

	ModifierOp* tmpOp = new (fMemoryManager) ModifierOp(Op::O_CLOSURE, id, -1, fMemoryManager);

	fOpVector->addElement(tmpOp);
	return tmpOp;
}

ChildOp* OpFactory::createNonGreedyClosureOp() {

	ChildOp* tmpOp = new (fMemoryManager) ChildOp(Op::O_NONGREEDYCLOSURE, fMemoryManager);

	fOpVector->addElement(tmpOp);
	return tmpOp;
}

ChildOp* OpFactory::createQuestionOp(bool nonGreedy) {

	ChildOp* tmpOp = new (fMemoryManager)  ChildOp(nonGreedy ? Op::O_NONGREEDYQUESTION :
											 Op::O_QUESTION, fMemoryManager);

	fOpVector->addElement(tmpOp);
	return tmpOp;
}

RangeOp* OpFactory::createRangeOp(const Token* const token) {

	RangeOp* tmpOp = new (fMemoryManager)  RangeOp(Op::O_RANGE, token, fMemoryManager);

	fOpVector->addElement(tmpOp);
	return tmpOp;
}

ChildOp* OpFactory::createLookOp(const short type, const Op* const next,
						         const Op* const branch) {

	ChildOp* tmpOp = new (fMemoryManager) ChildOp(type, fMemoryManager);

	tmpOp->setNextOp(next);
	tmpOp->setChild(branch);
	fOpVector->addElement(tmpOp);
	return tmpOp;
}

CharOp* OpFactory::createBackReferenceOp(int refNo) {

	CharOp* tmpOp = new (fMemoryManager) CharOp(Op::O_BACKREFERENCE, refNo, fMemoryManager);

	fOpVector->addElement(tmpOp);
	return tmpOp;
}

StringOp* OpFactory::createStringOp(const XMLCh* const literal) {

	StringOp* tmpOp = new (fMemoryManager) StringOp(Op::O_STRING, literal, fMemoryManager);

	fOpVector->addElement(tmpOp);
	return tmpOp;
}

ChildOp* OpFactory::createIndependentOp(const Op* const next,
							            const Op* const branch) {

	ChildOp* tmpOp = new (fMemoryManager) ChildOp(Op::O_INDEPENDENT, fMemoryManager);

	tmpOp->setNextOp(next);
	tmpOp->setChild(branch);
	fOpVector->addElement(tmpOp);
	return tmpOp;
}

ModifierOp* OpFactory::createModifierOp(const Op* const next,
                                        const Op* const branch,
                                        const int add, const int mask) {

	ModifierOp* tmpOp = new (fMemoryManager) ModifierOp(Op::O_MODIFIER, add, mask, fMemoryManager);

	tmpOp->setNextOp(next);
	tmpOp->setChild(branch);
	return tmpOp;
}

ConditionOp* OpFactory::createConditionOp(const Op* const next, const int ref,
								          const Op* const conditionFlow,
								          const Op* const yesFlow,
								          const Op* const noFlow) {

	ConditionOp* tmpOp = new (fMemoryManager) ConditionOp(Op::O_CONDITION, ref, conditionFlow,
										 yesFlow, noFlow, fMemoryManager);

	tmpOp->setNextOp(next);
	return tmpOp;
}

XERCES_CPP_NAMESPACE_END

/**
  * End of file OpFactory.cpp
  */
<|endoftext|>


<commit_before>/*
 * THE NEW CHRONOTEXT TOOLKIT: https://github.com/arielm/new-chronotext-toolkit
 * COPYRIGHT (C) 2012-2014, ARIEL MALKA ALL RIGHTS RESERVED.
 *
 * THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE MODIFIED BSD LICENSE:
 * https://github.com/arielm/new-chronotext-toolkit/blob/master/LICENSE.md
 */

#include "chronotext/Log.h"

#if defined(CINDER_MSW)
#include "cinder/msw/OutputDebugStringStream.h"
#elif defined(CINDER_ANDROID)
#include "cinder/android/LogStream.h"
#elif defined(CINDER_MAC) && defined(FORCE_SYSLOG)
#include "chronotext/utils/SyslogStringStream.h"
#endif

using namespace std;
using namespace ci;

namespace chronotext
{
    namespace log
    {
        std::ostream& cout()
        {
#if defined(CINDER_MSW)
            static msw::dostream COUT;
            return COUT;
#elif defined(CINDER_ANDROID)
            static android::dostream COUT;
            return COUT;
#elif defined(CINDER_MAC) && defined(FORCE_SYSLOG)
            static mac::dostream COUT;
            return COUT;
#else
            return std::cout;
#endif
        }
    }

    Log& Log::instance()
    {
        static Log instance;
        return instance;
    }

    Log& Log::operator<<(Tag tag)
    {
        boost::mutex::scoped_lock lock(mtx);

        log::cout() << "[" << tag.value << "] ";
        return *this;
    }

    Log& Log::operator<<(ostream_manipulator manip)
    {
        boost::mutex::scoped_lock lock(mtx);

        log::cout() << endl;
        return *this;
    }
}
<commit_msg>ContextRework: MAKING IT CLEAR THAT THE NEW Log SUPPORTS ALL THE std::ostream “MANIPULATORS” (I.E. NOT ONLY std::endl)<commit_after>/*
 * THE NEW CHRONOTEXT TOOLKIT: https://github.com/arielm/new-chronotext-toolkit
 * COPYRIGHT (C) 2012-2014, ARIEL MALKA ALL RIGHTS RESERVED.
 *
 * THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE MODIFIED BSD LICENSE:
 * https://github.com/arielm/new-chronotext-toolkit/blob/master/LICENSE.md
 */

#include "chronotext/Log.h"

#if defined(CINDER_MSW)
#include "cinder/msw/OutputDebugStringStream.h"
#elif defined(CINDER_ANDROID)
#include "cinder/android/LogStream.h"
#elif defined(CINDER_MAC) && defined(FORCE_SYSLOG)
#include "chronotext/utils/SyslogStringStream.h"
#endif

using namespace std;
using namespace ci;

namespace chronotext
{
    namespace log
    {
        std::ostream& cout()
        {
#if defined(CINDER_MSW)
            static msw::dostream COUT;
            return COUT;
#elif defined(CINDER_ANDROID)
            static android::dostream COUT;
            return COUT;
#elif defined(CINDER_MAC) && defined(FORCE_SYSLOG)
            static mac::dostream COUT;
            return COUT;
#else
            return std::cout;
#endif
        }
    }

    Log& Log::instance()
    {
        static Log instance;
        return instance;
    }

    Log& Log::operator<<(Tag tag)
    {
        boost::mutex::scoped_lock lock(mtx);

        log::cout() << "[" << tag.value << "] ";
        return *this;
    }

    Log& Log::operator<<(ostream_manipulator manip)
    {
        boost::mutex::scoped_lock lock(mtx);

        log::cout() << manip;
        return *this;
    }
}
<|endoftext|>


<commit_before>#include "deviceinfowidget.h"
#include "../sysex/commands.h"
#include "ui_deviceinfowidget.h"

#include <QHeaderView>
#include <QListWidgetItem>
#include <QTableWidget>

DeviceInfoWidget::DeviceInfoWidget(MioMain *parent, Device *device,
                                   DeviceInfo *deviceInfo, QString windowTitle)
    : MultiInfoWidget(parent, device, windowTitle), deviceInfo(deviceInfo) {
  infoSections = std::vector<std::string>();
  if (device->getCommands()->isCommandSupported(SysExMessage::GET_INFO_LIST))
    infoSections.push_back("Global");
  if (device->getCommands()->isCommandSupported(
          SysExMessage::GET_ETHERNET_PORT_INFO))
    infoSections.push_back("Network");
}

DeviceInfoWidget::~DeviceInfoWidget() {}

QWidget *DeviceInfoWidget::createWidget(std::string infoName) {
  if (infoName == "Global") {
    QWidget *w = new QWidget(this->parentWidget());
    QGridLayout *lo = new QGridLayout();
    w->setLayout(lo);
    if (this->deviceInfo) {
      std::vector<InfoItem> *infoItems = this->deviceInfo->getDeviceInfos();
      QTableWidget *tw = new QTableWidget(infoItems->size(), 2, this);
      tw->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
      for (unsigned int i = 0; i < infoItems->size(); i++) {
        InfoItem infoItem = infoItems->at(i);
        tw->setItem(i, 0, new QTableWidgetItem(infoItem.name.c_str()));
        tw->setItem(i, 1, new QTableWidgetItem(infoItem.value.c_str()));
      }
      lo->addWidget(tw, 0, 0);
    }
    return w;
  } else {
    QWidget *w = new QWidget(this->parentWidget());
    QGridLayout *lo = new QGridLayout();
    w->setLayout(lo);
    QLabel *l = new QLabel(w);
    l->setText(QString::fromStdString(infoName));
    lo->addWidget(l, 0, 0);
    return w;
  }
}
<commit_msg>Set headers in deviceInfoTable, mark read only cells<commit_after>#include "deviceinfowidget.h"
#include "../sysex/commands.h"
#include "ui_deviceinfowidget.h"

#include <QHeaderView>
#include <QListWidgetItem>
#include <QTableWidget>

DeviceInfoWidget::DeviceInfoWidget(MioMain *parent, Device *device,
                                   DeviceInfo *deviceInfo, QString windowTitle)
    : MultiInfoWidget(parent, device, windowTitle), deviceInfo(deviceInfo) {
  infoSections = std::vector<std::string>();
  if (device->getCommands()->isCommandSupported(SysExMessage::GET_INFO_LIST))
    infoSections.push_back("Global");
  if (device->getCommands()->isCommandSupported(
          SysExMessage::GET_ETHERNET_PORT_INFO))
    infoSections.push_back("Network");
}

DeviceInfoWidget::~DeviceInfoWidget() {}

QWidget *DeviceInfoWidget::createWidget(std::string infoName) {
  if (infoName == "Global") {
    QWidget *w = new QWidget(this->parentWidget());
    QGridLayout *lo = new QGridLayout();
    QPalette qp;

    w->setLayout(lo);
    if (this->deviceInfo) {
      std::vector<InfoItem> *infoItems = this->deviceInfo->getDeviceInfos();
      QTableWidget *tw = new QTableWidget(infoItems->size(), 2, this);
      tw->setHorizontalHeaderItem(0, new QTableWidgetItem(tr("Name")));
      tw->setHorizontalHeaderItem(1, new QTableWidgetItem(tr("Value")));
      tw->verticalHeader()->hide();
      tw->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
      for (unsigned int i = 0; i < infoItems->size(); i++) {
        InfoItem infoItem = infoItems->at(i);
        QTableWidgetItem *name = new QTableWidgetItem(infoItem.name.c_str());
        name->setForeground(qp.dark());
        QTableWidgetItem *value = new QTableWidgetItem(infoItem.value.c_str());
        name->setFlags(name->flags() & ~Qt::ItemIsEditable);
        if (!infoItem.editable) {
          value->setFlags(value->flags() & ~Qt::ItemIsEditable);
          value->setForeground(qp.dark());
        }
        tw->setItem(i, 0, name);
        tw->setItem(i, 1, value);
      }
      lo->addWidget(tw, 0, 0);
    }
    return w;
  } else {
    QWidget *w = new QWidget(this->parentWidget());
    QGridLayout *lo = new QGridLayout();
    w->setLayout(lo);
    QLabel *l = new QLabel(w);
    l->setText(QString::fromStdString(infoName));
    lo->addWidget(l, 0, 0);
    return w;
  }
}
<|endoftext|>


<commit_before>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2013 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include <xenia/gpu/graphics_system.h>

#include <xenia/cpu/processor.h>
#include <xenia/gpu/graphics_driver.h>
#include <xenia/gpu/ring_buffer_worker.h>
#include <xenia/gpu/xenos/registers.h>

using namespace xe;
using namespace xe::gpu;
using namespace xe::gpu::xenos;

GraphicsSystem::GraphicsSystem(const CreationParams* params) :
    interrupt_callback_(0), interrupt_callback_data_(0),
    last_interrupt_time_(0), swap_pending_(false) {
  memory_ = xe_memory_retain(params->memory);

  worker_ = new RingBufferWorker(memory_);

  // Set during Initialize();
  driver_ = 0;

  // Create the run loop used for any windows/etc.
  // This must be done on the thread we create the driver.
  run_loop_ = xe_run_loop_create();

  // Create worker thread.
  // This will initialize the graphics system.
  // Init needs to happen there so that any thread-local stuff
  // is created on the right thread.
  running_ = true;
  thread_ = xe_thread_create(
      "GraphicsSystem",
      (xe_thread_callback)ThreadStartThunk, this);
  xe_thread_start(thread_);
}

GraphicsSystem::~GraphicsSystem() {
  // TODO(benvanik): thread join.
  running_ = false;
  xe_thread_release(thread_);

  // TODO(benvanik): worker join/etc.
  delete worker_;

  xe_run_loop_release(run_loop_);
  xe_memory_release(memory_);
}

xe_memory_ref GraphicsSystem::memory() {
  return xe_memory_retain(memory_);
}

shared_ptr<cpu::Processor> GraphicsSystem::processor() {
  return processor_;
}

void GraphicsSystem::set_processor(shared_ptr<cpu::Processor> processor) {
  processor_ = processor;
}

void GraphicsSystem::ThreadStart() {
  xe_run_loop_ref run_loop = xe_run_loop_retain(run_loop_);

  // Initialize driver and ringbuffer.
  Initialize();
  XEASSERTNOTNULL(driver_);

  // Main run loop.
  while (running_) {
    // Peek main run loop.
    if (xe_run_loop_pump(run_loop)) {
      break;
    }
    if (!running_) {
      break;
    }

    // Pump worker.
    worker_->Pump();

    // Pump graphics system.
    Pump();
  }
  running_ = false;

  Shutdown();

  xe_run_loop_release(run_loop);

  // TODO(benvanik): call module API to kill?
}

void GraphicsSystem::Initialize() {
}

void GraphicsSystem::Shutdown() {
}

void GraphicsSystem::SetInterruptCallback(uint32_t callback,
                                          uint32_t user_data) {
  interrupt_callback_ = callback;
  interrupt_callback_data_ = user_data;
  XELOGGPU("SetInterruptCallback(%.4X, %.4X)", callback, user_data);
}

void GraphicsSystem::InitializeRingBuffer(uint32_t ptr, uint32_t page_count) {
  XEASSERTNOTNULL(driver_);
  worker_->Initialize(driver_, ptr, page_count);
}

void GraphicsSystem::EnableReadPointerWriteBack(uint32_t ptr,
                                                uint32_t block_size) {
  worker_->EnableReadPointerWriteBack(ptr, block_size);
}

uint64_t GraphicsSystem::ReadRegister(uint32_t r) {
  XELOGGPU("ReadRegister(%.4X)", r);

  RegisterFile* regs = driver_->register_file();

  switch (r) {
  case 0x6544: // ? vblank pending?
    return 1;
  }

  XEASSERT(r >= 0 && r < kXEGpuRegisterCount);
  return regs->values[r].u32;
}

void GraphicsSystem::WriteRegister(uint32_t r, uint64_t value) {
  XELOGGPU("WriteRegister(%.4X, %.8X)", r, value);

  RegisterFile* regs = driver_->register_file();

  switch (r) {
    case 0x0714: // CP_RB_WPTR
      worker_->UpdateWritePointer((uint32_t)value);
      break;
    default:
      XELOGW("Unknown GPU register %.4X write: %.8X", r, value);
      break;
  }

  XEASSERT(r >= 0 && r < kXEGpuRegisterCount);
  regs->values[r].u32 = (uint32_t)value;
}

void GraphicsSystem::DispatchInterruptCallback() {
  // NOTE: we may be executing in some random thread.
  last_interrupt_time_ = xe_pal_now();
  if (!interrupt_callback_) {
    return;
  }
  processor_->ExecuteInterrupt(
      interrupt_callback_, 0, interrupt_callback_data_);
}
<commit_msg>Wait until the ringbuffer thread is spun up. This could be made much nicer.<commit_after>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2013 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include <xenia/gpu/graphics_system.h>

#include <xenia/cpu/processor.h>
#include <xenia/gpu/graphics_driver.h>
#include <xenia/gpu/ring_buffer_worker.h>
#include <xenia/gpu/xenos/registers.h>

using namespace xe;
using namespace xe::gpu;
using namespace xe::gpu::xenos;

GraphicsSystem::GraphicsSystem(const CreationParams* params) :
    interrupt_callback_(0), interrupt_callback_data_(0),
    last_interrupt_time_(0), swap_pending_(false) {
  memory_ = xe_memory_retain(params->memory);

  worker_ = new RingBufferWorker(memory_);

  // Set during Initialize();
  driver_ = 0;

  // Create the run loop used for any windows/etc.
  // This must be done on the thread we create the driver.
  run_loop_ = xe_run_loop_create();

  // Create worker thread.
  // This will initialize the graphics system.
  // Init needs to happen there so that any thread-local stuff
  // is created on the right thread.
  running_ = true;
  thread_ = xe_thread_create(
      "GraphicsSystem",
      (xe_thread_callback)ThreadStartThunk, this);
  xe_thread_start(thread_);
}

GraphicsSystem::~GraphicsSystem() {
  // TODO(benvanik): thread join.
  running_ = false;
  xe_thread_release(thread_);

  // TODO(benvanik): worker join/etc.
  delete worker_;

  xe_run_loop_release(run_loop_);
  xe_memory_release(memory_);
}

xe_memory_ref GraphicsSystem::memory() {
  return xe_memory_retain(memory_);
}

shared_ptr<cpu::Processor> GraphicsSystem::processor() {
  return processor_;
}

void GraphicsSystem::set_processor(shared_ptr<cpu::Processor> processor) {
  processor_ = processor;
}

void GraphicsSystem::ThreadStart() {
  xe_run_loop_ref run_loop = xe_run_loop_retain(run_loop_);

  // Initialize driver and ringbuffer.
  Initialize();
  XEASSERTNOTNULL(driver_);

  // Main run loop.
  while (running_) {
    // Peek main run loop.
    if (xe_run_loop_pump(run_loop)) {
      break;
    }
    if (!running_) {
      break;
    }

    // Pump worker.
    worker_->Pump();

    // Pump graphics system.
    Pump();
  }
  running_ = false;

  Shutdown();

  xe_run_loop_release(run_loop);

  // TODO(benvanik): call module API to kill?
}

void GraphicsSystem::Initialize() {
}

void GraphicsSystem::Shutdown() {
}

void GraphicsSystem::SetInterruptCallback(uint32_t callback,
                                          uint32_t user_data) {
  interrupt_callback_ = callback;
  interrupt_callback_data_ = user_data;
  XELOGGPU("SetInterruptCallback(%.4X, %.4X)", callback, user_data);
}

void GraphicsSystem::InitializeRingBuffer(uint32_t ptr, uint32_t page_count) {
  // TODO(benvanik): an event?
  while (!driver_) {
    Sleep(0);
  }
  XEASSERTNOTNULL(driver_);
  worker_->Initialize(driver_, ptr, page_count);
}

void GraphicsSystem::EnableReadPointerWriteBack(uint32_t ptr,
                                                uint32_t block_size) {
  worker_->EnableReadPointerWriteBack(ptr, block_size);
}

uint64_t GraphicsSystem::ReadRegister(uint32_t r) {
  XELOGGPU("ReadRegister(%.4X)", r);

  RegisterFile* regs = driver_->register_file();

  switch (r) {
  case 0x6544: // ? vblank pending?
    return 1;
  }

  XEASSERT(r >= 0 && r < kXEGpuRegisterCount);
  return regs->values[r].u32;
}

void GraphicsSystem::WriteRegister(uint32_t r, uint64_t value) {
  XELOGGPU("WriteRegister(%.4X, %.8X)", r, value);

  RegisterFile* regs = driver_->register_file();

  switch (r) {
    case 0x0714: // CP_RB_WPTR
      worker_->UpdateWritePointer((uint32_t)value);
      break;
    default:
      XELOGW("Unknown GPU register %.4X write: %.8X", r, value);
      break;
  }

  XEASSERT(r >= 0 && r < kXEGpuRegisterCount);
  regs->values[r].u32 = (uint32_t)value;
}

void GraphicsSystem::DispatchInterruptCallback() {
  // NOTE: we may be executing in some random thread.
  last_interrupt_time_ = xe_pal_now();
  if (!interrupt_callback_) {
    return;
  }
  processor_->ExecuteInterrupt(
      interrupt_callback_, 0, interrupt_callback_data_);
}
<|endoftext|>


<commit_before>#include "logging.h"
#include "common/config.h"
#include "spdlog/sinks/null_sink.h"

std::shared_ptr<spdlog::logger> stderrLogger(
    const std::string& name,
    const std::string& pattern,
    const std::vector<std::string>& files,
    bool quiet) {
  std::vector<spdlog::sink_ptr> sinks;

  auto stderr_sink = spdlog::sinks::stderr_sink_mt::instance();

  if(!quiet)
    sinks.push_back(stderr_sink);

  for(auto&& file : files) {
    auto file_sink
        = std::make_shared<spdlog::sinks::simple_file_sink_st>(file, true);
    sinks.push_back(file_sink);
  }

  auto logger
      = std::make_shared<spdlog::logger>(name, begin(sinks), end(sinks));

  spdlog::register_logger(logger);
  logger->set_pattern(pattern);
  return logger;
}

bool
set_loglevel(spdlog::logger& logger, std::string const level) {
  if (level == "trace")
    logger.set_level(spdlog::level::trace);
  else if (level == "debug")
    logger.set_level(spdlog::level::debug);
  else if (level == "info")
    logger.set_level(spdlog::level::info);
  else if (level == "err" or level == "error")
    logger.set_level(spdlog::level::err);
  else if (level == "critical")
    logger.set_level(spdlog::level::critical);
  else if (level == "off")
    logger.set_level(spdlog::level::off);
  else {
    logger.warn("Unknown log level '{}' for logger '{}'",
                level.c_str(), logger.name().c_str());
    return false;
  }
  return true;
}

Logger checkedLog(std::string logger) {
  Logger ret = spdlog::get(logger);
  if(ret) {
    return ret;
  }
  else {
    auto null_sink = std::make_shared<spdlog::sinks::null_sink_st>();
    return std::make_shared<spdlog::logger>("null_logger", null_sink);
  }
}

void createLoggers(const marian::Config* options) {
  std::vector<std::string> generalLogs;
  std::vector<std::string> validLogs;
  if(options && options->has("log")) {
    generalLogs.push_back(options->get<std::string>("log"));
    validLogs.push_back(options->get<std::string>("log"));
  }

  if(options && options->has("valid-log")) {
    validLogs.push_back(options->get<std::string>("valid-log"));
  }

  bool quiet = options->get<bool>("quiet");
  Logger info{stderrLogger("info", "[%Y-%m-%d %T] %v", generalLogs, quiet)};
  Logger warn{stderrLogger("warn", "[%Y-%m-%d %T] [warn] %v", generalLogs, quiet)};
  Logger config{stderrLogger("config", "[%Y-%m-%d %T] [config] %v", generalLogs, quiet)};
  Logger memory{stderrLogger("memory", "[%Y-%m-%d %T] [memory] %v", generalLogs, quiet)};
  Logger data{stderrLogger("data", "[%Y-%m-%d %T] [data] %v", generalLogs, quiet)};
  Logger valid{stderrLogger("valid", "[%Y-%m-%d %T] [valid] %v", validLogs, quiet)};
  Logger translate{stderrLogger("translate", "%v", generalLogs, quiet)};
  Logger devnull{stderrLogger("devnull", "%v", {}, quiet)};
  devnull->set_level(spdlog::level::off);

  if(options && options->has("log-level")) {
    std::string loglevel = options->get<std::string>("log-level");
    if (!set_loglevel(*info, loglevel)) return;
    set_loglevel(*warn, loglevel);
    set_loglevel(*config, loglevel);
    set_loglevel(*memory, loglevel);
    set_loglevel(*data, loglevel);
    set_loglevel(*valid, loglevel);
    set_loglevel(*translate, loglevel);
  }

}
<commit_msg>Fix createLoggers with no arguments<commit_after>#include "logging.h"
#include "common/config.h"
#include "spdlog/sinks/null_sink.h"

std::shared_ptr<spdlog::logger> stderrLogger(
    const std::string& name,
    const std::string& pattern,
    const std::vector<std::string>& files,
    bool quiet) {
  std::vector<spdlog::sink_ptr> sinks;

  auto stderr_sink = spdlog::sinks::stderr_sink_mt::instance();

  if(!quiet)
    sinks.push_back(stderr_sink);

  for(auto&& file : files) {
    auto file_sink
        = std::make_shared<spdlog::sinks::simple_file_sink_st>(file, true);
    sinks.push_back(file_sink);
  }

  auto logger
      = std::make_shared<spdlog::logger>(name, begin(sinks), end(sinks));

  spdlog::register_logger(logger);
  logger->set_pattern(pattern);
  return logger;
}

bool
set_loglevel(spdlog::logger& logger, std::string const level) {
  if (level == "trace")
    logger.set_level(spdlog::level::trace);
  else if (level == "debug")
    logger.set_level(spdlog::level::debug);
  else if (level == "info")
    logger.set_level(spdlog::level::info);
  else if (level == "err" or level == "error")
    logger.set_level(spdlog::level::err);
  else if (level == "critical")
    logger.set_level(spdlog::level::critical);
  else if (level == "off")
    logger.set_level(spdlog::level::off);
  else {
    logger.warn("Unknown log level '{}' for logger '{}'",
                level.c_str(), logger.name().c_str());
    return false;
  }
  return true;
}

Logger checkedLog(std::string logger) {
  Logger ret = spdlog::get(logger);
  if(ret) {
    return ret;
  }
  else {
    auto null_sink = std::make_shared<spdlog::sinks::null_sink_st>();
    return std::make_shared<spdlog::logger>("null_logger", null_sink);
  }
}

void createLoggers(const marian::Config* options) {
  std::vector<std::string> generalLogs;
  std::vector<std::string> validLogs;
  if(options && options->has("log")) {
    generalLogs.push_back(options->get<std::string>("log"));
    validLogs.push_back(options->get<std::string>("log"));
  }

  if(options && options->has("valid-log")) {
    validLogs.push_back(options->get<std::string>("valid-log"));
  }

  bool quiet = options && options->get<bool>("quiet");
  Logger info{stderrLogger("info", "[%Y-%m-%d %T] %v", generalLogs, quiet)};
  Logger warn{stderrLogger("warn", "[%Y-%m-%d %T] [warn] %v", generalLogs, quiet)};
  Logger config{stderrLogger("config", "[%Y-%m-%d %T] [config] %v", generalLogs, quiet)};
  Logger memory{stderrLogger("memory", "[%Y-%m-%d %T] [memory] %v", generalLogs, quiet)};
  Logger data{stderrLogger("data", "[%Y-%m-%d %T] [data] %v", generalLogs, quiet)};
  Logger valid{stderrLogger("valid", "[%Y-%m-%d %T] [valid] %v", validLogs, quiet)};
  Logger translate{stderrLogger("translate", "%v", generalLogs, quiet)};
  Logger devnull{stderrLogger("devnull", "%v", {}, quiet)};
  devnull->set_level(spdlog::level::off);

  if(options && options->has("log-level")) {
    std::string loglevel = options->get<std::string>("log-level");
    if (!set_loglevel(*info, loglevel)) return;
    set_loglevel(*warn, loglevel);
    set_loglevel(*config, loglevel);
    set_loglevel(*memory, loglevel);
    set_loglevel(*data, loglevel);
    set_loglevel(*valid, loglevel);
    set_loglevel(*translate, loglevel);
  }

}
<|endoftext|>


<commit_before>#include <sys/stat.h>

#include <glog/logging.h>

#include "fatal.hpp"
#include "logging.hpp"

using std::string;

using namespace mesos::internal;

void Logging::registerOptions(Configurator* conf)
{
  conf->addOption<bool>("quiet", 'q', "Disable logging to stderr", false);
  conf->addOption<string>("log_dir",
                          "Where to put logs (default: MESOS_HOME/logs)");
}

void Logging::init(const char* programName, const Params& conf)
{
  // Set glog's parameters through Google Flags variables
  string logDir = getLogDir(conf);
  if (logDir != "") {
    if (mkdir(logDir.c_str(), 0755) < 0 && errno != EEXIST) {
      fatalerror("Failed to create log directory %s", logDir.c_str());
    }
    FLAGS_log_dir = logDir;
  }
  FLAGS_logbufsecs = 1;
  google::InitGoogleLogging(programName);

  if (!isQuiet(conf))
    google::SetStderrLogging(google::INFO);

  LOG(INFO) << "Logging to " << FLAGS_log_dir;
}

string Logging::getLogDir(const Params& conf)
{
  if (conf.contains("log_dir"))
    return conf.get("log_dir", "");
  else if (conf.contains("home"))
    return conf.get("home", "") + "/logs";
  else
    return "";
}

bool Logging::isQuiet(const Params& conf)
{
  return conf.get<bool>("quiet", false);
}
<commit_msg>Made log buffer interval configurable and made it default to 0 seconds. This makes Mesos behave more as expected out of the box, outputting all lines to the log file when they are written. Unfortunately, the old default logbufsecs value of 1 didn't do this because Google Log doesn't actually flush logs this often if you aren't repeatedly writing messages (see http://code.google.com/p/google-glog/issues/detail?id=52). It might be nice to have a thread periodically flush the log until glog fixes this issue, but for now it's good to have a default behavior that's sensible.<commit_after>#include <sys/stat.h>

#include <glog/logging.h>

#include "fatal.hpp"
#include "logging.hpp"

using std::string;

using namespace mesos::internal;

void Logging::registerOptions(Configurator* conf)
{
  conf->addOption<bool>("quiet", 'q', "Disable logging to stderr", false);
  conf->addOption<string>("log_dir",
                          "Where to put logs (default: MESOS_HOME/logs)");
  conf->addOption<int>("log_buf_secs",
                       "How many seconds to buffer log messages for\n",
                       0);
}

void Logging::init(const char* programName, const Params& conf)
{
  // Set glog's parameters through Google Flags variables
  string logDir = getLogDir(conf);
  if (logDir != "") {
    if (mkdir(logDir.c_str(), 0755) < 0 && errno != EEXIST) {
      fatalerror("Failed to create log directory %s", logDir.c_str());
    }
    FLAGS_log_dir = logDir;
  }
  FLAGS_logbufsecs = conf.get<int>("log_buf_secs", 0);
  google::InitGoogleLogging(programName);

  if (!isQuiet(conf))
    google::SetStderrLogging(google::INFO);

  LOG(INFO) << "Logging to " << FLAGS_log_dir;
}

string Logging::getLogDir(const Params& conf)
{
  if (conf.contains("log_dir"))
    return conf.get("log_dir", "");
  else if (conf.contains("home"))
    return conf.get("home", "") + "/logs";
  else
    return "";
}

bool Logging::isQuiet(const Params& conf)
{
  return conf.get<bool>("quiet", false);
}
<|endoftext|>


<commit_before>/*
    Copyright 2011 Joe Hermaszewski. All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

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

    The views and conclusions contained in the software and documentation are
    those of the authors and should not be interpreted as representing official
    policies, either expressed or implied, of Joe Hermaszewski.
*/

#include "lexer.hpp"

#include <cassert>
#include <algorithm>
#include <functional>
#include <map>
#include <memory>
#include <string>
#include <utility>

#include <compiler/terminal_types.hpp>

namespace JoeLang
{
namespace Compiler
{

//------------------------------------------------------------------------------
// Lexer
//------------------------------------------------------------------------------

Lexer::Lexer( std::string string )
    :m_string( std::move( string ) )
    ,m_position( m_string.begin() )
{
    ConsumeIgnoredTerminals();
}

TerminalType Lexer::ReadPunctuationTerminal( TerminalType terminal,
                                             std::string& string ) const
{
    // Find this terminal type in the punctuation terminal map
    std::map<TerminalType, LiteralTerminal>::const_iterator literal_iterator =
        g_punctuationTerminals.find( terminal );

    // If it wasn't in the map, return UNKNOWN_CHARACTER
    if( literal_iterator == g_punctuationTerminals.end() )
        return TerminalType::UNKNOWN_CHARACTER;

    // Try and read this terminal
    const LiteralTerminal& terminal_reader = literal_iterator->second;
    std::size_t chars_read = terminal_reader.Read( m_position, m_string.end() );

    // If it didn't match, return UNKNOWN_CHARACTER
    if( !chars_read )
        return TerminalType::UNKNOWN_CHARACTER;

    // Check that this terminal isn't also matched by something longer
    for( const auto& c: g_punctuationTerminals )
        if( c.second.matched_string.size() >
                                        terminal_reader.matched_string.size() &&
            c.second.Read( m_position, m_string.end() ) )
            return c.first;

    // Fill up string
    string = std::string( m_position, m_position + chars_read );
    return terminal;
}

TerminalType Lexer::ReadLiteralTerminal( TerminalType terminal,
                                         std::string& string ) const
{
    // Find this terminal type in the literal terminal map
    std::map<TerminalType, FunctionalTerminal>::const_iterator
                        functional_iterator = g_literalTerminals.find(terminal);

    // If it wasn't in the map, return UNKNOWN_CHARACTER
    if( functional_iterator == g_literalTerminals.end() )
        return TerminalType::UNKNOWN_CHARACTER;

    // Try and match this terminal
    const FunctionalTerminal& terminal_reader = functional_iterator->second;
    std::size_t chars_read = terminal_reader.Read( m_position, m_string.end() );

    // if it didn't match return
    if( !chars_read )
        return TerminalType::UNKNOWN_CHARACTER;

    // fill up string
    string = std::string( m_position, m_position + chars_read );
    return terminal;
}

TerminalType Lexer::ReadKeywordTerminal( TerminalType terminal,
                                         std::string& string ) const
{
    // Find this terminal in the punctuation terminal map
    std::map<TerminalType, LiteralTerminal>::const_iterator literal_iterator =
        g_keywordTerminals.find(terminal);

    // If it wasn't in the map return
    if( literal_iterator == g_keywordTerminals.end() )
        return TerminalType::UNKNOWN_CHARACTER;

    // Try and read this terminal
    const LiteralTerminal& terminal_reader = literal_iterator->second;
    std::size_t chars_read = terminal_reader.Read( m_position, m_string.end() );

    // If it didn't match return
    if( !chars_read )
        return TerminalType::UNKNOWN_CHARACTER;

    // Check that this terminal isn't also matched by something longer
    for( const auto& c: g_keywordTerminals )
        if( c.second.matched_string.size() >
                                        terminal_reader.matched_string.size() &&
            c.second.Read( m_position, m_string.end() ) )
            return c.first;

    // fill up the string
    string = std::string( m_position, m_position + chars_read );
    return terminal;
}

bool Lexer::Expect( TerminalType terminal_type, std::string& string )
{
    // If we've reached the end of the string
    if( terminal_type == TerminalType::END_OF_INPUT &&
        m_position == m_string.end() )
        return true;

    TerminalType t;

    // See if it's a punctuation terminal
    t = ReadPunctuationTerminal( terminal_type, string );

    // If it wasn't matched by the punctuation try and match it as a literal
    if( t == TerminalType::UNKNOWN_CHARACTER )
        t = ReadLiteralTerminal( terminal_type, string );

    // If it wasn't matched try and match a keyword
    if( t == TerminalType::UNKNOWN_CHARACTER )
        t = ReadKeywordTerminal( terminal_type, string );

    // If we've found a map, advance the position and clean up any whitespace
    if( t == terminal_type )
    {
        ReadChars( string.size() );
        ConsumeIgnoredTerminals();
        return true;
    }
    return false;
}

TerminalType Lexer::PeekNextTerminal( std::string& string ) const
{
    // Try and match any punctuation terminals
    for( const auto& t_reader : g_punctuationTerminals )
    {
        TerminalType t = ReadPunctuationTerminal( t_reader.first, string );
        if( t != TerminalType::UNKNOWN_CHARACTER )
            return t;
    }

    // Try and match any literal terminals
    for( const auto& t_reader : g_literalTerminals )
    {
        TerminalType t = ReadLiteralTerminal( t_reader.first, string );
        if( t != TerminalType::UNKNOWN_CHARACTER )
            return t;
    }

    // Try and match any keyword terminals
    for( const auto& t_reader : g_keywordTerminals )
    {
        TerminalType t = ReadPunctuationTerminal( t_reader.first, string );
        if( t != TerminalType::UNKNOWN_CHARACTER )
            return t;
    }

    // If it's anything else
    return TerminalType::UNKNOWN_CHARACTER;
}

bool Lexer::PeekIdentifier( std::string& string ) const
{
    return ReadLiteralTerminal( TerminalType::IDENTIFIER, string ) ==
           TerminalType::IDENTIFIER;
}

std::size_t Lexer::GetPosition() const
{
    return m_position - m_string.begin();
}

std::size_t Lexer::GetColumnNumber() const
{
    return m_columnNumber;
}

std::size_t Lexer::GetLineNumber() const
{
    return m_lineNumber;
}

void Lexer::ConsumeIgnoredTerminals()
{
    int chars_read = 0;
    // While we keep having eaten something, try and parse the next terminal
    do
    {
        for( const auto& terminal_reader : g_ignoredTerminals )
        {
            chars_read = terminal_reader.second.Read( m_position,
                                                      m_string.end() );
            if( chars_read )
                break;
        }
        ReadChars( chars_read );
    } while( chars_read );
}

void Lexer::ReadChars( std::size_t num_chars )
{
    std::string::const_iterator end = m_position + num_chars;
    assert( end <= m_string.end() &&
            "Trying to advance the lexer past the end of the file" );
    while( m_position < end )
    {
        if( *m_position == '\n' )
        {
            ++m_lineNumber;
            m_columnNumber = 0;
        }
        ++m_columnNumber;
        ++m_position;
    }
}

} // namespace Compiler
} // namespace JoeLang
<commit_msg>[!] reading keywords in peek terminal<commit_after>/*
    Copyright 2011 Joe Hermaszewski. All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

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

    The views and conclusions contained in the software and documentation are
    those of the authors and should not be interpreted as representing official
    policies, either expressed or implied, of Joe Hermaszewski.
*/

#include "lexer.hpp"

#include <cassert>
#include <algorithm>
#include <functional>
#include <map>
#include <memory>
#include <string>
#include <utility>

#include <compiler/terminal_types.hpp>

namespace JoeLang
{
namespace Compiler
{

//------------------------------------------------------------------------------
// Lexer
//------------------------------------------------------------------------------

Lexer::Lexer( std::string string )
    :m_string( std::move( string ) )
    ,m_position( m_string.begin() )
{
    ConsumeIgnoredTerminals();
}

TerminalType Lexer::ReadPunctuationTerminal( TerminalType terminal,
                                             std::string& string ) const
{
    // Find this terminal type in the punctuation terminal map
    std::map<TerminalType, LiteralTerminal>::const_iterator literal_iterator =
        g_punctuationTerminals.find( terminal );

    // If it wasn't in the map, return UNKNOWN_CHARACTER
    if( literal_iterator == g_punctuationTerminals.end() )
        return TerminalType::UNKNOWN_CHARACTER;

    // Try and read this terminal
    const LiteralTerminal& terminal_reader = literal_iterator->second;
    std::size_t chars_read = terminal_reader.Read( m_position, m_string.end() );

    // If it didn't match, return UNKNOWN_CHARACTER
    if( !chars_read )
        return TerminalType::UNKNOWN_CHARACTER;

    // Check that this terminal isn't also matched by something longer
    for( const auto& c: g_punctuationTerminals )
        if( c.second.matched_string.size() >
                                        terminal_reader.matched_string.size() &&
            c.second.Read( m_position, m_string.end() ) )
            return c.first;

    // Fill up string
    string = std::string( m_position, m_position + chars_read );
    return terminal;
}

TerminalType Lexer::ReadLiteralTerminal( TerminalType terminal,
                                         std::string& string ) const
{
    // Find this terminal type in the literal terminal map
    std::map<TerminalType, FunctionalTerminal>::const_iterator
                        functional_iterator = g_literalTerminals.find(terminal);

    // If it wasn't in the map, return UNKNOWN_CHARACTER
    if( functional_iterator == g_literalTerminals.end() )
        return TerminalType::UNKNOWN_CHARACTER;

    // Try and match this terminal
    const FunctionalTerminal& terminal_reader = functional_iterator->second;
    std::size_t chars_read = terminal_reader.Read( m_position, m_string.end() );

    // if it didn't match return
    if( !chars_read )
        return TerminalType::UNKNOWN_CHARACTER;

    // fill up string
    string = std::string( m_position, m_position + chars_read );
    return terminal;
}

TerminalType Lexer::ReadKeywordTerminal( TerminalType terminal,
                                         std::string& string ) const
{
    // Find this terminal in the punctuation terminal map
    std::map<TerminalType, LiteralTerminal>::const_iterator literal_iterator =
        g_keywordTerminals.find(terminal);

    // If it wasn't in the map return
    if( literal_iterator == g_keywordTerminals.end() )
        return TerminalType::UNKNOWN_CHARACTER;

    // Try and read this terminal
    const LiteralTerminal& terminal_reader = literal_iterator->second;
    std::size_t chars_read = terminal_reader.Read( m_position, m_string.end() );

    // If it didn't match return
    if( !chars_read )
        return TerminalType::UNKNOWN_CHARACTER;

    // Check that this terminal isn't also matched by something longer
    for( const auto& c: g_keywordTerminals )
        if( c.second.matched_string.size() >
                                        terminal_reader.matched_string.size() &&
            c.second.Read( m_position, m_string.end() ) )
            return c.first;

    // fill up the string
    string = std::string( m_position, m_position + chars_read );
    return terminal;
}

bool Lexer::Expect( TerminalType terminal_type, std::string& string )
{
    // If we've reached the end of the string
    if( terminal_type == TerminalType::END_OF_INPUT &&
        m_position == m_string.end() )
        return true;

    TerminalType t;

    // See if it's a punctuation terminal
    t = ReadPunctuationTerminal( terminal_type, string );

    // If it wasn't matched by the punctuation try and match it as a literal
    if( t == TerminalType::UNKNOWN_CHARACTER )
        t = ReadLiteralTerminal( terminal_type, string );

    // If it wasn't matched try and match a keyword
    if( t == TerminalType::UNKNOWN_CHARACTER )
        t = ReadKeywordTerminal( terminal_type, string );

    // If we've found a map, advance the position and clean up any whitespace
    if( t == terminal_type )
    {
        ReadChars( string.size() );
        ConsumeIgnoredTerminals();
        return true;
    }
    return false;
}

TerminalType Lexer::PeekNextTerminal( std::string& string ) const
{
    // Try and match any punctuation terminals
    for( const auto& t_reader : g_punctuationTerminals )
    {
        TerminalType t = ReadPunctuationTerminal( t_reader.first, string );
        if( t != TerminalType::UNKNOWN_CHARACTER )
            return t;
    }

    // Try and match any literal terminals
    for( const auto& t_reader : g_literalTerminals )
    {
        TerminalType t = ReadLiteralTerminal( t_reader.first, string );
        if( t != TerminalType::UNKNOWN_CHARACTER )
            return t;
    }

    // Try and match any keyword terminals
    for( const auto& t_reader : g_keywordTerminals )
    {
        TerminalType t = ReadKeywordTerminal( t_reader.first, string );
        if( t != TerminalType::UNKNOWN_CHARACTER )
            return t;
    }

    // If it's anything else
    return TerminalType::UNKNOWN_CHARACTER;
}

bool Lexer::PeekIdentifier( std::string& string ) const
{
    return ReadLiteralTerminal( TerminalType::IDENTIFIER, string ) ==
           TerminalType::IDENTIFIER;
}

std::size_t Lexer::GetPosition() const
{
    return m_position - m_string.begin();
}

std::size_t Lexer::GetColumnNumber() const
{
    return m_columnNumber;
}

std::size_t Lexer::GetLineNumber() const
{
    return m_lineNumber;
}

void Lexer::ConsumeIgnoredTerminals()
{
    int chars_read = 0;
    // While we keep having eaten something, try and parse the next terminal
    do
    {
        for( const auto& terminal_reader : g_ignoredTerminals )
        {
            chars_read = terminal_reader.second.Read( m_position,
                                                      m_string.end() );
            if( chars_read )
                break;
        }
        ReadChars( chars_read );
    } while( chars_read );
}

void Lexer::ReadChars( std::size_t num_chars )
{
    std::string::const_iterator end = m_position + num_chars;
    assert( end <= m_string.end() &&
            "Trying to advance the lexer past the end of the file" );
    while( m_position < end )
    {
        if( *m_position == '\n' )
        {
            ++m_lineNumber;
            m_columnNumber = 0;
        }
        ++m_columnNumber;
        ++m_position;
    }
}

} // namespace Compiler
} // namespace JoeLang
<|endoftext|>


<commit_before>#include "stdafx.h"

namespace uih::ole {

CLIPFORMAT get_clipboard_format_drop_description()
{
    static const auto cfRet = (CLIPFORMAT)RegisterClipboardFormat(CFSTR_DROPDESCRIPTION);
    return cfRet;
}

CLIPFORMAT DragWindowFormat()
{
    static const auto cfRet = (CLIPFORMAT)RegisterClipboardFormat(L"DragWindow");
    return cfRet;
}

CLIPFORMAT IsShowingLayeredFormat()
{
    static const auto cfRet = (CLIPFORMAT)RegisterClipboardFormat(L"IsShowingLayered");
    return cfRet;
}

CLIPFORMAT IsShowingTextFormat()
{
    static const auto cfRet = (CLIPFORMAT)RegisterClipboardFormat(L"IsShowingText");
    return cfRet;
}

CLIPFORMAT DisableDragTextFormat()
{
    static const auto cfRet = (CLIPFORMAT)RegisterClipboardFormat(L"DisableDragText");
    return cfRet;
}

CLIPFORMAT IsComputingImageFormat()
{
    static const auto cfRet = (CLIPFORMAT)RegisterClipboardFormat(L"IsComutingImage");
    return cfRet;
}

CLIPFORMAT UsingDefaultDragImageFormat()
{
    static const auto cfRet = (CLIPFORMAT)RegisterClipboardFormat(L"UsingDefaultDragImage");
    return cfRet;
}

CLIPFORMAT PreferredDropEffectFormat()
{
    static const auto cfRet = (CLIPFORMAT)RegisterClipboardFormat(CFSTR_PREFERREDDROPEFFECT);
    return cfRet;
}

template <typename T>
HRESULT GetDataObjectDataSimple(IDataObject* pDataObj, CLIPFORMAT cf, T& p_out)
{
    HRESULT hr;

    FORMATETC fe = {0};
    fe.cfFormat = cf;
    fe.dwAspect = DVASPECT_CONTENT;
    fe.lindex = -1;
    fe.tymed = TYMED_HGLOBAL;

    STGMEDIUM stgm = {0};
    if (SUCCEEDED(hr = pDataObj->GetData(&fe, &stgm))) {
        void* pData = GlobalLock(stgm.hGlobal);
        if (pData) {
            p_out = *static_cast<T*>(pData);
            GlobalUnlock(pData);
        }
        ReleaseStgMedium(&stgm);
    }
    return hr;
}

HRESULT GetDragWindow(IDataObject* pDataObj, HWND& p_wnd)
{
    HRESULT hr;
    DWORD dw;
    if (SUCCEEDED(hr = GetDataObjectDataSimple(pDataObj, DragWindowFormat(), dw)))
        p_wnd = (HWND)ULongToHandle(dw);

    return hr;
}

HRESULT GetIsShowingLayered(IDataObject* pDataObj, BOOL& p_out)
{
    return GetDataObjectDataSimple(pDataObj, IsShowingLayeredFormat(), p_out);
}

HRESULT set_blob(IDataObject* pdtobj, CLIPFORMAT cf, const void* pvBlob, UINT cbBlob)
{
    HRESULT hr = E_OUTOFMEMORY;
    void* pv = GlobalAlloc(GPTR, cbBlob);
    if (pv) {
        CopyMemory(pv, pvBlob, cbBlob);

        FORMATETC fmte = {cf, nullptr, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};

        // The STGMEDIUM structure is used to define how to handle a global memory transfer.
        // This structure includes a flag, tymed, which indicates the medium
        // to be used, and a union comprising pointers and a handle for getting whichever
        // medium is specified in tymed.
        STGMEDIUM medium = {0};
        medium.tymed = TYMED_HGLOBAL;
        medium.hGlobal = pv;

        hr = pdtobj->SetData(&fmte, &medium, TRUE);
        if (FAILED(hr)) {
            GlobalFree(pv);
        }
    }
    return hr;
}

HRESULT set_drop_description(IDataObject* pdtobj, DROPIMAGETYPE dit, const char* msg, const char* insert)
{
    if (mmh::is_windows_vista_or_newer()) {
        DROPDESCRIPTION dd_prev;
        memset(&dd_prev, 0, sizeof(dd_prev));

        bool dd_prev_valid
            = (SUCCEEDED(GetDataObjectDataSimple(pdtobj, get_clipboard_format_drop_description(), dd_prev)));

        pfc::stringcvt::string_os_from_utf8 wmsg(msg);
        pfc::stringcvt::string_os_from_utf8 winsert(insert);

        // Only set the drop description if it has actually changed (otherwise things get a bit crazy near the edge of
        // the screen).
        if (!dd_prev_valid || dd_prev.type != dit || wcscmp(dd_prev.szInsert, winsert)
            || wcscmp(dd_prev.szMessage, wmsg)) {
            DROPDESCRIPTION dd;
            dd.type = dit;
            wcscpy_s(dd.szMessage, wmsg.get_ptr());
            wcscpy_s(dd.szInsert, winsert.get_ptr());
            return set_blob(pdtobj, get_clipboard_format_drop_description(), &dd, sizeof(dd));
        }
        return S_OK;
    }
    return E_NOTIMPL;
}

HRESULT set_using_default_drag_image(IDataObject* pdtobj, BOOL value)
{
    return set_blob(pdtobj, UsingDefaultDragImageFormat(), &value, sizeof(value));
}

HRESULT set_is_showing_text(IDataObject* pdtobj, BOOL value)
{
    return set_blob(pdtobj, IsShowingTextFormat(), &value, sizeof(value));
}

HRESULT set_disable_drag_text(IDataObject* pdtobj, BOOL value)
{
    return set_blob(pdtobj, DisableDragTextFormat(), &value, sizeof(value));
}

HRESULT set_is_computing_image(IDataObject* pdtobj, BOOL value)
{
    return set_blob(pdtobj, IsComputingImageFormat(), &value, sizeof(value));
}

HRESULT SetPreferredDropEffect(IDataObject* pdtobj, DWORD effect)
{
    return set_blob(pdtobj, PreferredDropEffectFormat(), &effect, sizeof(effect));
}

HRESULT do_drag_drop(HWND wnd, WPARAM initialKeyState, IDataObject* pDataObject, DWORD dwEffect, DWORD preferredEffect,
    DWORD* pdwEffect, SHDRAGIMAGE* lpsdi)
{
    if (preferredEffect)
        SetPreferredDropEffect(pDataObject, preferredEffect);

    mmh::ComPtr<IDropSource> pDropSource;
    // if (!IsVistaOrNewer())
    pDropSource = new uih::ole::IDropSourceGeneric(wnd, pDataObject, initialKeyState, true, lpsdi);
    return SHDoDragDrop(wnd, pDataObject, pDropSource, dwEffect, pdwEffect);
}

HRESULT STDMETHODCALLTYPE IDropSourceGeneric::QueryInterface(REFIID iid, void** ppvObject)
{
    if (ppvObject == nullptr)
        return E_INVALIDARG;

    *ppvObject = nullptr;

    if (iid == IID_IUnknown) {
        AddRef();
        *ppvObject = (IUnknown*)this;
        return S_OK;
    }

    if (iid == IID_IDropSource) {
        AddRef();
        *ppvObject = (IDropSource*)this;
        return S_OK;
    }
    return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE IDropSourceGeneric::AddRef()
{
    return InterlockedIncrement(&m_refcount);
}
ULONG STDMETHODCALLTYPE IDropSourceGeneric::Release()
{
    LONG rv = InterlockedDecrement(&m_refcount);
    if (!rv) {
        delete this;
    }
    return rv;
}

HRESULT STDMETHODCALLTYPE IDropSourceGeneric::QueryContinueDrag(BOOL fEscapePressed, DWORD grfKeyState)
{
    if (fEscapePressed || ((m_initial_key_state & MK_LBUTTON) && (grfKeyState & MK_RBUTTON))) {
        return DRAGDROP_S_CANCEL;
    }

    if (((m_initial_key_state & MK_LBUTTON) && !(grfKeyState & MK_LBUTTON))
        || ((m_initial_key_state & MK_RBUTTON) && !(grfKeyState & MK_RBUTTON))) {
        return DRAGDROP_S_DROP;
    }
    return S_OK;
}

HRESULT STDMETHODCALLTYPE IDropSourceGeneric::GiveFeedback(DWORD dwEffect)
{
    HWND wnd_drag = nullptr;
    BOOL isShowingLayered = FALSE;
    if (IsThemeActive())
        GetIsShowingLayered(m_data_object, isShowingLayered);

    if (SUCCEEDED(GetDragWindow(m_data_object, wnd_drag)) && wnd_drag)
        PostMessage(wnd_drag, DDWM_UPDATEWINDOW, NULL, NULL);

    if (isShowingLayered) {
        if (!m_prev_is_showing_layered) {
            auto cursor = LoadCursor(nullptr, IDC_ARROW);
            SetCursor(cursor);
        }
        if (wnd_drag) {
            WPARAM wp = 1;
            if (dwEffect & DROPEFFECT_COPY)
                wp = 3;
            else if (dwEffect & DROPEFFECT_MOVE)
                wp = 2;
            else if (dwEffect & DROPEFFECT_LINK)
                wp = 4;

            PostMessage(wnd_drag, WM_USER + 2, wp, NULL);
        }
    }

    m_prev_is_showing_layered = isShowingLayered != 0;

    return isShowingLayered ? S_OK : DRAGDROP_S_USEDEFAULTCURSORS;
}

IDropSourceGeneric::IDropSourceGeneric(
    HWND wnd, IDataObject* pDataObj, DWORD initial_key_state, bool b_allowdropdescriptiontext, SHDRAGIMAGE* lpsdi)
    : m_refcount(0), m_initial_key_state(initial_key_state), m_prev_is_showing_layered(false), m_data_object(pDataObj)
{
    HRESULT hr;

    if (b_allowdropdescriptiontext) {
        if (SUCCEEDED(m_drag_source_helper.instantiate(CLSID_DragDropHelper, nullptr, CLSCTX_INPROC_SERVER))) {
            mmh::ComPtr<IDragSourceHelper2> pDragSourceHelper2 = m_drag_source_helper;
            if (pDragSourceHelper2.is_valid()) {
                hr = pDragSourceHelper2->SetFlags(DSH_ALLOWDROPDESCRIPTIONTEXT);
            }
            if (lpsdi) {
                hr = m_drag_source_helper->InitializeFromBitmap(lpsdi, pDataObj);
                if (FAILED(hr) && lpsdi->hbmpDragImage) {
                    DeleteObject(lpsdi->hbmpDragImage);
                    lpsdi->hbmpDragImage = nullptr;
                }
            } else
                hr = m_drag_source_helper->InitializeFromWindow(wnd, nullptr, pDataObj);
            if (IsThemeActive() && IsAppThemed()) {
                set_using_default_drag_image(pDataObj);
            }
        }
    }
}
} // namespace uih::ole
<commit_msg>Avoid crash in ole::set_drop_description() with long strings<commit_after>#include "stdafx.h"

namespace uih::ole {

CLIPFORMAT get_clipboard_format_drop_description()
{
    static const auto cfRet = (CLIPFORMAT)RegisterClipboardFormat(CFSTR_DROPDESCRIPTION);
    return cfRet;
}

CLIPFORMAT DragWindowFormat()
{
    static const auto cfRet = (CLIPFORMAT)RegisterClipboardFormat(L"DragWindow");
    return cfRet;
}

CLIPFORMAT IsShowingLayeredFormat()
{
    static const auto cfRet = (CLIPFORMAT)RegisterClipboardFormat(L"IsShowingLayered");
    return cfRet;
}

CLIPFORMAT IsShowingTextFormat()
{
    static const auto cfRet = (CLIPFORMAT)RegisterClipboardFormat(L"IsShowingText");
    return cfRet;
}

CLIPFORMAT DisableDragTextFormat()
{
    static const auto cfRet = (CLIPFORMAT)RegisterClipboardFormat(L"DisableDragText");
    return cfRet;
}

CLIPFORMAT IsComputingImageFormat()
{
    static const auto cfRet = (CLIPFORMAT)RegisterClipboardFormat(L"IsComutingImage");
    return cfRet;
}

CLIPFORMAT UsingDefaultDragImageFormat()
{
    static const auto cfRet = (CLIPFORMAT)RegisterClipboardFormat(L"UsingDefaultDragImage");
    return cfRet;
}

CLIPFORMAT PreferredDropEffectFormat()
{
    static const auto cfRet = (CLIPFORMAT)RegisterClipboardFormat(CFSTR_PREFERREDDROPEFFECT);
    return cfRet;
}

template <typename T>
HRESULT GetDataObjectDataSimple(IDataObject* pDataObj, CLIPFORMAT cf, T& p_out)
{
    HRESULT hr;

    FORMATETC fe = {0};
    fe.cfFormat = cf;
    fe.dwAspect = DVASPECT_CONTENT;
    fe.lindex = -1;
    fe.tymed = TYMED_HGLOBAL;

    STGMEDIUM stgm = {0};
    if (SUCCEEDED(hr = pDataObj->GetData(&fe, &stgm))) {
        void* pData = GlobalLock(stgm.hGlobal);
        if (pData) {
            p_out = *static_cast<T*>(pData);
            GlobalUnlock(pData);
        }
        ReleaseStgMedium(&stgm);
    }
    return hr;
}

HRESULT GetDragWindow(IDataObject* pDataObj, HWND& p_wnd)
{
    HRESULT hr;
    DWORD dw;
    if (SUCCEEDED(hr = GetDataObjectDataSimple(pDataObj, DragWindowFormat(), dw)))
        p_wnd = (HWND)ULongToHandle(dw);

    return hr;
}

HRESULT GetIsShowingLayered(IDataObject* pDataObj, BOOL& p_out)
{
    return GetDataObjectDataSimple(pDataObj, IsShowingLayeredFormat(), p_out);
}

HRESULT set_blob(IDataObject* pdtobj, CLIPFORMAT cf, const void* pvBlob, UINT cbBlob)
{
    HRESULT hr = E_OUTOFMEMORY;
    void* pv = GlobalAlloc(GPTR, cbBlob);
    if (pv) {
        CopyMemory(pv, pvBlob, cbBlob);

        FORMATETC fmte = {cf, nullptr, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};

        // The STGMEDIUM structure is used to define how to handle a global memory transfer.
        // This structure includes a flag, tymed, which indicates the medium
        // to be used, and a union comprising pointers and a handle for getting whichever
        // medium is specified in tymed.
        STGMEDIUM medium = {0};
        medium.tymed = TYMED_HGLOBAL;
        medium.hGlobal = pv;

        hr = pdtobj->SetData(&fmte, &medium, TRUE);
        if (FAILED(hr)) {
            GlobalFree(pv);
        }
    }
    return hr;
}

HRESULT set_drop_description(IDataObject* pdtobj, DROPIMAGETYPE dit, const char* msg, const char* insert)
{
    if (mmh::is_windows_vista_or_newer()) {
        DROPDESCRIPTION dd_prev;
        memset(&dd_prev, 0, sizeof(dd_prev));

        bool dd_prev_valid
            = (SUCCEEDED(GetDataObjectDataSimple(pdtobj, get_clipboard_format_drop_description(), dd_prev)));

        pfc::stringcvt::string_os_from_utf8 wmsg(msg);
        pfc::stringcvt::string_os_from_utf8 winsert(insert);

        // Only set the drop description if it has actually changed (otherwise things get a bit crazy near the edge of
        // the screen).
        if (!dd_prev_valid || dd_prev.type != dit || wcscmp(dd_prev.szInsert, winsert)
            || wcscmp(dd_prev.szMessage, wmsg)) {
            DROPDESCRIPTION dd;
            dd.type = dit;
            wcsncpy_s(dd.szMessage, wmsg.get_ptr(), _TRUNCATE);
            wcsncpy_s(dd.szInsert, winsert.get_ptr(), _TRUNCATE);
            return set_blob(pdtobj, get_clipboard_format_drop_description(), &dd, sizeof(dd));
        }
        return S_OK;
    }
    return E_NOTIMPL;
}

HRESULT set_using_default_drag_image(IDataObject* pdtobj, BOOL value)
{
    return set_blob(pdtobj, UsingDefaultDragImageFormat(), &value, sizeof(value));
}

HRESULT set_is_showing_text(IDataObject* pdtobj, BOOL value)
{
    return set_blob(pdtobj, IsShowingTextFormat(), &value, sizeof(value));
}

HRESULT set_disable_drag_text(IDataObject* pdtobj, BOOL value)
{
    return set_blob(pdtobj, DisableDragTextFormat(), &value, sizeof(value));
}

HRESULT set_is_computing_image(IDataObject* pdtobj, BOOL value)
{
    return set_blob(pdtobj, IsComputingImageFormat(), &value, sizeof(value));
}

HRESULT SetPreferredDropEffect(IDataObject* pdtobj, DWORD effect)
{
    return set_blob(pdtobj, PreferredDropEffectFormat(), &effect, sizeof(effect));
}

HRESULT do_drag_drop(HWND wnd, WPARAM initialKeyState, IDataObject* pDataObject, DWORD dwEffect, DWORD preferredEffect,
    DWORD* pdwEffect, SHDRAGIMAGE* lpsdi)
{
    if (preferredEffect)
        SetPreferredDropEffect(pDataObject, preferredEffect);

    mmh::ComPtr<IDropSource> pDropSource;
    // if (!IsVistaOrNewer())
    pDropSource = new uih::ole::IDropSourceGeneric(wnd, pDataObject, initialKeyState, true, lpsdi);
    return SHDoDragDrop(wnd, pDataObject, pDropSource, dwEffect, pdwEffect);
}

HRESULT STDMETHODCALLTYPE IDropSourceGeneric::QueryInterface(REFIID iid, void** ppvObject)
{
    if (ppvObject == nullptr)
        return E_INVALIDARG;

    *ppvObject = nullptr;

    if (iid == IID_IUnknown) {
        AddRef();
        *ppvObject = (IUnknown*)this;
        return S_OK;
    }

    if (iid == IID_IDropSource) {
        AddRef();
        *ppvObject = (IDropSource*)this;
        return S_OK;
    }
    return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE IDropSourceGeneric::AddRef()
{
    return InterlockedIncrement(&m_refcount);
}
ULONG STDMETHODCALLTYPE IDropSourceGeneric::Release()
{
    LONG rv = InterlockedDecrement(&m_refcount);
    if (!rv) {
        delete this;
    }
    return rv;
}

HRESULT STDMETHODCALLTYPE IDropSourceGeneric::QueryContinueDrag(BOOL fEscapePressed, DWORD grfKeyState)
{
    if (fEscapePressed || ((m_initial_key_state & MK_LBUTTON) && (grfKeyState & MK_RBUTTON))) {
        return DRAGDROP_S_CANCEL;
    }

    if (((m_initial_key_state & MK_LBUTTON) && !(grfKeyState & MK_LBUTTON))
        || ((m_initial_key_state & MK_RBUTTON) && !(grfKeyState & MK_RBUTTON))) {
        return DRAGDROP_S_DROP;
    }
    return S_OK;
}

HRESULT STDMETHODCALLTYPE IDropSourceGeneric::GiveFeedback(DWORD dwEffect)
{
    HWND wnd_drag = nullptr;
    BOOL isShowingLayered = FALSE;
    if (IsThemeActive())
        GetIsShowingLayered(m_data_object, isShowingLayered);

    if (SUCCEEDED(GetDragWindow(m_data_object, wnd_drag)) && wnd_drag)
        PostMessage(wnd_drag, DDWM_UPDATEWINDOW, NULL, NULL);

    if (isShowingLayered) {
        if (!m_prev_is_showing_layered) {
            auto cursor = LoadCursor(nullptr, IDC_ARROW);
            SetCursor(cursor);
        }
        if (wnd_drag) {
            WPARAM wp = 1;
            if (dwEffect & DROPEFFECT_COPY)
                wp = 3;
            else if (dwEffect & DROPEFFECT_MOVE)
                wp = 2;
            else if (dwEffect & DROPEFFECT_LINK)
                wp = 4;

            PostMessage(wnd_drag, WM_USER + 2, wp, NULL);
        }
    }

    m_prev_is_showing_layered = isShowingLayered != 0;

    return isShowingLayered ? S_OK : DRAGDROP_S_USEDEFAULTCURSORS;
}

IDropSourceGeneric::IDropSourceGeneric(
    HWND wnd, IDataObject* pDataObj, DWORD initial_key_state, bool b_allowdropdescriptiontext, SHDRAGIMAGE* lpsdi)
    : m_refcount(0), m_initial_key_state(initial_key_state), m_prev_is_showing_layered(false), m_data_object(pDataObj)
{
    HRESULT hr;

    if (b_allowdropdescriptiontext) {
        if (SUCCEEDED(m_drag_source_helper.instantiate(CLSID_DragDropHelper, nullptr, CLSCTX_INPROC_SERVER))) {
            mmh::ComPtr<IDragSourceHelper2> pDragSourceHelper2 = m_drag_source_helper;
            if (pDragSourceHelper2.is_valid()) {
                hr = pDragSourceHelper2->SetFlags(DSH_ALLOWDROPDESCRIPTIONTEXT);
            }
            if (lpsdi) {
                hr = m_drag_source_helper->InitializeFromBitmap(lpsdi, pDataObj);
                if (FAILED(hr) && lpsdi->hbmpDragImage) {
                    DeleteObject(lpsdi->hbmpDragImage);
                    lpsdi->hbmpDragImage = nullptr;
                }
            } else
                hr = m_drag_source_helper->InitializeFromWindow(wnd, nullptr, pDataObj);
            if (IsThemeActive() && IsAppThemed()) {
                set_using_default_drag_image(pDataObj);
            }
        }
    }
}
} // namespace uih::ole
<|endoftext|>


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

#ifndef INCLUDED_SVLDLLAPI_H
#include "svtools/svldllapi.h"
#endif

#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#ifndef INCLUDED_SVTOOLS_OPTIONS_HXX
#include <svtools/options.hxx>
#endif

#define SVT_SEARCHPATH_DELIMITER      ';'

// class SvtPathOptions --------------------------------------------------

class SvtPathOptions_Impl;
class SVL_DLLPUBLIC SvtPathOptions: public svt::detail::Options
{
private:
    SvtPathOptions_Impl*    pImp;

public:
    enum Pathes
    {
        PATH_ADDIN,
        PATH_AUTOCORRECT,
        PATH_AUTOTEXT,
        PATH_BACKUP,
        PATH_BASIC,
        PATH_BITMAP,
        PATH_CONFIG,
        PATH_DICTIONARY,
        PATH_FAVORITES,
        PATH_FILTER,
        PATH_GALLERY,
        PATH_GRAPHIC,
        PATH_HELP,
        PATH_LINGUISTIC,
        PATH_MODULE,
        PATH_PALETTE,
        PATH_PLUGIN,
        PATH_STORAGE,
        PATH_TEMP,
        PATH_TEMPLATE,
        PATH_USERCONFIG,
        PATH_WORK,
        PATH_UICONFIG,
        PATH_FINGERPRINT,
        PATH_COUNT // should always be the last element
    };

    SvtPathOptions();
    virtual ~SvtPathOptions();

    // get the pathes, not const because of using a mutex
    const String&   GetAddinPath() const;
    const String&   GetAutoCorrectPath() const;
    const String&   GetAutoTextPath() const;
    const String&   GetBackupPath() const;
    const String&   GetBasicPath() const;
    const String&   GetBitmapPath() const;
    const String&   GetConfigPath() const;
    const String&   GetDictionaryPath() const;
    const String&   GetFavoritesPath() const;
    const String&   GetFilterPath() const;
    const String&   GetGalleryPath() const;
    const String&   GetGraphicPath() const;
    const String&   GetHelpPath() const;
    const String&   GetLinguisticPath() const;
    const String&   GetModulePath() const;
    const String&   GetPalettePath() const;
    const String&   GetPluginPath() const;
    const String&   GetStoragePath() const;
    const String&   GetTempPath() const;
    const String&   GetTemplatePath() const;
    const String&   GetUserConfigPath() const;
    const String&   GetWorkPath() const;
    const String&   GetUIConfigPath() const;
    const String&   GetFingerprintPath() const;

    BOOL            IsPathReadonly(Pathes ePath)const;
    const String&   GetPath(Pathes ePath) const;

    // set the pathes
    void            SetAddinPath( const String& rPath );
    void            SetAutoCorrectPath( const String& rPath );
    void            SetAutoTextPath( const String& rPath );
    void            SetBackupPath( const String& rPath );
    void            SetBasicPath( const String& rPath );
    void            SetBitmapPath( const String& rPath );
    void            SetConfigPath( const String& rPath );
    void            SetDictionaryPath( const String& rPath );
    void            SetFavoritesPath( const String& rPath );
    void            SetFilterPath( const String& rPath );
    void            SetGalleryPath( const String& rPath );
    void            SetGraphicPath( const String& rPath );
    void            SetHelpPath( const String& rPath );
    void            SetLinguisticPath( const String& rPath );
    void            SetModulePath( const String& rPath );
    void            SetPalettePath( const String& rPath );
    void            SetPluginPath( const String& rPath );
    void            SetStoragePath( const String& rPath );
    void            SetTempPath( const String& rPath );
    void            SetTemplatePath( const String& rPath );
    void            SetUserConfigPath( const String& rPath );
    void            SetWorkPath( const String& rPath );
    void            SetPath( SvtPathOptions::Pathes ePath, const String& rNewPath );

    String          SubstituteVariable( const String& rVar );
    String          UseVariable( const String& rVar );
    sal_Bool        SearchFile( String& rIniFile, Pathes ePath = PATH_USERCONFIG );
    ::com::sun::star::lang::Locale GetLocale() const;
    sal_Bool        IsReadonly() const;
};

#endif // #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.4.2); FILE MERGED 2008/04/01 15:44:33 thb 1.4.2.3: #i85898# Stripping all external header guards 2008/04/01 12:43:14 thb 1.4.2.2: #i85898# Stripping all external header guards 2008/03/31 13:01:07 rt 1.4.2.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: pathoptions.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#define INCLUDED_SVTOOLS_PATHOPTIONS_HXX

#include "svtools/svldllapi.h"
#include <tools/string.hxx>
#include <com/sun/star/lang/Locale.hpp>
#include <svtools/options.hxx>

#define SVT_SEARCHPATH_DELIMITER      ';'

// class SvtPathOptions --------------------------------------------------

class SvtPathOptions_Impl;
class SVL_DLLPUBLIC SvtPathOptions: public svt::detail::Options
{
private:
    SvtPathOptions_Impl*    pImp;

public:
    enum Pathes
    {
        PATH_ADDIN,
        PATH_AUTOCORRECT,
        PATH_AUTOTEXT,
        PATH_BACKUP,
        PATH_BASIC,
        PATH_BITMAP,
        PATH_CONFIG,
        PATH_DICTIONARY,
        PATH_FAVORITES,
        PATH_FILTER,
        PATH_GALLERY,
        PATH_GRAPHIC,
        PATH_HELP,
        PATH_LINGUISTIC,
        PATH_MODULE,
        PATH_PALETTE,
        PATH_PLUGIN,
        PATH_STORAGE,
        PATH_TEMP,
        PATH_TEMPLATE,
        PATH_USERCONFIG,
        PATH_WORK,
        PATH_UICONFIG,
        PATH_FINGERPRINT,
        PATH_COUNT // should always be the last element
    };

    SvtPathOptions();
    virtual ~SvtPathOptions();

    // get the pathes, not const because of using a mutex
    const String&   GetAddinPath() const;
    const String&   GetAutoCorrectPath() const;
    const String&   GetAutoTextPath() const;
    const String&   GetBackupPath() const;
    const String&   GetBasicPath() const;
    const String&   GetBitmapPath() const;
    const String&   GetConfigPath() const;
    const String&   GetDictionaryPath() const;
    const String&   GetFavoritesPath() const;
    const String&   GetFilterPath() const;
    const String&   GetGalleryPath() const;
    const String&   GetGraphicPath() const;
    const String&   GetHelpPath() const;
    const String&   GetLinguisticPath() const;
    const String&   GetModulePath() const;
    const String&   GetPalettePath() const;
    const String&   GetPluginPath() const;
    const String&   GetStoragePath() const;
    const String&   GetTempPath() const;
    const String&   GetTemplatePath() const;
    const String&   GetUserConfigPath() const;
    const String&   GetWorkPath() const;
    const String&   GetUIConfigPath() const;
    const String&   GetFingerprintPath() const;

    BOOL            IsPathReadonly(Pathes ePath)const;
    const String&   GetPath(Pathes ePath) const;

    // set the pathes
    void            SetAddinPath( const String& rPath );
    void            SetAutoCorrectPath( const String& rPath );
    void            SetAutoTextPath( const String& rPath );
    void            SetBackupPath( const String& rPath );
    void            SetBasicPath( const String& rPath );
    void            SetBitmapPath( const String& rPath );
    void            SetConfigPath( const String& rPath );
    void            SetDictionaryPath( const String& rPath );
    void            SetFavoritesPath( const String& rPath );
    void            SetFilterPath( const String& rPath );
    void            SetGalleryPath( const String& rPath );
    void            SetGraphicPath( const String& rPath );
    void            SetHelpPath( const String& rPath );
    void            SetLinguisticPath( const String& rPath );
    void            SetModulePath( const String& rPath );
    void            SetPalettePath( const String& rPath );
    void            SetPluginPath( const String& rPath );
    void            SetStoragePath( const String& rPath );
    void            SetTempPath( const String& rPath );
    void            SetTemplatePath( const String& rPath );
    void            SetUserConfigPath( const String& rPath );
    void            SetWorkPath( const String& rPath );
    void            SetPath( SvtPathOptions::Pathes ePath, const String& rNewPath );

    String          SubstituteVariable( const String& rVar );
    String          UseVariable( const String& rVar );
    sal_Bool        SearchFile( String& rIniFile, Pathes ePath = PATH_USERCONFIG );
    ::com::sun::star::lang::Locale GetLocale() const;
    sal_Bool        IsReadonly() const;
};

#endif // #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX

<|endoftext|>