<commit_before>// SystemTray.cc
// Copyright (c) 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

// $Id: SystemTray.cc,v 1.3 2003/08/27 00:11:24 fluxgen Exp $

#include "SystemTray.hh"

#include "FbTk/EventManager.hh"

#include "AtomHandler.hh"
#include "fluxbox.hh"

#include <X11/Xutil.h>

#include <iostream>
#include <string>

using namespace std;

/// helper class for tray windows, so we dont call XDestroyWindow
class TrayWindow: public FbTk::FbWindow {
public:
    TrayWindow(Window win):FbTk::FbWindow(win) { }
};

/// handles clientmessage event and notifies systemtray
class SystemTrayHandler: public AtomHandler {
public:
    SystemTrayHandler(SystemTray &tray):m_tray(tray) {
    }
    // client message is the only thing we care about
    bool checkClientMessage(const XClientMessageEvent &ce,
                            BScreen * screen, WinClient * const winclient) {
        return m_tray.clientMessage(ce);
    }

    void initForScreen(BScreen &screen) { };
    void setupFrame(FluxboxWindow &win) { };
    void setupClient(WinClient &winclient) { };

    void updateClientList(BScreen &screen) { };
    void updateWorkspaceNames(BScreen &screen) { };
    void updateCurrentWorkspace(BScreen &screen) { };
    void updateWorkspaceCount(BScreen &screen) { };

    void updateFrameClose(FluxboxWindow &win) { };
    void updateClientClose(WinClient &winclient) { };
    void updateWorkspace(FluxboxWindow &win) { };
    void updateState(FluxboxWindow &win) { };
    void updateHints(FluxboxWindow &win) { };
    void updateLayer(FluxboxWindow &win) { };

    virtual bool propertyNotify(WinClient &winclient, Atom the_property) { return false; }

private:
    SystemTray &m_tray;
};

SystemTray::SystemTray(const FbTk::FbWindow &parent):
    ToolbarItem(ToolbarItem::FIXED),
    m_window(parent, 0, 0, 1, 1, ExposureMask | ButtonPressMask | ButtonReleaseMask |
             SubstructureNotifyMask | SubstructureRedirectMask) {

    FbTk::EventManager::instance()->add(*this, m_window);

    // setup atom name to _NET_SYSTEM_TRAY_S<screen number>
    char intbuff[16];
    sprintf(intbuff, "%d", m_window.screenNumber());
    std::string atom_name("_NET_SYSTEM_TRAY_S");
    atom_name += intbuff; // append number

    Display *disp = FbTk::App::instance()->display();

    // get selection owner and see if it's free
    Atom tray_atom = XInternAtom(disp, atom_name.c_str(), False);
    Window owner = XGetSelectionOwner(disp, tray_atom);
    if (owner != 0)
        return;  // the're can't be more than one owner

    // ok, it was free. Lets set owner
#ifdef DEBUG
    cerr<<__FILE__<<"("<<__FUNCTION__<<"): SETTING OWNER!"<<endl;
#endif // DEBUG
    // set owner
    XSetSelectionOwner(disp, tray_atom, m_window.window(), CurrentTime);
    m_handler.reset(new SystemTrayHandler(*this));
    Fluxbox::instance()->addAtomHandler(m_handler.get());
    Window root_window = RootWindow(disp, m_window.screenNumber());

    // send selection owner msg
    XEvent ce;
    ce.xclient.type = ClientMessage;
    ce.xclient.message_type = XInternAtom(disp, "MANAGER", False);
    ce.xclient.display = disp;
    ce.xclient.window = root_window;
    ce.xclient.format = 32;
    ce.xclient.data.l[0] = CurrentTime; // timestamp
    ce.xclient.data.l[1] = tray_atom; // manager selection atom
    ce.xclient.data.l[2] = m_window.window(); // the window owning the selection
    ce.xclient.data.l[3] = 0l; // selection specific data
    ce.xclient.data.l[4] = 0l; // selection specific data

    XSendEvent(disp, root_window, false, StructureNotifyMask, &ce);

}

SystemTray::~SystemTray() {
    // remove us, else fluxbox might delete the memory too
    Fluxbox::instance()->removeAtomHandler(m_handler.get());
    removeAllClients();
}

void SystemTray::move(int x, int y) {
    m_window.move(x, y);
}

void SystemTray::resize(unsigned int width, unsigned int height) {
    if (width != m_window.width() ||
        height != m_window.height()) {
        m_window.resize(SystemTray::width(), height);
        rearrangeClients();
    }
}

void SystemTray::moveResize(int x, int y,
                            unsigned int width, unsigned int height) {
    move(x, y);
    resize(width, height);
}

void SystemTray::hide() {
    m_window.hide();
}

void SystemTray::show() {
    m_window.show();
}

unsigned int SystemTray::width() const {
    return m_clients.size()*height(); //*m_tray_width;
}

unsigned int SystemTray::height() const {
    return m_window.height();
}

unsigned int SystemTray::borderWidth() const {
    return m_window.borderWidth();
}

bool SystemTray::clientMessage(const XClientMessageEvent &event) {
    static const int SYSTEM_TRAY_REQUEST_DOCK  =  0;
    //    static const int SYSTEM_TRAY_BEGIN_MESSAGE =  1;
    //    static const int SYSTEM_TRAY_CANCEL_MESSAGE = 2;

    if (event.message_type ==
        XInternAtom(FbTk::App::instance()->display(), "_NET_SYSTEM_TRAY_OPCODE", False)) {

        int type = event.data.l[1];
        if (type == SYSTEM_TRAY_REQUEST_DOCK) {
            addClient(event.data.l[2]);
        }
        /*
        else if (type == SYSTEM_TRAY_BEGIN_MESSAGE)
            cerr<<"BEGIN MESSAGE"<<endl;
        else if (type == SYSTEM_TRAY_CANCEL_MESSAGE)
            cerr<<"CANCEL MESSAGE"<<endl;
        */

        return true;
    }

    return false;
}

SystemTray::ClientList::iterator SystemTray::findClient(Window win) {

    ClientList::iterator it = m_clients.begin();
    ClientList::iterator it_end = m_clients.end();
    for (; it != it_end; ++it) {
        if ((*it)->window() == win)
            break;
    }

    return it;
}

void SystemTray::addClient(Window win) {
    if (win == 0)
        return;

    ClientList::iterator it = findClient(win);
    if (it != m_clients.end())
        return;

#ifdef DEBUG
    cerr<<__FILE__<<"("<<__FUNCTION__<<"): 0x"<<hex<<win<<dec<<endl;
#endif // DEBUG

    FbTk::FbWindow *traywin = new TrayWindow(win);
    m_clients.push_back(traywin);
    FbTk::EventManager::instance()->add(*this, win);
    XChangeSaveSet(FbTk::App::instance()->display(), win, SetModeInsert);
    traywin->reparent(m_window, 0, 0);
    traywin->show();

    resize(width(), m_clients.size()*height());

    rearrangeClients();
}

void SystemTray::removeClient(Window win) {
    ClientList::iterator tray_it = findClient(win);
    if (tray_it == m_clients.end())
        return;

#ifdef DEBUG
    cerr<<__FILE__<<"("<<__FUNCTION__<<"): 0x"<<hex<<win<<dec<<endl;
#endif // DEBUG

    FbTk::FbWindow *traywin = *tray_it;
    m_clients.erase(tray_it);
    delete traywin;
    resize(width(), height());
    rearrangeClients();
}

void SystemTray::exposeEvent(XExposeEvent &event) {
    m_window.clear();
}

void SystemTray::handleEvent(XEvent &event) {
    if (event.type == DestroyNotify)
        removeClient(event.xdestroywindow.window);
    else if (event.type == ConfigureNotify) {
        // we got configurenotify from an client
        // check and see if we need to update it's size
        ClientList::iterator it = findClient(event.xconfigure.window);
        if (it != m_clients.end()) {
            if (static_cast<unsigned int>(event.xconfigure.width) != (*it)->width() ||
                static_cast<unsigned int>(event.xconfigure.height) != (*it)->height())
                (*it)->resize((*it)->width(), (*it)->height());
        }
    }
}

void SystemTray::rearrangeClients() {
    // move and resize clients
    ClientList::iterator client_it = m_clients.begin();
    ClientList::iterator client_it_end = m_clients.end();
    int next_x = 0;
    for (; client_it != client_it_end; ++client_it, next_x += height()) {
        (*client_it)->moveResize(next_x, 0, height(), height());

#ifdef DEBUG
        cerr<<__FILE__<<"("<<__FUNCTION__<<"): "<<(*client_it)->width()<<", "<<(*client_it)->height()<<endl;
#endif // DEBUG
    }
}

void SystemTray::removeAllClients() {
    while (!m_clients.empty()) {
        m_clients.back()->hide();
        delete m_clients.back();
        m_clients.pop_back();
    }
}
<commit_msg>fixed resize after client death<commit_after>// SystemTray.cc
// Copyright (c) 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

// $Id: SystemTray.cc,v 1.4 2003/08/28 13:44:58 fluxgen Exp $

#include "SystemTray.hh"

#include "FbTk/EventManager.hh"

#include "AtomHandler.hh"
#include "fluxbox.hh"

#include <X11/Xutil.h>

#include <string>

using namespace std;

/// helper class for tray windows, so we dont call XDestroyWindow
class TrayWindow: public FbTk::FbWindow {
public:
    TrayWindow(Window win):FbTk::FbWindow(win) { }
};

/// handles clientmessage event and notifies systemtray
class SystemTrayHandler: public AtomHandler {
public:
    SystemTrayHandler(SystemTray &tray):m_tray(tray) {
    }
    // client message is the only thing we care about
    bool checkClientMessage(const XClientMessageEvent &ce,
                            BScreen * screen, WinClient * const winclient) {
        return m_tray.clientMessage(ce);
    }

    void initForScreen(BScreen &screen) { };
    void setupFrame(FluxboxWindow &win) { };
    void setupClient(WinClient &winclient) { };

    void updateClientList(BScreen &screen) { };
    void updateWorkspaceNames(BScreen &screen) { };
    void updateCurrentWorkspace(BScreen &screen) { };
    void updateWorkspaceCount(BScreen &screen) { };

    void updateFrameClose(FluxboxWindow &win) { };
    void updateClientClose(WinClient &winclient) { };
    void updateWorkspace(FluxboxWindow &win) { };
    void updateState(FluxboxWindow &win) { };
    void updateHints(FluxboxWindow &win) { };
    void updateLayer(FluxboxWindow &win) { };

    virtual bool propertyNotify(WinClient &winclient, Atom the_property) { return false; }

private:
    SystemTray &m_tray;
};

