<commit_before>/*************************************************************************
 *
 *  $RCSfile: fontcfg.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: os $ $Date: 2002-06-11 08:38:52 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _FONTCFG_HXX
#define _FONTCFG_HXX

#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _LANG_HXX
#include <tools/lang.hxx>
#endif

#define FONT_STANDARD       0
#define FONT_OUTLINE        1
#define FONT_LIST           2
#define FONT_CAPTION        3
#define FONT_INDEX          4
#define FONT_STANDARD_CJK   5
#define FONT_OUTLINE_CJK    6
#define FONT_LIST_CJK       7
#define FONT_CAPTION_CJK    8
#define FONT_INDEX_CJK      9
#define FONT_STANDARD_CTL   10
#define FONT_OUTLINE_CTL    11
#define FONT_LIST_CTL       12
#define FONT_CAPTION_CTL    13
#define FONT_INDEX_CTL      14
#define DEF_FONT_COUNT      15

#define FONT_PER_GROUP      5

#define FONT_GROUP_DEFAULT  0
#define FONT_GROUP_CJK      1
#define FONT_GROUP_CTL      2

class SwStdFontConfig : public utl::ConfigItem
{
    String      sDefaultFonts[DEF_FONT_COUNT];

    com::sun::star::uno::Sequence<rtl::OUString>    GetPropertyNames();

    void ChangeString(USHORT nFontType, const String& rSet)
        {
            if(sDefaultFonts[nFontType] != rSet)
            {
                SetModified();
                sDefaultFonts[nFontType] = rSet;
            }
        }
public:
    SwStdFontConfig();
    ~SwStdFontConfig();

    virtual void    Commit();

    const String&   GetFontStandard(sal_uInt8 nFontGroup) const {return sDefaultFonts[FONT_STANDARD + FONT_PER_GROUP * nFontGroup];}
    const String&   GetFontOutline(sal_uInt8 nFontGroup)  const {return sDefaultFonts[FONT_OUTLINE + FONT_PER_GROUP * nFontGroup];}
    const String&   GetFontList   (sal_uInt8 nFontGroup)  const {return sDefaultFonts[FONT_LIST + FONT_PER_GROUP * nFontGroup];}
    const String&   GetFontCaption(sal_uInt8 nFontGroup)  const {return sDefaultFonts[FONT_CAPTION + FONT_PER_GROUP * nFontGroup];}
    const String&   GetFontIndex  (sal_uInt8 nFontGroup)  const {return sDefaultFonts[FONT_INDEX + FONT_PER_GROUP * nFontGroup];}

    const String&   GetFontFor(USHORT nFontType)  const {return sDefaultFonts[nFontType];}
    BOOL            IsFontDefault(USHORT nFontType) const;

    void     SetFontStandard(const String& rSet, sal_uInt8 nFontGroup)
                    {ChangeString(FONT_STANDARD + FONT_PER_GROUP * nFontGroup, rSet);}

    void     SetFontOutline(const String& rSet, sal_uInt8 nFontGroup)
                    {    ChangeString(FONT_OUTLINE + FONT_PER_GROUP * nFontGroup, rSet);}
    void     SetFontList   (const String& rSet, sal_uInt8 nFontGroup)
                    {    ChangeString(FONT_LIST + FONT_PER_GROUP * nFontGroup, rSet);}
    void     SetFontCaption(const String& rSet, sal_uInt8 nFontGroup)
                    {    ChangeString(FONT_CAPTION + FONT_PER_GROUP * nFontGroup, rSet);}
    void     SetFontIndex  (const String& rSet, sal_uInt8 nFontGroup)
                    {    ChangeString(FONT_INDEX + FONT_PER_GROUP * nFontGroup, rSet);}

    static String   GetDefaultFor(USHORT nFontType, LanguageType eLang);
};
#endif

<commit_msg>INTEGRATION: CWS tune03 (1.4.750); FILE MERGED 2004/07/19 19:11:26 mhu 1.4.750.1: #i29979# Added SW_DLLPUBLIC/PRIVATE (see swdllapi.h) to exported symbols/classes.<commit_after>/*************************************************************************
 *
 *  $RCSfile: fontcfg.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2004-08-23 08:58:46 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _FONTCFG_HXX
#define _FONTCFG_HXX

#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _LANG_HXX
#include <tools/lang.hxx>
#endif

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif

#define FONT_STANDARD       0
#define FONT_OUTLINE        1
#define FONT_LIST           2
#define FONT_CAPTION        3
#define FONT_INDEX          4
#define FONT_STANDARD_CJK   5
#define FONT_OUTLINE_CJK    6
#define FONT_LIST_CJK       7
#define FONT_CAPTION_CJK    8
#define FONT_INDEX_CJK      9
#define FONT_STANDARD_CTL   10
#define FONT_OUTLINE_CTL    11
#define FONT_LIST_CTL       12
#define FONT_CAPTION_CTL    13
#define FONT_INDEX_CTL      14
#define DEF_FONT_COUNT      15

#define FONT_PER_GROUP      5

#define FONT_GROUP_DEFAULT  0
#define FONT_GROUP_CJK      1
#define FONT_GROUP_CTL      2

class SW_DLLPUBLIC SwStdFontConfig : public utl::ConfigItem
{
    String      sDefaultFonts[DEF_FONT_COUNT];

    SW_DLLPRIVATE com::sun::star::uno::Sequence<rtl::OUString>    GetPropertyNames();

    void ChangeString(USHORT nFontType, const String& rSet)
        {
            if(sDefaultFonts[nFontType] != rSet)
            {
                SetModified();
                sDefaultFonts[nFontType] = rSet;
            }
        }
public:
    SwStdFontConfig();
    ~SwStdFontConfig();

    virtual void    Commit();

    const String&   GetFontStandard(sal_uInt8 nFontGroup) const {return sDefaultFonts[FONT_STANDARD + FONT_PER_GROUP * nFontGroup];}
    const String&   GetFontOutline(sal_uInt8 nFontGroup)  const {return sDefaultFonts[FONT_OUTLINE + FONT_PER_GROUP * nFontGroup];}
    const String&   GetFontList   (sal_uInt8 nFontGroup)  const {return sDefaultFonts[FONT_LIST + FONT_PER_GROUP * nFontGroup];}
    const String&   GetFontCaption(sal_uInt8 nFontGroup)  const {return sDefaultFonts[FONT_CAPTION + FONT_PER_GROUP * nFontGroup];}
    const String&   GetFontIndex  (sal_uInt8 nFontGroup)  const {return sDefaultFonts[FONT_INDEX + FONT_PER_GROUP * nFontGroup];}

    const String&   GetFontFor(USHORT nFontType)  const {return sDefaultFonts[nFontType];}
    BOOL            IsFontDefault(USHORT nFontType) const;

    void     SetFontStandard(const String& rSet, sal_uInt8 nFontGroup)
                    {ChangeString(FONT_STANDARD + FONT_PER_GROUP * nFontGroup, rSet);}

    void     SetFontOutline(const String& rSet, sal_uInt8 nFontGroup)
                    {    ChangeString(FONT_OUTLINE + FONT_PER_GROUP * nFontGroup, rSet);}
    void     SetFontList   (const String& rSet, sal_uInt8 nFontGroup)
                    {    ChangeString(FONT_LIST + FONT_PER_GROUP * nFontGroup, rSet);}
    void     SetFontCaption(const String& rSet, sal_uInt8 nFontGroup)
                    {    ChangeString(FONT_CAPTION + FONT_PER_GROUP * nFontGroup, rSet);}
    void     SetFontIndex  (const String& rSet, sal_uInt8 nFontGroup)
                    {    ChangeString(FONT_INDEX + FONT_PER_GROUP * nFontGroup, rSet);}

    static String   GetDefaultFor(USHORT nFontType, LanguageType eLang);
};
#endif

<|endoftext|>


<commit_before>#include "./window.h"
#include <QOpenGLContext>
#include <QDebug>
#include <QCoreApplication>
#include <QKeyEvent>
#include <QStateMachine>
#include <QAbstractState>
#include <QAbstractTransition>
#include <iostream>
#include "./graphics/gl.h"
#include "./abstract_scene.h"

Window::Window(std::shared_ptr<AbstractScene> scene, QWindow *parent)
  : QQuickView(parent), scene(scene)
{
  setClearBeforeRendering(false);

  connect(this, SIGNAL(widthChanged(int)), this, SLOT(resizeOpenGL()));
  connect(this, SIGNAL(heightChanged(int)), this, SLOT(resizeOpenGL()));

  connect(reinterpret_cast<QObject *>(engine()), SIGNAL(quit()), this,
          SLOT(close()));

  connect(this, SIGNAL(beforeRendering()), this, SLOT(render()),
          Qt::DirectConnection);

  auto format = createSurfaceFormat();
  setFormat(format);

  timer.start();
}

Window::~Window()
{
  delete gl;
}

QSurfaceFormat Window::createSurfaceFormat()
{
  QSurfaceFormat format;
  format.setDepthBufferSize(24);
  format.setMajorVersion(4);
  format.setMinorVersion(3);
  format.setSamples(4);

  return format;
}

void Window::initializeOpenGL()
{
  context = openglContext();
  gl = new Graphics::Gl();
  gl->initialize(context, size());

  glAssert(gl->glDisable(GL_CULL_FACE));
  glAssert(gl->glDisable(GL_DEPTH_TEST));
  glAssert(gl->glDisable(GL_STENCIL_TEST));
  glAssert(gl->glDisable(GL_BLEND));
  glAssert(gl->glDepthMask(GL_FALSE));
  // gl->glEnable(GL_DEPTH_TEST);
  // gl->glEnable(GL_BLEND);
  // gl->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}

void Window::keyReleaseEvent(QKeyEvent *event)
{
  QQuickView::keyReleaseEvent(event);
  keysPressed -= static_cast<Qt::Key>(event->key());
}

void Window::keyPressEvent(QKeyEvent *event)
{
  QQuickView::keyPressEvent(event);
  keysPressed += static_cast<Qt::Key>(event->key());
}

void Window::handleLazyInitialization()
{
  static bool initialized = false;
  if (!initialized)
  {
    initializeOpenGL();

    scene->setContext(context, gl);
    scene->resize(size().width(), size().height());
    scene->initialize();
    initialized = true;
  }
}

void Window::render()
{
  handleLazyInitialization();

  update();
  scene->render();

  // Use to check for missing release calls
  // resetOpenGLState();

  QQuickView::update();
}

void Window::resizeOpenGL()
{
  if (!gl)
    return;

  scene->resize(width(), height());
  gl->setSize(this->size());
}

void Window::update()
{
  double frameTime = timer.restart() / 1000.0;
  updateAverageFrameTime(frameTime);

  scene->update(frameTime, keysPressed);
}

void Window::toggleFullscreen()
{
  setVisibility(visibility() == QWindow::Windowed ? QWindow::FullScreen
                                                  : QWindow::Windowed);
}

void Window::updateAverageFrameTime(double frameTime)
{
  runningTime += frameTime;
  ++framesInSecond;

  if (runningTime > 1.0)
  {
    avgFrameTime = runningTime / framesInSecond;
    emit averageFrameTimeUpdated();

    framesInSecond = 0;
    runningTime = 0;
  }
}

<commit_msg>Disable multi sampling for now. Fixes #47.<commit_after>#include "./window.h"
#include <QOpenGLContext>
#include <QDebug>
#include <QCoreApplication>
#include <QKeyEvent>
#include <QStateMachine>
#include <QAbstractState>
#include <QAbstractTransition>
#include <iostream>
#include "./graphics/gl.h"
#include "./abstract_scene.h"

Window::Window(std::shared_ptr<AbstractScene> scene, QWindow *parent)
  : QQuickView(parent), scene(scene)
{
  setClearBeforeRendering(false);

  connect(this, SIGNAL(widthChanged(int)), this, SLOT(resizeOpenGL()));
  connect(this, SIGNAL(heightChanged(int)), this, SLOT(resizeOpenGL()));

  connect(reinterpret_cast<QObject *>(engine()), SIGNAL(quit()), this,
          SLOT(close()));

  connect(this, SIGNAL(beforeRendering()), this, SLOT(render()),
          Qt::DirectConnection);

  auto format = createSurfaceFormat();
  setFormat(format);

  timer.start();
}

Window::~Window()
{
  delete gl;
}

QSurfaceFormat Window::createSurfaceFormat()
{
  QSurfaceFormat format;
  format.setDepthBufferSize(24);
  format.setMajorVersion(4);
  format.setMinorVersion(3);
  // format.setSamples(4);

  return format;
}

void Window::initializeOpenGL()
{
  context = openglContext();
  gl = new Graphics::Gl();
  gl->initialize(context, size());

  glAssert(gl->glDisable(GL_CULL_FACE));
  glAssert(gl->glDisable(GL_DEPTH_TEST));
  glAssert(gl->glDisable(GL_STENCIL_TEST));
  glAssert(gl->glDisable(GL_BLEND));
  glAssert(gl->glDepthMask(GL_FALSE));
  // gl->glEnable(GL_DEPTH_TEST);
  // gl->glEnable(GL_BLEND);
  // gl->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}

void Window::keyReleaseEvent(QKeyEvent *event)
{
  QQuickView::keyReleaseEvent(event);
  keysPressed -= static_cast<Qt::Key>(event->key());
}

void Window::keyPressEvent(QKeyEvent *event)
{
  QQuickView::keyPressEvent(event);
  keysPressed += static_cast<Qt::Key>(event->key());
}

void Window::handleLazyInitialization()
{
  static bool initialized = false;
  if (!initialized)
  {
    initializeOpenGL();

    scene->setContext(context, gl);
    scene->resize(size().width(), size().height());
    scene->initialize();
    initialized = true;
  }
}

void Window::render()
{
  handleLazyInitialization();

  update();
  scene->render();

  // Use to check for missing release calls
  // resetOpenGLState();

  QQuickView::update();
}

void Window::resizeOpenGL()
{
  if (!gl)
    return;

  scene->resize(width(), height());
  gl->setSize(this->size());
}

void Window::update()
{
  double frameTime = timer.restart() / 1000.0;
  updateAverageFrameTime(frameTime);

  scene->update(frameTime, keysPressed);
}

void Window::toggleFullscreen()
{
  setVisibility(visibility() == QWindow::Windowed ? QWindow::FullScreen
                                                  : QWindow::Windowed);
}

void Window::updateAverageFrameTime(double frameTime)
{
  runningTime += frameTime;
  ++framesInSecond;

  if (runningTime > 1.0)
  {
    avgFrameTime = runningTime / framesInSecond;
    emit averageFrameTimeUpdated();

    framesInSecond = 0;
    runningTime = 0;
  }
}

<|endoftext|>


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

#include <csignal>
#include <cstring>
#include <string>
#include <memory>
#include <cerrno>

#include <unistd.h>

#include <linenoise.h>

#include <ydsh/ydsh.h>
#include "misc/unicode.hpp"

static DSState *state;

struct Deleter {
    void operator()(char *ptr) {
        free(ptr);
    }
};

using StrWrapper = std::unique_ptr<char, Deleter>;

/**
 * line is not nullptr
 */
