<commit_before>/*
  This file is part of KOrganizer.

  Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/

#include "kowhatsnextview.h"
#include "akonadicalendar.h"
#include "koglobals.h"
#include "koprefs.h"

#include <akonadi/kcal/utils.h>

#include <KCal/IncidenceFormatter>
#include <KCal/Todo>

#include <QBoxLayout>

using namespace Akonadi;

void WhatsNextTextBrowser::setSource( const QUrl &name )
{
  QString uri = name.toString();
  if ( uri.startsWith( QLatin1String( "event:" ) ) ) {
    emit showIncidence( uri );
  } else if ( uri.startsWith( QLatin1String( "todo:" ) ) ) {
    emit showIncidence( uri );
  } else {
    KTextBrowser::setSource( uri );
  }
}

KOWhatsNextView::KOWhatsNextView( QWidget *parent )
  : KOrg::BaseView( parent )
{
  mView = new WhatsNextTextBrowser( this );
  connect( mView, SIGNAL(showIncidence(const QString &)),
           SLOT(showIncidence(const QString &)) );

  QBoxLayout *topLayout = new QVBoxLayout( this );
  topLayout->addWidget(mView);
}

KOWhatsNextView::~KOWhatsNextView()
{
}

int KOWhatsNextView::currentDateCount()
{
  return mStartDate.daysTo( mEndDate );
}

void KOWhatsNextView::updateView()
{
  KIconLoader kil( "korganizer" );
  QString ipath;
  kil.loadIcon( "office-calendar", KIconLoader::NoGroup, 32,
                KIconLoader::DefaultState, QStringList(), &ipath );

  mText = "
\n";
  mText += "

";
  mText += "";
  mText += " ";
  mText += i18n( "What's Next?" ) + "
";
  mText += "
\n
";

  mText += "
";
  if ( mStartDate.daysTo( mEndDate ) < 1 ) {
    mText += KGlobal::locale()->formatDate( mStartDate );
  } else {
    mText += i18nc(
      "date from - to", "%1 - %2",
      KGlobal::locale()->formatDate( mStartDate ),
      KGlobal::locale()->formatDate( mEndDate ) );
  }
  mText+="
\n";

  Item::List events;
  KDateTime::Spec timeSpec = KOPrefs::instance()->timeSpec();

  events = calendar()->events( mStartDate, mEndDate, timeSpec, false );
  events = calendar()->sortEvents( events, EventSortStartDate, SortDirectionAscending );

  if ( events.count() > 0 ) {
    mText += "

";
    kil.loadIcon( "view-calendar-day", KIconLoader::NoGroup, 22,
                  KIconLoader::DefaultState, QStringList(), &ipath );
    mText += "
";
    mText += i18n( "Events:" ) + "
\n";
    mText += "
\n";
    Event::List::ConstIterator it;
    Q_FOREACH( const Item& evItem, events ) {
      Event::Ptr ev = Akonadi::event( evItem );
      if ( !ev->recurs() ) {
        appendEvent( evItem );
      } else {
        Recurrence *recur = ev->recurrence();
        int duration = ev->dtStart().secsTo( ev->dtEnd() );
        KDateTime start = recur->getPreviousDateTime( KDateTime( mStartDate, QTime(), timeSpec ) );
        KDateTime end = start.addSecs( duration );
        KDateTime endDate( mEndDate, QTime( 23, 59, 59 ), timeSpec );
        if ( end.date() >= mStartDate ) {
          appendEvent( evItem, start.dateTime(), end.dateTime() );
        }
        DateTimeList times = recur->timesInInterval( start, endDate );
        int count = times.count();
        if ( count > 0 ) {
          int i = 0;
          if ( times[0] == start ) {
            ++i;  // start has already been appended
          }
          if ( !times[count - 1].isValid() ) {
            --count;  // list overflow
          }
          for ( ;  i < count && times[i].date() <= mEndDate;  ++i ) {
            appendEvent( evItem, times[i].dateTime() );
          }
        }
      }
    }
    mText += "
\n";
  }

  mTodos.clear();
  Item::List todos = calendar()->todos( TodoSortDueDate, SortDirectionAscending );
  if ( todos.count() > 0 ) {
    kil.loadIcon( "view-calendar-tasks", KIconLoader::NoGroup, 22,
                  KIconLoader::DefaultState, QStringList(), &ipath );
    mText += "
";
    mText += i18n( "To-do:" ) + "
\n";
    mText += "
\n";
    Todo::List::ConstIterator it;
    Q_FOREACH( const Item & todoItem, todos ) {
      Todo::Ptr todo = Akonadi::todo( todoItem );
      if ( !todo->isCompleted() && todo->hasDueDate() && todo->dtDue().date() <= mEndDate ) {
        appendTodo( todoItem );
      }
    }
    bool gotone = false;
    int priority = 1;
    while ( !gotone && priority <= 9 ) {
      Q_FOREACH( const Item & todoItem, todos ) {
        Todo::Ptr todo = Akonadi::todo( todoItem );
        if ( !todo->isCompleted() && ( todo->priority() == priority ) ) {
          appendTodo( todoItem );
          gotone = true;
        }
      }
      priority++;
    }
    mText += "
\n";
  }

  QStringList myEmails( KOPrefs::instance()->allEmails() );
  int replies = 0;
  events = calendar()->events( QDate::currentDate(), QDate( 2975, 12, 6 ), timeSpec );
  Q_FOREACH( const Item& evItem, events ) {
    Event::Ptr ev = Akonadi::event( evItem );
    Attendee *me = ev->attendeeByMails( myEmails );
    if ( me != 0 ) {
      if ( me->status() == Attendee::NeedsAction && me->RSVP() ) {
        if ( replies == 0 ) {
          mText += "

";
          kil.loadIcon( "mail-reply-sender", KIconLoader::NoGroup, 22,
                        KIconLoader::DefaultState, QStringList(), &ipath );
          mText += "
";
          mText += i18n( "Events and to-dos that need a reply:" ) + "
\n";
          mText += "
\n";
        }
        replies++;
        appendEvent( evItem );
      }
    }
  }
  todos = calendar()->todos();
  Todo::List::ConstIterator it3;
  Q_FOREACH( const Item & todoItem, todos ) {
    Todo::Ptr to = Akonadi::todo( todoItem );
    Attendee *me = to->attendeeByMails( myEmails );
    if ( me != 0 ) {
      if ( me->status() == Attendee::NeedsAction && me->RSVP() ) {
        if ( replies == 0 ) {
          mText += "

";
          kil.loadIcon( "mail-reply-sender", KIconLoader::NoGroup, 22,
                        KIconLoader::DefaultState, QStringList(), &ipath );
          mText += "
";
          mText += i18n( "Events and to-dos that need a reply:" ) + "
\n";
          mText += "
\n";
        }
        replies++;
        appendEvent( todoItem );
      }
    }
  }
  if ( replies > 0 ) {
    mText += "
\n";
  }

  mText += "
\n
\n";

  mView->setText(mText);
}

void KOWhatsNextView::showDates( const QDate &start, const QDate &end )
{
  mStartDate = start;
  mEndDate = end;
  updateView();
}

void KOWhatsNextView::showIncidences( const Item::List &incidenceList, const QDate &date )
{
  Q_UNUSED( incidenceList );
  Q_UNUSED( date );
}

void KOWhatsNextView::changeIncidenceDisplay( const Item &incidence, int action )
{
  Q_UNUSED( incidence );

  switch( action ) {
  case KOGlobals::INCIDENCEADDED:
  case KOGlobals::INCIDENCEEDITED:
  case KOGlobals::INCIDENCEDELETED:
    updateView();
    break;
  default:
    break;
  }
}

void KOWhatsNextView::appendEvent( const Item &aitem, const QDateTime &start,
                                   const QDateTime &end )
{
  const Incidence::Ptr incidence = Akonadi::incidence( aitem );
  mText += "
";
  if ( const Event::Ptr event = Akonadi::event( aitem ) ) {
    KDateTime::Spec timeSpec = KOPrefs::instance()->timeSpec();
    KDateTime starttime( start, timeSpec );
    if ( !starttime.isValid() ) {
      starttime = event->dtStart();
    }
    KDateTime endtime( end, timeSpec );
    if ( !endtime.isValid() ) {
      endtime = starttime.addSecs( event->dtStart().secsTo( event->dtEnd() ) );
    }

    if ( starttime.date().daysTo( endtime.date() ) >= 1 ) {
      mText += i18nc(
        "date from - to", "%1 - %2",
        KGlobal::locale()->formatDateTime(
          starttime.toTimeSpec( KOPrefs::instance()->timeSpec() ) ),
        KGlobal::locale()->formatDateTime(
          endtime.toTimeSpec( KOPrefs::instance()->timeSpec() ) ) );
    } else {
      mText += i18nc(
        "date, from - to", "%1, %2 - %3",
        KGlobal::locale()->formatDate(
          starttime.toTimeSpec( KOPrefs::instance()->timeSpec() ).date(), KLocale::ShortDate ),
        KGlobal::locale()->formatTime(
          starttime.toTimeSpec( KOPrefs::instance()->timeSpec() ).time() ),
        KGlobal::locale()->formatTime(
          endtime.toTimeSpec( KOPrefs::instance()->timeSpec() ).time() ) );
    }
  }
  mText += "	type() == "Event" ) {
    mText += "href=\"event:";
  }
  if ( incidence->type() == "Todo" ) {
    mText += "href=\"todo:";
  }
  mText += incidence->uid() + "\">";
  mText += incidence->summary();
  mText += "
\n";
}

void KOWhatsNextView::appendTodo( const Item &aitem )
{
  if ( mTodos.contains( aitem ) ) {
    return;
  }

  mTodos.append( aitem );

  const Incidence::Ptr incidence = Akonadi::incidence( aitem );
  mText += "
uid() + "\">";
  mText += incidence->summary();
  mText += "";

  if ( const Todo::Ptr todo = Akonadi::todo( aitem ) ) {
    if ( todo->hasDueDate() ) {
      mText += i18nc( "to-do due date", "  (Due: %1)",
                      IncidenceFormatter::dateTimeToString( todo->dtDue(), todo->allDay() ) );
    }
  }
  mText += "
\n";
}

void KOWhatsNextView::showIncidence( const QString &uid )
{
#ifdef AKONADI_PORT_DISABLED
  Item incidence;

  AkonadiCalendar* cal = dynamic_cast<AkonadiCalendar*>( calendar() );
  if ( !cal )
    return; //PENDING(AKONADI_PORT) remove this dyncast and guard

  if ( uid.startsWith( QLatin1String( "event:" ) ) ) {
    incidence = cal->itemForIncidence( cal->incidence( uid.mid( 6 ) ) );
  } else if ( uid.startsWith( QLatin1String( "todo:" ) ) ) {
    incidence = cal->itemForIncidence( cal->incidence( uid.mid( 5 ) ) );
  }
  if ( incidence.isValid() ) {
    emit showIncidenceSignal( incidence );
  }
#endif // AKONADI_PORT_DISABLED
}

#include "kowhatsnextview.moc"
<commit_msg>port++<commit_after>/*
  This file is part of KOrganizer.

  Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/

#include "kowhatsnextview.h"
#include "akonadicalendar.h"
#include "koglobals.h"
#include "koprefs.h"

#include <akonadi/kcal/utils.h>

#include <KCal/IncidenceFormatter>
#include <KCal/Todo>

#include <QBoxLayout>

using namespace Akonadi;

void WhatsNextTextBrowser::setSource( const QUrl &name )
{
  QString uri = name.toString();
  if ( uri.startsWith( QLatin1String( "event:" ) ) ) {
    emit showIncidence( uri );
  } else if ( uri.startsWith( QLatin1String( "todo:" ) ) ) {
    emit showIncidence( uri );
  } else {
    KTextBrowser::setSource( uri );
  }
}

KOWhatsNextView::KOWhatsNextView( QWidget *parent )
  : KOrg::BaseView( parent )
{
  mView = new WhatsNextTextBrowser( this );
  connect( mView, SIGNAL(showIncidence(const QString &)),
           SLOT(showIncidence(const QString &)) );

  QBoxLayout *topLayout = new QVBoxLayout( this );
  topLayout->addWidget(mView);
}

KOWhatsNextView::~KOWhatsNextView()
{
}

int KOWhatsNextView::currentDateCount()
{
  return mStartDate.daysTo( mEndDate );
}

void KOWhatsNextView::updateView()
{
  KIconLoader kil( "korganizer" );
  QString ipath;
  kil.loadIcon( "office-calendar", KIconLoader::NoGroup, 32,
                KIconLoader::DefaultState, QStringList(), &ipath );

  mText = "
\n";
  mText += "

";
  mText += "";
  mText += " ";
  mText += i18n( "What's Next?" ) + "
";
  mText += "
\n
";

  mText += "
";
  if ( mStartDate.daysTo( mEndDate ) < 1 ) {
    mText += KGlobal::locale()->formatDate( mStartDate );
  } else {
    mText += i18nc(
      "date from - to", "%1 - %2",
      KGlobal::locale()->formatDate( mStartDate ),
      KGlobal::locale()->formatDate( mEndDate ) );
  }
  mText+="
\n";

  Item::List events;
  KDateTime::Spec timeSpec = KOPrefs::instance()->timeSpec();

  events = calendar()->events( mStartDate, mEndDate, timeSpec, false );
  events = calendar()->sortEvents( events, EventSortStartDate, SortDirectionAscending );

  if ( events.count() > 0 ) {
    mText += "

";
    kil.loadIcon( "view-calendar-day", KIconLoader::NoGroup, 22,
                  KIconLoader::DefaultState, QStringList(), &ipath );
    mText += "
";
    mText += i18n( "Events:" ) + "
\n";
    mText += "
\n";
    Event::List::ConstIterator it;
    Q_FOREACH( const Item& evItem, events ) {
      Event::Ptr ev = Akonadi::event( evItem );
      if ( !ev->recurs() ) {
        appendEvent( evItem );
      } else {
        Recurrence *recur = ev->recurrence();
        int duration = ev->dtStart().secsTo( ev->dtEnd() );
        KDateTime start = recur->getPreviousDateTime( KDateTime( mStartDate, QTime(), timeSpec ) );
        KDateTime end = start.addSecs( duration );
        KDateTime endDate( mEndDate, QTime( 23, 59, 59 ), timeSpec );
        if ( end.date() >= mStartDate ) {
          appendEvent( evItem, start.dateTime(), end.dateTime() );
        }
        DateTimeList times = recur->timesInInterval( start, endDate );
        int count = times.count();
        if ( count > 0 ) {
          int i = 0;
          if ( times[0] == start ) {
            ++i;  // start has already been appended
          }
          if ( !times[count - 1].isValid() ) {
            --count;  // list overflow
          }
          for ( ;  i < count && times[i].date() <= mEndDate;  ++i ) {
            appendEvent( evItem, times[i].dateTime() );
          }
        }
      }
    }
    mText += "
\n";
  }

  mTodos.clear();
  Item::List todos = calendar()->todos( TodoSortDueDate, SortDirectionAscending );
  if ( todos.count() > 0 ) {
    kil.loadIcon( "view-calendar-tasks", KIconLoader::NoGroup, 22,
                  KIconLoader::DefaultState, QStringList(), &ipath );
    mText += "
";
    mText += i18n( "To-do:" ) + "
\n";
    mText += "
\n";
    Todo::List::ConstIterator it;
    Q_FOREACH( const Item & todoItem, todos ) {
      Todo::Ptr todo = Akonadi::todo( todoItem );
      if ( !todo->isCompleted() && todo->hasDueDate() && todo->dtDue().date() <= mEndDate ) {
        appendTodo( todoItem );
      }
    }
    bool gotone = false;
    int priority = 1;
    while ( !gotone && priority <= 9 ) {
      Q_FOREACH( const Item & todoItem, todos ) {
        Todo::Ptr todo = Akonadi::todo( todoItem );
        if ( !todo->isCompleted() && ( todo->priority() == priority ) ) {
          appendTodo( todoItem );
          gotone = true;
        }
      }
      priority++;
    }
    mText += "
\n";
  }

  QStringList myEmails( KOPrefs::instance()->allEmails() );
  int replies = 0;
  events = calendar()->events( QDate::currentDate(), QDate( 2975, 12, 6 ), timeSpec );
  Q_FOREACH( const Item& evItem, events ) {
    Event::Ptr ev = Akonadi::event( evItem );
    Attendee *me = ev->attendeeByMails( myEmails );
    if ( me != 0 ) {
      if ( me->status() == Attendee::NeedsAction && me->RSVP() ) {
        if ( replies == 0 ) {
          mText += "

";
          kil.loadIcon( "mail-reply-sender", KIconLoader::NoGroup, 22,
                        KIconLoader::DefaultState, QStringList(), &ipath );
          mText += "
";
          mText += i18n( "Events and to-dos that need a reply:" ) + "
\n";
          mText += "
\n";
        }
        replies++;
        appendEvent( evItem );
      }
    }
  }
  todos = calendar()->todos();
  Todo::List::ConstIterator it3;
  Q_FOREACH( const Item & todoItem, todos ) {
    Todo::Ptr to = Akonadi::todo( todoItem );
    Attendee *me = to->attendeeByMails( myEmails );
    if ( me != 0 ) {
      if ( me->status() == Attendee::NeedsAction && me->RSVP() ) {
        if ( replies == 0 ) {
          mText += "

";
          kil.loadIcon( "mail-reply-sender", KIconLoader::NoGroup, 22,
                        KIconLoader::DefaultState, QStringList(), &ipath );
          mText += "
";
          mText += i18n( "Events and to-dos that need a reply:" ) + "
\n";
          mText += "
\n";
        }
        replies++;
        appendEvent( todoItem );
      }
    }
  }
  if ( replies > 0 ) {
    mText += "
\n";
  }

  mText += "
\n
\n";

  mView->setText(mText);
}

void KOWhatsNextView::showDates( const QDate &start, const QDate &end )
{
  mStartDate = start;
  mEndDate = end;
  updateView();
}

void KOWhatsNextView::showIncidences( const Item::List &incidenceList, const QDate &date )
{
  Q_UNUSED( incidenceList );
  Q_UNUSED( date );
}

void KOWhatsNextView::changeIncidenceDisplay( const Item &incidence, int action )
{
  Q_UNUSED( incidence );

  switch( action ) {
  case KOGlobals::INCIDENCEADDED:
  case KOGlobals::INCIDENCEEDITED:
  case KOGlobals::INCIDENCEDELETED:
    updateView();
    break;
  default:
    break;
  }
}

void KOWhatsNextView::appendEvent( const Item &aitem, const QDateTime &start,
                                   const QDateTime &end )
{
  const Incidence::Ptr incidence = Akonadi::incidence( aitem );
  mText += "
";
  if ( const Event::Ptr event = Akonadi::event( aitem ) ) {
    KDateTime::Spec timeSpec = KOPrefs::instance()->timeSpec();
    KDateTime starttime( start, timeSpec );
    if ( !starttime.isValid() ) {
      starttime = event->dtStart();
    }
    KDateTime endtime( end, timeSpec );
    if ( !endtime.isValid() ) {
      endtime = starttime.addSecs( event->dtStart().secsTo( event->dtEnd() ) );
    }

    if ( starttime.date().daysTo( endtime.date() ) >= 1 ) {
      mText += i18nc(
        "date from - to", "%1 - %2",
        KGlobal::locale()->formatDateTime(
          starttime.toTimeSpec( KOPrefs::instance()->timeSpec() ) ),
        KGlobal::locale()->formatDateTime(
          endtime.toTimeSpec( KOPrefs::instance()->timeSpec() ) ) );
    } else {
      mText += i18nc(
        "date, from - to", "%1, %2 - %3",
        KGlobal::locale()->formatDate(
          starttime.toTimeSpec( KOPrefs::instance()->timeSpec() ).date(), KLocale::ShortDate ),
        KGlobal::locale()->formatTime(
          starttime.toTimeSpec( KOPrefs::instance()->timeSpec() ).time() ),
        KGlobal::locale()->formatTime(
          endtime.toTimeSpec( KOPrefs::instance()->timeSpec() ).time() ) );
    }
  }
  mText += "	type() == "Event" ) {
    mText += "href=\"event:";
  }
  if ( incidence->type() == "Todo" ) {
    mText += "href=\"todo:";
  }
  mText += incidence->uid() + "\">";
  mText += incidence->summary();
  mText += "
\n";
}

void KOWhatsNextView::appendTodo( const Item &aitem )
{
  if ( mTodos.contains( aitem ) ) {
    return;
  }

  mTodos.append( aitem );

  const Incidence::Ptr incidence = Akonadi::incidence( aitem );
  mText += "
uid() + "\">";
  mText += incidence->summary();
  mText += "";

  if ( const Todo::Ptr todo = Akonadi::todo( aitem ) ) {
    if ( todo->hasDueDate() ) {
      mText += i18nc( "to-do due date", "  (Due: %1)",
                      IncidenceFormatter::dateTimeToString( todo->dtDue(), todo->allDay() ) );
    }
  }
  mText += "
\n";
}

void KOWhatsNextView::showIncidence( const QString &uid )
{
  Item incidence;

  AkonadiCalendar* cal = dynamic_cast<AkonadiCalendar*>( calendar() );
  if ( !cal )
    return; //PENDING(AKONADI_PORT) remove this dyncast and guard

  if ( uid.startsWith( QLatin1String( "event:" ) ) ) {
    incidence = cal->incidence( cal->itemIdForIncidenceUid(uid.mid( 6 )) );
  } else if ( uid.startsWith( QLatin1String( "todo:" ) ) ) {
    incidence = cal->incidence( cal->itemIdForIncidenceUid(uid.mid( 5 )) );
  }

  if ( incidence.isValid() ) {
    emit showIncidenceSignal( incidence );
  }
}

#include "kowhatsnextview.moc"
<|endoftext|>


<commit_before>/*
 * FakeESOut.cpp
 *****************************************************************************
 * Copyright © 2014-2015 VideoLAN and VLC Authors
 *
 * This program 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 program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "FakeESOut.hpp"
#include "FakeESOutID.hpp"
#include <vlc_es_out.h>
#include <vlc_block.h>
#include <cassert>

using namespace adaptive;

FakeESOut::FakeESOut( es_out_t *es, CommandsFactory *factory )
{
    real_es_out = es;
    fakeesout = new es_out_t;

    fakeesout->pf_add = esOutAdd_Callback;
    fakeesout->pf_control = esOutControl_Callback;
    fakeesout->pf_del = esOutDel_Callback;
    fakeesout->pf_destroy = esOutDestroy_Callback;
    fakeesout->pf_send = esOutSend_Callback;
    fakeesout->p_sys = (es_out_sys_t*) this;

    commandsFactory = factory;
    timestamps_offset = 0;
    extrainfo = NULL;
}

es_out_t * FakeESOut::getEsOut()
{
    return fakeesout;
}

FakeESOut::~FakeESOut()
{
    delete commandsFactory;

    recycleAll();
    gc();

    delete fakeesout;
}

void FakeESOut::setTimestampOffset(mtime_t offset)
{
    timestamps_offset = offset;
}

void FakeESOut::setExtraInfoProvider( ExtraFMTInfoInterface *extra )
{
    extrainfo = extra;
}

FakeESOutID * FakeESOut::createNewID( const es_format_t *p_fmt )
{
    es_format_t fmtcopy;
    es_format_Init( &fmtcopy, 0, 0 );
    es_format_Copy( &fmtcopy, p_fmt );
    fmtcopy.i_group = 0; /* Always ignore group for adaptive */

    if( extrainfo )
        extrainfo->fillExtraFMTInfo( &fmtcopy );

    FakeESOutID *es_id = new (std::nothrow) FakeESOutID( this, &fmtcopy );
    if(likely(es_id))
        fakeesidlist.push_back( es_id );

    es_format_Clean( &fmtcopy );

    return es_id;
}