SystemTray::SystemTray(const FbTk::FbWindow &parent):
    ToolbarItem(ToolbarItem::FIXED),
    m_window(parent, 0, 0, 1, 1, ExposureMask | ButtonPressMask | ButtonReleaseMask |
             SubstructureNotifyMask | SubstructureRedirectMask) {

    FbTk::EventManager::instance()->add(*this, m_window);

    // setup atom name to _NET_SYSTEM_TRAY_S<screen number>
    char intbuff[16];
    sprintf(intbuff, "%d", m_window.screenNumber());
    std::string atom_name("_NET_SYSTEM_TRAY_S");
    atom_name += intbuff; // append number

    Display *disp = FbTk::App::instance()->display();

    // get selection owner and see if it's free
    Atom tray_atom = XInternAtom(disp, atom_name.c_str(), False);
    Window owner = XGetSelectionOwner(disp, tray_atom);
    if (owner != 0)
        return;  // the're can't be more than one owner

    // ok, it was free. Lets set owner
#ifdef DEBUG
    cerr<<__FILE__<<"("<<__FUNCTION__<<"): SETTING OWNER!"<<endl;
#endif // DEBUG
    // set owner
    XSetSelectionOwner(disp, tray_atom, m_window.window(), CurrentTime);
    m_handler.reset(new SystemTrayHandler(*this));
    Fluxbox::instance()->addAtomHandler(m_handler.get());
    Window root_window = RootWindow(disp, m_window.screenNumber());

    // send selection owner msg
    XEvent ce;
    ce.xclient.type = ClientMessage;
    ce.xclient.message_type = XInternAtom(disp, "MANAGER", False);
    ce.xclient.display = disp;
    ce.xclient.window = root_window;
    ce.xclient.format = 32;
    ce.xclient.data.l[0] = CurrentTime; // timestamp
    ce.xclient.data.l[1] = tray_atom; // manager selection atom
    ce.xclient.data.l[2] = m_window.window(); // the window owning the selection
    ce.xclient.data.l[3] = 0l; // selection specific data
    ce.xclient.data.l[4] = 0l; // selection specific data

    XSendEvent(disp, root_window, false, StructureNotifyMask, &ce);

}

SystemTray::~SystemTray() {
    // remove us, else fluxbox might delete the memory too
    Fluxbox::instance()->removeAtomHandler(m_handler.get());
    removeAllClients();
}

void SystemTray::move(int x, int y) {
    m_window.move(x, y);
}

void SystemTray::resize(unsigned int width, unsigned int height) {
    if (width != m_window.width() ||
        height != m_window.height()) {
        m_window.resize(SystemTray::width(), height);
        rearrangeClients();
    }
}

void SystemTray::moveResize(int x, int y,
                            unsigned int width, unsigned int height) {
    move(x, y);
    resize(width, height);
}

void SystemTray::hide() {
    m_window.hide();
}

void SystemTray::show() {
    m_window.show();
}

unsigned int SystemTray::width() const {
    return m_clients.size()*height();
}

unsigned int SystemTray::height() const {
    return m_window.height();
}

unsigned int SystemTray::borderWidth() const {
    return m_window.borderWidth();
}

bool SystemTray::clientMessage(const XClientMessageEvent &event) {
    static const int SYSTEM_TRAY_REQUEST_DOCK  =  0;
    //    static const int SYSTEM_TRAY_BEGIN_MESSAGE =  1;
    //    static const int SYSTEM_TRAY_CANCEL_MESSAGE = 2;

    if (event.message_type ==
        XInternAtom(FbTk::App::instance()->display(), "_NET_SYSTEM_TRAY_OPCODE", False)) {

        int type = event.data.l[1];
        if (type == SYSTEM_TRAY_REQUEST_DOCK) {
            addClient(event.data.l[2]);
        }
        /*
        else if (type == SYSTEM_TRAY_BEGIN_MESSAGE)
            cerr<<"BEGIN MESSAGE"<<endl;
        else if (type == SYSTEM_TRAY_CANCEL_MESSAGE)
            cerr<<"CANCEL MESSAGE"<<endl;
        */

        return true;
    }

    return false;
}

SystemTray::ClientList::iterator SystemTray::findClient(Window win) {

    ClientList::iterator it = m_clients.begin();
    ClientList::iterator it_end = m_clients.end();
    for (; it != it_end; ++it) {
        if ((*it)->window() == win)
            break;
    }

    return it;
}

void SystemTray::addClient(Window win) {
    if (win == 0)
        return;

    ClientList::iterator it = findClient(win);
    if (it != m_clients.end())
        return;

#ifdef DEBUG
    cerr<<__FILE__<<"("<<__FUNCTION__<<"): 0x"<<hex<<win<<dec<<endl;
#endif // DEBUG
    if (m_clients.size() == 0)
        show();

    FbTk::FbWindow *traywin = new TrayWindow(win);
    m_clients.push_back(traywin);
    FbTk::EventManager::instance()->add(*this, win);
    FbTk::EventManager::instance()->addParent(*this, window());
    XChangeSaveSet(FbTk::App::instance()->display(), win, SetModeInsert);
    traywin->reparent(m_window, 0, 0);
    traywin->show();

    resize(width(), m_clients.size()*height());

    rearrangeClients();
}

void SystemTray::removeClient(Window win) {
    ClientList::iterator tray_it = findClient(win);
    if (tray_it == m_clients.end())
        return;

#ifdef DEBUG
    cerr<<__FILE__<<"("<<__FUNCTION__<<"): 0x"<<hex<<win<<dec<<endl;
#endif // DEBUG
    FbTk::FbWindow *traywin = *tray_it;
    m_clients.erase(tray_it);
    delete traywin;
    resize(width(), height());
    rearrangeClients();
    if (m_clients.size() == 0) {
        // so we send configurenotify signal to parent
        m_window.resize(1, 1);
        hide();
    }
}

void SystemTray::exposeEvent(XExposeEvent &event) {
    m_window.clear();
}

void SystemTray::handleEvent(XEvent &event) {
    if (event.type == DestroyNotify) {
        removeClient(event.xdestroywindow.window);
    } else if (event.type == ConfigureNotify) {
        // we got configurenotify from an client
        // check and see if we need to update it's size
        ClientList::iterator it = findClient(event.xconfigure.window);
        if (it != m_clients.end()) {
            if (static_cast<unsigned int>(event.xconfigure.width) != (*it)->width() ||
                static_cast<unsigned int>(event.xconfigure.height) != (*it)->height())
                (*it)->resize((*it)->width(), (*it)->height());
        }
    }
}

void SystemTray::rearrangeClients() {
    // move and resize clients
    ClientList::iterator client_it = m_clients.begin();
    ClientList::iterator client_it_end = m_clients.end();
    int next_x = 0;
    for (; client_it != client_it_end; ++client_it, next_x += height()) {
        (*client_it)->moveResize(next_x, 0, height(), height());

#ifdef DEBUG
        cerr<<__FILE__<<"("<<__FUNCTION__<<"): "<<(*client_it)->width()<<", "<<(*client_it)->height()<<endl;
#endif // DEBUG
    }
}

void SystemTray::removeAllClients() {
    while (!m_clients.empty()) {
        m_clients.back()->hide();
        delete m_clients.back();
        m_clients.pop_back();
    }
}
<|endoftext|>


<commit_before>#include "Trackobot.h"

#include <QDir>
#include <QStandardPaths>

#include <QLocalServer>
#include <QLocalSocket>

#include "Updater.h"
#include "Settings.h"

#if defined Q_OS_MAC
#include "CocoaInitializer.h"
#include "SparkleUpdater.h"
#elif defined Q_OS_WIN
#include "WinSparkleUpdater.h"
#elif defined Q_OS_LINUX
//TODO: update notifier
#endif

#include "Hearthstone.h"
#include "WebProfile.h"

#include <cassert>
#include <QTranslator>

Updater *gUpdater = NULL;

Trackobot::Trackobot( int& argc, char **argv )
  : QApplication( argc, argv ),
    mWindow( NULL ),
    mOverlay( NULL ),
    mSingleInstanceServer( NULL )
{
  SetupApplication();
  mWebProfile = new WebProfile( this );
  mResultTracker = new ResultTracker( this );
  mLogTracker = new HearthstoneLogTracker( this );
}

Trackobot::~Trackobot() {
  if( mOverlay ) {
    delete mOverlay;
    mOverlay = NULL;
  }

  if( mWindow ) {
    delete mWindow;
    mWindow = NULL;
  }

  if( mSingleInstanceServer ) {
    delete mSingleInstanceServer;
    mSingleInstanceServer = NULL;
  }
}

int Trackobot::Run() {
  if( IsAlreadyRunning() )
    return 1;

  LOG( "Launch v%s on %s", VERSION, qt2cstr( QDate::currentDate().toString( Qt::ISODate ) ) );

  SetupUpdater();

  CreateUI();

  WireStuff();

  Initialize();

  SetupLogging();

  int exitCode = exec();

  // Tear down
  LOG( "Shutdown" );

  return exitCode;
}

bool Trackobot::IsAlreadyRunning() {
  // Enforce single instance
  const char serverName[] = "trackobot";

  QLocalSocket socket;
  socket.connectToServer( serverName );
  if( socket.waitForConnected( 500 ) ) {
    return true;
  }

  QLocalServer::removeServer( serverName );
  mSingleInstanceServer = new QLocalServer( NULL );
  if( !mSingleInstanceServer->listen(serverName) ) {
    return true;
  }

  return false;
}

void Trackobot::SetupApplication() {
#if defined Q_OS_MAC
  setAttribute( Qt::AA_UseHighDpiPixmaps );
  QIcon icon( ":/icons/mac_black.png" );
  icon.addFile( ":/icons/mac_black@2x.png" );
#elif defined Q_OS_WIN
  QIcon icon( ":/icons/win.ico" );
#elif defined Q_OS_LINUX
  QIcon icon = QIcon( ":/icons/Track-o-Bot.png" );

  /*QTranslator qtTranslator;
  qtTranslator.load("qt_" + QLocale::system().name(),
          QLibraryInfo::location(QLibraryInfo::TranslationsPath));
  installTranslator(&qtTranslator);*/

  QTranslator *translator = new QTranslator( this );
  QLocale locale = QLocale::system();
  LOG(locale.name().toLatin1());
  if(translator->load(
              QLatin1String("Track-o-Bot_") + locale.name().toLatin1(),
              QLatin1String(":/i18n"))){
      LOG("Translation loaded");
      installTranslator(translator);
  }
#endif
  setApplicationName( "Track-o-Bot" ); // for proper DataLocation handling
  setOrganizationName( "spidy.ch" );
  setOrganizationDomain( "spidy.ch" );
  setWindowIcon( icon );
}

void Trackobot::SetupLogging() {
  // Logging
  QString dataLocation = QStandardPaths::writableLocation( QStandardPaths::DataLocation );
  if( !QFile::exists(dataLocation) ) {
    QDir dir;
    dir.mkpath( dataLocation );
  }
  QString logFilePath = dataLocation + QDir::separator() + applicationName() + ".log";
  Logger::Instance()->SetLogPath( logFilePath );
  Logger::Instance()->StartProcessing();
}