static bool isSkipLine(const StrWrapper &line) {
    const char *ptr = line.get();
    for(int i = 0; ptr[i] != '\0'; i++) {
        switch(ptr[i]) {
        case ' ':
        case '\t':
        case '\r':
        case '\n':
            break;
        default:
            return false;
        }
    }
    return true;
}

/**
 * line is not nullptr
 */
static bool checkLineContinuation(const StrWrapper &line) {
    const char *ptr = line.get();
    for(unsigned int i = 0; ptr[i] != '\0'; i++) {
        if(ptr[i] == '\\' && ptr[i + 1] == '\0') {
            return true;
        }
    }
    return false;
}

static const std::string *lineBuf = nullptr;

static bool readLine(std::string &line) {
    line.clear();
    lineBuf = &line;
    DSState_syncHistorySize(state);

    bool continuation = false;
    while(true) {
        errno = 0;
        auto str = StrWrapper(linenoise(DSState_prompt(state, continuation ? 2 : 1)));
        if(str == nullptr) {
            if(errno == EAGAIN) {
                continuation = false;
                line.clear();
                continue;
            }
            return false;
        }

        if(isSkipLine(str)) {
            continue;
        }
        line += str.get();
        continuation = checkLineContinuation(str);
        if(continuation) {
            line.pop_back(); // remove '\\'
            continue;
        }
        break;
    }

    DSState_addHistory(state, line.c_str());
    line += '\n';    // terminate newline
    return true;
}

// for linenoise encoding function
using namespace ydsh;

static std::size_t prevUtf8CharLen(const char *buf, int pos) {
    int end = pos--;
    while(pos >= 0 && ((unsigned char)buf[pos] & 0xC0) == 0x80) {
        pos--;
    }
    return end - pos;
}

static std::size_t encoding_nextCharLen(const char *buf, std::size_t bufSize,
                                        std::size_t pos, std::size_t *columSize) {
    std::size_t startPos = pos;
    const char *limit = buf + bufSize;
    int codePoint = 0;
    unsigned int byteSize = UnicodeUtil::utf8ToCodePoint(buf + pos, limit, codePoint);
    int width = UnicodeUtil::localeAwareWidth(codePoint);
    if(width < 1) {
        return 0;
    }

    if(columSize != nullptr) {
        *columSize = width;
    }
    pos += byteSize;

    // skip next combining character
    while(pos < bufSize) {
        byteSize = UnicodeUtil::utf8ToCodePoint(buf + pos, limit, codePoint);
        if(UnicodeUtil::localeAwareWidth(codePoint) > 0) {
            break;
        }
        pos += byteSize;
    }
    return pos - startPos;
}

static std::size_t encoding_prevCharLen(const char *buf, std::size_t,
                                        std::size_t pos, std::size_t *columSize) {
    std::size_t end = pos;
    while (pos > 0) {
        std::size_t len = prevUtf8CharLen(buf, pos);
        pos -= len;
        int codePoint = UnicodeUtil::utf8ToCodePoint(buf + pos, len);
        int width = UnicodeUtil::localeAwareWidth(codePoint);
        if(width > 0) {
            if(columSize != nullptr) {
                *columSize = width;
            }
            return end - pos;
        }
    }
    return 0;
}

static std::size_t encoding_readCode(int fd, char *buf, std::size_t bufSize, int *codePoint) {
    if(bufSize < 1) {
        return -1;
    }

    int readSize = read(fd, &buf[0], 1);
    if(readSize <= 0) {
        return readSize;
    }

    unsigned int byteSize = UnicodeUtil::utf8ByteSize(buf[0]);
    if(byteSize < 1 || byteSize > 4) {
        return -1;
    }

    if(byteSize > 1) {
        if(bufSize < byteSize) {
            return -1;
        }
        readSize = read(fd, &buf[1], byteSize - 1);
        if(readSize <= 0) {
            return readSize;
        }
    }
    return UnicodeUtil::utf8ToCodePoint(buf, bufSize, *codePoint);
}

static std::size_t encoding_strLen(const char *str) {
    unsigned int size = 0;
    const char *end = str + strlen(str);
    for(const char *ptr = str; ptr != end;) {
        int codePoint = 0;
        unsigned int b = UnicodeUtil::utf8ToCodePoint(ptr, end, codePoint);
        if(codePoint < 0) {
            return strlen(str);
        }
        int codeSize = UnicodeUtil::localeAwareWidth(codePoint);
        size += codeSize < 0 ? 0 : codeSize;
        ptr += b;
    }
    return size;
}

static void completeCallback(const char *buf, size_t cursor, linenoiseCompletions *lc) {
    std::string actualBuf(*lineBuf);
    size_t actualCursor = actualBuf.size() + cursor;
    actualBuf += buf;
    actualBuf += '\n';

    auto *c = DSState_complete(state, actualBuf.c_str(), actualCursor);
    lc->len = DSCandidates_size(c);
    lc->cvec = static_cast<char**>(malloc(sizeof(char *) * lc->len));
    for(unsigned int i = 0; i < lc->len; i++) {
        lc->cvec[i] = strdup(DSCandidates_get(c, i));
    }
    DSCandidates_release(&c);
}

static const char *historyCallback(const char *buf, int *historyIndex, historyOp op) {
    const unsigned int size = DSState_history(state)->size;
    switch(op) {
    case LINENOISE_HISTORY_OP_NEXT:
    case LINENOISE_HISTORY_OP_PREV: {
        if(size > 1) {
            DSState_setHistoryAt(state, size - *historyIndex - 1, buf);
            *historyIndex += (op == LINENOISE_HISTORY_OP_PREV) ? 1 : -1;
            if(*historyIndex < 0) {
                *historyIndex = 0;
                return nullptr;
            }
            if(static_cast<unsigned int>(*historyIndex) >= size) {
                *historyIndex = size - 1;
                return nullptr;
            }
            return DSState_history(state)->data[size - *historyIndex - 1];
        }
        break;
    }
    case LINENOISE_HISTORY_OP_DELETE:
        DSState_deleteHistoryAt(state, size - 1);
        break;
    case LINENOISE_HISTORY_OP_INIT:
        DSState_addHistory(state, "");
        break;
    }
    return nullptr;
}

/**
 * after execution, delete ctx
 */
int exec_interactive(DSState *dsState) {
    *linenoiseInputFD() = dup(STDIN_FILENO);
    *linenoiseOutputFD() = dup(STDOUT_FILENO);
    *linenoiseErrorFD() = dup(STDERR_FILENO);

    linenoiseSetEncodingFunctions(
            encoding_prevCharLen,
            encoding_nextCharLen,
            encoding_readCode,
            encoding_strLen);

    linenoiseSetCompletionCallback(completeCallback);

    linenoiseSetHistoryCallback(historyCallback);

    DSState_setOption(dsState, DS_OPTION_TOPLEVEL | DS_OPTION_HISTORY | DS_OPTION_JOB_CONTROL | DS_OPTION_INTERACTIVE);
    DSState_syncHistorySize(dsState);
    DSState_loadHistory(dsState, nullptr);
    state = dsState;

    int status = 0;
    for(std::string line; readLine(line);) {
        DSError e{};
        status = DSState_eval(dsState, nullptr, line.c_str(), line.size(), &e);
        if(e.kind == DS_ERROR_KIND_EXIT || e.kind == DS_ERROR_KIND_ASSERTION_ERROR) {
            break;
        }
    }
    DSState_saveHistory(dsState, nullptr);
    return status;
}

<commit_msg>add missing header<commit_after>/*
 * Copyright (C) 2015-2017 Nagisa Sekiguchi
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <csignal>
#include <cstring>
#include <string>
#include <memory>
#include <cerrno>
#include <cstdlib>

#include <unistd.h>

#include <linenoise.h>

#include <ydsh/ydsh.h>
#include "misc/unicode.hpp"

static DSState *state;

struct Deleter {
    void operator()(char *ptr) {
        free(ptr);
    }
};

using StrWrapper = std::unique_ptr<char, Deleter>;

/**
 * line is not nullptr
 */
static bool isSkipLine(const StrWrapper &line) {
    const char *ptr = line.get();
    for(int i = 0; ptr[i] != '\0'; i++) {
        switch(ptr[i]) {
        case ' ':
        case '\t':
        case '\r':
        case '\n':
            break;
        default:
            return false;
        }
    }
    return true;
}

/**
 * line is not nullptr
 */
static bool checkLineContinuation(const StrWrapper &line) {
    const char *ptr = line.get();
    for(unsigned int i = 0; ptr[i] != '\0'; i++) {
        if(ptr[i] == '\\' && ptr[i + 1] == '\0') {
            return true;
        }
    }
    return false;
}

static const std::string *lineBuf = nullptr;

static bool readLine(std::string &line) {
    line.clear();
    lineBuf = &line;
    DSState_syncHistorySize(state);

    bool continuation = false;
    while(true) {
        errno = 0;
        auto str = StrWrapper(linenoise(DSState_prompt(state, continuation ? 2 : 1)));
        if(str == nullptr) {
            if(errno == EAGAIN) {
                continuation = false;
                line.clear();
                continue;
            }
            return false;
        }

        if(isSkipLine(str)) {
            continue;
        }
        line += str.get();
        continuation = checkLineContinuation(str);
        if(continuation) {
            line.pop_back(); // remove '\\'
            continue;
        }
        break;
    }

    DSState_addHistory(state, line.c_str());
    line += '\n';    // terminate newline
    return true;
}

// for linenoise encoding function
using namespace ydsh;

static std::size_t prevUtf8CharLen(const char *buf, int pos) {
    int end = pos--;
    while(pos >= 0 && ((unsigned char)buf[pos] & 0xC0) == 0x80) {
        pos--;
    }
    return end - pos;
}