void FakeESOut::createOrRecycleRealEsID( FakeESOutID *es_id )
{
    std::list<FakeESOutID *>::iterator it;
    es_out_id_t *realid = NULL;

    bool b_select = false;
    for( it=recycle_candidates.begin(); it!=recycle_candidates.end(); ++it )
    {
        FakeESOutID *cand = *it;
        if ( cand->isCompatible( es_id ) )
        {
            realid = cand->realESID();
            cand->setRealESID( NULL );
            delete *it;
            recycle_candidates.erase( it );
            break;
        }
        else if( cand->getFmt()->i_cat == es_id->getFmt()->i_cat )
        {
            /* We need to enforce same selection when not reused
               Otherwise the es will select any other compatible track
               and will end this in a activate/select loop when reactivating a track */
            es_out_Control( real_es_out, ES_OUT_GET_ES_STATE, cand->realESID(), &b_select );
        }
    }

    if( !realid )
    {
        realid = es_out_Add( real_es_out, es_id->getFmt() );
        if( b_select )
            es_out_Control( real_es_out, ES_OUT_SET_ES_STATE, realid, b_select );
    }

    es_id->setRealESID( realid );
}

mtime_t FakeESOut::getTimestampOffset() const
{
    return timestamps_offset;
}

size_t FakeESOut::esCount() const
{
    size_t i_count = 0;
    std::list<FakeESOutID *>::const_iterator it;
    for( it=fakeesidlist.begin(); it!=fakeesidlist.end(); ++it )
        if( (*it)->realESID() )
            i_count++;
    return i_count;
}