void Trackobot::SetupUpdater() {
#if defined Q_OS_MAC
  CocoaInitializer cocoaInitializer;
  gUpdater = new SparkleUpdater( mWebProfile->WebserviceURL( "/appcast.xml" ) );
#elif defined Q_OS_WIN
  gUpdater = new WinSparkleUpdater( mWebProfile->WebserviceURL( "/appcast_win.xml" ) );
#elif defined Q_OS_LINUX
  gUpdater = NULL;
#endif
}

void Trackobot::CreateUI() {
  mOverlay = new Overlay();
  mWindow = new Window();
}

void Trackobot::WireStuff() {
  assert( mWindow && mLogTracker && mOverlay );

  // ResultTracker
  connect( mLogTracker, &HearthstoneLogTracker::HandleOutcome, mResultTracker, &ResultTracker::HandleOutcome );
  connect( mLogTracker, &HearthstoneLogTracker::HandleOrder, mResultTracker, &ResultTracker::HandleOrder );
  connect( mLogTracker, &HearthstoneLogTracker::HandleOwnClass, mResultTracker, &ResultTracker::HandleOwnClass ) ;
  connect( mLogTracker, &HearthstoneLogTracker::HandleOpponentClass, mResultTracker, &ResultTracker::HandleOpponentClass );
  connect( mLogTracker, &HearthstoneLogTracker::HandleGameMode, mResultTracker, &ResultTracker::HandleGameMode );
  connect( mLogTracker, &HearthstoneLogTracker::HandleLegend, mResultTracker, &ResultTracker::HandleLegend );
  connect( mLogTracker, &HearthstoneLogTracker::HandleTurn, mResultTracker, &ResultTracker::HandleTurn );
  connect( mLogTracker, &HearthstoneLogTracker::HandleCardsPlayedUpdate, mResultTracker, &ResultTracker::HandleCardsPlayedUpdate );

  connect( mLogTracker, &HearthstoneLogTracker::HandleSpectating, mResultTracker, &ResultTracker::HandleSpectating );
  connect( mLogTracker, &HearthstoneLogTracker::HandleMatchStart, mResultTracker, &ResultTracker::HandleMatchStart );
  connect( mLogTracker, &HearthstoneLogTracker::HandleMatchEnd, mResultTracker, &ResultTracker::HandleMatchEnd );

  // Overlay
  connect( mLogTracker, &HearthstoneLogTracker::HandleCardsDrawnUpdate, mOverlay, &Overlay::HandleCardsDrawnUpdate );

  // Window
  connect( mWindow, &Window::OpenProfile, mWebProfile, &WebProfile::OpenProfile );
}

void Trackobot::Initialize() {

  // Make sure Account exists or create one
  mWebProfile->EnsureAccountIsSetUp();

  // Enable HS Logging
  Hearthstone::Instance()->EnableLogging();

  // Create Result Tracker
}

<commit_msg>Improve code style.<commit_after>#include "Trackobot.h"

#include <QDir>
#include <QStandardPaths>

#include <QLocalServer>
#include <QLocalSocket>

#include "Updater.h"
#include "Settings.h"

#if defined Q_OS_MAC
#include "CocoaInitializer.h"
#include "SparkleUpdater.h"
#elif defined Q_OS_WIN
#include "WinSparkleUpdater.h"
#elif defined Q_OS_LINUX
//TODO: update notifier
#endif

#include "Hearthstone.h"
#include "WebProfile.h"

#include <cassert>
#include <QTranslator>

Updater *gUpdater = NULL;

Trackobot::Trackobot( int& argc, char **argv )
  : QApplication( argc, argv ),
    mWindow( NULL ),
    mOverlay( NULL ),
    mSingleInstanceServer( NULL )
{
  SetupApplication();
  mWebProfile = new WebProfile( this );
  mResultTracker = new ResultTracker( this );
  mLogTracker = new HearthstoneLogTracker( this );
}

Trackobot::~Trackobot() {
  if( mOverlay ) {
    delete mOverlay;
    mOverlay = NULL;
  }

  if( mWindow ) {
    delete mWindow;
    mWindow = NULL;
  }

  if( mSingleInstanceServer ) {
    delete mSingleInstanceServer;
    mSingleInstanceServer = NULL;
  }
}

int Trackobot::Run() {
  if( IsAlreadyRunning() )
    return 1;

  LOG( "Launch v%s on %s", VERSION, qt2cstr( QDate::currentDate().toString( Qt::ISODate ) ) );

  SetupUpdater();

  CreateUI();

  WireStuff();

  Initialize();

  SetupLogging();

  int exitCode = exec();

  // Tear down
  LOG( "Shutdown" );

  return exitCode;
}

bool Trackobot::IsAlreadyRunning() {
  // Enforce single instance
  const char serverName[] = "trackobot";

  QLocalSocket socket;
  socket.connectToServer( serverName );
  if( socket.waitForConnected( 500 ) ) {
    return true;
  }

  QLocalServer::removeServer( serverName );
  mSingleInstanceServer = new QLocalServer( NULL );
  if( !mSingleInstanceServer->listen(serverName) ) {
    return true;
  }

  return false;
}

void Trackobot::SetupApplication() {
#if defined Q_OS_MAC
  setAttribute( Qt::AA_UseHighDpiPixmaps );
  QIcon icon( ":/icons/mac_black.png" );
  icon.addFile( ":/icons/mac_black@2x.png" );
#elif defined Q_OS_WIN
  QIcon icon( ":/icons/win.ico" );
#elif defined Q_OS_LINUX
  QIcon icon = QIcon( ":/icons/Track-o-Bot.png" );

  /*QTranslator qtTranslator;
  qtTranslator.load("qt_" + QLocale::system().name(),
          QLibraryInfo::location(QLibraryInfo::TranslationsPath));
  installTranslator(&qtTranslator);*/

  QTranslator *translator = new QTranslator( this );
  QLocale locale = QLocale::system();
  LOG( locale.name().toLatin1() );
  if( translator->load(
              QLatin1String( "Track-o-Bot_" ) + locale.name().toLatin1(),
              QLatin1String( ":/i18n" ) ) ) {
      LOG( "Translation loaded" );
      installTranslator( translator );
  }
#endif
  setApplicationName( "Track-o-Bot" ); // for proper DataLocation handling
  setOrganizationName( "spidy.ch" );
  setOrganizationDomain( "spidy.ch" );
  setWindowIcon( icon );
}

void Trackobot::SetupLogging() {
  // Logging
  QString dataLocation = QStandardPaths::writableLocation( QStandardPaths::DataLocation );
  if( !QFile::exists(dataLocation) ) {
    QDir dir;
    dir.mkpath( dataLocation );
  }
  QString logFilePath = dataLocation + QDir::separator() + applicationName() + ".log";
  Logger::Instance()->SetLogPath( logFilePath );
  Logger::Instance()->StartProcessing();
}

void Trackobot::SetupUpdater() {
#if defined Q_OS_MAC
  CocoaInitializer cocoaInitializer;
  gUpdater = new SparkleUpdater( mWebProfile->WebserviceURL( "/appcast.xml" ) );
#elif defined Q_OS_WIN
  gUpdater = new WinSparkleUpdater( mWebProfile->WebserviceURL( "/appcast_win.xml" ) );
#elif defined Q_OS_LINUX
  gUpdater = NULL;
#endif
}

void Trackobot::CreateUI() {
  mOverlay = new Overlay();
  mWindow = new Window();
}

void Trackobot::WireStuff() {
  assert( mWindow && mLogTracker && mOverlay );

  // ResultTracker
  connect( mLogTracker, &HearthstoneLogTracker::HandleOutcome, mResultTracker, &ResultTracker::HandleOutcome );
  connect( mLogTracker, &HearthstoneLogTracker::HandleOrder, mResultTracker, &ResultTracker::HandleOrder );
  connect( mLogTracker, &HearthstoneLogTracker::HandleOwnClass, mResultTracker, &ResultTracker::HandleOwnClass ) ;
  connect( mLogTracker, &HearthstoneLogTracker::HandleOpponentClass, mResultTracker, &ResultTracker::HandleOpponentClass );
  connect( mLogTracker, &HearthstoneLogTracker::HandleGameMode, mResultTracker, &ResultTracker::HandleGameMode );
  connect( mLogTracker, &HearthstoneLogTracker::HandleLegend, mResultTracker, &ResultTracker::HandleLegend );
  connect( mLogTracker, &HearthstoneLogTracker::HandleTurn, mResultTracker, &ResultTracker::HandleTurn );
  connect( mLogTracker, &HearthstoneLogTracker::HandleCardsPlayedUpdate, mResultTracker, &ResultTracker::HandleCardsPlayedUpdate );

  connect( mLogTracker, &HearthstoneLogTracker::HandleSpectating, mResultTracker, &ResultTracker::HandleSpectating );
  connect( mLogTracker, &HearthstoneLogTracker::HandleMatchStart, mResultTracker, &ResultTracker::HandleMatchStart );
  connect( mLogTracker, &HearthstoneLogTracker::HandleMatchEnd, mResultTracker, &ResultTracker::HandleMatchEnd );

  // Overlay
  connect( mLogTracker, &HearthstoneLogTracker::HandleCardsDrawnUpdate, mOverlay, &Overlay::HandleCardsDrawnUpdate );

  // Window
  connect( mWindow, &Window::OpenProfile, mWebProfile, &WebProfile::OpenProfile );
}

void Trackobot::Initialize() {

  // Make sure Account exists or create one
  mWebProfile->EnsureAccountIsSetUp();

  // Enable HS Logging
  Hearthstone::Instance()->EnableLogging();

  // Create Result Tracker
}

<|endoftext|>


<commit_before>// RUN: pp-trace -ignore FileChanged,MacroDefined %s -target x86_64 -fms-extensions -w | FileCheck --strict-whitespace %s

#pragma comment(compiler, "compiler comment")
#pragma comment(exestr, "exestr comment")
#pragma comment(lib, "lib comment")
#pragma comment(linker, "linker comment")
#pragma comment(user, "user comment")

#pragma detect_mismatch("name argument", "value argument")

#pragma __debug(assert)

#pragma message("message argument")

#pragma warning(push, 1)
#pragma warning(pop)
#pragma warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)