static std::size_t encoding_nextCharLen(const char *buf, std::size_t bufSize,
                                        std::size_t pos, std::size_t *columSize) {
    std::size_t startPos = pos;
    const char *limit = buf + bufSize;
    int codePoint = 0;
    unsigned int byteSize = UnicodeUtil::utf8ToCodePoint(buf + pos, limit, codePoint);
    int width = UnicodeUtil::localeAwareWidth(codePoint);
    if(width < 1) {
        return 0;
    }

    if(columSize != nullptr) {
        *columSize = width;
    }
    pos += byteSize;

    // skip next combining character
    while(pos < bufSize) {
        byteSize = UnicodeUtil::utf8ToCodePoint(buf + pos, limit, codePoint);
        if(UnicodeUtil::localeAwareWidth(codePoint) > 0) {
            break;
        }
        pos += byteSize;
    }
    return pos - startPos;
}

static std::size_t encoding_prevCharLen(const char *buf, std::size_t,
                                        std::size_t pos, std::size_t *columSize) {
    std::size_t end = pos;
    while (pos > 0) {
        std::size_t len = prevUtf8CharLen(buf, pos);
        pos -= len;
        int codePoint = UnicodeUtil::utf8ToCodePoint(buf + pos, len);
        int width = UnicodeUtil::localeAwareWidth(codePoint);
        if(width > 0) {
            if(columSize != nullptr) {
                *columSize = width;
            }
            return end - pos;
        }
    }
    return 0;
}

static std::size_t encoding_readCode(int fd, char *buf, std::size_t bufSize, int *codePoint) {
    if(bufSize < 1) {
        return -1;
    }

    int readSize = read(fd, &buf[0], 1);
    if(readSize <= 0) {
        return readSize;
    }

    unsigned int byteSize = UnicodeUtil::utf8ByteSize(buf[0]);
    if(byteSize < 1 || byteSize > 4) {
        return -1;
    }

    if(byteSize > 1) {
        if(bufSize < byteSize) {
            return -1;
        }
        readSize = read(fd, &buf[1], byteSize - 1);
        if(readSize <= 0) {
            return readSize;
        }
    }
    return UnicodeUtil::utf8ToCodePoint(buf, bufSize, *codePoint);
}

static std::size_t encoding_strLen(const char *str) {
    unsigned int size = 0;
    const char *end = str + strlen(str);
    for(const char *ptr = str; ptr != end;) {
        int codePoint = 0;
        unsigned int b = UnicodeUtil::utf8ToCodePoint(ptr, end, codePoint);
        if(codePoint < 0) {
            return strlen(str);
        }
        int codeSize = UnicodeUtil::localeAwareWidth(codePoint);
        size += codeSize < 0 ? 0 : codeSize;
        ptr += b;
    }
    return size;
}

static void completeCallback(const char *buf, size_t cursor, linenoiseCompletions *lc) {
    std::string actualBuf(*lineBuf);
    size_t actualCursor = actualBuf.size() + cursor;
    actualBuf += buf;
    actualBuf += '\n';

    auto *c = DSState_complete(state, actualBuf.c_str(), actualCursor);
    lc->len = DSCandidates_size(c);
    lc->cvec = static_cast<char**>(malloc(sizeof(char *) * lc->len));
    for(unsigned int i = 0; i < lc->len; i++) {
        lc->cvec[i] = strdup(DSCandidates_get(c, i));
    }
    DSCandidates_release(&c);
}

static const char *historyCallback(const char *buf, int *historyIndex, historyOp op) {
    const unsigned int size = DSState_history(state)->size;
    switch(op) {
    case LINENOISE_HISTORY_OP_NEXT:
    case LINENOISE_HISTORY_OP_PREV: {
        if(size > 1) {
            DSState_setHistoryAt(state, size - *historyIndex - 1, buf);
            *historyIndex += (op == LINENOISE_HISTORY_OP_PREV) ? 1 : -1;
            if(*historyIndex < 0) {
                *historyIndex = 0;
                return nullptr;
            }
            if(static_cast<unsigned int>(*historyIndex) >= size) {
                *historyIndex = size - 1;
                return nullptr;
            }
            return DSState_history(state)->data[size - *historyIndex - 1];
        }
        break;
    }
    case LINENOISE_HISTORY_OP_DELETE:
        DSState_deleteHistoryAt(state, size - 1);
        break;
    case LINENOISE_HISTORY_OP_INIT:
        DSState_addHistory(state, "");
        break;
    }
    return nullptr;
}

/**
 * after execution, delete ctx
 */
int exec_interactive(DSState *dsState) {
    *linenoiseInputFD() = dup(STDIN_FILENO);
    *linenoiseOutputFD() = dup(STDOUT_FILENO);
    *linenoiseErrorFD() = dup(STDERR_FILENO);

    linenoiseSetEncodingFunctions(
            encoding_prevCharLen,
            encoding_nextCharLen,
            encoding_readCode,
            encoding_strLen);

    linenoiseSetCompletionCallback(completeCallback);

    linenoiseSetHistoryCallback(historyCallback);

    DSState_setOption(dsState, DS_OPTION_TOPLEVEL | DS_OPTION_HISTORY | DS_OPTION_JOB_CONTROL | DS_OPTION_INTERACTIVE);
    DSState_syncHistorySize(dsState);
    DSState_loadHistory(dsState, nullptr);
    state = dsState;

    int status = 0;
    for(std::string line; readLine(line);) {
        DSError e{};
        status = DSState_eval(dsState, nullptr, line.c_str(), line.size(), &e);
        if(e.kind == DS_ERROR_KIND_EXIT || e.kind == DS_ERROR_KIND_ASSERTION_ERROR) {
            break;
        }
    }
    DSState_saveHistory(dsState, nullptr);
    return status;
}

<|endoftext|>


<commit_before>/*
  This class sets up a common interface for dealing with Orreries.

  It provides a uniform interface where by
    - We can load Orrery model(s) from disk
    - Obtain a list of GM and (x, y, z) data for all bodies in the Orrery
      at a given time point

  It packages loading Orrery files (like SPK files) and getting gravitational
  body locations into one interface.
*/
#include <string>
#include <vector>

#include "vector.hpp"

namespace orrery {

struct OrreryBody {
    std::string name;
    float       GM; // GM value for body
    sim::Vector pos; // Position referenced to solar system barycenter
    float       r; // Radius of body (for collision tests)
};

typedef std::vector<OrreryBody> OrreryBodyVec;

class Orrery {

protected:
    bool          ok;
    OrreryBodyVec bodies;

public:
    Orrery() { ok = false; }
    bool is_ok() { return ok; }

    // Given a model file path, load this orrery file
    // Return false if an error occurs while loading the file
    virtual bool load_orrery_model(std::string fname) = 0;

    // Fill out the (x, y, z) of each Orrery body and return us an immutable
    // vector containing this information.
    virtual const OrreryBodyVec& get_orrery_at(double jd) = 0;
};
}<commit_msg>need #pragma once<commit_after>/*
  This class sets up a common interface for dealing with Orreries.

  It provides a uniform interface where by
    - We can load Orrery model(s) from disk
    - Obtain a list of GM and (x, y, z) data for all bodies in the Orrery
      at a given time point
*/
#pragma once

#include <string>
#include <vector>

#include "vector.hpp"

namespace orrery {

struct OrreryBody {
    std::string name;
    float       GM;  // GM value for body
    sim::Vector pos; // Position referenced to solar system barycenter
    float       r;   // Radius of body (for collision tests)
};

typedef std::vector<OrreryBody> OrreryBodyVec;

class Orrery {

protected:
    bool          ok;
    OrreryBodyVec bodies;

public:
    Orrery() { ok = false; }
    bool is_ok() { return ok; }

    // Given a model file path, load this orrery file
    // Return false if an error occurs while loading the file
    virtual bool load_orrery_model(std::string fname) = 0;

    // Fill out the (x, y, z) of each Orrery body and return us an immutable
    // vector containing this information.
    virtual const OrreryBodyVec& get_orrery_at(double jd) = 0;
};
}<|endoftext|>


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

#include "util/numeric/int128.h"

#include "base/macros.h"
#include "gtest/gtest.h"

namespace crashpad {
namespace test {
namespace {

TEST(Int128, UInt128) {
#if defined(ARCH_CPU_LITTLE_ENDIAN)
  const uint8_t kBytes[] =
      {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
#else
  const uint8_t kBytes[] =
      {15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
#endif

  uint128_struct uint128;
  static_assert(sizeof(uint128) == sizeof(kBytes), "sizes must be equal");

  uint128 = bit_cast<uint128_struct>(kBytes);

  EXPECT_EQ(0x0706050403020100u, uint128.lo);
  EXPECT_EQ(0x0f0e0d0c0b0a0908u, uint128.hi);
}

}  // namespace
}  // namespace test
}  // namespace crashpad
<commit_msg>Update to use base/bit_cast.h to follow to follow https://codereview.chromium.org/399313006<commit_after>// Copyright 2014 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "util/numeric/int128.h"

#include "base/bit_cast.h"
#include "gtest/gtest.h"

namespace crashpad {
namespace test {
namespace {

TEST(Int128, UInt128) {
#if defined(ARCH_CPU_LITTLE_ENDIAN)
  const uint8_t kBytes[] =
      {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
#else
  const uint8_t kBytes[] =
      {15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
#endif

  uint128_struct uint128;
  static_assert(sizeof(uint128) == sizeof(kBytes), "sizes must be equal");

  uint128 = bit_cast<uint128_struct>(kBytes);

  EXPECT_EQ(0x0706050403020100u, uint128.lo);
  EXPECT_EQ(0x0f0e0d0c0b0a0908u, uint128.hi);
}

}  // namespace
}  // namespace test
}  // namespace crashpad
<|endoftext|>


<commit_before>/* -*- c++ -*- */
/*
 * Copyright © 2010 Intel Corporation
 *
 * 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 (including the next
 * paragraph) 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.
 */

#include "glsl_symbol_table.h"

class symbol_table_entry {
public:
   /* Callers of this ralloc-based new need not call delete. It's
    * easier to just ralloc_free 'ctx' (or any of its ancestors). */
   static void* operator new(size_t size, void *ctx)
   {
      void *entry = ralloc_size(ctx, size);
      assert(entry != NULL);
      return entry;
   }

   /* If the user *does* call delete, that's OK, we will just ralloc_free. */
   static void operator delete(void *entry)
   {
      ralloc_free(entry);
   }

   bool add_interface(const glsl_type *i, enum ir_variable_mode mode)
   {
      const glsl_type **dest;

      switch (mode) {
      case ir_var_uniform:
         dest = &ibu;
         break;
      case ir_var_shader_in:
         dest = &ibi;
         break;
      case ir_var_shader_out:
         dest = &ibo;
         break;
      default:
         assert(!"Unsupported interface variable mode!");
         return false;
      }

      if (*dest != NULL) {
         return false;
      } else {
         *dest = i;
         return true;
      }
   }

   const glsl_type *get_interface(enum ir_variable_mode mode)
   {
      switch (mode) {
      case ir_var_uniform:
         return ibu;
      case ir_var_shader_in:
         return ibi;
      case ir_var_shader_out:
         return ibo;
      default:
         assert(!"Unsupported interface variable mode!");
         return NULL;
      }
   }

   symbol_table_entry(ir_variable *v)               :
      v(v), f(0), t(0), ibu(0), ibi(0), ibo(0), a(0) {}
   symbol_table_entry(ir_function *f)               :
      v(0), f(f), t(0), ibu(0), ibi(0), ibo(0), a(0) {}
   symbol_table_entry(const glsl_type *t)           :
      v(0), f(0), t(t), ibu(0), ibi(0), ibo(0), a(0) {}
   symbol_table_entry(const glsl_type *t, enum ir_variable_mode mode) :
      v(0), f(0), t(0), ibu(0), ibi(0), ibo(0), a(0)
   {
      assert(t->is_interface());
      add_interface(t, mode);
   }
   symbol_table_entry(const class ast_type_specifier *a):
      v(0), f(0), t(0), ibu(0), ibi(0), ibo(0), a(a) {}