void FakeESOut::schedulePCRReset()
{
    AbstractCommand *command = commandsFactory->creatEsOutControlResetPCRCommand();
    if( likely(command) )
        commandsqueue.Schedule( command );
}

void FakeESOut::scheduleAllForDeletion()
{
    std::list<FakeESOutID *>::const_iterator it;
    for( it=fakeesidlist.begin(); it!=fakeesidlist.end(); ++it )
    {
        FakeESOutID *es_id = *it;
        if(!es_id->scheduledForDeletion())
        {
            AbstractCommand *command = commandsFactory->createEsOutDelCommand( es_id );
            if( likely(command) )
            {
                commandsqueue.Schedule( command );
                es_id->setScheduledForDeletion();
            }
        }
    }
}

void FakeESOut::recycleAll()
{
    /* Only used when demux is killed and commands queue is cancelled */
    commandsqueue.Abort( true );
    assert(commandsqueue.isEmpty());
    recycle_candidates.splice( recycle_candidates.end(), fakeesidlist );
}

void FakeESOut::gc()
{
    if( recycle_candidates.empty() )
        return;

    std::list<FakeESOutID *>::iterator it;
    for( it=recycle_candidates.begin(); it!=recycle_candidates.end(); ++it )
    {
        if( (*it)->realESID() )
        {
            es_out_Control( real_es_out, ES_OUT_SET_ES_STATE, (*it)->realESID(), false );
            es_out_Del( real_es_out, (*it)->realESID() );
        }
        delete *it;
    }
    recycle_candidates.clear();
}

bool FakeESOut::hasSelectedEs() const
{
    bool b_selected = false;
    std::list<FakeESOutID *>::const_iterator it;
    for( it=fakeesidlist.begin(); it!=fakeesidlist.end() && !b_selected; ++it )
    {
        FakeESOutID *esID = *it;
        if( esID->realESID() )
            es_out_Control( real_es_out, ES_OUT_GET_ES_STATE, esID->realESID(), &b_selected );
    }
    return b_selected;
}

bool FakeESOut::restarting() const
{
    return !recycle_candidates.empty();
}

void FakeESOut::recycle( FakeESOutID *id )
{
    fakeesidlist.remove( id );
    recycle_candidates.push_back( id );
}

/* Static callbacks */
/* Always pass Fake ES ID to slave demuxes, it is just an opaque struct to them */
es_out_id_t * FakeESOut::esOutAdd_Callback(es_out_t *fakees, const es_format_t *p_fmt)
{
    FakeESOut *me = (FakeESOut *) fakees->p_sys;
    /* Feed the slave demux/stream_Demux with FakeESOutID struct,
     * we'll create real ES later on main demux on execution */
    FakeESOutID *es_id = me->createNewID( p_fmt );
    if( likely(es_id) )
    {
        assert(!es_id->scheduledForDeletion());
        AbstractCommand *command = me->commandsFactory->createEsOutAddCommand( es_id );
        if( likely(command) )
        {
            me->commandsqueue.Schedule( command );
            return reinterpret_cast<es_out_id_t *>(es_id);
        }
        else
        {
            delete es_id;
        }
    }
    return NULL;
}

int FakeESOut::esOutSend_Callback(es_out_t *fakees, es_out_id_t *p_es, block_t *p_block)
{
    FakeESOut *me = (FakeESOut *) fakees->p_sys;
    FakeESOutID *es_id = reinterpret_cast<FakeESOutID *>( p_es );
    assert(!es_id->scheduledForDeletion());
    mtime_t offset = me->getTimestampOffset();
    if( p_block->i_dts > VLC_TS_INVALID )
    {
        p_block->i_dts += offset;
        if( p_block->i_pts > VLC_TS_INVALID )
                p_block->i_pts += offset;
    }
    AbstractCommand *command = me->commandsFactory->createEsOutSendCommand( es_id, p_block );
    if( likely(command) )
    {
        me->commandsqueue.Schedule( command );
        return VLC_SUCCESS;
    }
    return VLC_EGENERIC;
}

void FakeESOut::esOutDel_Callback(es_out_t *fakees, es_out_id_t *p_es)
{
    FakeESOut *me = (FakeESOut *) fakees->p_sys;
    FakeESOutID *es_id = reinterpret_cast<FakeESOutID *>( p_es );
    AbstractCommand *command = me->commandsFactory->createEsOutDelCommand( es_id );
    if( likely(command) )
    {
        me->commandsqueue.Schedule( command );
        es_id->setScheduledForDeletion();
    }
}

int FakeESOut::esOutControl_Callback(es_out_t *fakees, int i_query, va_list args)
{
    FakeESOut *me = (FakeESOut *) fakees->p_sys;

    switch( i_query )
    {
        case ES_OUT_SET_PCR:
        case ES_OUT_SET_GROUP_PCR:
        {
            int i_group;
            if( i_query == ES_OUT_SET_GROUP_PCR )
                i_group = static_cast<int>(va_arg( args, int ));
            else
                i_group = 0;
            int64_t  pcr = static_cast<int64_t>(va_arg( args, int64_t ));
            pcr += me->getTimestampOffset();
            AbstractCommand *command = me->commandsFactory->createEsOutControlPCRCommand( i_group, pcr );
            if( likely(command) )
            {
                me->commandsqueue.Schedule( command );
                return VLC_SUCCESS;
            }
        }
        break;

        /* For others, we don't have the delorean, so always lie */
        case ES_OUT_GET_ES_STATE:
        {
            static_cast<void*>(va_arg( args, es_out_id_t * ));
            bool *pb = static_cast<bool *>(va_arg( args, bool * ));
            *pb = true;
            // ft
        }
        case ES_OUT_SET_ES:
        case ES_OUT_SET_ES_DEFAULT:
        case ES_OUT_SET_ES_STATE:
            return VLC_SUCCESS;

    }

    return VLC_EGENERIC;
}