// CHECK: ---
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:3:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaComment
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:3:9"
// CHECK-NEXT:   Kind: compiler
// CHECK-NEXT:   Str: compiler comment
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:4:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaComment
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:4:9"
// CHECK-NEXT:   Kind: exestr
// CHECK-NEXT:   Str: exestr comment
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:5:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaComment
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:5:9"
// CHECK-NEXT:   Kind: lib
// CHECK-NEXT:   Str: lib comment
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:6:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaComment
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:6:9"
// CHECK-NEXT:   Kind: linker
// CHECK-NEXT:   Str: linker comment
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:7:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaComment
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:7:9"
// CHECK-NEXT:   Kind: user
// CHECK-NEXT:   Str: user comment
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:9:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaDetectMismatch
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:9:9"
// CHECK-NEXT:   Name: name argument
// CHECK-NEXT:   Value: value argument
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:11:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:13:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaMessage
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:13:9"
// CHECK-NEXT:   Namespace:
// CHECK-NEXT:   Kind: PMK_Message
// CHECK-NEXT:   Str: message argument
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:15:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaWarningPush
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:15:9"
// CHECK-NEXT:   Level: 1
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:16:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaWarningPop
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:16:9"
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:17:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaWarning
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:17:9"
// CHECK-NEXT:   WarningSpec: disable
// CHECK-NEXT:   Ids: [1, 2, 3]
// CHECK-NEXT: - Callback: PragmaWarning
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:17:9"
// CHECK-NEXT:   WarningSpec: error
// CHECK-NEXT:   Ids: [4, 5, 6]
// CHECK-NEXT: - Callback: PragmaWarning
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:17:9"
// CHECK-NEXT:   WarningSpec: suppress
// CHECK-NEXT:   Ids: [7, 8, 9]
// CHECK-NEXT: - Callback: EndOfMainFile
// CHECK-NEXT: ...
<commit_msg>test: use target triple for the test<commit_after>// RUN: pp-trace -ignore FileChanged,MacroDefined %s -target x86_64-unknown-windows-msvc -fms-extensions -w | FileCheck --strict-whitespace %s

#pragma comment(compiler, "compiler comment")
#pragma comment(exestr, "exestr comment")
#pragma comment(lib, "lib comment")
#pragma comment(linker, "linker comment")
#pragma comment(user, "user comment")

#pragma detect_mismatch("name argument", "value argument")

#pragma __debug(assert)

#pragma message("message argument")

#pragma warning(push, 1)
#pragma warning(pop)
#pragma warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)

// CHECK: ---
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:3:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaComment
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:3:9"
// CHECK-NEXT:   Kind: compiler
// CHECK-NEXT:   Str: compiler comment
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:4:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaComment
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:4:9"
// CHECK-NEXT:   Kind: exestr
// CHECK-NEXT:   Str: exestr comment
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:5:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaComment
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:5:9"
// CHECK-NEXT:   Kind: lib
// CHECK-NEXT:   Str: lib comment
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:6:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaComment
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:6:9"
// CHECK-NEXT:   Kind: linker
// CHECK-NEXT:   Str: linker comment
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:7:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaComment
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:7:9"
// CHECK-NEXT:   Kind: user
// CHECK-NEXT:   Str: user comment
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:9:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaDetectMismatch
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:9:9"
// CHECK-NEXT:   Name: name argument
// CHECK-NEXT:   Value: value argument
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:11:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:13:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaMessage
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:13:9"
// CHECK-NEXT:   Namespace:
// CHECK-NEXT:   Kind: PMK_Message
// CHECK-NEXT:   Str: message argument
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:15:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaWarningPush
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:15:9"
// CHECK-NEXT:   Level: 1
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:16:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaWarningPop
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:16:9"
// CHECK-NEXT: - Callback: PragmaDirective
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:17:1"
// CHECK-NEXT:   Introducer: PIK_HashPragma
// CHECK-NEXT: - Callback: PragmaWarning
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:17:9"
// CHECK-NEXT:   WarningSpec: disable
// CHECK-NEXT:   Ids: [1, 2, 3]
// CHECK-NEXT: - Callback: PragmaWarning
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:17:9"
// CHECK-NEXT:   WarningSpec: error
// CHECK-NEXT:   Ids: [4, 5, 6]
// CHECK-NEXT: - Callback: PragmaWarning
// CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:17:9"
// CHECK-NEXT:   WarningSpec: suppress
// CHECK-NEXT:   Ids: [7, 8, 9]
// CHECK-NEXT: - Callback: EndOfMainFile
// CHECK-NEXT: ...
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2018 Red Hat, Inc.
 *
 * Licensed under the GNU Lesser General Public License Version 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "iniparser.hpp"

const char * IniParser::CantOpenFile::what() const noexcept
{
    return "IniParser: Can't open file";
}

const char * IniParser::MissingSectionHeader::what() const noexcept
{
    return "IniParser: Missing section header";
}

const char * IniParser::MissingBracket::what() const noexcept
{
    return "IniParser: Missing ']'";
}

const char * IniParser::EmptySectionName::what() const noexcept
{
    return "IniParser: Empty section name";
}

const char * IniParser::TextAfterSection::what() const noexcept
{
    return "IniParser: Text after section";
}

const char * IniParser::IllegalContinuationLine::what() const noexcept
{
    return "IniParser: Illegal continuation line";
}

const char * IniParser::MissingKey::what() const noexcept
{
    return "IniParser: Missing key";
}

const char * IniParser::MissingEqual::what() const noexcept
{
    return "IniParser: Missing '='";
}

IniParser::IniParser(const std::string & filePath)
: ifs(filePath)
{
    if (!ifs)
        throw CantOpenFile();
    ifs.exceptions(std::ifstream::badbit);
    lineNumber = 0;
}

void IniParser::trimValue() noexcept {
    if (value.length() > 1 &&
        value.front() == value.back() &&
        (value.front() == '\"' || value.front() == '\'')) {
        value.erase(--value.end());
        value.erase(value.begin());
    }
}