   ir_variable *v;
   ir_function *f;
   const glsl_type *t;
   const glsl_type *ibu;
   const glsl_type *ibi;
   const glsl_type *ibo;
   const class ast_type_specifier *a;
};

glsl_symbol_table::glsl_symbol_table()
{
   this->separate_function_namespace = false;
   this->table = _mesa_symbol_table_ctor();
   this->mem_ctx = ralloc_context(NULL);
}

glsl_symbol_table::~glsl_symbol_table()
{
   _mesa_symbol_table_dtor(table);
   ralloc_free(mem_ctx);
}

void glsl_symbol_table::push_scope()
{
   _mesa_symbol_table_push_scope(table);
}

void glsl_symbol_table::pop_scope()
{
   _mesa_symbol_table_pop_scope(table);
}

bool glsl_symbol_table::name_declared_this_scope(const char *name)
{
   return _mesa_symbol_table_symbol_scope(table, -1, name) == 0;
}

bool glsl_symbol_table::add_variable(ir_variable *v)
{
   if (this->separate_function_namespace) {
      /* In 1.10, functions and variables have separate namespaces. */
      symbol_table_entry *existing = get_entry(v->name);
      if (name_declared_this_scope(v->name)) {
	 /* If there's already an existing function (not a constructor!) in
	  * the current scope, just update the existing entry to include 'v'.
	  */
	 if (existing->v == NULL && existing->t == NULL) {
	    existing->v = v;
	    return true;
	 }
      } else {
	 /* If not declared at this scope, add a new entry.  But if an existing
	  * entry includes a function, propagate that to this block - otherwise
	  * the new variable declaration would shadow the function.
	  */
	 symbol_table_entry *entry = new(mem_ctx) symbol_table_entry(v);
	 if (existing != NULL)
	    entry->f = existing->f;
	 int added = _mesa_symbol_table_add_symbol(table, -1, v->name, entry);
	 assert(added == 0);
	 (void)added;
	 return true;
      }
      return false;
   }

   /* 1.20+ rules: */
   symbol_table_entry *entry = new(mem_ctx) symbol_table_entry(v);
   return _mesa_symbol_table_add_symbol(table, -1, v->name, entry) == 0;
}

bool glsl_symbol_table::add_type(const char *name, const glsl_type *t)
{
   symbol_table_entry *entry = new(mem_ctx) symbol_table_entry(t);
   return _mesa_symbol_table_add_symbol(table, -1, name, entry) == 0;
}

bool glsl_symbol_table::add_type_ast(const char *name, const class ast_type_specifier *a)
{
   symbol_table_entry *entry = new(mem_ctx) symbol_table_entry(a);
   char ast_name[strlen("#ast.") + strlen(name) + 1];
   strcpy(ast_name, "#ast.");
   strcat(ast_name + strlen("#ast."), name);
   return _mesa_symbol_table_add_symbol(table, -1, ast_name, entry) == 0;
}

bool glsl_symbol_table::add_interface(const char *name, const glsl_type *i,
                                      enum ir_variable_mode mode)
{
   assert(i->is_interface());
   symbol_table_entry *entry = get_entry(name);
   if (entry == NULL) {
      symbol_table_entry *entry =
         new(mem_ctx) symbol_table_entry(i, mode);
      bool add_interface_symbol_result =
         _mesa_symbol_table_add_symbol(table, -1, name, entry) == 0;
      assert(add_interface_symbol_result);
      return add_interface_symbol_result;
   } else {
      return entry->add_interface(i, mode);
   }
}

bool glsl_symbol_table::add_function(ir_function *f)
{
   if (this->separate_function_namespace && name_declared_this_scope(f->name)) {
      /* In 1.10, functions and variables have separate namespaces. */
      symbol_table_entry *existing = get_entry(f->name);
      if ((existing->f == NULL) && (existing->t == NULL)) {
	 existing->f = f;
	 return true;
      }
   }
   symbol_table_entry *entry = new(mem_ctx) symbol_table_entry(f);
   return _mesa_symbol_table_add_symbol(table, -1, f->name, entry) == 0;
}

void glsl_symbol_table::add_global_function(ir_function *f)
{
   symbol_table_entry *entry = new(mem_ctx) symbol_table_entry(f);
   int added = _mesa_symbol_table_add_global_symbol(table, -1, f->name, entry);
   assert(added == 0);
   (void)added;
}

ir_variable *glsl_symbol_table::get_variable(const char *name)
{
   symbol_table_entry *entry = get_entry(name);
   return entry != NULL ? entry->v : NULL;
}

const glsl_type *glsl_symbol_table::get_type(const char *name)
{
   symbol_table_entry *entry = get_entry(name);
   return entry != NULL ? entry->t : NULL;
}

const class ast_type_specifier *glsl_symbol_table::get_type_ast(const char *name)
{
   char ast_name[strlen("#ast.") + strlen(name) + 1];
   strcpy(ast_name, "#ast.");
   strcat(ast_name + strlen("#ast."), name);
   symbol_table_entry *entry = get_entry(ast_name);
   return entry != NULL ? entry->a : NULL;
}

const glsl_type *glsl_symbol_table::get_interface(const char *name,
                                                  enum ir_variable_mode mode)
{
   symbol_table_entry *entry = get_entry(name);
   return entry != NULL ? entry->get_interface(mode) : NULL;
}

ir_function *glsl_symbol_table::get_function(const char *name)
{
   symbol_table_entry *entry = get_entry(name);
   return entry != NULL ? entry->f : NULL;
}

symbol_table_entry *glsl_symbol_table::get_entry(const char *name)
{
   return (symbol_table_entry *)
      _mesa_symbol_table_find_symbol(table, -1, name);
}
<commit_msg>glsl: Avoid variable length arrays.<commit_after>/* -*- c++ -*- */
/*
 * Copyright © 2010 Intel Corporation
 *
 * 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 (including the next
 * paragraph) 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.
 */

#include "glsl_symbol_table.h"

class symbol_table_entry {
public:
   /* Callers of this ralloc-based new need not call delete. It's
    * easier to just ralloc_free 'ctx' (or any of its ancestors). */
   static void* operator new(size_t size, void *ctx)
   {
      void *entry = ralloc_size(ctx, size);
      assert(entry != NULL);
      return entry;
   }

   /* If the user *does* call delete, that's OK, we will just ralloc_free. */
   static void operator delete(void *entry)
   {
      ralloc_free(entry);
   }

   bool add_interface(const glsl_type *i, enum ir_variable_mode mode)
   {
      const glsl_type **dest;

      switch (mode) {
      case ir_var_uniform:
         dest = &ibu;
         break;
      case ir_var_shader_in:
         dest = &ibi;
         break;
      case ir_var_shader_out:
         dest = &ibo;
         break;
      default:
         assert(!"Unsupported interface variable mode!");
         return false;
      }

      if (*dest != NULL) {
         return false;
      } else {
         *dest = i;
         return true;
      }
   }

   const glsl_type *get_interface(enum ir_variable_mode mode)
   {
      switch (mode) {
      case ir_var_uniform:
         return ibu;
      case ir_var_shader_in:
         return ibi;
      case ir_var_shader_out:
         return ibo;
      default:
         assert(!"Unsupported interface variable mode!");
         return NULL;
      }
   }

   symbol_table_entry(ir_variable *v)               :
      v(v), f(0), t(0), ibu(0), ibi(0), ibo(0), a(0) {}
   symbol_table_entry(ir_function *f)               :
      v(0), f(f), t(0), ibu(0), ibi(0), ibo(0), a(0) {}
   symbol_table_entry(const glsl_type *t)           :
      v(0), f(0), t(t), ibu(0), ibi(0), ibo(0), a(0) {}
   symbol_table_entry(const glsl_type *t, enum ir_variable_mode mode) :
      v(0), f(0), t(0), ibu(0), ibi(0), ibo(0), a(0)
   {
      assert(t->is_interface());
      add_interface(t, mode);
   }
   symbol_table_entry(const class ast_type_specifier *a):
      v(0), f(0), t(0), ibu(0), ibi(0), ibo(0), a(a) {}

   ir_variable *v;
   ir_function *f;
   const glsl_type *t;
   const glsl_type *ibu;
   const glsl_type *ibi;
   const glsl_type *ibo;
   const class ast_type_specifier *a;
};

glsl_symbol_table::glsl_symbol_table()
{
   this->separate_function_namespace = false;
   this->table = _mesa_symbol_table_ctor();
   this->mem_ctx = ralloc_context(NULL);
}

glsl_symbol_table::~glsl_symbol_table()
{
   _mesa_symbol_table_dtor(table);
   ralloc_free(mem_ctx);
}

void glsl_symbol_table::push_scope()
{
   _mesa_symbol_table_push_scope(table);
}

void glsl_symbol_table::pop_scope()
{
   _mesa_symbol_table_pop_scope(table);
}

bool glsl_symbol_table::name_declared_this_scope(const char *name)
{
   return _mesa_symbol_table_symbol_scope(table, -1, name) == 0;
}

bool glsl_symbol_table::add_variable(ir_variable *v)
{
   if (this->separate_function_namespace) {
      /* In 1.10, functions and variables have separate namespaces. */
      symbol_table_entry *existing = get_entry(v->name);
      if (name_declared_this_scope(v->name)) {
	 /* If there's already an existing function (not a constructor!) in
	  * the current scope, just update the existing entry to include 'v'.
	  */
	 if (existing->v == NULL && existing->t == NULL) {
	    existing->v = v;
	    return true;
	 }
      } else {
	 /* If not declared at this scope, add a new entry.  But if an existing
	  * entry includes a function, propagate that to this block - otherwise
	  * the new variable declaration would shadow the function.
	  */
	 symbol_table_entry *entry = new(mem_ctx) symbol_table_entry(v);
	 if (existing != NULL)
	    entry->f = existing->f;
	 int added = _mesa_symbol_table_add_symbol(table, -1, v->name, entry);
	 assert(added == 0);
	 (void)added;
	 return true;
      }
      return false;
   }

   /* 1.20+ rules: */
   symbol_table_entry *entry = new(mem_ctx) symbol_table_entry(v);
   return _mesa_symbol_table_add_symbol(table, -1, v->name, entry) == 0;
}

bool glsl_symbol_table::add_type(const char *name, const glsl_type *t)
{
   symbol_table_entry *entry = new(mem_ctx) symbol_table_entry(t);
   return _mesa_symbol_table_add_symbol(table, -1, name, entry) == 0;
}

static char *make_ast_name(const char *name)
{
   char *ast_name = new char[strlen("#ast.") + strlen(name) + 1];
   strcpy(ast_name, "#ast.");
   strcat(ast_name + strlen("#ast."), name);
   return ast_name;
}

bool glsl_symbol_table::add_type_ast(const char *name, const class ast_type_specifier *a)
{
   symbol_table_entry *entry = new(mem_ctx) symbol_table_entry(a);
   char *ast_name = make_ast_name(name);
   bool ret = _mesa_symbol_table_add_symbol(table, -1, ast_name, entry) == 0;
   delete [] ast_name;
   return ret;
}

bool glsl_symbol_table::add_interface(const char *name, const glsl_type *i,
                                      enum ir_variable_mode mode)
{
   assert(i->is_interface());
   symbol_table_entry *entry = get_entry(name);
   if (entry == NULL) {
      symbol_table_entry *entry =
         new(mem_ctx) symbol_table_entry(i, mode);
      bool add_interface_symbol_result =
         _mesa_symbol_table_add_symbol(table, -1, name, entry) == 0;
      assert(add_interface_symbol_result);
      return add_interface_symbol_result;
   } else {
      return entry->add_interface(i, mode);
   }
}

bool glsl_symbol_table::add_function(ir_function *f)
{
   if (this->separate_function_namespace && name_declared_this_scope(f->name)) {
      /* In 1.10, functions and variables have separate namespaces. */
      symbol_table_entry *existing = get_entry(f->name);
      if ((existing->f == NULL) && (existing->t == NULL)) {
	 existing->f = f;
	 return true;
      }
   }
   symbol_table_entry *entry = new(mem_ctx) symbol_table_entry(f);
   return _mesa_symbol_table_add_symbol(table, -1, f->name, entry) == 0;
}

void glsl_symbol_table::add_global_function(ir_function *f)
{
   symbol_table_entry *entry = new(mem_ctx) symbol_table_entry(f);
   int added = _mesa_symbol_table_add_global_symbol(table, -1, f->name, entry);
   assert(added == 0);
   (void)added;
}

ir_variable *glsl_symbol_table::get_variable(const char *name)
{
   symbol_table_entry *entry = get_entry(name);
   return entry != NULL ? entry->v : NULL;
}

const glsl_type *glsl_symbol_table::get_type(const char *name)
{
   symbol_table_entry *entry = get_entry(name);
   return entry != NULL ? entry->t : NULL;
}

const class ast_type_specifier *glsl_symbol_table::get_type_ast(const char *name)
{
   char *ast_name = make_ast_name(name);
   symbol_table_entry *entry = get_entry(ast_name);
   delete [] ast_name;
   return entry != NULL ? entry->a : NULL;
}

const glsl_type *glsl_symbol_table::get_interface(const char *name,
                                                  enum ir_variable_mode mode)
{
   symbol_table_entry *entry = get_entry(name);
   return entry != NULL ? entry->get_interface(mode) : NULL;
}

ir_function *glsl_symbol_table::get_function(const char *name)
{
   symbol_table_entry *entry = get_entry(name);
   return entry != NULL ? entry->f : NULL;
}

symbol_table_entry *glsl_symbol_table::get_entry(const char *name)
{
   return (symbol_table_entry *)
      _mesa_symbol_table_find_symbol(table, -1, name);
}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile: mitkPropertyManager.cpp,v $
Language:  C++
Date:      $Date$
Version:   $Revision: 1.12 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "QmitkPointListWidget.h"

#include "mitkGlobalInteraction.h"
#include "mitkPointSetReader.h"
#include "mitkPointSetWriter.h"
#include "mitkInteractionConst.h"
#include "mitkPointOperation.h"

#include <QGridLayout>
#include <QPushButton>
#include <QMessageBox>
#include <QFileDialog>
#include <QKeyEvent>

#include "btnSetPoints.xpm"
#include "btnClear.xpm"
#include "btnLoad.xpm"
#include "btnSave.xpm"

QmitkPointListWidget::QmitkPointListWidget( QWidget* parent, Qt::WindowFlags f )
:QWidget( parent, f ), m_ListView(NULL), m_BtnEdit(NULL), m_BtnClear(NULL), m_BtnLoad(NULL),
 m_BtnSave(NULL), m_PointSetNode(NULL), m_Interactor(NULL), m_EditAllowed(true),
 m_NodeObserverTag(0)
{
  QGridLayout* layout = new QGridLayout;
  layout->setContentsMargins( 0, 0, 0, 0 );

  m_ListView = new QmitkPointListView;
  layout->addWidget(m_ListView, 0, 0, 1, 1);
  m_ListView->setToolTip("Use F2 to move the selected point up, use F3 to move the selected point down, double click on a point toggles editing");
  connect( m_ListView, SIGNAL(PointSelectionChanged()), this, SIGNAL(PointSelectionChanged()) );  // forward signal from list view

  QWidget* buttonWidget = new QWidget;
  layout->addWidget( buttonWidget, 1, 0, 1, 1 );

  QHBoxLayout* buttonLayout = new QHBoxLayout;
  buttonWidget->setLayout( buttonLayout );
  buttonLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);