void FakeESOut::esOutDestroy_Callback(es_out_t *fakees)
{
    FakeESOut *me = (FakeESOut *) fakees->p_sys;
    AbstractCommand *command = me->commandsFactory->createEsOutDestroyCommand();
    if( likely(command) )
        me->commandsqueue.Schedule( command );
}
/* !Static callbacks */
<commit_msg>demux: adaptive: missing break on es recycling (fix #16952)<commit_after>/*
 * FakeESOut.cpp
 *****************************************************************************
 * Copyright © 2014-2015 VideoLAN and VLC Authors
 *
 * This program 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 program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "FakeESOut.hpp"
#include "FakeESOutID.hpp"
#include <vlc_es_out.h>
#include <vlc_block.h>
#include <cassert>

using namespace adaptive;

FakeESOut::FakeESOut( es_out_t *es, CommandsFactory *factory )
{
    real_es_out = es;
    fakeesout = new es_out_t;

    fakeesout->pf_add = esOutAdd_Callback;
    fakeesout->pf_control = esOutControl_Callback;
    fakeesout->pf_del = esOutDel_Callback;
    fakeesout->pf_destroy = esOutDestroy_Callback;
    fakeesout->pf_send = esOutSend_Callback;
    fakeesout->p_sys = (es_out_sys_t*) this;

    commandsFactory = factory;
    timestamps_offset = 0;
    extrainfo = NULL;
}

es_out_t * FakeESOut::getEsOut()
{
    return fakeesout;
}

FakeESOut::~FakeESOut()
{
    delete commandsFactory;

    recycleAll();
    gc();

    delete fakeesout;
}

void FakeESOut::setTimestampOffset(mtime_t offset)
{
    timestamps_offset = offset;
}

void FakeESOut::setExtraInfoProvider( ExtraFMTInfoInterface *extra )
{
    extrainfo = extra;
}

FakeESOutID * FakeESOut::createNewID( const es_format_t *p_fmt )
{
    es_format_t fmtcopy;
    es_format_Init( &fmtcopy, 0, 0 );
    es_format_Copy( &fmtcopy, p_fmt );
    fmtcopy.i_group = 0; /* Always ignore group for adaptive */

    if( extrainfo )
        extrainfo->fillExtraFMTInfo( &fmtcopy );

    FakeESOutID *es_id = new (std::nothrow) FakeESOutID( this, &fmtcopy );
    if(likely(es_id))
        fakeesidlist.push_back( es_id );

    es_format_Clean( &fmtcopy );

    return es_id;
}

void FakeESOut::createOrRecycleRealEsID( FakeESOutID *es_id )
{
    std::list<FakeESOutID *>::iterator it;
    es_out_id_t *realid = NULL;

    bool b_select = false;
    for( it=recycle_candidates.begin(); it!=recycle_candidates.end(); ++it )
    {
        FakeESOutID *cand = *it;
        if ( cand->isCompatible( es_id ) )
        {
            realid = cand->realESID();
            cand->setRealESID( NULL );
            delete *it;
            recycle_candidates.erase( it );
            break;
        }
        else if( cand->getFmt()->i_cat == es_id->getFmt()->i_cat )
        {
            /* We need to enforce same selection when not reused
               Otherwise the es will select any other compatible track
               and will end this in a activate/select loop when reactivating a track */
            es_out_Control( real_es_out, ES_OUT_GET_ES_STATE, cand->realESID(), &b_select );
            break;
        }
    }

    if( !realid )
    {
        realid = es_out_Add( real_es_out, es_id->getFmt() );
        if( b_select )
            es_out_Control( real_es_out, ES_OUT_SET_ES_STATE, realid, b_select );
    }

    es_id->setRealESID( realid );
}

mtime_t FakeESOut::getTimestampOffset() const
{
    return timestamps_offset;
}

size_t FakeESOut::esCount() const
{
    size_t i_count = 0;
    std::list<FakeESOutID *>::const_iterator it;
    for( it=fakeesidlist.begin(); it!=fakeesidlist.end(); ++it )
        if( (*it)->realESID() )
            i_count++;
    return i_count;
}

void FakeESOut::schedulePCRReset()
{
    AbstractCommand *command = commandsFactory->creatEsOutControlResetPCRCommand();
    if( likely(command) )
        commandsqueue.Schedule( command );
}

void FakeESOut::scheduleAllForDeletion()
{
    std::list<FakeESOutID *>::const_iterator it;
    for( it=fakeesidlist.begin(); it!=fakeesidlist.end(); ++it )
    {
        FakeESOutID *es_id = *it;
        if(!es_id->scheduledForDeletion())
        {
            AbstractCommand *command = commandsFactory->createEsOutDelCommand( es_id );
            if( likely(command) )
            {
                commandsqueue.Schedule( command );
                es_id->setScheduledForDeletion();
            }
        }
    }
}

void FakeESOut::recycleAll()
{
    /* Only used when demux is killed and commands queue is cancelled */
    commandsqueue.Abort( true );
    assert(commandsqueue.isEmpty());
    recycle_candidates.splice( recycle_candidates.end(), fakeesidlist );
}

void FakeESOut::gc()
{
    if( recycle_candidates.empty() )
        return;

    std::list<FakeESOutID *>::iterator it;
    for( it=recycle_candidates.begin(); it!=recycle_candidates.end(); ++it )
    {
        if( (*it)->realESID() )
        {
            es_out_Control( real_es_out, ES_OUT_SET_ES_STATE, (*it)->realESID(), false );
            es_out_Del( real_es_out, (*it)->realESID() );
        }
        delete *it;
    }
    recycle_candidates.clear();
}

bool FakeESOut::hasSelectedEs() const
{
    bool b_selected = false;
    std::list<FakeESOutID *>::const_iterator it;
    for( it=fakeesidlist.begin(); it!=fakeesidlist.end() && !b_selected; ++it )
    {
        FakeESOutID *esID = *it;
        if( esID->realESID() )
            es_out_Control( real_es_out, ES_OUT_GET_ES_STATE, esID->realESID(), &b_selected );
    }
    return b_selected;
}

bool FakeESOut::restarting() const
{
    return !recycle_candidates.empty();
}

void FakeESOut::recycle( FakeESOutID *id )
{
    fakeesidlist.remove( id );
    recycle_candidates.push_back( id );
}

/* Static callbacks */
/* Always pass Fake ES ID to slave demuxes, it is just an opaque struct to them */
es_out_id_t * FakeESOut::esOutAdd_Callback(es_out_t *fakees, const es_format_t *p_fmt)
{
    FakeESOut *me = (FakeESOut *) fakees->p_sys;
    /* Feed the slave demux/stream_Demux with FakeESOutID struct,
     * we'll create real ES later on main demux on execution */
    FakeESOutID *es_id = me->createNewID( p_fmt );
    if( likely(es_id) )
    {
        assert(!es_id->scheduledForDeletion());
        AbstractCommand *command = me->commandsFactory->createEsOutAddCommand( es_id );
        if( likely(command) )
        {
            me->commandsqueue.Schedule( command );
            return reinterpret_cast<es_out_id_t *>(es_id);
        }
        else
        {
            delete es_id;
        }
    }
    return NULL;
}

int FakeESOut::esOutSend_Callback(es_out_t *fakees, es_out_id_t *p_es, block_t *p_block)
{
    FakeESOut *me = (FakeESOut *) fakees->p_sys;
    FakeESOutID *es_id = reinterpret_cast<FakeESOutID *>( p_es );
    assert(!es_id->scheduledForDeletion());
    mtime_t offset = me->getTimestampOffset();
    if( p_block->i_dts > VLC_TS_INVALID )
    {
        p_block->i_dts += offset;
        if( p_block->i_pts > VLC_TS_INVALID )
                p_block->i_pts += offset;
    }
    AbstractCommand *command = me->commandsFactory->createEsOutSendCommand( es_id, p_block );
    if( likely(command) )
    {
        me->commandsqueue.Schedule( command );
        return VLC_SUCCESS;
    }
    return VLC_EGENERIC;
}

void FakeESOut::esOutDel_Callback(es_out_t *fakees, es_out_id_t *p_es)
{
    FakeESOut *me = (FakeESOut *) fakees->p_sys;
    FakeESOutID *es_id = reinterpret_cast<FakeESOutID *>( p_es );
    AbstractCommand *command = me->commandsFactory->createEsOutDelCommand( es_id );
    if( likely(command) )
    {
        me->commandsqueue.Schedule( command );
        es_id->setScheduledForDeletion();
    }
}

int FakeESOut::esOutControl_Callback(es_out_t *fakees, int i_query, va_list args)
{
    FakeESOut *me = (FakeESOut *) fakees->p_sys;

    switch( i_query )
    {
        case ES_OUT_SET_PCR:
        case ES_OUT_SET_GROUP_PCR:
        {
            int i_group;
            if( i_query == ES_OUT_SET_GROUP_PCR )
                i_group = static_cast<int>(va_arg( args, int ));
            else
                i_group = 0;
            int64_t  pcr = static_cast<int64_t>(va_arg( args, int64_t ));
            pcr += me->getTimestampOffset();
            AbstractCommand *command = me->commandsFactory->createEsOutControlPCRCommand( i_group, pcr );
            if( likely(command) )
            {
                me->commandsqueue.Schedule( command );
                return VLC_SUCCESS;
            }
        }
        break;

        /* For others, we don't have the delorean, so always lie */
        case ES_OUT_GET_ES_STATE:
        {
            static_cast<void*>(va_arg( args, es_out_id_t * ));
            bool *pb = static_cast<bool *>(va_arg( args, bool * ));
            *pb = true;
            // ft
        }
        case ES_OUT_SET_ES:
        case ES_OUT_SET_ES_DEFAULT:
        case ES_OUT_SET_ES_STATE:
            return VLC_SUCCESS;

    }

    return VLC_EGENERIC;
}

void FakeESOut::esOutDestroy_Callback(es_out_t *fakees)
{
    FakeESOut *me = (FakeESOut *) fakees->p_sys;
    AbstractCommand *command = me->commandsFactory->createEsOutDestroyCommand();
    if( likely(command) )
        me->commandsqueue.Schedule( command );
}
/* !Static callbacks */
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/include/usr/fapi2/plat_target_filter.H $                  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2020                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 * @file plat_target_filter.H
 * @brief platform bit-mask definitions for fapi2 TargetFilter enum
 */

#ifndef __FAPI2_PLAT_TARGET_FILTER__
#define __FAPI2_PLAT_TARGET_FILTER__

#include <stdint.h>

//
// Define TargetFilter enum values for the platform
//
namespace fapi2
{
namespace PlatTargetFilter
{

// overrideAttribute x86.nfp requires this file to not be in C++11 format
#ifndef CONTEXT_x86_nfp
#define CONSTEXPR constexpr
#else
#define CONSTEXPR const
#endif

// These values must contain only 1 bit 'on' so that they can be ORed
// together as composite filters

// Logic inside Target::getChildren() requires these values to match the
//  chiplet numbers, i.e. chiplet0 = 0x8000000000000000
CONSTEXPR uint64_t BIT0 = 0x8000000000000000;
CONSTEXPR uint64_t PLAT_TARGET_FILTER_TP          = (BIT0 >>  1);  // Pervasive 1
CONSTEXPR uint64_t PLAT_TARGET_FILTER_NEST_NORTH  = (BIT0 >>  2);  // Pervasive 2
CONSTEXPR uint64_t PLAT_TARGET_FILTER_NEST_SOUTH  = (BIT0 >>  3);  // Pervasive 3
CONSTEXPR uint64_t PLAT_TARGET_FILTER_PCI0        = (BIT0 >>  8);  // Pervasive 8
CONSTEXPR uint64_t PLAT_TARGET_FILTER_PCI1        = (BIT0 >>  9);  // Pervasive 9
CONSTEXPR uint64_t PLAT_TARGET_FILTER_MC0         = (BIT0 >> 12);  // Pervasive 12
CONSTEXPR uint64_t PLAT_TARGET_FILTER_MC1         = (BIT0 >> 13);  // Pervasive 13
CONSTEXPR uint64_t PLAT_TARGET_FILTER_MC2         = (BIT0 >> 14);  // Pervasive 14
CONSTEXPR uint64_t PLAT_TARGET_FILTER_MC3         = (BIT0 >> 15);  // Pervasive 15
CONSTEXPR uint64_t PLAT_TARGET_FILTER_PAU0        = (BIT0 >> 16);  // Pervasive 16
CONSTEXPR uint64_t PLAT_TARGET_FILTER_PAU1        = (BIT0 >> 17);  // Pervasive 17
CONSTEXPR uint64_t PLAT_TARGET_FILTER_PAU2        = (BIT0 >> 18);  // Pervasive 18
CONSTEXPR uint64_t PLAT_TARGET_FILTER_PAU3        = (BIT0 >> 19);  // Pervasive 19
CONSTEXPR uint64_t PLAT_TARGET_FILTER_IOHS0       = (BIT0 >> 24);  // Pervasive 24
CONSTEXPR uint64_t PLAT_TARGET_FILTER_IOHS1       = (BIT0 >> 25);  // Pervasive 25
CONSTEXPR uint64_t PLAT_TARGET_FILTER_IOHS2       = (BIT0 >> 26);  // Pervasive 26
CONSTEXPR uint64_t PLAT_TARGET_FILTER_IOHS3       = (BIT0 >> 27);  // Pervasive 27
CONSTEXPR uint64_t PLAT_TARGET_FILTER_IOHS4       = (BIT0 >> 28);  // Pervasive 28
CONSTEXPR uint64_t PLAT_TARGET_FILTER_IOHS5       = (BIT0 >> 29);  // Pervasive 29
CONSTEXPR uint64_t PLAT_TARGET_FILTER_IOHS6       = (BIT0 >> 30);  // Pervasive 30
CONSTEXPR uint64_t PLAT_TARGET_FILTER_IOHS7       = (BIT0 >> 31);  // Pervasive 31
CONSTEXPR uint64_t PLAT_TARGET_FILTER_EQ0         = (BIT0 >> 32);  // Pervasive 32
CONSTEXPR uint64_t PLAT_TARGET_FILTER_EQ1         = (BIT0 >> 33);  // Pervasive 33
CONSTEXPR uint64_t PLAT_TARGET_FILTER_EQ2         = (BIT0 >> 34);  // Pervasive 34
CONSTEXPR uint64_t PLAT_TARGET_FILTER_EQ3         = (BIT0 >> 35);  // Pervasive 35
CONSTEXPR uint64_t PLAT_TARGET_FILTER_EQ4         = (BIT0 >> 36);  // Pervasive 36
CONSTEXPR uint64_t PLAT_TARGET_FILTER_EQ5         = (BIT0 >> 37);  // Pervasive 37
CONSTEXPR uint64_t PLAT_TARGET_FILTER_EQ6         = (BIT0 >> 38);  // Pervasive 38
CONSTEXPR uint64_t PLAT_TARGET_FILTER_EQ7         = (BIT0 >> 39);  // Pervasive 39

#undef CONSTEXPR

} // namespace PlatTargetFilter

} // namespace fapi2

#endif
<commit_msg>Add constant for ekb compile<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/include/usr/fapi2/plat_target_filter.H $                  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2022                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 * @file plat_target_filter.H
 * @brief platform bit-mask definitions for fapi2 TargetFilter enum
 */

#ifndef __FAPI2_PLAT_TARGET_FILTER__
#define __FAPI2_PLAT_TARGET_FILTER__

#include <stdint.h>

//
// Define TargetFilter enum values for the platform
//
namespace fapi2
{
namespace PlatTargetFilter
{

// overrideAttribute x86.nfp requires this file to not be in C++11 format
#ifndef CONTEXT_x86_nfp
#define CONSTEXPR constexpr
#else
#define CONSTEXPR const
#endif

// These values must contain only 1 bit 'on' so that they can be ORed
// together as composite filters

// Logic inside Target::getChildren() requires these values to match the
//  chiplet numbers, i.e. chiplet0 = 0x8000000000000000
CONSTEXPR uint64_t BIT0 = 0x8000000000000000;
CONSTEXPR uint64_t PLAT_TARGET_FILTER_TP          = (BIT0 >>  1);  // Pervasive 1
CONSTEXPR uint64_t PLAT_TARGET_FILTER_NEST_NORTH  = (BIT0 >>  2);  // Pervasive 2
CONSTEXPR uint64_t PLAT_TARGET_FILTER_NEST_SOUTH  = (BIT0 >>  3);  // Pervasive 3
CONSTEXPR uint64_t PLAT_TARGET_FILTER_PCI0        = (BIT0 >>  8);  // Pervasive 8
CONSTEXPR uint64_t PLAT_TARGET_FILTER_PCI1        = (BIT0 >>  9);  // Pervasive 9
CONSTEXPR uint64_t PLAT_TARGET_FILTER_MC0         = (BIT0 >> 12);  // Pervasive 12
CONSTEXPR uint64_t PLAT_TARGET_FILTER_MC1         = (BIT0 >> 13);  // Pervasive 13
CONSTEXPR uint64_t PLAT_TARGET_FILTER_MC2         = (BIT0 >> 14);  // Pervasive 14
CONSTEXPR uint64_t PLAT_TARGET_FILTER_MC3         = (BIT0 >> 15);  // Pervasive 15
CONSTEXPR uint64_t PLAT_TARGET_FILTER_PAU0        = (BIT0 >> 16);  // Pervasive 16
CONSTEXPR uint64_t PLAT_TARGET_FILTER_PAU1        = (BIT0 >> 17);  // Pervasive 17
CONSTEXPR uint64_t PLAT_TARGET_FILTER_PAU2        = (BIT0 >> 18);  // Pervasive 18
CONSTEXPR uint64_t PLAT_TARGET_FILTER_PAU3        = (BIT0 >> 19);  // Pervasive 19
CONSTEXPR uint64_t PLAT_TARGET_FILTER_IOHS0       = (BIT0 >> 24);  // Pervasive 24
CONSTEXPR uint64_t PLAT_TARGET_FILTER_IOHS1       = (BIT0 >> 25);  // Pervasive 25
CONSTEXPR uint64_t PLAT_TARGET_FILTER_IOHS2       = (BIT0 >> 26);  // Pervasive 26
CONSTEXPR uint64_t PLAT_TARGET_FILTER_IOHS3       = (BIT0 >> 27);  // Pervasive 27
CONSTEXPR uint64_t PLAT_TARGET_FILTER_IOHS4       = (BIT0 >> 28);  // Pervasive 28
CONSTEXPR uint64_t PLAT_TARGET_FILTER_IOHS5       = (BIT0 >> 29);  // Pervasive 29
CONSTEXPR uint64_t PLAT_TARGET_FILTER_IOHS6       = (BIT0 >> 30);  // Pervasive 30
CONSTEXPR uint64_t PLAT_TARGET_FILTER_IOHS7       = (BIT0 >> 31);  // Pervasive 31
CONSTEXPR uint64_t PLAT_TARGET_FILTER_EQ0         = (BIT0 >> 32);  // Pervasive 32
CONSTEXPR uint64_t PLAT_TARGET_FILTER_EQ1         = (BIT0 >> 33);  // Pervasive 33
CONSTEXPR uint64_t PLAT_TARGET_FILTER_EQ2         = (BIT0 >> 34);  // Pervasive 34
CONSTEXPR uint64_t PLAT_TARGET_FILTER_EQ3         = (BIT0 >> 35);  // Pervasive 35
CONSTEXPR uint64_t PLAT_TARGET_FILTER_EQ4         = (BIT0 >> 36);  // Pervasive 36
CONSTEXPR uint64_t PLAT_TARGET_FILTER_EQ5         = (BIT0 >> 37);  // Pervasive 37
CONSTEXPR uint64_t PLAT_TARGET_FILTER_EQ6         = (BIT0 >> 38);  // Pervasive 38
CONSTEXPR uint64_t PLAT_TARGET_FILTER_EQ7         = (BIT0 >> 39);  // Pervasive 39

// placeholder for Odyssey compile in ekb, will fix with full support later
CONSTEXPR uint64_t PLAT_TARGET_FILTER_MC = 0xFFFFFFFFFFFFFFFF;

#undef CONSTEXPR

} // namespace PlatTargetFilter

} // namespace fapi2

#endif
<|endoftext|>


<commit_before>/**
 * \file
 * <!--
 * Copyright 2015 Develer S.r.l. (http://www.develer.com/)
 * -->
 *
 * \brief SessionManager class implementation
 *
 * \author Aurelien Rainone <aurelien@develer.org>
 */

#include "sessionmanager.h"
#include "outputmanager.h"

#include <QMessageBox>
#include <QSerialPortInfo>
#include <QFile>

SessionManager::SessionManager(QObject *parent)
    : QObject(parent)
{
    serial = new QSerialPort(this);
    in_progress = false;

    connect(serial, &QSerialPort::readyRead, this, &SessionManager::readData);
    connect(serial, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>
                (&QSerialPort::error), this, &SessionManager::handleError);
}

SessionManager::~SessionManager()
{
    // closes connection if needed
    if (serial->isOpen())
        serial->close();
}

void SessionManager::handleError(QSerialPort::SerialPortError serialPortError)
{
    switch (serialPortError)
    {
        // no error
        case QSerialPort::NoError:
            break;

        // recoverable errors : inform user and clear error
        case QSerialPort::OpenError:

            QMessageBox::warning(NULL, tr("Error"), serial->errorString());
            // reset error
            serial->clearError();
            break;

        // unrecoverable errors : inform user and close the port/connection
        default:
            if (in_progress)
            {
                QMessageBox::critical(NULL, tr("Error"), serial->errorString());

                // on some error (ex: hot unplugging) the 'QSerialPort::error' property successively
                // takes multiple values.
                // to prevent from displaying successive error messages, the in_progress flag is
                // set to indicate that we are not interested by next messages, until the user tries to open
                // again the serial port
                in_progress = false;
                if (serial->isOpen())
                {
                    serial->clearError();
                    serial->close();
                }
            }
            break;
    }
}

void SessionManager::openSession(const QHash<QString, QString>& port_cfg)
{
    bool cfg_ok = true, ok;

    // try converting port config from the hash
    QSerialPort::BaudRate baud_rate = static_cast<QSerialPort::BaudRate>
            (port_cfg["baud_rate"].toInt(&ok));
    cfg_ok &= ok;

    QSerialPort::DataBits data_bits = static_cast<QSerialPort::DataBits>
            (port_cfg["data_bits"].toInt(&ok));
    cfg_ok &= ok;

    QSerialPort::Parity parity = static_cast<QSerialPort::Parity>
            (port_cfg["parity"].toInt(&ok));
    cfg_ok &= ok;

    QSerialPort::StopBits stop_bits = static_cast<QSerialPort::StopBits>
            (port_cfg["stop_bits"].toInt(&ok));
    cfg_ok &= ok;

    QSerialPort::FlowControl flow_control = static_cast<QSerialPort::FlowControl>
            (port_cfg["flow_control"].toInt(&ok));
    cfg_ok &= ok;

    // a conversion didn't make it
    Q_ASSERT_X(cfg_ok, "SessionManager::openSession", "a conversion didn't make it");

    // closes connection if needed
    if (serial->isOpen())
        serial->close();

    // configure port
#ifdef Q_OS_MAC
    // connection error on MacOsX if port name is set with setPortName instead
    // of setPort (issue #7)
    serial->setPort(QSerialPortInfo(port_cfg[QStringLiteral("device")]));
#else
    // tested on linux and windows
    // and this is necessary to make QSerialPort work with pseudo
    // terminal created with socat for example
    serial->setPortName(port_cfg[QStringLiteral("device")]);
#endif
    serial->setBaudRate(baud_rate);
    serial->setDataBits(data_bits);
    serial->setParity(parity);
    serial->setStopBits(stop_bits);
    serial->setFlowControl(flow_control);

    // flag indicating that a connection is in progress (eventually successful or not)
    in_progress = true;

    // open serial port
    if (serial->open(QIODevice::ReadWrite))
    {
        curr_cfg = port_cfg;
        emit sessionStarted();
    }
}

bool SessionManager::isSessionOpen() const
{
    return serial->isOpen();
}

void SessionManager::saveToFile(const QByteArray &data)
{
    QFile dump(curr_cfg["dump_file"]);

    // mode is OR'ed with 'Text' flag in "Ascii" mode
    QIODevice::OpenMode mode = QIODevice::Append;

    if (curr_cfg["dump_file"] == QString::number(ConnectDialog::Ascii))
        mode |= QIODevice::Text;

    if (dump.open(mode))
        dump.write(data);
}

void SessionManager::readData()
{
    QByteArray data(serial->readAll());

    emit dataReceived(data);

    // append to dump file if configured
    if (curr_cfg["dump_enabled"] == "1")
        saveToFile(data);
}

void SessionManager::sendToSerial(const QByteArray &data)
{
    serial->write(data);
}

<commit_msg>add qt version check<commit_after>/**
 * \file
 * <!--
 * Copyright 2015 Develer S.r.l. (http://www.develer.com/)
 * -->
 *
 * \brief SessionManager class implementation
 *
 * \author Aurelien Rainone <aurelien@develer.org>
 */

#include "sessionmanager.h"
#include "outputmanager.h"

#include <QMessageBox>
#include <QSerialPortInfo>
#include <QFile>

SessionManager::SessionManager(QObject *parent)
    : QObject(parent)
{
    serial = new QSerialPort(this);
    in_progress = false;

    connect(serial, &QSerialPort::readyRead, this, &SessionManager::readData);
    connect(serial, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>
                (&QSerialPort::error), this, &SessionManager::handleError);
}

SessionManager::~SessionManager()
{
    // closes connection if needed
    if (serial->isOpen())
        serial->close();
}

void SessionManager::handleError(QSerialPort::SerialPortError serialPortError)
{
    switch (serialPortError)
    {
        // no error
        case QSerialPort::NoError:
            break;

        // recoverable errors : inform user and clear error
        case QSerialPort::OpenError:

            QMessageBox::warning(NULL, tr("Error"), serial->errorString());
            // reset error
            serial->clearError();
            break;

        // unrecoverable errors : inform user and close the port/connection
        default:
            if (in_progress)
            {
                QMessageBox::critical(NULL, tr("Error"), serial->errorString());

                // on some error (ex: hot unplugging) the 'QSerialPort::error' property successively
                // takes multiple values.
                // to prevent from displaying successive error messages, the in_progress flag is
                // set to indicate that we are not interested by next messages, until the user tries to open
                // again the serial port
                in_progress = false;
                if (serial->isOpen())
                {
                    serial->clearError();
                    serial->close();
                }
            }
            break;
    }
}

void SessionManager::openSession(const QHash<QString, QString>& port_cfg)
{
    bool cfg_ok = true, ok;

    // try converting port config from the hash
    QSerialPort::BaudRate baud_rate = static_cast<QSerialPort::BaudRate>
            (port_cfg["baud_rate"].toInt(&ok));
    cfg_ok &= ok;

    QSerialPort::DataBits data_bits = static_cast<QSerialPort::DataBits>
            (port_cfg["data_bits"].toInt(&ok));
    cfg_ok &= ok;

    QSerialPort::Parity parity = static_cast<QSerialPort::Parity>
            (port_cfg["parity"].toInt(&ok));
    cfg_ok &= ok;

    QSerialPort::StopBits stop_bits = static_cast<QSerialPort::StopBits>
            (port_cfg["stop_bits"].toInt(&ok));
    cfg_ok &= ok;

    QSerialPort::FlowControl flow_control = static_cast<QSerialPort::FlowControl>
            (port_cfg["flow_control"].toInt(&ok));
    cfg_ok &= ok;

    // a conversion didn't make it
    Q_ASSERT_X(cfg_ok, "SessionManager::openSession", "a conversion didn't make it");

    // closes connection if needed
    if (serial->isOpen())
        serial->close();

    // configure port
#if (QT_VERSION < QT_VERSION_CHECK(5, 5, 0)) && Q_OS_MAC
    // connection error on MacOsX if port name is set with setPortName instead
    // of setPort (issue #7)
    serial->setPort(QSerialPortInfo(port_cfg[QStringLiteral("device")]));
#else
    // tested on linux and windows
    // and this is necessary to make QSerialPort work with pseudo
    // terminal created with socat for example
    serial->setPortName(port_cfg[QStringLiteral("device")]);
#endif
    serial->setBaudRate(baud_rate);
    serial->setDataBits(data_bits);
    serial->setParity(parity);
    serial->setStopBits(stop_bits);
    serial->setFlowControl(flow_control);

    // flag indicating that a connection is in progress (eventually successful or not)
    in_progress = true;

    // open serial port
    if (serial->open(QIODevice::ReadWrite))
    {
        curr_cfg = port_cfg;
        emit sessionStarted();
    }
}

bool SessionManager::isSessionOpen() const
{
    return serial->isOpen();
}

void SessionManager::saveToFile(const QByteArray &data)
{
    QFile dump(curr_cfg["dump_file"]);

    // mode is OR'ed with 'Text' flag in "Ascii" mode
    QIODevice::OpenMode mode = QIODevice::Append;

    if (curr_cfg["dump_file"] == QString::number(ConnectDialog::Ascii))
        mode |= QIODevice::Text;

    if (dump.open(mode))
        dump.write(data);
}

void SessionManager::readData()
{
    QByteArray data(serial->readAll());

    emit dataReceived(data);

    // append to dump file if configured
    if (curr_cfg["dump_enabled"] == "1")
        saveToFile(data);
}

void SessionManager::sendToSerial(const QByteArray &data)
{
    serial->write(data);
}

<|endoftext|>


<commit_before>/******************************************************************************
 * BRICS_3D - 3D Perception and Modeling Library
 * Copyright (c) 2015, KU Leuven
 *
 * Author: Sebastian Blumenthal
 *
 *
 * This software is published under a dual-license: GNU Lesser General Public
 * License LGPL 2.1 and Modified BSD license. The dual-license implies that
 * users of this code may choose which terms they prefer.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License LGPL and the BSD license for
 * more details.
 *
 ******************************************************************************/

#include "JSONDeserializer.h"
#include <assert.h>

namespace brics_3d {
namespace rsg {

JSONDeserializer::JSONDeserializer(WorldModel* wm) :
		wm(wm) {
	mapUnknownParentIdsToRootId = false;
}

JSONDeserializer::~JSONDeserializer() {

}

int JSONDeserializer::write(const char *dataBuffer, int dataLength, int &transferredBytes) {
	return -1;
}

int JSONDeserializer::write(std::string data) {

	libvariant::Variant model = libvariant:: Deserialize(data, libvariant::SERIALIZE_GUESS); // GUESS seems to be more permissive with parsing than JSON

	// Start to parse it
	if(!model.Contains("type")) {
		LOG(ERROR) << "Top level model type does not exist.";
		return -1;
	}

	std::string type = model.Get("type").AsString();
	if(type.compare("RSGUpdate") == 0) {
		LOG(DEBUG) << "JSONDeserializer: Found a model for an update.";
	} else if (type.compare("WorldModelAgent") == 0) {
		LOG(DEBUG) << "JSONDeserializer: Found model for a WorldModelAgent.";
	} else {
		// This is indented for debugging purposes only
		LOG(DEBUG) << "JSONDeserializer: Found a model for a graph primitive";

		Id rootId = 0;
		if (mapUnknownParentIdsToRootId) {
			rootId = wm->getRootNodeId();
		}

		handleGraphPrimitive(model, rootId);
	}

	return 0;
}

bool JSONDeserializer::handleGraphPrimitive(libvariant::Variant& atom, rsg::Id parentId) {
	LOG(DEBUG) << "JSONDeserializer: handleGraphPrimitive";
	if(atom.Contains("type")) {
		string type = atom.Get("type").AsString();
		LOG(DEBUG) << "JSONDeserializer: Atom has type identifier = "<< type; ;

		if(type.compare("Node") == 0) {
			doAddNode(atom, parentId);
		} else if (type.compare("Group") == 0) {
			doAddGroup(atom, parentId);
		} else { // ...
			LOG(WARNING) << "JSONDeserializer: Unknown atom type. Skippping it.";
		}
	} else {
		LOG(ERROR) << "SONDeserializer: Atom has no type identifier";
		return false;
	}

	return true;
}

bool JSONDeserializer::doAddNode(libvariant::Variant& group, rsg::Id parentId) {
	LOG(DEBUG) << "JSONDeserializer: doAddNode: type is = " << group.Get("type").AsString();

	/* Id */
	rsg::Id id = rsg::JSONTypecaster::getIdFromJSON(group, "id");
	assert(!id.isNil());

	/* attributes */
	std::vector<rsg::Attribute> attributes = rsg::JSONTypecaster::getAttributesFromJSON(group);

	/* create it */
	wm->scene.addNode(parentId, id, attributes, true);

	return true;
}

bool JSONDeserializer::doAddGroup(libvariant::Variant& group, rsg::Id parentId) {
	LOG(DEBUG) << "JSONDeserializer: doAddGroup: type is = " << group.Get("type").AsString();

	/* Id */
	rsg::Id id = rsg::JSONTypecaster::getIdFromJSON(group, "id");
	assert(!id.isNil());

	/* attributes */
	std::vector<rsg::Attribute> attributes = rsg::JSONTypecaster::getAttributesFromJSON(group);

	/* create it */
	wm->scene.addGroup(parentId, id, attributes, true);

	/* childs (recursion) */
	if(group.Contains("childs")) {
		LOG(DEBUG) << "JSONDeserializer: Group has the following childs:";

		libvariant::Variant attributeList = group.Get("childs");
		if (attributeList.IsList()) {
			for (libvariant::Variant::ListIterator i(attributeList.ListBegin()), e(attributeList.ListEnd()); i!=e; ++i) {
				assert(i->Contains("type"));
				string childType = i->Get("type").AsString();
				LOG(DEBUG) << "JSONDeserializer: \t\t type = " << childType;

				if(childType.compare("Child") == 0) {
					libvariant::Variant child = i->Get("child");
					handleGraphPrimitive(child, id);
				} else if (childType.compare("ChildId") == 0) {
					// TODO stamps
					assert(i->Contains("childId"));
					rsg::Id childId = rsg::JSONTypecaster::getIdFromJSON(*i, "childId");
					LOG(DEBUG) << "JSONDeserializer: Adding parent -> child relation: " << id << " -> " << childId;
					// add parent
				}
			}
		}
	}

	return true;
}

bool JSONDeserializer::doAddTransformNode(libvariant::Variant& group,
		rsg::Id parentId) {
	return false;
}

bool JSONDeserializer::doAddGeometricNode(libvariant::Variant& group,
		rsg::Id parentId) {
	return false;
}

bool JSONDeserializer::doAddRemoteRootNode(libvariant::Variant& group,
		rsg::Id parentId) {
	return false;
}

bool JSONDeserializer::doAddConnection(libvariant::Variant& group,
		rsg::Id parentId) {
	return false;
}

bool JSONDeserializer::doSetNodeAttributes(libvariant::Variant& group,
		rsg::Id parentId) {
	return false;
}

bool JSONDeserializer::doSetTransform(libvariant::Variant& group,
		rsg::Id parentId) {
	return false;
}

bool JSONDeserializer::doDeleteNode(libvariant::Variant& group,
		rsg::Id parentId) {
	return false;
}

bool JSONDeserializer::doAddParent(libvariant::Variant& group,
		rsg::Id parentId) {
	return false;
}

bool JSONDeserializer::doRemoveParent(libvariant::Variant& group,
		rsg::Id parentId) {
	return false;
}

} /* namespace rsg */
} /* namespace brics_3d */

/* EOF */
<commit_msg>Adjustments for revised type indentifiers.<commit_after>/******************************************************************************
 * BRICS_3D - 3D Perception and Modeling Library
 * Copyright (c) 2015, KU Leuven
 *
 * Author: Sebastian Blumenthal
 *
 *
 * This software is published under a dual-license: GNU Lesser General Public
 * License LGPL 2.1 and Modified BSD license. The dual-license implies that
 * users of this code may choose which terms they prefer.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License LGPL and the BSD license for
 * more details.
 *
 ******************************************************************************/

#include "JSONDeserializer.h"
#include <assert.h>

namespace brics_3d {
namespace rsg {

JSONDeserializer::JSONDeserializer(WorldModel* wm) :
		wm(wm) {
	mapUnknownParentIdsToRootId = false;
}

JSONDeserializer::~JSONDeserializer() {

}

int JSONDeserializer::write(const char *dataBuffer, int dataLength, int &transferredBytes) {
	return -1;
}

int JSONDeserializer::write(std::string data) {

	libvariant::Variant model = libvariant:: Deserialize(data, libvariant::SERIALIZE_GUESS); // GUESS seems to be more permissive with parsing than JSON

	// Start to parse it
	if(model.Contains("@worldmodeltype")) {

		std::string type = model.Get("@worldmodeltype").AsString();
		if(type.compare("RSGUpdate") == 0) {
			LOG(DEBUG) << "JSONDeserializer: Found a model for an update.";
		} else if (type.compare("WorldModelAgent") == 0) {
			LOG(DEBUG) << "JSONDeserializer: Found model for a WorldModelAgent.";
		}

	} else {
		LOG(WARNING) << "Top level model type does not exist.";
	}

	/* This is indented for debugging purposes only */
	if (model.Contains("@graphtype")) {
		LOG(DEBUG) << "JSONDeserializer: Found a model for a graph primitive";

		Id rootId = 0;
		if (mapUnknownParentIdsToRootId) {
			rootId = wm->getRootNodeId();
		}

		handleGraphPrimitive(model, rootId);
	}

	return 0;
}

bool JSONDeserializer::handleGraphPrimitive(libvariant::Variant& atom, rsg::Id parentId) {
	LOG(DEBUG) << "JSONDeserializer: handleGraphPrimitive";
	if(atom.Contains("@graphtype")) {
		string type = atom.Get("@graphtype").AsString();
		LOG(DEBUG) << "JSONDeserializer: Atom has graphtype identifier = " << type; ;

		if(type.compare("Node") == 0) {
			doAddNode(atom, parentId);
		} else if (type.compare("Group") == 0) {
			doAddGroup(atom, parentId);
		} else { // ...
			LOG(WARNING) << "JSONDeserializer: Unknown atom graphtype. Skippping it.";
		}
	} else {
		LOG(ERROR) << "JSONDeserializer: Atom has no graphtype identifier";
		return false;
	}

	return true;
}

bool JSONDeserializer::doAddNode(libvariant::Variant& group, rsg::Id parentId) {
	LOG(DEBUG) << "JSONDeserializer: doAddNode: type is = " << group.Get("@graphtype").AsString();

	/* Id */
	rsg::Id id = rsg::JSONTypecaster::getIdFromJSON(group, "id");
	assert(!id.isNil());

	/* attributes */
	std::vector<rsg::Attribute> attributes = rsg::JSONTypecaster::getAttributesFromJSON(group);

	/* create it */
	wm->scene.addNode(parentId, id, attributes, true);

	return true;
}

bool JSONDeserializer::doAddGroup(libvariant::Variant& group, rsg::Id parentId) {
	LOG(DEBUG) << "JSONDeserializer: doAddGroup: type is = " << group.Get("@graphtype").AsString();

	/* Id */
	rsg::Id id = rsg::JSONTypecaster::getIdFromJSON(group, "id");
	assert(!id.isNil());

	/* attributes */
	std::vector<rsg::Attribute> attributes = rsg::JSONTypecaster::getAttributesFromJSON(group);

	/* create it */
	wm->scene.addGroup(parentId, id, attributes, true);

	/* childs (recursion) */
	if(group.Contains("childs")) {
		LOG(DEBUG) << "JSONDeserializer: Group has the following childs:";

		libvariant::Variant attributeList = group.Get("childs");
		if (attributeList.IsList()) {
			for (libvariant::Variant::ListIterator i(attributeList.ListBegin()), e(attributeList.ListEnd()); i!=e; ++i) {
				assert(i->Contains("@childtype"));
				string childType = i->Get("@childtype").AsString();
				LOG(DEBUG) << "JSONDeserializer: \t\t type = " << childType;

				if(childType.compare("Child") == 0) {
					libvariant::Variant child = i->Get("child");
					handleGraphPrimitive(child, id);
				} else if (childType.compare("ChildId") == 0) {
					// TODO stamps
					assert(i->Contains("childId"));
					rsg::Id childId = rsg::JSONTypecaster::getIdFromJSON(*i, "childId");
					LOG(DEBUG) << "JSONDeserializer: Adding parent -> child relation: " << id << " -> " << childId;
					// add parent
				}
			}
		}
	}

	return true;
}

bool JSONDeserializer::doAddTransformNode(libvariant::Variant& group,
		rsg::Id parentId) {
	return false;
}

bool JSONDeserializer::doAddGeometricNode(libvariant::Variant& group,
		rsg::Id parentId) {
	return false;
}

bool JSONDeserializer::doAddRemoteRootNode(libvariant::Variant& group,
		rsg::Id parentId) {
	return false;
}

bool JSONDeserializer::doAddConnection(libvariant::Variant& group,
		rsg::Id parentId) {
	return false;
}

bool JSONDeserializer::doSetNodeAttributes(libvariant::Variant& group,
		rsg::Id parentId) {
	return false;
}

bool JSONDeserializer::doSetTransform(libvariant::Variant& group,
		rsg::Id parentId) {
	return false;
}

bool JSONDeserializer::doDeleteNode(libvariant::Variant& group,
		rsg::Id parentId) {
	return false;
}

bool JSONDeserializer::doAddParent(libvariant::Variant& group,
		rsg::Id parentId) {
	return false;
}

bool JSONDeserializer::doRemoveParent(libvariant::Variant& group,
		rsg::Id parentId) {
	return false;
}

} /* namespace rsg */
} /* namespace brics_3d */

/* EOF */
<|endoftext|>


<commit_before>/*
 * dwialgos.cpp
 *
 * Created on: Jun 18, 2012
 * @author Ralph Schurade
 */
#include "dwialgos.h"
#include "../data/enums.h"

#include "../data/mesh/tesselation.h"
#include "../data/datasets/dataset3d.h"
#include "../data/datasets/datasetbingham.h"
#include "../data/datasets/datasetdwi.h"
#include "../data/datasets/datasetfibers.h"
#include "../data/datasets/datasetscalar.h"
#include "../data/datasets/datasettensor.h"
#include "../data/datasets/datasetsh.h"

#include "fmath.h"
#include "track.h"
#include "qball.h"
#include "bingham.h"

#include "../thirdparty/newmat10/newmat.h"
#include "../thirdparty/newmat10/newmatap.h"

#include <QDebug>
#include <QVector>
#include <QVector3D>

DWIAlgos::DWIAlgos()
{
}

DWIAlgos::~DWIAlgos()
{
}

QList<Dataset*> DWIAlgos::qBall( Dataset* ds )
{
    qDebug() << "start calculating qBall";
    QVector<QVector3D> bvecs = dynamic_cast<DatasetDWI*>( ds )->getBvecs();

    Matrix gradients( bvecs.size(), 3 );
    for ( int i = 0; i < bvecs.size(); ++i )
    {
        gradients( i + 1, 1 ) = bvecs.at( i ).x();
        gradients( i + 1, 2 ) = bvecs.at( i ).y();
        gradients( i + 1, 3 ) = bvecs.at( i ).z();
    }

    double lambda = 0.006;
    int order = 4;
    Matrix qBallBase = QBall::calcQBallBase( gradients, lambda, order );

    QVector<ColumnVector>* data = dynamic_cast<DatasetDWI*>( ds )->getData();

    QVector<ColumnVector> qBallVector;

    for ( int i = 0; i < data->size(); ++i )
    {
        qBallVector.push_back( qBallBase * data->at( i ) );
    }

    DatasetSH* out = new DatasetSH( QDir( "Q-Ball" ), qBallVector, dynamic_cast<DatasetDWI*>( ds )->getHeader() );
    out->properties( "maingl" )->set( Fn::Property::D_NAME, "QBall" );
    out->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::QBALL );
    out->properties( "maingl" )->set( Fn::Property::D_LOD, 2 );
    out->properties( "maingl" )->set( Fn::Property::D_ORDER, order );
    out->properties( "maingl" )->set( Fn::Property::D_RENDER_SLICE, 1 );
    out->properties( "maingl" )->set( Fn::Property::D_SCALING, 1.0f );
    out->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );
    out->properties( "maingl" )->set( Fn::Property::D_MINMAX_SCALING, true );

    qDebug() << "finished calculating qBall";

    QList<Dataset*> l;
    l.push_back( out );
    return l;
}