IniParser::ItemType IniParser::next()
{
    bool previousLineWithKeyVal = false;
    while (!line.empty() || !ifs.eof()) {
        if (line.empty()) {
            std::getline(ifs, line);
            ++lineNumber;
        }

        // remove UTF-8 BOM
        if (lineNumber == 1 && line.length() >= 3 &&
            static_cast<unsigned char>(line[0]) == 0xEF &&
            static_cast<unsigned char>(line[1]) == 0xBB &&
            static_cast<unsigned char>(line[2]) == 0xBF)
            line.erase(0, 3);

        if (line[0] == '#' || line[0] == ';') {// do not support [rR][eE][mM] comment
            line.clear();
            continue;
        }
        auto start = line.find_first_not_of(" \t\r");
        if (start == std::string::npos) {
            line.clear();
            continue;
        }
        auto end = line.find_last_not_of(" \t\r");

        if (previousLineWithKeyVal && (start == 0 || line[start] == '[')) {
            trimValue();
            return ItemType::KEY_VAL;
        }

        if (line[start] == '[') {
            auto endSectPos = line.find("]", ++start);
            if (endSectPos == line.npos)
                throw MissingBracket(lineNumber);
            else if (endSectPos == start)
                throw EmptySectionName(lineNumber);
            for (auto idx = endSectPos + 1; idx < end; ++idx)
            {
                auto ch = line[idx];
                if (ch == '#' || ch == ';')
                    break;
                if (ch != ' ' && ch != '\t' && ch != '\r')
                    throw TextAfterSection(lineNumber);
            }
            this->section = line.substr(start, endSectPos - start);
            line.clear();
            return ItemType::SECTION;
        }

        if (section.empty())
            throw MissingSectionHeader(lineNumber);

        if (start > 0) {
            if (!previousLineWithKeyVal)
                throw IllegalContinuationLine(lineNumber);
            value += "\n" + line.substr(start, end - start + 1);
            line.clear();
        } else {
            if (line[start] == '=')
                throw MissingKey(lineNumber);
            auto eqlpos = line.find_first_of("=");
            if (eqlpos == std::string::npos)
                throw MissingEqual(lineNumber);
            auto endkeypos = line.find_last_not_of(" \t", eqlpos - 1);
            auto valuepos = line.find_first_not_of(" \t", eqlpos + 1);
            key = line.substr(start, endkeypos - start + 1);
            if (valuepos != line.npos)
                value = line.substr(valuepos, end - valuepos + 1);
            else
                value.clear();
            previousLineWithKeyVal = true;
            line.clear();
        }
    }
    trimValue();
    return previousLineWithKeyVal ? ItemType::KEY_VAL : ItemType::END_OF_INPUT;
}
<commit_msg>IniParser: comment line and zero length line terminate multiline value<commit_after>/*
 * Copyright (C) 2018 Red Hat, Inc.
 *
 * Licensed under the GNU Lesser General Public License Version 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "iniparser.hpp"

const char * IniParser::CantOpenFile::what() const noexcept
{
    return "IniParser: Can't open file";
}

const char * IniParser::MissingSectionHeader::what() const noexcept
{
    return "IniParser: Missing section header";
}

const char * IniParser::MissingBracket::what() const noexcept
{
    return "IniParser: Missing ']'";
}

const char * IniParser::EmptySectionName::what() const noexcept
{
    return "IniParser: Empty section name";
}

const char * IniParser::TextAfterSection::what() const noexcept
{
    return "IniParser: Text after section";
}

const char * IniParser::IllegalContinuationLine::what() const noexcept
{
    return "IniParser: Illegal continuation line";
}

const char * IniParser::MissingKey::what() const noexcept
{
    return "IniParser: Missing key";
}

const char * IniParser::MissingEqual::what() const noexcept
{
    return "IniParser: Missing '='";
}

IniParser::IniParser(const std::string & filePath)
: ifs(filePath)
{
    if (!ifs)
        throw CantOpenFile();
    ifs.exceptions(std::ifstream::badbit);
    lineNumber = 0;
}

void IniParser::trimValue() noexcept {
    if (value.length() > 1 &&
        value.front() == value.back() &&
        (value.front() == '\"' || value.front() == '\'')) {
        value.erase(--value.end());
        value.erase(value.begin());
    }
}

IniParser::ItemType IniParser::next()
{
    bool previousLineWithKeyVal = false;
    while (!line.empty() || !ifs.eof()) {
        if (line.empty()) {
            std::getline(ifs, line);
            ++lineNumber;
        }

        // remove UTF-8 BOM
        if (lineNumber == 1 && line.length() >= 3 &&
            static_cast<unsigned char>(line[0]) == 0xEF &&
            static_cast<unsigned char>(line[1]) == 0xBB &&
            static_cast<unsigned char>(line[2]) == 0xBF)
            line.erase(0, 3);

        if (line.length() == 0 || line[0] == '#' || line[0] == ';') {// do not support [rR][eE][mM] comment
            if (previousLineWithKeyVal) {
                trimValue();
                return ItemType::KEY_VAL;
            }
            line.clear();
            continue;
        }
        auto start = line.find_first_not_of(" \t\r");
        if (start == std::string::npos) {
            line.clear();
            continue;
        }
        auto end = line.find_last_not_of(" \t\r");

        if (previousLineWithKeyVal && (start == 0 || line[start] == '[')) {
            trimValue();
            return ItemType::KEY_VAL;
        }

        if (line[start] == '[') {
            auto endSectPos = line.find("]", ++start);
            if (endSectPos == line.npos)
                throw MissingBracket(lineNumber);
            else if (endSectPos == start)
                throw EmptySectionName(lineNumber);
            for (auto idx = endSectPos + 1; idx < end; ++idx)
            {
                auto ch = line[idx];
                if (ch == '#' || ch == ';')
                    break;
                if (ch != ' ' && ch != '\t' && ch != '\r')
                    throw TextAfterSection(lineNumber);
            }
            this->section = line.substr(start, endSectPos - start);
            line.clear();
            return ItemType::SECTION;
        }

        if (section.empty())
            throw MissingSectionHeader(lineNumber);

        if (start > 0) {
            if (!previousLineWithKeyVal)
                throw IllegalContinuationLine(lineNumber);
            value += "\n" + line.substr(start, end - start + 1);
            line.clear();
        } else {
            if (line[start] == '=')
                throw MissingKey(lineNumber);
            auto eqlpos = line.find_first_of("=");
            if (eqlpos == std::string::npos)
                throw MissingEqual(lineNumber);
            auto endkeypos = line.find_last_not_of(" \t", eqlpos - 1);
            auto valuepos = line.find_first_not_of(" \t", eqlpos + 1);
            key = line.substr(start, endkeypos - start + 1);
            if (valuepos != line.npos)
                value = line.substr(valuepos, end - valuepos + 1);
            else
                value.clear();
            previousLineWithKeyVal = true;
            line.clear();
        }
    }
    trimValue();
    return previousLineWithKeyVal ? ItemType::KEY_VAL : ItemType::END_OF_INPUT;
}
<|endoftext|>


<commit_before>/*
Copyright 2016 Colin Girling

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 "../Test.hpp"
#include "../TestString.hpp"

TEST_MEMBER_FUNCTION(TestString, TestString, char_const_ptr)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char const*");

    {
        TestString empty_string;
        CHECK_TRUE(empty_string.IsEmpty());
    }

    {
        TestString empty_string(NULL);
        CHECK_TRUE(empty_string.IsEmpty());
    }

    {
        TestString str("Hello");
        CHECK_FALSE(str.IsEmpty());
        CHECK_EQUAL(str.GetLength(), 5U);
    }
}

TEST_MEMBER_FUNCTION(TestString, TestString, char_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char,size_type");

    {
        TestString str('a', 1U);
        CHECK_FALSE(str.IsEmpty());
        CHECK_ZERO(StrCmp(str.Ptr(), "a"));
    }

    {
        TestString str('b', 2U);
        CHECK_FALSE(str.IsEmpty());
        CHECK_ZERO(StrCmp(str.Ptr(), "bb"));
    }
}

TEST_MEMBER_FUNCTION(TestString, TestString, TestString_const_ref)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("TestString const&");

    {
        TestString str_src;
        TestString str(str_src);
        CHECK_TRUE(str.IsEmpty());
    }

    {
        TestString str_src("Hello");
        TestString str(str_src);
        CHECK_FALSE(str.IsEmpty());
        CHECK_ZERO(StrCmp(str.Ptr(), str_src.Ptr()));
    }
}

TEST_MEMBER_FUNCTION(TestString, operator_assignment, char_const_ptr)
{
    using ocl::TestString;

    TEST_OVERRIDE_FUNCTION_NAME_ARGS("operator =", "char const*");

    char const* hello_str = "Hello";

    TestString str;
    str = "";
    CHECK_TRUE(str.IsEmpty());
    CHECK_ZERO(str.GetLength());
    str = hello_str;
    CHECK_FALSE(str.IsEmpty());
    CHECK_ZERO(StrCmp(str.Ptr(), hello_str));
    CHECK_EQUAL(str.GetLength(), StrLen(hello_str));
}

TEST_MEMBER_FUNCTION(TestString, operator_assignment, TestString_const_ref)
{
    using ocl::TestString;

    TEST_OVERRIDE_FUNCTION_NAME_ARGS("operator =", "TestString const&");

    TestString empty_string;
    TestString hello_string("Hello");

    TestString str;
    str = empty_string;
    CHECK_TRUE(str.IsEmpty());
    CHECK_ZERO(str.GetLength());

    str = hello_string;
    CHECK_FALSE(str.IsEmpty());
    CHECK_ZERO(StrCmp(str.Ptr(), hello_string.Ptr()));
    CHECK_EQUAL(str.GetLength(), hello_string.GetLength());

    // Ensure assigning to nothing will clear any existing string.
    str = empty_string;
    CHECK_TRUE(str.IsEmpty());
    CHECK_ZERO(str.GetLength());
}

TEST_MEMBER_FUNCTION(TestString, operator_plus_equal, char_const_ptr)
{
    using ocl::TestString;

    TEST_OVERRIDE_FUNCTION_NAME_ARGS("operator +=", "char const* str");

    TestString str;
    str += static_cast<char const*>(NULL);
    CHECK_TRUE(str.IsEmpty());
    CHECK_EQUAL(str.GetLength(), 0U);

    str += "";
    CHECK_TRUE(str.IsEmpty());
    CHECK_EQUAL(str.GetLength(), 0U);

    str += "H";
    CHECK_ZERO(StrCmp(str.Ptr(), "H"));
    CHECK_EQUAL(str.GetLength(), 1U);

    str += "ello";
    CHECK_ZERO(StrCmp(str.Ptr(), "Hello"));
    CHECK_EQUAL(str.GetLength(), 5U);
}

TEST_MEMBER_FUNCTION(TestString, operator_plus_equal, TestString_const_ref)
{
    using ocl::TestString;

    TEST_OVERRIDE_FUNCTION_NAME_ARGS("operator +=", "TestString const&");

    TestString empty_string;
    TestString str;

    str += empty_string;
    CHECK_TRUE(str.IsEmpty());
    CHECK_EQUAL(str.GetLength(), 0U);

    TestString h_str("H");
    str += h_str;
    CHECK_ZERO(StrCmp(str.Ptr(), h_str.Ptr()));
    CHECK_EQUAL(str.GetLength(), 1U);

    TestString ello_str("ello");
    str += ello_str;
    CHECK_ZERO(StrCmp(str.Ptr(), "Hello"));
    CHECK_EQUAL(str.GetLength(), 5U);
}

TEST_CONST_MEMBER_FUNCTION(TestString, operator_subscript, size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_FUNCTION_NAME("operator []");

    TestString const str("Hello");

    CHECK_EQUAL(str[0U], 'H');
    CHECK_EQUAL(str[4U], 'o');
}

TEST_MEMBER_FUNCTION(TestString, operator_subscript, size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_FUNCTION_NAME("operator []");

    TestString str("Hello");

    char& ch0 = str[0U];
    CHECK_EQUAL(ch0, 'H');
    ch0 = 'h';
    CHECK_EQUAL(str[0U], 'h');

    char& ch4 = str[4U];
    CHECK_EQUAL(ch4, 'o');
    ch4 = 'Z';
    CHECK_EQUAL(str[4U], 'Z');
}

TEST_CONST_MEMBER_FUNCTION(TestString, char_const_ptr, NA)
{
    using ocl::TestString;

    TEST_OVERRIDE_FUNCTION_NAME("char const*");

    char const* hello_str = "Hello";

    TestString str;
    char const* ptr = static_cast<char const*>(str);
    CHECK_NOT_NULL(ptr);
    CHECK_EQUAL(*ptr, '\0');

    str = hello_str;
    ptr = static_cast<char const*>(str);
    CHECK_NOT_NULL(ptr);
    CHECK_ZERO(StrCmp(ptr, hello_str));
    CHECK_EQUAL(StrLen(ptr), 5U);
}

TEST_CONST_MEMBER_FUNCTION(TestString, operator_is_equal, char_const_ptr)
{
    using ocl::TestString;

    TEST_OVERRIDE_FUNCTION_NAME_ARGS("operator ==", "char const*");

    TestString str;
    CHECK_TRUE(str == "");
    CHECK_TRUE(str == static_cast<char const*>(NULL));

    str = "A";
    CHECK_TRUE(str == "A");
    CHECK_FALSE(str == "a");
}

TEST_MEMBER_FUNCTION(TestString, operator_is_equal, TestString_const_ref)
{
    using ocl::TestString;

    TEST_OVERRIDE_FUNCTION_NAME_ARGS("operator ==", "TestString const&");

    TestString empty_string;
    TestString a_str("a");
    TestString A_str("A");

    TestString str;
    CHECK_TRUE(str == empty_string);

    str = A_str;
    CHECK_TRUE(str == A_str);
    CHECK_FALSE(str == a_str);
}

TEST_CONST_MEMBER_FUNCTION(TestString, Ptr, NA)
{
    using ocl::TestString;

    char const* hello_string = "Hello";

    TestString str;
    CHECK_NOT_NULL(str.Ptr());
    CHECK_ZERO(StrCmp(str.Ptr(), ""));

    str = hello_string;

    // Make sure assignment of hello_string does not just reference the same pointer.
    CHECK_NOT_EQUAL(str.Ptr(), hello_string);

    CHECK_ZERO(StrCmp(str.Ptr(), hello_string));
}

TEST_CONST_MEMBER_FUNCTION(TestString, GetLength, NA)
{
    using ocl::TestString;

}

TEST_CONST_MEMBER_FUNCTION(TestString, IsEmpty, NA)
{
    using ocl::TestString;

}

TEST_MEMBER_FUNCTION(TestString, Clear, NA)
{
    using ocl::TestString;

}

TEST_CONST_MEMBER_FUNCTION(TestString, Find, char_size_type_ref_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char,size_type&,size_type");

}

TEST_MEMBER_FUNCTION(TestString, GetSubString, TestString_ref_size_type_size_type_bool)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("TestString&,size_type,size_type,bool");

}

TEST_MEMBER_FUNCTION(TestString, Assign, char_const_ptr)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char const*");

}

TEST_MEMBER_FUNCTION(TestString, Assign, TestString_const_ref)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("TestString const&");

}

TEST_MEMBER_FUNCTION(TestString, Move, char_ptr_ref_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char*&,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Prepend, char_const_ptr)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char const*");

}

TEST_MEMBER_FUNCTION(TestString, Append, char_const_ptr)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char const*");

}

TEST_MEMBER_FUNCTION(TestString, Append, char_const_ptr_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char const*,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, TestString_const_ptr)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("TestString const&");

}

TEST_MEMBER_FUNCTION(TestString, Append, bool)
{
    using ocl::TestString;

}

TEST_MEMBER_FUNCTION(TestString, Append, char)
{
    using ocl::TestString;

}

TEST_MEMBER_FUNCTION(TestString, Append, char_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, char_size_type_char_const_ptr_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char,size_type,char const*,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, signed_char_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("signed char,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, unsigned_char_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("unsigned char,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, signed_short_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("signed short,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, unsigned_short_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("unsigned short,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, signed_int_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("signed int,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, unsigned_int_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("unsigned int,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, signed_long_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("signed long,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, unsigned_long_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("unsigned long,size_type");

}
<commit_msg>Added unit tests for GetLength, IsEmpty and Clear functions of TestString class.<commit_after>/*
Copyright 2016 Colin Girling

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 "../Test.hpp"
#include "../TestString.hpp"

TEST_MEMBER_FUNCTION(TestString, TestString, char_const_ptr)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char const*");

    {
        TestString empty_string;
        CHECK_TRUE(empty_string.IsEmpty());
    }

    {
        TestString empty_string(NULL);
        CHECK_TRUE(empty_string.IsEmpty());
    }

    {
        TestString str("Hello");
        CHECK_FALSE(str.IsEmpty());
        CHECK_EQUAL(str.GetLength(), 5U);
    }
}

TEST_MEMBER_FUNCTION(TestString, TestString, char_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char,size_type");

    {
        TestString str('a', 1U);
        CHECK_FALSE(str.IsEmpty());
        CHECK_ZERO(StrCmp(str.Ptr(), "a"));
    }

    {
        TestString str('b', 2U);
        CHECK_FALSE(str.IsEmpty());
        CHECK_ZERO(StrCmp(str.Ptr(), "bb"));
    }
}

TEST_MEMBER_FUNCTION(TestString, TestString, TestString_const_ref)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("TestString const&");

    {
        TestString str_src;
        TestString str(str_src);
        CHECK_TRUE(str.IsEmpty());
    }

    {
        TestString str_src("Hello");
        TestString str(str_src);
        CHECK_FALSE(str.IsEmpty());
        CHECK_ZERO(StrCmp(str.Ptr(), str_src.Ptr()));
    }
}

TEST_MEMBER_FUNCTION(TestString, operator_assignment, char_const_ptr)
{
    using ocl::TestString;

    TEST_OVERRIDE_FUNCTION_NAME_ARGS("operator =", "char const*");

    char const* hello_str = "Hello";

    TestString str;
    str = "";
    CHECK_TRUE(str.IsEmpty());
    CHECK_ZERO(str.GetLength());
    str = hello_str;
    CHECK_FALSE(str.IsEmpty());
    CHECK_ZERO(StrCmp(str.Ptr(), hello_str));
    CHECK_EQUAL(str.GetLength(), StrLen(hello_str));
}

TEST_MEMBER_FUNCTION(TestString, operator_assignment, TestString_const_ref)
{
    using ocl::TestString;

    TEST_OVERRIDE_FUNCTION_NAME_ARGS("operator =", "TestString const&");

    TestString empty_string;
    TestString hello_string("Hello");

    TestString str;
    str = empty_string;
    CHECK_TRUE(str.IsEmpty());
    CHECK_ZERO(str.GetLength());

    str = hello_string;
    CHECK_FALSE(str.IsEmpty());
    CHECK_ZERO(StrCmp(str.Ptr(), hello_string.Ptr()));
    CHECK_EQUAL(str.GetLength(), hello_string.GetLength());

    // Ensure assigning to nothing will clear any existing string.
    str = empty_string;
    CHECK_TRUE(str.IsEmpty());
    CHECK_ZERO(str.GetLength());
}

TEST_MEMBER_FUNCTION(TestString, operator_plus_equal, char_const_ptr)
{
    using ocl::TestString;

    TEST_OVERRIDE_FUNCTION_NAME_ARGS("operator +=", "char const* str");

    TestString str;
    str += static_cast<char const*>(NULL);
    CHECK_TRUE(str.IsEmpty());
    CHECK_EQUAL(str.GetLength(), 0U);

    str += "";
    CHECK_TRUE(str.IsEmpty());
    CHECK_EQUAL(str.GetLength(), 0U);

    str += "H";
    CHECK_ZERO(StrCmp(str.Ptr(), "H"));
    CHECK_EQUAL(str.GetLength(), 1U);

    str += "ello";
    CHECK_ZERO(StrCmp(str.Ptr(), "Hello"));
    CHECK_EQUAL(str.GetLength(), 5U);
}

TEST_MEMBER_FUNCTION(TestString, operator_plus_equal, TestString_const_ref)
{
    using ocl::TestString;

    TEST_OVERRIDE_FUNCTION_NAME_ARGS("operator +=", "TestString const&");

    TestString empty_string;
    TestString str;

    str += empty_string;
    CHECK_TRUE(str.IsEmpty());
    CHECK_EQUAL(str.GetLength(), 0U);

    TestString h_str("H");
    str += h_str;
    CHECK_ZERO(StrCmp(str.Ptr(), h_str.Ptr()));
    CHECK_EQUAL(str.GetLength(), 1U);

    TestString ello_str("ello");
    str += ello_str;
    CHECK_ZERO(StrCmp(str.Ptr(), "Hello"));
    CHECK_EQUAL(str.GetLength(), 5U);
}

TEST_CONST_MEMBER_FUNCTION(TestString, operator_subscript, size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_FUNCTION_NAME("operator []");

    TestString const str("Hello");

    CHECK_EQUAL(str[0U], 'H');
    CHECK_EQUAL(str[4U], 'o');
}

TEST_MEMBER_FUNCTION(TestString, operator_subscript, size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_FUNCTION_NAME("operator []");

    TestString str("Hello");

    char& ch0 = str[0U];
    CHECK_EQUAL(ch0, 'H');
    ch0 = 'h';
    CHECK_EQUAL(str[0U], 'h');

    char& ch4 = str[4U];
    CHECK_EQUAL(ch4, 'o');
    ch4 = 'Z';
    CHECK_EQUAL(str[4U], 'Z');
}

TEST_CONST_MEMBER_FUNCTION(TestString, char_const_ptr, NA)
{
    using ocl::TestString;

    TEST_OVERRIDE_FUNCTION_NAME("char const*");

    char const* hello_str = "Hello";

    TestString str;
    char const* ptr = static_cast<char const*>(str);
    CHECK_NOT_NULL(ptr);
    CHECK_EQUAL(*ptr, '\0');

    str = hello_str;
    ptr = static_cast<char const*>(str);
    CHECK_NOT_NULL(ptr);
    CHECK_ZERO(StrCmp(ptr, hello_str));
    CHECK_EQUAL(StrLen(ptr), 5U);
}

TEST_CONST_MEMBER_FUNCTION(TestString, operator_is_equal, char_const_ptr)
{
    using ocl::TestString;

    TEST_OVERRIDE_FUNCTION_NAME_ARGS("operator ==", "char const*");

    TestString str;
    CHECK_TRUE(str == "");
    CHECK_TRUE(str == static_cast<char const*>(NULL));

    str = "A";
    CHECK_TRUE(str == "A");
    CHECK_FALSE(str == "a");
}

TEST_MEMBER_FUNCTION(TestString, operator_is_equal, TestString_const_ref)
{
    using ocl::TestString;

    TEST_OVERRIDE_FUNCTION_NAME_ARGS("operator ==", "TestString const&");

    TestString empty_string;
    TestString a_str("a");
    TestString A_str("A");

    TestString str;
    CHECK_TRUE(str == empty_string);

    str = A_str;
    CHECK_TRUE(str == A_str);
    CHECK_FALSE(str == a_str);
}

TEST_CONST_MEMBER_FUNCTION(TestString, Ptr, NA)
{
    using ocl::TestString;

    char const* hello_string = "Hello";

    TestString str;
    CHECK_NOT_NULL(str.Ptr());
    CHECK_ZERO(StrCmp(str.Ptr(), ""));

    str = hello_string;

    // Make sure assignment of hello_string does not just reference the same pointer.
    CHECK_NOT_EQUAL(str.Ptr(), hello_string);

    CHECK_ZERO(StrCmp(str.Ptr(), hello_string));
}

TEST_CONST_MEMBER_FUNCTION(TestString, GetLength, NA)
{
    using ocl::TestString;

    TestString str;
    CHECK_ZERO(str.GetLength());

    str = "A";
    CHECK_EQUAL(str.GetLength(), 1U);

    str += "B";
    CHECK_EQUAL(str.GetLength(), 2U);

    str.Clear();
    CHECK_ZERO(str.GetLength());
}

TEST_CONST_MEMBER_FUNCTION(TestString, IsEmpty, NA)
{
    using ocl::TestString;

    TestString str;
    CHECK_TRUE(str.IsEmpty());

    str = "A";
    CHECK_FALSE(str.IsEmpty());

    str += "B";
    CHECK_FALSE(str.IsEmpty());

    str.Clear();
    CHECK_TRUE(str.IsEmpty());
}

TEST_MEMBER_FUNCTION(TestString, Clear, NA)
{
    using ocl::TestString;

    TestString str;
    str.Clear();
    CHECK_TRUE(str.IsEmpty());

    str = "A";
    str.Clear();
    CHECK_TRUE(str.IsEmpty());

    str += "B";
    str.Clear();
    CHECK_TRUE(str.IsEmpty());
}

TEST_CONST_MEMBER_FUNCTION(TestString, Find, char_size_type_ref_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char,size_type&,size_type");

}

TEST_MEMBER_FUNCTION(TestString, GetSubString, TestString_ref_size_type_size_type_bool)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("TestString&,size_type,size_type,bool");

}

TEST_MEMBER_FUNCTION(TestString, Assign, char_const_ptr)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char const*");

}

TEST_MEMBER_FUNCTION(TestString, Assign, TestString_const_ref)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("TestString const&");

}

TEST_MEMBER_FUNCTION(TestString, Move, char_ptr_ref_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char*&,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Prepend, char_const_ptr)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char const*");

}

TEST_MEMBER_FUNCTION(TestString, Append, char_const_ptr)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char const*");

}

TEST_MEMBER_FUNCTION(TestString, Append, char_const_ptr_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char const*,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, TestString_const_ptr)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("TestString const&");

}

TEST_MEMBER_FUNCTION(TestString, Append, bool)
{
    using ocl::TestString;

}

TEST_MEMBER_FUNCTION(TestString, Append, char)
{
    using ocl::TestString;

}

TEST_MEMBER_FUNCTION(TestString, Append, char_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, char_size_type_char_const_ptr_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("char,size_type,char const*,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, signed_char_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("signed char,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, unsigned_char_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("unsigned char,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, signed_short_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("signed short,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, unsigned_short_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("unsigned short,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, signed_int_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("signed int,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, unsigned_int_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("unsigned int,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, signed_long_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("signed long,size_type");

}

TEST_MEMBER_FUNCTION(TestString, Append, unsigned_long_size_type)
{
    using ocl::TestString;

    TEST_OVERRIDE_ARGS("unsigned long,size_type");

}
<|endoftext|>


<commit_before>/*!
 * @file alignment.cpp
 *
 * @brief Alignment class source file
 */