  const QIcon iconEdit( btnSetPoints_xpm ); // installs/removes pointset interactor
  m_BtnEdit = new QPushButton( iconEdit, "", this );
  m_BtnEdit->setToolTip("Toggle point editing (use SHIFT  + Left Mouse Button to add Points)");
  connect( m_BtnEdit, SIGNAL(toggled(bool)), this, SLOT(OnEditPointSetButtonToggled(bool)) );
  m_BtnEdit->setCheckable( true );
  buttonLayout->addWidget( m_BtnEdit );

  const QIcon iconClear( btnClear_xpm ); // clears whole point set
  m_BtnClear = new QPushButton( iconClear, "", this );
  m_BtnClear->setToolTip("Erase all points from list. Use the delete key to delete the selected point.");
  connect( m_BtnClear, SIGNAL(clicked()), this, SLOT(OnClearPointSetButtonClicked()) );
  buttonLayout->addWidget(m_BtnClear);

  const QIcon iconLoad( btnLoad_xpm ); // loads a point set from file
  m_BtnLoad = new QPushButton( iconLoad, "", this );
  m_BtnLoad->setToolTip("Load list of points from file (REPLACES current content)");
  connect( m_BtnLoad, SIGNAL(clicked()), this, SLOT(OnLoadPointSetButtonClicked()) );
  buttonLayout->addWidget(m_BtnLoad);

  const QIcon iconSave( btnSave_xpm ); // saves point set to file
  m_BtnSave = new QPushButton( iconSave, "", this );
  m_BtnSave->setToolTip("Save points to file");
  connect( m_BtnSave, SIGNAL(clicked()), this, SLOT(OnSavePointSetButtonClicked()) );
  buttonLayout->addWidget(m_BtnSave);

  layout->setRowStretch(0, 10);
  layout->setRowStretch(1, 1);
  this->setLayout( layout );