QList<Dataset*> DWIAlgos::qBallSharp( Dataset* ds, int order )
{
    QVector<ColumnVector> qBallVector;
    QBall::sharpQBall( dynamic_cast<DatasetDWI*>( ds ), order, qBallVector );
    qDebug() << "create dataset";

    QString name = QString( "Qball_" + QString::number( order ) + "_" + ds->properties( "maingl" )->get( Fn::Property::D_NAME ).toString() );

    DatasetSH* out = new DatasetSH( QDir( name ), qBallVector, dynamic_cast<DatasetDWI*>( ds )->getHeader() );
    out->properties( "maingl" )->set( Fn::Property::D_NAME, name );
    out->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::QBALL );
    out->properties( "maingl" )->set( Fn::Property::D_LOD, 2 );
    out->properties( "maingl" )->set( Fn::Property::D_ORDER, order );
    out->properties( "maingl" )->set( Fn::Property::D_RENDER_SLICE, 1 );
    out->properties( "maingl" )->set( Fn::Property::D_SCALING, 1.0f );
    out->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );
    out->properties( "maingl" )->set( Fn::Property::D_MINMAX_SCALING, true );

    qDebug() << "finished calculating qBall";

    QList<Dataset*> l;
    l.push_back( out );
    return l;
}

QList<Dataset*> DWIAlgos::tensorFit( Dataset* ds )
{
    QVector<QVector3D> bvecs = dynamic_cast<DatasetDWI*>( ds )->getBvecs();
    QVector<float> bvals = dynamic_cast<DatasetDWI*>( ds )->getBvals();
    QVector<ColumnVector>* data = dynamic_cast<DatasetDWI*>( ds )->getData();
    QVector<float>* b0Images = dynamic_cast<DatasetDWI*>( ds )->getB0Data();

    QVector<Matrix> tensors;
    FMath::fitTensors( *data, *b0Images, bvecs, bvals, tensors );

    DatasetTensor* out = new DatasetTensor( QDir( ds->properties( "maingl" )->get( Fn::Property::D_FILENAME ).toString() ), tensors, dynamic_cast<DatasetDWI*>( ds )->getHeader() );
    out->properties( "maingl" )->set( Fn::Property::D_NAME, "Tensor" );
    out->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::TENSORFIT );
    out->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );

    QList<Dataset*> l;
    l.push_back( out );
    return l;
}