#include <limits>
#include <algorithm>

#include "node.hpp"
#include "edge.hpp"
#include "graph.hpp"
#include "alignment.hpp"

AlignmentParams::AlignmentParams(int16_t m, int16_t mm, int16_t gap_opn,
    int16_t gap_ext, AlignmentType t) :
        match(m), mismatch(mm), insertion_open(gap_opn), insertion_extend(gap_ext),
        deletion_open(gap_opn), deletion_extend(gap_ext), type(t) {
}

AlignmentParams::AlignmentParams(int16_t m, int16_t mm, int16_t ins_opn,
    int16_t ins_ext, int16_t del_opn, int16_t del_ext, AlignmentType t) :
        match(m), mismatch(mm), insertion_open(ins_opn), insertion_extend(ins_ext),
        deletion_open(del_opn), deletion_extend(del_ext), type(t) {
}

AlignmentParams::~AlignmentParams() {
}

Alignment::MatrixElement::MatrixElement(int32_t s, int32_t p_i, int32_t p_j,
    int16_t del, int16_t ins) :
        score(s), prev_i(p_i), prev_j(p_j), deletion_cost(del), insertion_cost(ins) {
}

Alignment::MatrixElement::~MatrixElement() {
}

Alignment::MatrixMove::MatrixMove(int32_t s, int32_t k, int32_t l, int32_t t) :
        score(s), i(k), j(l), type(t) {
}