  ObserveNewNode(NULL);
}

QmitkPointListWidget::~QmitkPointListWidget()
{
  if (m_Interactor)
    mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
  m_Interactor = NULL;
  if (m_PointSetNode != NULL)
    m_PointSetNode->RemoveObserver( m_NodeObserverTag );
  m_PointSetNode = NULL;
}

void QmitkPointListWidget::SetPointSetNode( mitk::DataTreeNode* node )
{
  ObserveNewNode(node);

  if (node)
  {
    mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( node->GetData() );
    m_ListView->SetPointSet( pointSet );
  }
  else
  {
    m_ListView->SetPointSet( NULL );
  }
}

void QmitkPointListWidget::SetMultiWidget( QmitkStdMultiWidget* multiWidget )
{
  m_ListView->SetMultiWidget( multiWidget );
}

void QmitkPointListWidget::DeactivateInteractor(bool deactivate)
{
  if (deactivate)
  {
    if (m_Interactor)
    {
      mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
      m_Interactor = NULL;
      m_BtnEdit->setChecked( false );
    }
  }
}

void QmitkPointListWidget::ObserveNewNode( mitk::DataTreeNode* node )
{
  // remove old observer
  if ( m_PointSetNode != NULL )
  {
    if (m_Interactor)
    {
      mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
      m_Interactor = NULL;
      m_BtnEdit->setChecked( false );
    }

    m_PointSetNode->RemoveObserver( m_NodeObserverTag );
  }

  m_PointSetNode = node;

  // add new observer if necessary
  if ( m_PointSetNode != NULL )
  {
    itk::ReceptorMemberCommand<QmitkPointListWidget>::Pointer command = itk::ReceptorMemberCommand<QmitkPointListWidget>::New();
    command->SetCallbackFunction( this, &QmitkPointListWidget::OnNodeDeleted );
    m_NodeObserverTag = m_PointSetNode->AddObserver( itk::DeleteEvent(), command );
  }
  else
  {
    m_NodeObserverTag = 0;
  }

  if (m_EditAllowed == true)
    m_BtnEdit->setEnabled( m_PointSetNode != NULL );
  else
    m_BtnEdit->setEnabled( false );

  m_BtnClear->setEnabled( m_PointSetNode != NULL );
  m_BtnLoad->setEnabled( m_PointSetNode != NULL );
  m_BtnSave->setEnabled( m_PointSetNode != NULL );
}

void QmitkPointListWidget::OnNodeDeleted( const itk::EventObject &  /*e*/ )
{
  m_PointSetNode = NULL;
  m_NodeObserverTag = 0;
  m_ListView->SetPointSet( NULL );
}

void QmitkPointListWidget::OnEditPointSetButtonToggled(bool checked)
{
  if (m_PointSetNode)
  {
    if (checked)
    {
      m_Interactor = mitk::PointSetInteractor::New("pointsetinteractor", m_PointSetNode);
      mitk::GlobalInteraction::GetInstance()->AddInteractor( m_Interactor );
    }
    else if ( m_Interactor )
    {
      mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
      m_Interactor = NULL;
    }
    emit EditPointSets(checked);
  }
}

void QmitkPointListWidget::OnClearPointSetButtonClicked()
{
  if (!m_PointSetNode) return;
  mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
  if (!pointSet) return;
  if (pointSet->GetSize() == 0) return; // we don't have to disturb by asking silly questions

  switch( QMessageBox::question( this, tr("Clear Points"),
          tr("Remove all points from the displayed list?"),
          QMessageBox::Yes | QMessageBox::No, QMessageBox::No))
  {
    case QMessageBox::Yes:
      if (pointSet)
      {
        mitk::PointSet::DataType::PointsContainer::Pointer pointsContainer = pointSet->GetPointSet()->GetPoints();
        pointsContainer->Initialize(); // a call to initialize results in clearing the points container

        //dummy call to update PointSetVtkMapper3D (bug fix oder better bug work around #2436)
        mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpREMOVE, pointSet->GetPoint(0), 0, false);
        pointSet->ExecuteOperation(doOp);
        delete doOp;
      }
      mitk::RenderingManager::GetInstance()->RequestUpdateAll();
      break;

    case QMessageBox::No:
    default:
      break;
  }
  emit PointListChanged();
}

void QmitkPointListWidget::OnLoadPointSetButtonClicked()
{
  if (!m_PointSetNode) return;

  // get the name of the file to load
  QString filename = QFileDialog::getOpenFileName( NULL, "Open MITK Pointset", "", "MITK Point Sets (*.mps)");
  if ( filename.isEmpty() ) return;

  // attempt to load file
  try
  {
    mitk::PointSetReader::Pointer reader = mitk::PointSetReader::New();
    reader->SetFileName( filename.toLatin1() );
    reader->Update();

    mitk::PointSet::Pointer pointSet = reader->GetOutput();
    if ( pointSet.IsNull() )
    {
      QMessageBox::warning( this, "Load point set", QString("File reader could not read %1").arg(filename) );
      return;
    }

    // loading successful

    bool interactionOn( m_Interactor.IsNotNull() );
    if (interactionOn)
    {
      OnEditPointSetButtonToggled(false);
    }

    m_PointSetNode->SetData( pointSet );
    m_ListView->SetPointSet( pointSet );

    if (interactionOn)
    {
      OnEditPointSetButtonToggled(true);
    }
  }
  catch(...)
  {
    QMessageBox::warning( this, "Load point set", QString("File reader collapsed while reading %1").arg(filename) );
  }
  emit PointListChanged();
}

void QmitkPointListWidget::OnSavePointSetButtonClicked()
{
  if (!m_PointSetNode)
    return;
  mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
  if (!pointSet)
    return; // don't write empty point sets. If application logic requires something else then do something else.
  if (pointSet->GetSize() == 0)
    return;

  // let the user choose a file
  std::string name("");

  QString fileNameProposal = QString("/%1.mps").arg(m_PointSetNode->GetName().c_str()); //"PointSet.mps";
  QString aFilename = QFileDialog::getSaveFileName( NULL, "Save point set", QDir::currentPath() + fileNameProposal, "MITK Pointset (*.mps)" );
  if ( aFilename.isEmpty() )
    return;

  try
  {
    // instantiate the writer and add the point-sets to write
    mitk::PointSetWriter::Pointer writer = mitk::PointSetWriter::New();
    writer->SetInput( pointSet );
    writer->SetFileName( aFilename.toLatin1() );
    writer->Update();
  }
  catch(...)
  {
    QMessageBox::warning( this, "Save point set",
                          QString("File writer reported problems writing %1\n\n"
                                  "PLEASE CHECK output file!").arg(aFilename) );
  }
}

void QmitkPointListWidget::EnableEditButton( bool enabled )
{
  m_EditAllowed = enabled;
  if (enabled == false)
    m_BtnEdit->setEnabled(false);
  else
    m_BtnEdit->setEnabled(true);
  OnEditPointSetButtonToggled(enabled);
}
<commit_msg>FIX (#3373): fixed layout<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile: mitkPropertyManager.cpp,v $
Language:  C++
Date:      $Date$
Version:   $Revision: 1.12 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "QmitkPointListWidget.h"

#include "mitkGlobalInteraction.h"
#include "mitkPointSetReader.h"
#include "mitkPointSetWriter.h"
#include "mitkInteractionConst.h"
#include "mitkPointOperation.h"

#include <QGridLayout>
#include <QPushButton>
#include <QMessageBox>
#include <QFileDialog>
#include <QKeyEvent>

#include "btnSetPoints.xpm"
#include "btnClear.xpm"
#include "btnLoad.xpm"
#include "btnSave.xpm"

QmitkPointListWidget::QmitkPointListWidget( QWidget* parent, Qt::WindowFlags f )
:QWidget( parent, f ), m_ListView(NULL), m_BtnEdit(NULL), m_BtnClear(NULL), m_BtnLoad(NULL),
 m_BtnSave(NULL), m_PointSetNode(NULL), m_Interactor(NULL), m_EditAllowed(true),
 m_NodeObserverTag(0)
{
  QGridLayout* layout = new QGridLayout;
  layout->setContentsMargins( 0, 0, 0, 0 );

  m_ListView = new QmitkPointListView;
  layout->addWidget(m_ListView, 0, 0, 1, 1);
  m_ListView->setToolTip("Use F2 to move the selected point up, use F3 to move the selected point down, double click on a point toggles editing");
  connect( m_ListView, SIGNAL(PointSelectionChanged()), this, SIGNAL(PointSelectionChanged()) );  // forward signal from list view

  QWidget* buttonWidget = new QWidget;
  layout->addWidget( buttonWidget, 1, 0, 1, 1 );

  QHBoxLayout* buttonLayout = new QHBoxLayout;
  buttonWidget->setLayout( buttonLayout );
  buttonLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);

  buttonLayout->setMargin(0);

  const QIcon iconEdit( btnSetPoints_xpm ); // installs/removes pointset interactor
  m_BtnEdit = new QPushButton( iconEdit, "", this );
  m_BtnEdit->setToolTip("Toggle point editing (use SHIFT  + Left Mouse Button to add Points)");
  connect( m_BtnEdit, SIGNAL(toggled(bool)), this, SLOT(OnEditPointSetButtonToggled(bool)) );
  m_BtnEdit->setCheckable( true );
  buttonLayout->addWidget( m_BtnEdit );

  const QIcon iconClear( btnClear_xpm ); // clears whole point set
  m_BtnClear = new QPushButton( iconClear, "", this );
  m_BtnClear->setToolTip("Erase all points from list. Use the delete key to delete the selected point.");
  connect( m_BtnClear, SIGNAL(clicked()), this, SLOT(OnClearPointSetButtonClicked()) );
  buttonLayout->addWidget(m_BtnClear);

  const QIcon iconLoad( btnLoad_xpm ); // loads a point set from file
  m_BtnLoad = new QPushButton( iconLoad, "", this );
  m_BtnLoad->setToolTip("Load list of points from file (REPLACES current content)");
  connect( m_BtnLoad, SIGNAL(clicked()), this, SLOT(OnLoadPointSetButtonClicked()) );
  buttonLayout->addWidget(m_BtnLoad);

  const QIcon iconSave( btnSave_xpm ); // saves point set to file
  m_BtnSave = new QPushButton( iconSave, "", this );
  m_BtnSave->setToolTip("Save points to file");
  connect( m_BtnSave, SIGNAL(clicked()), this, SLOT(OnSavePointSetButtonClicked()) );
  buttonLayout->addWidget(m_BtnSave);

  layout->setRowStretch(0, 10);
  layout->setRowStretch(1, 1);
  this->setLayout( layout );

  ObserveNewNode(NULL);
}

QmitkPointListWidget::~QmitkPointListWidget()
{
  if (m_Interactor)
    mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
  m_Interactor = NULL;
  if (m_PointSetNode != NULL)
    m_PointSetNode->RemoveObserver( m_NodeObserverTag );
  m_PointSetNode = NULL;
}

void QmitkPointListWidget::SetPointSetNode( mitk::DataTreeNode* node )
{
  ObserveNewNode(node);

  if (node)
  {
    mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( node->GetData() );
    m_ListView->SetPointSet( pointSet );
  }
  else
  {
    m_ListView->SetPointSet( NULL );
  }
}

void QmitkPointListWidget::SetMultiWidget( QmitkStdMultiWidget* multiWidget )
{
  m_ListView->SetMultiWidget( multiWidget );
}

void QmitkPointListWidget::DeactivateInteractor(bool deactivate)
{
  if (deactivate)
  {
    if (m_Interactor)
    {
      mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
      m_Interactor = NULL;
      m_BtnEdit->setChecked( false );
    }
  }
}

void QmitkPointListWidget::ObserveNewNode( mitk::DataTreeNode* node )
{
  // remove old observer
  if ( m_PointSetNode != NULL )
  {
    if (m_Interactor)
    {
      mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
      m_Interactor = NULL;
      m_BtnEdit->setChecked( false );
    }

    m_PointSetNode->RemoveObserver( m_NodeObserverTag );
  }

  m_PointSetNode = node;

  // add new observer if necessary
  if ( m_PointSetNode != NULL )
  {
    itk::ReceptorMemberCommand<QmitkPointListWidget>::Pointer command = itk::ReceptorMemberCommand<QmitkPointListWidget>::New();
    command->SetCallbackFunction( this, &QmitkPointListWidget::OnNodeDeleted );
    m_NodeObserverTag = m_PointSetNode->AddObserver( itk::DeleteEvent(), command );
  }
  else
  {
    m_NodeObserverTag = 0;
  }

  if (m_EditAllowed == true)
    m_BtnEdit->setEnabled( m_PointSetNode != NULL );
  else
    m_BtnEdit->setEnabled( false );

  m_BtnClear->setEnabled( m_PointSetNode != NULL );
  m_BtnLoad->setEnabled( m_PointSetNode != NULL );
  m_BtnSave->setEnabled( m_PointSetNode != NULL );
}

void QmitkPointListWidget::OnNodeDeleted( const itk::EventObject &  /*e*/ )
{
  m_PointSetNode = NULL;
  m_NodeObserverTag = 0;
  m_ListView->SetPointSet( NULL );
}

void QmitkPointListWidget::OnEditPointSetButtonToggled(bool checked)
{
  if (m_PointSetNode)
  {
    if (checked)
    {
      m_Interactor = mitk::PointSetInteractor::New("pointsetinteractor", m_PointSetNode);
      mitk::GlobalInteraction::GetInstance()->AddInteractor( m_Interactor );
    }
    else if ( m_Interactor )
    {
      mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
      m_Interactor = NULL;
    }
    emit EditPointSets(checked);
  }
}

void QmitkPointListWidget::OnClearPointSetButtonClicked()
{
  if (!m_PointSetNode) return;
  mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
  if (!pointSet) return;
  if (pointSet->GetSize() == 0) return; // we don't have to disturb by asking silly questions

  switch( QMessageBox::question( this, tr("Clear Points"),
          tr("Remove all points from the displayed list?"),
          QMessageBox::Yes | QMessageBox::No, QMessageBox::No))
  {
    case QMessageBox::Yes:
      if (pointSet)
      {
        mitk::PointSet::DataType::PointsContainer::Pointer pointsContainer = pointSet->GetPointSet()->GetPoints();
        pointsContainer->Initialize(); // a call to initialize results in clearing the points container

        //dummy call to update PointSetVtkMapper3D (bug fix oder better bug work around #2436)
        mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpREMOVE, pointSet->GetPoint(0), 0, false);
        pointSet->ExecuteOperation(doOp);
        delete doOp;
      }
      mitk::RenderingManager::GetInstance()->RequestUpdateAll();
      break;

    case QMessageBox::No:
    default:
      break;
  }
  emit PointListChanged();
}

void QmitkPointListWidget::OnLoadPointSetButtonClicked()
{
  if (!m_PointSetNode) return;

  // get the name of the file to load
  QString filename = QFileDialog::getOpenFileName( NULL, "Open MITK Pointset", "", "MITK Point Sets (*.mps)");
  if ( filename.isEmpty() ) return;

  // attempt to load file
  try
  {
    mitk::PointSetReader::Pointer reader = mitk::PointSetReader::New();
    reader->SetFileName( filename.toLatin1() );
    reader->Update();

    mitk::PointSet::Pointer pointSet = reader->GetOutput();
    if ( pointSet.IsNull() )
    {
      QMessageBox::warning( this, "Load point set", QString("File reader could not read %1").arg(filename) );
      return;
    }

    // loading successful

    bool interactionOn( m_Interactor.IsNotNull() );
    if (interactionOn)
    {
      OnEditPointSetButtonToggled(false);
    }

    m_PointSetNode->SetData( pointSet );
    m_ListView->SetPointSet( pointSet );

    if (interactionOn)
    {
      OnEditPointSetButtonToggled(true);
    }
  }
  catch(...)
  {
    QMessageBox::warning( this, "Load point set", QString("File reader collapsed while reading %1").arg(filename) );
  }
  emit PointListChanged();
}

void QmitkPointListWidget::OnSavePointSetButtonClicked()
{
  if (!m_PointSetNode)
    return;
  mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
  if (!pointSet)
    return; // don't write empty point sets. If application logic requires something else then do something else.
  if (pointSet->GetSize() == 0)
    return;

  // let the user choose a file
  std::string name("");

  QString fileNameProposal = QString("/%1.mps").arg(m_PointSetNode->GetName().c_str()); //"PointSet.mps";
  QString aFilename = QFileDialog::getSaveFileName( NULL, "Save point set", QDir::currentPath() + fileNameProposal, "MITK Pointset (*.mps)" );
  if ( aFilename.isEmpty() )
    return;

  try
  {
    // instantiate the writer and add the point-sets to write
    mitk::PointSetWriter::Pointer writer = mitk::PointSetWriter::New();
    writer->SetInput( pointSet );
    writer->SetFileName( aFilename.toLatin1() );
    writer->Update();
  }
  catch(...)
  {
    QMessageBox::warning( this, "Save point set",
                          QString("File writer reported problems writing %1\n\n"
                                  "PLEASE CHECK output file!").arg(aFilename) );
  }
}

void QmitkPointListWidget::EnableEditButton( bool enabled )
{
  m_EditAllowed = enabled;
  if (enabled == false)
    m_BtnEdit->setEnabled(false);
  else
    m_BtnEdit->setEnabled(true);
  OnEditPointSetButtonToggled(enabled);
}
<|endoftext|>


<commit_before>// Output file should have no calls to error() with folding.
// RUN: %clang_cc1 -triple i386-unknown-unknown -O3 -emit-llvm -o %t %s
// RUN: FileCheck %s < %t

static unsigned pow(unsigned Base, unsigned Power) {
  unsigned Val = 1;
  while (Power--)
    Val *= Base;
  return Val;
}

struct TempTracker {
  unsigned Product, Index;

  TempTracker() : Product(1), Index(0) {}

};

// FIXME: This can be used to check elision as well, if P = 0 hacks are removed.
struct A {
  TempTracker &TT;
  mutable unsigned P;
  bool Truth;

  A(TempTracker &_TT, unsigned _P, bool _Truth = true)
    : TT(_TT), P(_P), Truth(_Truth) {}
  A(const A &RHS) : TT(RHS.TT), P(RHS.P), Truth(RHS.Truth) { RHS.P = 0; }
  ~A() {
    if (P)
      TT.Product *= pow(P, ++TT.Index);
  }

  A &operator=(const A &RHS) {
    TT = RHS.TT;
    P = RHS.P;
    Truth = RHS.Truth;
    RHS.P = 0;
    return *this;
  }