QList<Dataset*> DWIAlgos::calcFAFromDWI( Dataset* ds )
{
    QVector<QVector3D> bvecs = dynamic_cast<DatasetDWI*>( ds )->getBvecs();
    QVector<float> bvals = dynamic_cast<DatasetDWI*>( ds )->getBvals();
    QVector<ColumnVector>* data = dynamic_cast<DatasetDWI*>( ds )->getData();
    QVector<float>* b0Images = dynamic_cast<DatasetDWI*>( ds )->getB0Data();

    QVector<Matrix> tensors;
    FMath::fitTensors( *data, *b0Images, bvecs, bvals, tensors );

    QVector<float> fa;
    FMath::fa( tensors, fa );

    DatasetScalar* out = new DatasetScalar( QDir( "fa.nii.gz" ), fa, dynamic_cast<DatasetDWI*>( ds )->getHeader() );
    out->properties( "maingl" )->set( Fn::Property::D_NAME, "FA" );
    out->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::FA );
    out->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );

    QList<Dataset*> l;
    l.push_back( out );
    return l;
}

QList<Dataset*> DWIAlgos::calcEVFromDWI( Dataset* ds )
{
    QVector<QVector3D> bvecs = dynamic_cast<DatasetDWI*>( ds )->getBvecs();
    QVector<float> bvals = dynamic_cast<DatasetDWI*>( ds )->getBvals();
    QVector<ColumnVector>* data = dynamic_cast<DatasetDWI*>( ds )->getData();
    QVector<float>* b0Images = dynamic_cast<DatasetDWI*>( ds )->getB0Data();

    QVector<Matrix> tensors;
    FMath::fitTensors( *data, *b0Images, bvecs, bvals, tensors );

    int blockSize = tensors.size();

    QVector<QVector3D> evec1( blockSize );
    QVector<float> eval1( blockSize );

    QVector<QVector3D> evec2( blockSize );
    QVector<float> eval2( blockSize );

    QVector<QVector3D> evec3( blockSize );
    QVector<float> eval3( blockSize );

    FMath::evecs( tensors, evec1, eval1, evec2, eval2, evec3, eval3 );

    Dataset3D* out = new Dataset3D( QDir( "evec1.nii.gz" ), evec1, dynamic_cast<DatasetDWI*>( ds )->getHeader() );
    out->properties( "maingl" )->set( Fn::Property::D_NAME, "evec 1" );
    out->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::EV );
    out->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );

//    DatasetScalar* out2 = new DatasetScalar( QDir( "eval1.nii.gz" ), eval1, dynamic_cast<DatasetDWI*>( ds )->getHeader() );
//    out2->properties( "maingl" )->set( Fn::Property::D_NAME, "eval 1" );
//    out2->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::EV );
//    out2->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );

    QList<Dataset*> l;
    l.push_back( out );
//    l.push_back( out2 );
    return l;
}

QList<Dataset*> DWIAlgos::calcFAFromTensor( Dataset* ds )
{
    QVector<Matrix>* tensors = dynamic_cast<DatasetTensor*>( ds )->getData();

    QVector<float> fa;
    FMath::fa( *tensors, fa );

    DatasetScalar* out = new DatasetScalar( QDir( "fa.nii.gz" ), fa, dynamic_cast<DatasetTensor*>( ds )->getHeader() );
    out->properties( "maingl" )->set( Fn::Property::D_NAME, "FA" );
    out->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::FA );
    out->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );

    QList<Dataset*> l;
    l.push_back( out );
    return l;
}

QList<Dataset*> DWIAlgos::calcEVFromTensor( Dataset* ds )
{
    QVector<Matrix>* tensors = dynamic_cast<DatasetTensor*>( ds )->getData();

    int blockSize = tensors->size();

    QVector<QVector3D> evec1( blockSize );
    QVector<float> eval1( blockSize );

    QVector<QVector3D> evec2( blockSize );
    QVector<float> eval2( blockSize );

    QVector<QVector3D> evec3( blockSize );
    QVector<float> eval3( blockSize );

    FMath::evecs( *tensors, evec1, eval1, evec2, eval2, evec3, eval3 );

    Dataset3D* out = new Dataset3D( QDir( "evec1.nii.gz" ), evec1, dynamic_cast<DatasetTensor*>( ds )->getHeader() );
    out->properties( "maingl" )->set( Fn::Property::D_NAME, "evec 1" );
    out->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::EV );
    out->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );

    DatasetScalar* out2 = new DatasetScalar( QDir( "eval1.nii.gz" ), eval1, dynamic_cast<DatasetTensor*>( ds )->getHeader() );
    out2->properties( "maingl" )->set( Fn::Property::D_NAME, "eval 1" );
    out2->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::EV );
    out2->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );

    QList<Dataset*> l;
    l.push_back( out );
    l.push_back( out2 );
    return l;
}

QList<Dataset*> DWIAlgos::fitBingham( Dataset* ds )
{
    int depth = 5;
    int neighbourhood = 3;
    int n_peaks = 3;

    QList<Dataset*> l= Bingham::calc_bingham( dynamic_cast<DatasetSH*>( ds ), depth, neighbourhood, n_peaks );
    if ( l.size() > 0 )
    {
        l[0]->properties( "maingl" )->set( Fn::Property::D_NAME, "bingham" );
        l[0]->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::BINGHAM );
        l[0]->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );
        //l[0]->properties( "maingl" )->set( "active", false );
    }
    return l;
}

QList<Dataset*> DWIAlgos::tensorTrack( Dataset* ds )
{
    Track* tracker = new Track( dynamic_cast<DatasetTensor*>( ds ) );
    tracker->startTracking();

    QList<Dataset*> l;
    DatasetFibers* fibs = new DatasetFibers( QDir( "new fibers"  ), tracker->getFibs() );
    l.push_back( fibs );

    return l;
}

QList<Dataset*> DWIAlgos::bingham2DWI( Dataset* ds )
{
    QList<Dataset*> l= Bingham::bingham2Tensor( dynamic_cast<DatasetBingham*>( ds ) );
    for ( int i = 0; i < l.size(); ++i )
    {
        l[i]->properties( "maingl" )->set( Fn::Property::D_NAME, "DWI FROM BINGHAM " + QString::number( i ) );
        l[i]->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::BINGHAM_2_TENSOR );
        l[i]->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );
    }
    return l;
}
<commit_msg>evec algo now also creates a fa*rgb image<commit_after>/*
 * dwialgos.cpp
 *
 * Created on: Jun 18, 2012
 * @author Ralph Schurade
 */