Alignment::MatrixMove::~MatrixMove() {
}

std::unique_ptr<Alignment> createAlignment(const std::string& sequence,
    GraphSharedPtr graph, AlignmentParams params) {

    return std::unique_ptr<Alignment>(new Alignment(sequence, graph,
        std::move(params)));
}

Alignment::Alignment(const std::string& sequence, GraphSharedPtr graph,
    AlignmentParams params) :
        sequence_(sequence), graph_(graph), params_(std::move(params)) {

    assert(sequence_.size() != 0);

    matrix_width_ = sequence_.size() + 1;
    matrix_height_ = graph_->nodes().size() + 1;

    H_.resize(matrix_width_ * matrix_height_, 0);
    F_.resize(matrix_width_ * matrix_height_, 0);
    E_.resize(matrix_width_ * matrix_height_, 0);

    int32_t big_negative_value = std::numeric_limits<int32_t>::min() + 1000;
    for (uint32_t j = 1; j < matrix_width_; ++j) {
        F_[j] = big_negative_value;
    }
    for (uint32_t i = 1; i < matrix_height_; ++i) {
        E_[i * matrix_width_] = big_negative_value;
    }

    is_aligned_ = false;
    max_i_ = -1;
    max_j_ = -1;
    max_score_ = params.type == AlignmentType::kNW ? big_negative_value : 0;

    graph_->topological_sort();
    const auto& sorted_nodes_ids = graph_->sorted_nodes_ids();

    node_id_to_graph_id_.resize(sorted_nodes_ids.size());
    for (uint32_t i = 0; i < sorted_nodes_ids.size(); ++i) {
        node_id_to_graph_id_[sorted_nodes_ids[i]] = i;
    }

    is_backtracked_ = false;

    if (params_.type == AlignmentType::kNW) {

        for (uint32_t j = 1; j < matrix_width_; ++j) {
            H_[j] = params_.insertion_open + (j - 1) * params_.insertion_extend;
            E_[j] = H_[j];
        }

        for (uint32_t node_id: sorted_nodes_ids) {
            const auto& node = graph_->node(node_id);
            uint32_t i = node_id_to_graph_id_[node_id] + 1;

            if (node->in_edges().size() == 0) {
                H_[i * matrix_width_] = params_.deletion_open;
            } else {
                int32_t max_score = big_negative_value;
                for (const auto& edge: node->in_edges()) {
                    uint32_t pred_i = node_id_to_graph_id_[edge->begin_node_id()] + 1;
                    max_score = std::max(max_score, H_[pred_i * matrix_width_]);
                }
                H_[i * matrix_width_] = max_score + params_.deletion_extend;
            }
            F_[i * matrix_width_] = H_[i * matrix_width_];
        }
    }

    // print_matrix();
}

Alignment::~Alignment() {
}

void Alignment::align_sequence_to_graph() {

    if (is_aligned_ == true) {
        return;
    }

    graph_->topological_sort();
    const auto& sorted_nodes_ids = graph_->sorted_nodes_ids();

    for (uint32_t node_id: sorted_nodes_ids) {
        const auto& node = graph_->node(node_id);
        char graph_letter = node->letter();
        uint32_t i = node_id_to_graph_id_[node_id] + 1;

        int32_t* H_row = &H_[i * matrix_width_];
        int32_t* F_row = &F_[i * matrix_width_];

        uint32_t pred_i = node->in_edges().empty() ? 0 :
            node_id_to_graph_id_[node->in_edges().front()->begin_node_id()] + 1;

        int32_t* H_pred_row = &H_[pred_i * matrix_width_];
        int32_t* F_pred_row = &F_[pred_i * matrix_width_];

        for (uint32_t j = 1; j < matrix_width_; ++j) {
            int32_t match_cost = graph_letter == sequence_[j - 1] ? params_.match : params_.mismatch;
            // update F
            F_row[j] = std::max(H_pred_row[j] + params_.insertion_open, F_pred_row[j] + params_.insertion_extend);
            // update H
            H_row[j] = std::max(H_pred_row[j - 1] + match_cost, F_row[j]);
        }

        // check other predeccessors
        for (uint32_t p = 1; p < node->in_edges().size(); ++p) {
            pred_i = node_id_to_graph_id_[node->in_edges()[p]->begin_node_id()] + 1;

            H_pred_row = &H_[pred_i * matrix_width_];
            F_pred_row = &F_[pred_i * matrix_width_];

            for (uint32_t j = 1; j < matrix_width_; ++j) {
                int32_t match_cost = graph_letter == sequence_[j - 1] ? params_.match : params_.mismatch;
                // update F
                F_row[j] = std::max(F_row[j], std::max(H_pred_row[j] + params_.insertion_open, F_pred_row[j] + params_.insertion_extend));
                // update H
                H_row[j] = std::max(H_row[j], std::max(H_pred_row[j - 1] + match_cost, F_row[j]));
            }
        }

        int32_t* E_row = &E_[i * matrix_width_];

        for (uint32_t j = 1; j < matrix_width_; ++j) {
            // update E
            E_row[j] = std::max(H_row[j - 1] + params_.deletion_open, E_row[j - 1] + params_.deletion_extend);
            // update H
            H_row[j] = std::max(H_row[j], E_row[j]);

            if (params_.type == AlignmentType::kSW) {
                H_row[j] = std::max(H_row[j], 0);
                update_max_score(H_row, i, j);
            } else if (params_.type == AlignmentType::kNW) {
                if (j == matrix_width_ - 1 && node->out_edges().size() == 0) {
                    update_max_score(H_row, i, j);
                }
            } else if (params_.type == AlignmentType::kOV) {
                if (j == matrix_width_ - 1 || node->out_edges().size() == 0) {
                    update_max_score(H_row, i, j);
                }
            }
        }
    }

    is_aligned_ = true;

    // print_matrix();
}

int32_t Alignment::alignment_score() const {
    assert(is_aligned_ == true && "No alignment done!");
    return max_score_;
}

void Alignment::backtrack() {

    if (is_backtracked_ == true) {
        return;
    }
    assert(is_aligned_  == true && "No alignment done!");

    if (max_i_ == -1 && max_j_ == -1) { // no alignment found
        is_backtracked_ = true;
        return;
    }

    uint32_t i = max_i_;
    uint32_t j = max_j_;
    // fprintf(stderr, "Score, i, j = %d, %d, %d\n", max_score_, i, j);

    auto sw_condition = [&]() { return (H_[i * matrix_width_ + j] == 0) ? false : true; };
    auto nw_condition = [&]() { return (i == 0 && j == 0) ? false : true; };
    auto ov_condition = [&]() { return (i == 0 || j == 0) ? false : true; };

    const auto& graph_id_to_node_id = graph_->sorted_nodes_ids();

    uint32_t prev_i = 0, prev_j = 0;

    while ((params_.type == AlignmentType::kSW && sw_condition()) ||
        (params_.type == AlignmentType::kNW && nw_condition()) ||
        (params_.type == AlignmentType::kOV && ov_condition())) {

        // bloody backtrack
        auto H_ij = H_[i * matrix_width_ + j];

        if (H_ij == E_[i * matrix_width_ + j]) {
            prev_i = i;
            prev_j = j - 1;
        } else {
            const auto& node = graph_->node(graph_id_to_node_id[i - 1]);

            if (node->in_edges().size() < 2) {
                uint32_t pred_i = node->in_edges().empty() ? 0 :
                    node_id_to_graph_id_[node->in_edges()[0]->begin_node_id()] + 1;

                prev_i = pred_i;
                if (H_ij != F_[i * matrix_width_ + j]) {
                    prev_j = j - 1;
                } else {
                    prev_j = j;
                }
            } else {
                if (H_ij != F_[i * matrix_width_ + j]) {
                    int32_t match_cost = sequence_[j - 1] == node->letter() ?
                        params_.match : params_.mismatch;

                    for (const auto& edge: node->in_edges()) {
                        uint32_t pred_i = node_id_to_graph_id_[edge->begin_node_id()] + 1;
                        if (H_ij == H_[pred_i * matrix_width_ + (j - 1)] + match_cost) {
                            prev_i = pred_i;
                            prev_j = j - 1;
                            break;
                        }
                    }
                } else {
                    for (const auto& edge: node->in_edges()) {
                        uint32_t pred_i = node_id_to_graph_id_[edge->begin_node_id()] + 1;
                        if ((F_[i * matrix_width_ + j] == F_[pred_i * matrix_width_ + j] + params_.insertion_extend) ||
                            (H_ij == H_[pred_i * matrix_width_ + j] + params_.insertion_open)){
                            prev_i = pred_i;
                            prev_j = j;
                            break;
                        }
                    }
                }
            }
        }

        alignment_node_ids_.emplace_back(i == prev_i ? -1 : graph_id_to_node_id[i - 1]);
        alignment_seq_ids_.emplace_back(j == prev_j ? -1 : j - 1);

        i = prev_i;
        j = prev_j;
    }

    std::reverse(alignment_node_ids_.begin(), alignment_node_ids_.end());
    std::reverse(alignment_seq_ids_.begin(), alignment_seq_ids_.end());

    is_backtracked_ = true;
}

inline void Alignment::update_max_score(int32_t* H_row, uint32_t i, uint32_t j) {
    if (max_score_ < H_row[j]) {
        max_score_ = H_row[j];
        max_i_ = i;
        max_j_ = j;
    }
}

void Alignment::print_matrix() {
    for (uint32_t i = 0; i < matrix_height_; ++i) {
        for (uint32_t j = 0; j < matrix_width_; ++j) {
            printf("(%3d %3d %3d) ", H_[i * matrix_width_ + j],
                E_[i * matrix_width_ + j], F_[i * matrix_width_ + j]);
        }
        printf("\n");
    }
    printf("\n");
}
<commit_msg>Fixed bug where alignment type was not valid<commit_after>/*!
 * @file alignment.cpp
 *
 * @brief Alignment class source file
 */

#include <limits>
#include <algorithm>

#include "node.hpp"
#include "edge.hpp"
#include "graph.hpp"
#include "alignment.hpp"

AlignmentParams::AlignmentParams(int16_t m, int16_t mm, int16_t gap_opn,
    int16_t gap_ext, AlignmentType t) :
        match(m), mismatch(mm), insertion_open(gap_opn), insertion_extend(gap_ext),
        deletion_open(gap_opn), deletion_extend(gap_ext), type(t) {

    assert(type == AlignmentType::kNW || type == AlignmentType::kSW || type == AlignmentType::kOV);
}