  operator bool () { return Truth; }
};

// 3, 7, 2
static unsigned f0(bool val = false) {
  TempTracker tt;
  {
    A a(tt, 2);
    if ((A(tt, 3), val))
      A b(tt, 5);
    A c(tt, 7);
  }
  return tt.Product;
}

// 3, 5, 7, 2
static unsigned f1(bool val = true) {
  TempTracker tt;
  {
    A a(tt, 2);
    if ((A(tt, 3), val))
      A b(tt, 5);
    A c(tt, 7);
  }
  return tt.Product;
}

// 5, 3, 7, 2
static unsigned f2() {
  TempTracker tt;
  {
    A a(tt, 2);
    if (A b = A(tt, 3))
      A c(tt, 5);
    A d(tt, 7);
  }
  return tt.Product;
}

// 7, 3, 11, 2
static unsigned f3() {
  TempTracker tt;
  {
    A a(tt, 2);
    if (A b = A(tt, 3, false))
      A c(tt, 5);
    else
      A c(tt, 7);
    A d(tt, 11);
  }
  return tt.Product;
}

// 3, 7, 2
static unsigned f4() {
  TempTracker tt;
  {
    A a(tt, 2);
    while (A b = A(tt, 3, false))
      A c(tt, 5);
    A c(tt, 7);
  }
  return tt.Product;
}

// 5, 3, 7, 2
static unsigned f5() {
  TempTracker tt;
  {
    A a(tt, 2);
    while (A b = A(tt, 3, true)) {
      A c(tt, 5);
      break;
    }
    A c(tt, 7);
  }
  return tt.Product;
}

// 3, 7, 11, 5, 13, 2
static unsigned f6() {
  TempTracker tt;
  {
    A a(tt, 2);
    for (A b = (A(tt, 3), A(tt, 5)), c = (A(tt, 7), A(tt, 11));;)
      break;
    A c(tt, 13);
  }
  return tt.Product;
}

extern "C" void error();
extern "C" void print(const char *Name, unsigned N);

#define ORDER3(a, b, c) (pow(a, 1) * pow(b, 2) * pow(c, 3))
#define ORDER4(a, b, c, d) (ORDER3(a, b, c) * pow(d, 4))
#define ORDER5(a, b, c, d, e) (ORDER4(a, b, c, d) * pow(e, 5))
#define ORDER6(a, b, c, d, e, f) (ORDER5(a, b, c, d, e) * pow(f, 6))
void test() {
// CHECK: call void @print(i8* {{.*}}, i32 1176)
  print("f0", f0());
  if (f0() != ORDER3(3, 7, 2))
    error();

// CHECK: call void @print(i8* {{.*}}, i32 411600)
  print("f1", f1());
  if (f1() != ORDER4(3, 5, 7, 2))
    error();

// CHECK: call void @print(i8* {{.*}}, i32 246960)
  print("f2", f2());
  if (f2() != ORDER4(5, 3, 7, 2))
    error();

// CHECK: call void @print(i8* {{.*}}, i32 1341648)
  print("f3", f3());
  if (f3() != ORDER4(7, 3, 11, 2))
    error();

// CHECK: call void @print(i8* {{.*}}, i32 1176)
  print("f4", f4());
  if (f4() != ORDER3(3, 7, 2))
    error();

// CHECK: call void @print(i8* {{.*}}, i32 246960)
  print("f5", f5());
  if (f5() != ORDER4(5, 3, 7, 2))
    error();

// FIXME: Clang/LLVM currently can't fold this to a constant. If the error check
// is present (since it avoids single-caller inlining). PR5645.

//  CHECK: call void @print(i8* {{.*}}, i32 1251552576)
  print("f6", f6());
//  if (f6() != ORDER6(3, 7, 11, 5, 13, 2))
//    error();
}

#ifdef HARNESS

#include <cstdlib>
#include <cstdio>

extern "C" void error() {
  abort();
}

extern "C" void print(const char *name, unsigned N) {
  printf("%s: %d\n", name, N);
}

int main() {
  test();
  return 0;
}

#endif
<commit_msg>Fix a FIXME, this test folds to a constant now.<commit_after>// Output file should have no calls to error() with folding.
// RUN: %clang_cc1 -triple i386-unknown-unknown -O3 -emit-llvm -o %t %s
// RUN: FileCheck %s < %t

static unsigned pow(unsigned Base, unsigned Power) {
  unsigned Val = 1;
  while (Power--)
    Val *= Base;
  return Val;
}

struct TempTracker {
  unsigned Product, Index;

  TempTracker() : Product(1), Index(0) {}

};

// FIXME: This can be used to check elision as well, if P = 0 hacks are removed.
struct A {
  TempTracker &TT;
  mutable unsigned P;
  bool Truth;

  A(TempTracker &_TT, unsigned _P, bool _Truth = true)
    : TT(_TT), P(_P), Truth(_Truth) {}
  A(const A &RHS) : TT(RHS.TT), P(RHS.P), Truth(RHS.Truth) { RHS.P = 0; }
  ~A() {
    if (P)
      TT.Product *= pow(P, ++TT.Index);
  }

  A &operator=(const A &RHS) {
    TT = RHS.TT;
    P = RHS.P;
    Truth = RHS.Truth;
    RHS.P = 0;
    return *this;
  }

  operator bool () { return Truth; }
};

// 3, 7, 2
static unsigned f0(bool val = false) {
  TempTracker tt;
  {
    A a(tt, 2);
    if ((A(tt, 3), val))
      A b(tt, 5);
    A c(tt, 7);
  }
  return tt.Product;
}

// 3, 5, 7, 2
static unsigned f1(bool val = true) {
  TempTracker tt;
  {
    A a(tt, 2);
    if ((A(tt, 3), val))
      A b(tt, 5);
    A c(tt, 7);
  }
  return tt.Product;
}

// 5, 3, 7, 2
static unsigned f2() {
  TempTracker tt;
  {
    A a(tt, 2);
    if (A b = A(tt, 3))
      A c(tt, 5);
    A d(tt, 7);
  }
  return tt.Product;
}

// 7, 3, 11, 2
static unsigned f3() {
  TempTracker tt;
  {
    A a(tt, 2);
    if (A b = A(tt, 3, false))
      A c(tt, 5);
    else
      A c(tt, 7);
    A d(tt, 11);
  }
  return tt.Product;
}

// 3, 7, 2
static unsigned f4() {
  TempTracker tt;
  {
    A a(tt, 2);
    while (A b = A(tt, 3, false))
      A c(tt, 5);
    A c(tt, 7);
  }
  return tt.Product;
}

// 5, 3, 7, 2
static unsigned f5() {
  TempTracker tt;
  {
    A a(tt, 2);
    while (A b = A(tt, 3, true)) {
      A c(tt, 5);
      break;
    }
    A c(tt, 7);
  }
  return tt.Product;
}

// 3, 7, 11, 5, 13, 2
static unsigned f6() {
  TempTracker tt;
  {
    A a(tt, 2);
    for (A b = (A(tt, 3), A(tt, 5)), c = (A(tt, 7), A(tt, 11));;)
      break;
    A c(tt, 13);
  }
  return tt.Product;
}

extern "C" void error();
extern "C" void print(const char *Name, unsigned N);

#define ORDER3(a, b, c) (pow(a, 1) * pow(b, 2) * pow(c, 3))
#define ORDER4(a, b, c, d) (ORDER3(a, b, c) * pow(d, 4))
#define ORDER5(a, b, c, d, e) (ORDER4(a, b, c, d) * pow(e, 5))
#define ORDER6(a, b, c, d, e, f) (ORDER5(a, b, c, d, e) * pow(f, 6))
void test() {
// CHECK: call void @print(i8* {{.*}}, i32 1176)
  print("f0", f0());
  if (f0() != ORDER3(3, 7, 2))
    error();

// CHECK: call void @print(i8* {{.*}}, i32 411600)
  print("f1", f1());
  if (f1() != ORDER4(3, 5, 7, 2))
    error();

// CHECK: call void @print(i8* {{.*}}, i32 246960)
  print("f2", f2());
  if (f2() != ORDER4(5, 3, 7, 2))
    error();

// CHECK: call void @print(i8* {{.*}}, i32 1341648)
  print("f3", f3());
  if (f3() != ORDER4(7, 3, 11, 2))
    error();

// CHECK: call void @print(i8* {{.*}}, i32 1176)
  print("f4", f4());
  if (f4() != ORDER3(3, 7, 2))
    error();

// CHECK: call void @print(i8* {{.*}}, i32 246960)
  print("f5", f5());
  if (f5() != ORDER4(5, 3, 7, 2))
    error();

// CHECK: call void @print(i8* {{.*}}, i32 1251552576)
  print("f6", f6());
  if (f6() != ORDER6(3, 7, 11, 5, 13, 2))
    error();
}

#ifdef HARNESS

#include <cstdlib>
#include <cstdio>

extern "C" void error() {
  abort();
}

extern "C" void print(const char *name, unsigned N) {
  printf("%s: %d\n", name, N);
}

int main() {
  test();
  return 0;
}

#endif
<|endoftext|>


<commit_before>/*!
 * \page YieldTestSuite_cpp Command-Line Test to Demonstrate How To Test the AirRAC Project
 * \code
 */
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <sstream>
#include <fstream>
#include <string>
// Boost Unit Test Framework (UTF)
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE YieldTestSuite
#include <boost/test/unit_test.hpp>
// StdAir
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
#include <stdair/basic/BasFileMgr.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/service/Logger.hpp>
// Airrac
#include <airrac/AIRRAC_Service.hpp>
#include <airrac/config/airrac-paths.hpp>

namespace boost_utf = boost::unit_test;

// (Boost) Unit Test XML Report
std::ofstream utfReportStream ("YieldTestSuite_utfresults.xml");

/**
 * Configuration for the Boost Unit Test Framework (UTF)
 */
struct UnitTestConfig {
  /** Constructor. */
  UnitTestConfig() {
    boost_utf::unit_test_log.set_stream (utfReportStream);
    boost_utf::unit_test_log.set_format (boost_utf::XML);
    boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units);
    //boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests);
  }

  /** Destructor. */
  ~UnitTestConfig() {
  }
};

// //////////////////////////////////////////////////////////////////////

/**
 * Build and search yields for a default list of travel solutions
 */
void testYieldQuoterHelper (const unsigned short iTestFlag,
                            const stdair::Filename_T iYieldInputFilename,
                            const bool isBuiltin) {

  // Output log File
  std::ostringstream oStr;
  oStr << "FQTTestSuite_" << iTestFlag << ".log";
  const stdair::Filename_T lLogFilename (oStr.str());

  // Set the log parameters
  std::ofstream logOutputFile;
  // Open and clean the log outputfile
  logOutputFile.open (lLogFilename.c_str());
  logOutputFile.clear();

  // Initialise the AirRAC service object
  const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG,
                                         logOutputFile);

  // Initialise the AirRAC service object
  AIRRAC::AIRRAC_Service airracService (lLogParams);

  // Build a sample list of travel solutions
  stdair::TravelSolutionList_T lTravelSolutionList;
  airracService.buildSampleTravelSolutions (lTravelSolutionList);

  // Check whether or not a (CSV) input file should be read
  if (isBuiltin == true) {

    // Build the default sample BOM tree (filled with yields) for AirRAC
    airracService.buildSampleBom();

  } else {

    // Build the BOM tree from parsing the yield input file
    AIRRAC::YieldFilePath lYieldFilePath (iYieldInputFilename);
    airracService.parseAndLoad (lYieldFilePath);
  }

  // Calculate the yields for the given travel solution
  airracService.calculateYields (lTravelSolutionList);

  // Close the log file
  logOutputFile.close();

}

// /////////////// Main: Unit Test Suite //////////////

// Set the UTF configuration (re-direct the output to a specific file)
BOOST_GLOBAL_FIXTURE (UnitTestConfig);

// Start the test suite
BOOST_AUTO_TEST_SUITE (master_test_suite)

/**
 * Test a simple yield search with an input file.
 */
BOOST_AUTO_TEST_CASE (airrac_simple_yield) {

  // Input file name
  const stdair::Filename_T lYieldInputFilename (STDAIR_SAMPLE_DIR "/yieldstore01.csv");

  // State whether the BOM tree should be built-in or parsed from an input file
  const bool isBuiltin = false;

  // Try to yieldQuote the sample default list of travel solutions
  BOOST_CHECK_NO_THROW (testYieldQuoterHelper (0, lYieldInputFilename, isBuiltin));

}

/**
 * Test an error detection functionality
 * Expected to throw AIRRAC::FareFileParsingFailedException
 */
BOOST_AUTO_TEST_CASE (airrac_error_parsing_input_file) {

  // Input file name
  const stdair::Filename_T lYieldInputFilename (STDAIR_SAMPLE_DIR "/yieldstoreError01.csv");

  // State whether the BOM tree should be built-in or parsed from an input file
  const bool isBuiltin = false;

  // Try to yield quote the sample default list of travel solutions
  BOOST_CHECK_THROW (testYieldQuoterHelper (1, lYieldInputFilename, isBuiltin),
                     AIRRAC::YieldFileParsingFailedException);
}

/**
 * Test an error detection functionality
 * Expected to throw AIRRAC::YieldInputFileNotFoundException
 */
BOOST_AUTO_TEST_CASE (airrac_error_missing_input_file) {

  // Input file name
  const stdair::Filename_T lYieldInputFilename (STDAIR_SAMPLE_DIR "/missingFile.csv");

  // State whether the BOM tree should be built-in or parsed from an input file
  const bool isBuiltin = false;

  // Try to yield quote the sample default list of travel solutions
  BOOST_CHECK_THROW (testYieldQuoterHelper (2, lYieldInputFilename, isBuiltin),
                     AIRRAC::YieldInputFileNotFoundException);
}

/**
 * Test a simple yield search with a default BOM tree.
 */