#include "dwialgos.h"
#include "../data/enums.h"

#include "../data/mesh/tesselation.h"
#include "../data/datasets/dataset3d.h"
#include "../data/datasets/datasetbingham.h"
#include "../data/datasets/datasetdwi.h"
#include "../data/datasets/datasetfibers.h"
#include "../data/datasets/datasetscalar.h"
#include "../data/datasets/datasettensor.h"
#include "../data/datasets/datasetsh.h"

#include "fmath.h"
#include "track.h"
#include "qball.h"
#include "bingham.h"

#include "../thirdparty/newmat10/newmat.h"
#include "../thirdparty/newmat10/newmatap.h"

#include <QDebug>
#include <QVector>
#include <QVector3D>

DWIAlgos::DWIAlgos()
{
}

DWIAlgos::~DWIAlgos()
{
}

QList<Dataset*> DWIAlgos::qBall( Dataset* ds )
{
    qDebug() << "start calculating qBall";
    QVector<QVector3D> bvecs = dynamic_cast<DatasetDWI*>( ds )->getBvecs();

    Matrix gradients( bvecs.size(), 3 );
    for ( int i = 0; i < bvecs.size(); ++i )
    {
        gradients( i + 1, 1 ) = bvecs.at( i ).x();
        gradients( i + 1, 2 ) = bvecs.at( i ).y();
        gradients( i + 1, 3 ) = bvecs.at( i ).z();
    }

    double lambda = 0.006;
    int order = 4;
    Matrix qBallBase = QBall::calcQBallBase( gradients, lambda, order );

    QVector<ColumnVector>* data = dynamic_cast<DatasetDWI*>( ds )->getData();

    QVector<ColumnVector> qBallVector;

    for ( int i = 0; i < data->size(); ++i )
    {
        qBallVector.push_back( qBallBase * data->at( i ) );
    }

    DatasetSH* out = new DatasetSH( QDir( "Q-Ball" ), qBallVector, dynamic_cast<DatasetDWI*>( ds )->getHeader() );
    out->properties( "maingl" )->set( Fn::Property::D_NAME, "QBall" );
    out->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::QBALL );
    out->properties( "maingl" )->set( Fn::Property::D_LOD, 2 );
    out->properties( "maingl" )->set( Fn::Property::D_ORDER, order );
    out->properties( "maingl" )->set( Fn::Property::D_RENDER_SLICE, 1 );
    out->properties( "maingl" )->set( Fn::Property::D_SCALING, 1.0f );
    out->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );
    out->properties( "maingl" )->set( Fn::Property::D_MINMAX_SCALING, true );

    qDebug() << "finished calculating qBall";

    QList<Dataset*> l;
    l.push_back( out );
    return l;
}

QList<Dataset*> DWIAlgos::qBallSharp( Dataset* ds, int order )
{
    QVector<ColumnVector> qBallVector;
    QBall::sharpQBall( dynamic_cast<DatasetDWI*>( ds ), order, qBallVector );
    qDebug() << "create dataset";

    QString name = QString( "Qball_" + QString::number( order ) + "_" + ds->properties( "maingl" )->get( Fn::Property::D_NAME ).toString() );

    DatasetSH* out = new DatasetSH( QDir( name ), qBallVector, dynamic_cast<DatasetDWI*>( ds )->getHeader() );
    out->properties( "maingl" )->set( Fn::Property::D_NAME, name );
    out->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::QBALL );
    out->properties( "maingl" )->set( Fn::Property::D_LOD, 2 );
    out->properties( "maingl" )->set( Fn::Property::D_ORDER, order );
    out->properties( "maingl" )->set( Fn::Property::D_RENDER_SLICE, 1 );
    out->properties( "maingl" )->set( Fn::Property::D_SCALING, 1.0f );
    out->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );
    out->properties( "maingl" )->set( Fn::Property::D_MINMAX_SCALING, true );

    qDebug() << "finished calculating qBall";

    QList<Dataset*> l;
    l.push_back( out );
    return l;
}

QList<Dataset*> DWIAlgos::tensorFit( Dataset* ds )
{
    QVector<QVector3D> bvecs = dynamic_cast<DatasetDWI*>( ds )->getBvecs();
    QVector<float> bvals = dynamic_cast<DatasetDWI*>( ds )->getBvals();
    QVector<ColumnVector>* data = dynamic_cast<DatasetDWI*>( ds )->getData();
    QVector<float>* b0Images = dynamic_cast<DatasetDWI*>( ds )->getB0Data();

    QVector<Matrix> tensors;
    FMath::fitTensors( *data, *b0Images, bvecs, bvals, tensors );

    DatasetTensor* out = new DatasetTensor( QDir( ds->properties( "maingl" )->get( Fn::Property::D_FILENAME ).toString() ), tensors, dynamic_cast<DatasetDWI*>( ds )->getHeader() );
    out->properties( "maingl" )->set( Fn::Property::D_NAME, "Tensor" );
    out->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::TENSORFIT );
    out->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );

    QList<Dataset*> l;
    l.push_back( out );
    return l;
}

QList<Dataset*> DWIAlgos::calcFAFromDWI( Dataset* ds )
{
    QVector<QVector3D> bvecs = dynamic_cast<DatasetDWI*>( ds )->getBvecs();
    QVector<float> bvals = dynamic_cast<DatasetDWI*>( ds )->getBvals();
    QVector<ColumnVector>* data = dynamic_cast<DatasetDWI*>( ds )->getData();
    QVector<float>* b0Images = dynamic_cast<DatasetDWI*>( ds )->getB0Data();

    QVector<Matrix> tensors;
    FMath::fitTensors( *data, *b0Images, bvecs, bvals, tensors );

    QVector<float> fa;
    FMath::fa( tensors, fa );

    DatasetScalar* out = new DatasetScalar( QDir( "fa.nii.gz" ), fa, dynamic_cast<DatasetDWI*>( ds )->getHeader() );
    out->properties( "maingl" )->set( Fn::Property::D_NAME, "FA" );
    out->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::FA );
    out->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );

    QList<Dataset*> l;
    l.push_back( out );
    return l;
}

QList<Dataset*> DWIAlgos::calcEVFromDWI( Dataset* ds )
{
    QVector<QVector3D> bvecs = dynamic_cast<DatasetDWI*>( ds )->getBvecs();
    QVector<float> bvals = dynamic_cast<DatasetDWI*>( ds )->getBvals();
    QVector<ColumnVector>* data = dynamic_cast<DatasetDWI*>( ds )->getData();
    QVector<float>* b0Images = dynamic_cast<DatasetDWI*>( ds )->getB0Data();

    QVector<Matrix> tensors;
    FMath::fitTensors( *data, *b0Images, bvecs, bvals, tensors );

    int blockSize = tensors.size();

    QVector<QVector3D> evec1( blockSize );
    QVector<float> eval1( blockSize );

    QVector<QVector3D> evec2( blockSize );
    QVector<float> eval2( blockSize );

    QVector<QVector3D> evec3( blockSize );
    QVector<float> eval3( blockSize );

    FMath::evecs( tensors, evec1, eval1, evec2, eval2, evec3, eval3 );

    QVector<float> fa;
    FMath::fa( tensors, fa );

    for ( int i = 0; i < evec1.size(); ++i )
    {
        evec2[i] = evec1[i] * fa[i] * 1.5;
    }

    QList<Dataset*> l;

    Dataset3D* out = new Dataset3D( QDir( "evec1.nii.gz" ), evec1, dynamic_cast<DatasetDWI*>( ds )->getHeader() );
    out->properties( "maingl" )->set( Fn::Property::D_NAME, "evec 1" );
    out->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::EV );
    out->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );
    l.push_back( out );

    Dataset3D* out2 = new Dataset3D( QDir( "fa_rgb.nii.gz" ), evec2, dynamic_cast<DatasetDWI*>( ds )->getHeader() );
    out2->properties( "maingl" )->set( Fn::Property::D_NAME, "fa rgb" );
    out2->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::EV );
    out2->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );
    l.push_back( out2 );

    return l;
}

QList<Dataset*> DWIAlgos::calcFAFromTensor( Dataset* ds )
{
    QVector<Matrix>* tensors = dynamic_cast<DatasetTensor*>( ds )->getData();

    QVector<float> fa;
    FMath::fa( *tensors, fa );

    DatasetScalar* out = new DatasetScalar( QDir( "fa.nii.gz" ), fa, dynamic_cast<DatasetTensor*>( ds )->getHeader() );
    out->properties( "maingl" )->set( Fn::Property::D_NAME, "FA" );
    out->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::FA );
    out->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );

    QList<Dataset*> l;
    l.push_back( out );
    return l;
}

QList<Dataset*> DWIAlgos::calcEVFromTensor( Dataset* ds )
{
    QVector<Matrix>* tensors = dynamic_cast<DatasetTensor*>( ds )->getData();

    int blockSize = tensors->size();

    QVector<QVector3D> evec1( blockSize );
    QVector<float> eval1( blockSize );

    QVector<QVector3D> evec2( blockSize );
    QVector<float> eval2( blockSize );

    QVector<QVector3D> evec3( blockSize );
    QVector<float> eval3( blockSize );

    FMath::evecs( *tensors, evec1, eval1, evec2, eval2, evec3, eval3 );

    QVector<float> fa;
    FMath::fa( *tensors, fa );

    for ( int i = 0; i < evec1.size(); ++i )
    {
        evec2[i] = evec1[i] * fa[i] * 1.5;
    }

    QList<Dataset*> l;

    Dataset3D* out = new Dataset3D( QDir( "evec1.nii.gz" ), evec1, dynamic_cast<DatasetTensor*>( ds )->getHeader() );
    out->properties( "maingl" )->set( Fn::Property::D_NAME, "evec 1" );
    out->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::EV );
    out->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );
    l.push_back( out );

    Dataset3D* out2 = new Dataset3D( QDir( "fa_rgb.nii.gz" ), evec2, dynamic_cast<DatasetTensor*>( ds )->getHeader() );
    out2->properties( "maingl" )->set( Fn::Property::D_NAME, "fa rgb" );
    out2->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::EV );
    out2->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );
    l.push_back( out2 );

    return l;
}

QList<Dataset*> DWIAlgos::fitBingham( Dataset* ds )
{
    int depth = 5;
    int neighbourhood = 3;
    int n_peaks = 3;

    QList<Dataset*> l= Bingham::calc_bingham( dynamic_cast<DatasetSH*>( ds ), depth, neighbourhood, n_peaks );
    if ( l.size() > 0 )
    {
        l[0]->properties( "maingl" )->set( Fn::Property::D_NAME, "bingham" );
        l[0]->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::BINGHAM );
        l[0]->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );
        //l[0]->properties( "maingl" )->set( "active", false );
    }
    return l;
}

QList<Dataset*> DWIAlgos::tensorTrack( Dataset* ds )
{
    Track* tracker = new Track( dynamic_cast<DatasetTensor*>( ds ) );
    tracker->startTracking();

    QList<Dataset*> l;
    DatasetFibers* fibs = new DatasetFibers( QDir( "new fibers"  ), tracker->getFibs() );
    l.push_back( fibs );

    return l;
}

QList<Dataset*> DWIAlgos::bingham2DWI( Dataset* ds )
{
    QList<Dataset*> l= Bingham::bingham2Tensor( dynamic_cast<DatasetBingham*>( ds ) );
    for ( int i = 0; i < l.size(); ++i )
    {
        l[i]->properties( "maingl" )->set( Fn::Property::D_NAME, "DWI FROM BINGHAM " + QString::number( i ) );
        l[i]->properties( "maingl" )->set( Fn::Property::D_CREATED_BY, (int)Fn::Algo::BINGHAM_2_TENSOR );
        l[i]->properties( "maingl" )->set( Fn::Property::D_DATATYPE, DT_FLOAT );
    }
    return l;
}
<|endoftext|>