AlignmentParams::AlignmentParams(int16_t m, int16_t mm, int16_t ins_opn,
    int16_t ins_ext, int16_t del_opn, int16_t del_ext, AlignmentType t) :
        match(m), mismatch(mm), insertion_open(ins_opn), insertion_extend(ins_ext),
        deletion_open(del_opn), deletion_extend(del_ext), type(t) {

    assert(type == AlignmentType::kNW || type == AlignmentType::kSW || type == AlignmentType::kOV);
}

AlignmentParams::~AlignmentParams() {
}

Alignment::MatrixElement::MatrixElement(int32_t s, int32_t p_i, int32_t p_j,
    int16_t del, int16_t ins) :
        score(s), prev_i(p_i), prev_j(p_j), deletion_cost(del), insertion_cost(ins) {
}

Alignment::MatrixElement::~MatrixElement() {
}

Alignment::MatrixMove::MatrixMove(int32_t s, int32_t k, int32_t l, int32_t t) :
        score(s), i(k), j(l), type(t) {
}

Alignment::MatrixMove::~MatrixMove() {
}

std::unique_ptr<Alignment> createAlignment(const std::string& sequence,
    GraphSharedPtr graph, AlignmentParams params) {

    return std::unique_ptr<Alignment>(new Alignment(sequence, graph,
        std::move(params)));
}

Alignment::Alignment(const std::string& sequence, GraphSharedPtr graph,
    AlignmentParams params) :
        sequence_(sequence), graph_(graph), params_(std::move(params)) {

    assert(sequence_.size() != 0);

    matrix_width_ = sequence_.size() + 1;
    matrix_height_ = graph_->nodes().size() + 1;

    H_.resize(matrix_width_ * matrix_height_, 0);
    F_.resize(matrix_width_ * matrix_height_, 0);
    E_.resize(matrix_width_ * matrix_height_, 0);

    int32_t big_negative_value = std::numeric_limits<int32_t>::min() + 1000;
    for (uint32_t j = 1; j < matrix_width_; ++j) {
        F_[j] = big_negative_value;
    }
    for (uint32_t i = 1; i < matrix_height_; ++i) {
        E_[i * matrix_width_] = big_negative_value;
    }

    is_aligned_ = false;
    max_i_ = -1;
    max_j_ = -1;
    max_score_ = params.type == AlignmentType::kNW ? big_negative_value : 0;

    graph_->topological_sort();
    const auto& sorted_nodes_ids = graph_->sorted_nodes_ids();

    node_id_to_graph_id_.resize(sorted_nodes_ids.size());
    for (uint32_t i = 0; i < sorted_nodes_ids.size(); ++i) {
        node_id_to_graph_id_[sorted_nodes_ids[i]] = i;
    }

    is_backtracked_ = false;

    if (params_.type == AlignmentType::kNW) {

        for (uint32_t j = 1; j < matrix_width_; ++j) {
            H_[j] = params_.insertion_open + (j - 1) * params_.insertion_extend;
            E_[j] = H_[j];
        }

        for (uint32_t node_id: sorted_nodes_ids) {
            const auto& node = graph_->node(node_id);
            uint32_t i = node_id_to_graph_id_[node_id] + 1;

            if (node->in_edges().size() == 0) {
                H_[i * matrix_width_] = params_.deletion_open;
            } else {
                int32_t max_score = big_negative_value;
                for (const auto& edge: node->in_edges()) {
                    uint32_t pred_i = node_id_to_graph_id_[edge->begin_node_id()] + 1;
                    max_score = std::max(max_score, H_[pred_i * matrix_width_]);
                }
                H_[i * matrix_width_] = max_score + params_.deletion_extend;
            }
            F_[i * matrix_width_] = H_[i * matrix_width_];
        }
    }

    // print_matrix();
}

Alignment::~Alignment() {
}

void Alignment::align_sequence_to_graph() {

    if (is_aligned_ == true) {
        return;
    }

    graph_->topological_sort();
    const auto& sorted_nodes_ids = graph_->sorted_nodes_ids();

    for (uint32_t node_id: sorted_nodes_ids) {
        const auto& node = graph_->node(node_id);
        char graph_letter = node->letter();
        uint32_t i = node_id_to_graph_id_[node_id] + 1;

        int32_t* H_row = &H_[i * matrix_width_];
        int32_t* F_row = &F_[i * matrix_width_];

        uint32_t pred_i = node->in_edges().empty() ? 0 :
            node_id_to_graph_id_[node->in_edges().front()->begin_node_id()] + 1;

        int32_t* H_pred_row = &H_[pred_i * matrix_width_];
        int32_t* F_pred_row = &F_[pred_i * matrix_width_];

        for (uint32_t j = 1; j < matrix_width_; ++j) {
            int32_t match_cost = graph_letter == sequence_[j - 1] ? params_.match : params_.mismatch;
            // update F
            F_row[j] = std::max(H_pred_row[j] + params_.insertion_open, F_pred_row[j] + params_.insertion_extend);
            // update H
            H_row[j] = std::max(H_pred_row[j - 1] + match_cost, F_row[j]);
        }

        // check other predeccessors
        for (uint32_t p = 1; p < node->in_edges().size(); ++p) {
            pred_i = node_id_to_graph_id_[node->in_edges()[p]->begin_node_id()] + 1;

            H_pred_row = &H_[pred_i * matrix_width_];
            F_pred_row = &F_[pred_i * matrix_width_];

            for (uint32_t j = 1; j < matrix_width_; ++j) {
                int32_t match_cost = graph_letter == sequence_[j - 1] ? params_.match : params_.mismatch;
                // update F
                F_row[j] = std::max(F_row[j], std::max(H_pred_row[j] + params_.insertion_open, F_pred_row[j] + params_.insertion_extend));
                // update H
                H_row[j] = std::max(H_row[j], std::max(H_pred_row[j - 1] + match_cost, F_row[j]));
            }
        }

        int32_t* E_row = &E_[i * matrix_width_];

        for (uint32_t j = 1; j < matrix_width_; ++j) {
            // update E
            E_row[j] = std::max(H_row[j - 1] + params_.deletion_open, E_row[j - 1] + params_.deletion_extend);
            // update H
            H_row[j] = std::max(H_row[j], E_row[j]);

            if (params_.type == AlignmentType::kSW) {
                H_row[j] = std::max(H_row[j], 0);
                update_max_score(H_row, i, j);
            } else if (params_.type == AlignmentType::kNW) {
                if (j == matrix_width_ - 1 && node->out_edges().size() == 0) {
                    update_max_score(H_row, i, j);
                }
            } else if (params_.type == AlignmentType::kOV) {
                if (j == matrix_width_ - 1 || node->out_edges().size() == 0) {
                    update_max_score(H_row, i, j);
                }
            }
        }
    }

    is_aligned_ = true;

    // print_matrix();
}

int32_t Alignment::alignment_score() const {
    assert(is_aligned_ == true && "No alignment done!");
    return max_score_;
}

void Alignment::backtrack() {

    if (is_backtracked_ == true) {
        return;
    }
    assert(is_aligned_  == true && "No alignment done!");

    if (max_i_ == -1 && max_j_ == -1) { // no alignment found
        is_backtracked_ = true;
        return;
    }

    uint32_t i = max_i_;
    uint32_t j = max_j_;
    // fprintf(stderr, "Score, i, j = %d, %d, %d\n", max_score_, i, j);

    auto sw_condition = [&]() { return (H_[i * matrix_width_ + j] == 0) ? false : true; };
    auto nw_condition = [&]() { return (i == 0 && j == 0) ? false : true; };
    auto ov_condition = [&]() { return (i == 0 || j == 0) ? false : true; };

    const auto& graph_id_to_node_id = graph_->sorted_nodes_ids();

    uint32_t prev_i = 0, prev_j = 0;

    while ((params_.type == AlignmentType::kSW && sw_condition()) ||
        (params_.type == AlignmentType::kNW && nw_condition()) ||
        (params_.type == AlignmentType::kOV && ov_condition())) {

        // bloody backtrack
        auto H_ij = H_[i * matrix_width_ + j];

        if (H_ij == E_[i * matrix_width_ + j]) {
            prev_i = i;
            prev_j = j - 1;
        } else {
            const auto& node = graph_->node(graph_id_to_node_id[i - 1]);

            if (node->in_edges().size() < 2) {
                uint32_t pred_i = node->in_edges().empty() ? 0 :
                    node_id_to_graph_id_[node->in_edges()[0]->begin_node_id()] + 1;

                prev_i = pred_i;
                if (H_ij != F_[i * matrix_width_ + j]) {
                    prev_j = j - 1;
                } else {
                    prev_j = j;
                }
            } else {
                if (H_ij != F_[i * matrix_width_ + j]) {
                    int32_t match_cost = sequence_[j - 1] == node->letter() ?
                        params_.match : params_.mismatch;

                    for (const auto& edge: node->in_edges()) {
                        uint32_t pred_i = node_id_to_graph_id_[edge->begin_node_id()] + 1;
                        if (H_ij == H_[pred_i * matrix_width_ + (j - 1)] + match_cost) {
                            prev_i = pred_i;
                            prev_j = j - 1;
                            break;
                        }
                    }
                } else {
                    for (const auto& edge: node->in_edges()) {
                        uint32_t pred_i = node_id_to_graph_id_[edge->begin_node_id()] + 1;
                        if ((F_[i * matrix_width_ + j] == F_[pred_i * matrix_width_ + j] + params_.insertion_extend) ||
                            (H_ij == H_[pred_i * matrix_width_ + j] + params_.insertion_open)){
                            prev_i = pred_i;
                            prev_j = j;
                            break;
                        }
                    }
                }
            }
        }

        alignment_node_ids_.emplace_back(i == prev_i ? -1 : graph_id_to_node_id[i - 1]);
        alignment_seq_ids_.emplace_back(j == prev_j ? -1 : j - 1);

        i = prev_i;
        j = prev_j;
    }

    std::reverse(alignment_node_ids_.begin(), alignment_node_ids_.end());
    std::reverse(alignment_seq_ids_.begin(), alignment_seq_ids_.end());

    is_backtracked_ = true;
}

inline void Alignment::update_max_score(int32_t* H_row, uint32_t i, uint32_t j) {
    if (max_score_ < H_row[j]) {
        max_score_ = H_row[j];
        max_i_ = i;
        max_j_ = j;
    }
}

void Alignment::print_matrix() {
    for (uint32_t i = 0; i < matrix_height_; ++i) {
        for (uint32_t j = 0; j < matrix_width_; ++j) {
            printf("(%3d %3d %3d) ", H_[i * matrix_width_ + j],
                E_[i * matrix_width_ + j], F_[i * matrix_width_ + j]);
        }
        printf("\n");
    }
    printf("\n");
}
<|endoftext|>