BOOST_AUTO_TEST_CASE (airrac_simple_yield_built_in) {

  // State whether the BOM tree should be built-in or parsed from an input file
  const bool isBuiltin = true;

  // Try to yield quote the sample default list of travel solutions
  BOOST_CHECK_NO_THROW (testYieldQuoterHelper (3, " ", isBuiltin));

}

// End the test suite
BOOST_AUTO_TEST_SUITE_END()

/*!
 * \endcode
 */

<commit_msg>[Test] Fixed a Boost UTF compatibility issue<commit_after>/*!
 * \page YieldTestSuite_cpp Command-Line Test to Demonstrate How To Test the AirRAC Project
 * \code
 */
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <sstream>
#include <fstream>
#include <string>
// Boost Unit Test Framework (UTF)
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE YieldTestSuite
#include <boost/test/unit_test.hpp>
// StdAir
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
#include <stdair/basic/BasFileMgr.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/service/Logger.hpp>
// Airrac
#include <airrac/AIRRAC_Service.hpp>
#include <airrac/config/airrac-paths.hpp>

namespace boost_utf = boost::unit_test;

// (Boost) Unit Test XML Report
std::ofstream utfReportStream ("YieldTestSuite_utfresults.xml");

/**
 * Configuration for the Boost Unit Test Framework (UTF)
 */
struct UnitTestConfig {
  /** Constructor. */
  UnitTestConfig() {
    boost_utf::unit_test_log.set_stream (utfReportStream);
#if defined(BOOST_VERSION) && BOOST_VERSION >= 105900
    boost_utf::unit_test_log.set_format (boost_utf::OF_XML);
#else // BOOST_VERSION
    boost_utf::unit_test_log.set_format (boost_utf::XML);
#endif // BOOST_VERSION
    boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units);
    //boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests);
  }

  /** Destructor. */
  ~UnitTestConfig() {
  }
};

// //////////////////////////////////////////////////////////////////////

/**
 * Build and search yields for a default list of travel solutions
 */
void testYieldQuoterHelper (const unsigned short iTestFlag,
                            const stdair::Filename_T iYieldInputFilename,
                            const bool isBuiltin) {

  // Output log File
  std::ostringstream oStr;
  oStr << "FQTTestSuite_" << iTestFlag << ".log";
  const stdair::Filename_T lLogFilename (oStr.str());

  // Set the log parameters
  std::ofstream logOutputFile;
  // Open and clean the log outputfile
  logOutputFile.open (lLogFilename.c_str());
  logOutputFile.clear();

  // Initialise the AirRAC service object
  const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG,
                                         logOutputFile);

  // Initialise the AirRAC service object
  AIRRAC::AIRRAC_Service airracService (lLogParams);

  // Build a sample list of travel solutions
  stdair::TravelSolutionList_T lTravelSolutionList;
  airracService.buildSampleTravelSolutions (lTravelSolutionList);

  // Check whether or not a (CSV) input file should be read
  if (isBuiltin == true) {

    // Build the default sample BOM tree (filled with yields) for AirRAC
    airracService.buildSampleBom();

  } else {

    // Build the BOM tree from parsing the yield input file
    AIRRAC::YieldFilePath lYieldFilePath (iYieldInputFilename);
    airracService.parseAndLoad (lYieldFilePath);
  }

  // Calculate the yields for the given travel solution
  airracService.calculateYields (lTravelSolutionList);

  // Close the log file
  logOutputFile.close();

}

// /////////////// Main: Unit Test Suite //////////////

// Set the UTF configuration (re-direct the output to a specific file)
BOOST_GLOBAL_FIXTURE (UnitTestConfig);

// Start the test suite
BOOST_AUTO_TEST_SUITE (master_test_suite)

/**
 * Test a simple yield search with an input file.
 */
BOOST_AUTO_TEST_CASE (airrac_simple_yield) {

  // Input file name
  const stdair::Filename_T lYieldInputFilename (STDAIR_SAMPLE_DIR "/yieldstore01.csv");

  // State whether the BOM tree should be built-in or parsed from an input file
  const bool isBuiltin = false;

  // Try to yieldQuote the sample default list of travel solutions
  BOOST_CHECK_NO_THROW (testYieldQuoterHelper (0, lYieldInputFilename, isBuiltin));

}

/**
 * Test an error detection functionality
 * Expected to throw AIRRAC::FareFileParsingFailedException
 */
BOOST_AUTO_TEST_CASE (airrac_error_parsing_input_file) {

  // Input file name
  const stdair::Filename_T lYieldInputFilename (STDAIR_SAMPLE_DIR "/yieldstoreError01.csv");

  // State whether the BOM tree should be built-in or parsed from an input file
  const bool isBuiltin = false;

  // Try to yield quote the sample default list of travel solutions
  BOOST_CHECK_THROW (testYieldQuoterHelper (1, lYieldInputFilename, isBuiltin),
                     AIRRAC::YieldFileParsingFailedException);
}

/**
 * Test an error detection functionality
 * Expected to throw AIRRAC::YieldInputFileNotFoundException
 */
BOOST_AUTO_TEST_CASE (airrac_error_missing_input_file) {

  // Input file name
  const stdair::Filename_T lYieldInputFilename (STDAIR_SAMPLE_DIR "/missingFile.csv");

  // State whether the BOM tree should be built-in or parsed from an input file
  const bool isBuiltin = false;

  // Try to yield quote the sample default list of travel solutions
  BOOST_CHECK_THROW (testYieldQuoterHelper (2, lYieldInputFilename, isBuiltin),
                     AIRRAC::YieldInputFileNotFoundException);
}

/**
 * Test a simple yield search with a default BOM tree.
 */
BOOST_AUTO_TEST_CASE (airrac_simple_yield_built_in) {

  // State whether the BOM tree should be built-in or parsed from an input file
  const bool isBuiltin = true;

  // Try to yield quote the sample default list of travel solutions
  BOOST_CHECK_NO_THROW (testYieldQuoterHelper (3, " ", isBuiltin));

}

// End the test suite
BOOST_AUTO_TEST_SUITE_END()

/*!
 * \endcode
 */

<|endoftext|>


<commit_before>#pragma once
#include "gl_core_4_5.h"

namespace GlProj
{
	namespace Graphics
	{
		enum class BufferType : GLenum
		{
			array = GL_ARRAY_BUFFER,
			copy_read = GL_COPY_READ_BUFFER,
			atomic_counter = GL_ATOMIC_COUNTER_BUFFER,
			copy_write = GL_COPY_WRITE_BUFFER,
			dispatch_indirect = GL_DISPATCH_INDIRECT_BUFFER,
			draw_indirect = GL_DRAW_INDIRECT_BUFFER,
			element_array = GL_ELEMENT_ARRAY_BUFFER,
			pixel_pack = GL_PIXEL_PACK_BUFFER,
			pixel_unpack = GL_PIXEL_UNPACK_BUFFER,
			query = GL_QUERY_BUFFER,
			shader_storage = GL_SHADER_STORAGE_BUFFER,
			texture = GL_TEXTURE_BUFFER,
			transform_feedback = GL_TRANSFORM_FEEDBACK_BUFFER,
			uniform = GL_UNIFORM_BUFFER,
		};

		enum class BufferUsage : GLenum
		{
			stream_draw = GL_STREAM_DRAW,
			stream_read = GL_STREAM_READ,
			stream_copy = GL_STREAM_COPY,
			static_draw = GL_STATIC_DRAW,
			static_read = GL_STATIC_READ,
			static_copy = GL_STATIC_COPY,
			dynamic_draw = GL_DYNAMIC_DRAW,
			dynamic_read = GL_DYNAMIC_READ,
			dynamic_copy = GL_DYNAMIC_COPY,
		};

		class MeshDataBuffer
		{
			GLuint meshDataHandle = invalidHandle;
			GLenum bufferType;
			GLenum dataType;
			GLint elementsPerVertex;
		public:
			static const constexpr GLuint invalidHandle = GLuint(-1);

			friend bool operator==(const MeshDataBuffer&, const MeshDataBuffer&) noexcept;
			friend bool operator!=(const MeshDataBuffer&, const MeshDataBuffer&) noexcept;

			MeshDataBuffer() noexcept = default;
			MeshDataBuffer(const MeshDataBuffer&) = delete;
			MeshDataBuffer(BufferType, GLsizeiptr, const GLvoid*, GLenum, GLint, BufferUsage = BufferUsage::static_read);
			MeshDataBuffer(MeshDataBuffer&&) noexcept;
			MeshDataBuffer& operator=(MeshDataBuffer&&) noexcept;
			~MeshDataBuffer();

			GLuint GetHandle() const noexcept;
			BufferType GetBufferType() const noexcept;
			GLenum GetDataType() const noexcept;
			GLint GetElementsPerVertex() const noexcept;

			void UpdateData(GLintptr offset, GLsizeiptr dataSize, const GLvoid* data) const noexcept;
			void* MapBuffer(GLintptr offset, GLsizeiptr dataSize, GLbitfield access) const noexcept;
			void UnmapBuffer() const noexcept;

			void Bind() const noexcept;
			void BindBase(GLuint) const noexcept;
			void BindRange(GLuint, GLintptr, GLsizeiptr) const noexcept;
		};
	}
}
<commit_msg>Switched the default buffer usage back to static draw, owing to warnings from the driver regarding filling data into a buffer marked as static read.<commit_after>#pragma once
#include "gl_core_4_5.h"

namespace GlProj
{
	namespace Graphics
	{
		enum class BufferType : GLenum
		{
			array = GL_ARRAY_BUFFER,
			copy_read = GL_COPY_READ_BUFFER,
			atomic_counter = GL_ATOMIC_COUNTER_BUFFER,
			copy_write = GL_COPY_WRITE_BUFFER,
			dispatch_indirect = GL_DISPATCH_INDIRECT_BUFFER,
			draw_indirect = GL_DRAW_INDIRECT_BUFFER,
			element_array = GL_ELEMENT_ARRAY_BUFFER,
			pixel_pack = GL_PIXEL_PACK_BUFFER,
			pixel_unpack = GL_PIXEL_UNPACK_BUFFER,
			query = GL_QUERY_BUFFER,
			shader_storage = GL_SHADER_STORAGE_BUFFER,
			texture = GL_TEXTURE_BUFFER,
			transform_feedback = GL_TRANSFORM_FEEDBACK_BUFFER,
			uniform = GL_UNIFORM_BUFFER,
		};

		enum class BufferUsage : GLenum
		{
			stream_draw = GL_STREAM_DRAW,
			stream_read = GL_STREAM_READ,
			stream_copy = GL_STREAM_COPY,
			static_draw = GL_STATIC_DRAW,
			static_read = GL_STATIC_READ,
			static_copy = GL_STATIC_COPY,
			dynamic_draw = GL_DYNAMIC_DRAW,
			dynamic_read = GL_DYNAMIC_READ,
			dynamic_copy = GL_DYNAMIC_COPY,
		};

		class MeshDataBuffer
		{
			GLuint meshDataHandle = invalidHandle;
			GLenum bufferType;
			GLenum dataType;
			GLint elementsPerVertex;
		public:
			static const constexpr GLuint invalidHandle = GLuint(-1);

			friend bool operator==(const MeshDataBuffer&, const MeshDataBuffer&) noexcept;
			friend bool operator!=(const MeshDataBuffer&, const MeshDataBuffer&) noexcept;

			MeshDataBuffer() noexcept = default;
			MeshDataBuffer(const MeshDataBuffer&) = delete;
			MeshDataBuffer(BufferType, GLsizeiptr, const GLvoid*, GLenum, GLint, BufferUsage = BufferUsage::static_draw);
			MeshDataBuffer(MeshDataBuffer&&) noexcept;
			MeshDataBuffer& operator=(MeshDataBuffer&&) noexcept;
			~MeshDataBuffer();

			GLuint GetHandle() const noexcept;
			BufferType GetBufferType() const noexcept;
			GLenum GetDataType() const noexcept;
			GLint GetElementsPerVertex() const noexcept;

			void UpdateData(GLintptr offset, GLsizeiptr dataSize, const GLvoid* data) const noexcept;
			void* MapBuffer(GLintptr offset, GLsizeiptr dataSize, GLbitfield access) const noexcept;
			void UnmapBuffer() const noexcept;

			void Bind() const noexcept;
			void BindBase(GLuint) const noexcept;
			void BindRange(GLuint, GLintptr, GLsizeiptr) const noexcept;
		};
	}
}
<|endoftext|>