<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_i18npool.hxx"

#include <math.h>
#include <stdio.h>

#include "calendar_jewish.hxx"

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::i18n;
using namespace ::rtl;

#define ERROR RuntimeException()

// not used
//static UErrorCode status; // status is shared in all calls to Calendar, it has to be reset for each call.

Calendar_jewish::Calendar_jewish()
{
    cCalendar = "com.sun.star.i18n.Calendar_jewish";
}

// The following C++ code is translated from the Lisp code in
// ``Calendrical Calculations'' by Nachum Dershowitz and Edward M. Reingold,
// Software---Practice & Experience, vol. 20, no. 9 (September, 1990),
// pp. 899--928.

// This code is in the public domain, but any use of it
// should acknowledge its source.
// http://www.ntu.edu.sg/home/ayxyan/date1.txt

// Hebrew dates

const int HebrewEpoch = -1373429; // Absolute date of start of Hebrew calendar

// True if year is an Hebrew leap year
sal_Bool HebrewLeapYear(sal_Int32 year) {
    return ((((7 * year) + 1) % 19) < 7);
}

// Last month of Hebrew year.
sal_Int32 LastMonthOfHebrewYear(sal_Int32 year) {
    return  (HebrewLeapYear(year)) ? 13 : 12;
}

// Number of days elapsed from the Sunday prior to the start of the
// Hebrew calendar to the mean conjunction of Tishri of Hebrew year.
sal_Int32 HebrewCalendarElapsedDays(sal_Int32 year) {
    sal_Int32 MonthsElapsed =
        (235 * ((year - 1) / 19))           // Months in complete cycles so far.
        + (12 * ((year - 1) % 19))          // Regular months in this cycle.
        + (7 * ((year - 1) % 19) + 1) / 19; // Leap months this cycle
    sal_Int32 PartsElapsed = 204 + 793 * (MonthsElapsed % 1080);
    int HoursElapsed =
        5 + 12 * MonthsElapsed + 793 * (MonthsElapsed  / 1080)
        + PartsElapsed / 1080;
    sal_Int32 ConjunctionDay = 1 + 29 * MonthsElapsed + HoursElapsed / 24;
    sal_Int32 ConjunctionParts = 1080 * (HoursElapsed % 24) + PartsElapsed % 1080;
    sal_Int32 AlternativeDay;

    if ((ConjunctionParts >= 19440)        // If new moon is at or after midday,
          || (((ConjunctionDay % 7) == 2)    // ...or is on a Tuesday...
          && (ConjunctionParts >= 9924)  // at 9 hours, 204 parts or later...
          && !(HebrewLeapYear(year)))   // ...of a common year,
          || (((ConjunctionDay % 7) == 1)    // ...or is on a Monday at...
          && (ConjunctionParts >= 16789) // 15 hours, 589 parts or later...
          && (HebrewLeapYear(year - 1))))// at the end of a leap year
        // Then postpone Rosh HaShanah one day
        AlternativeDay = ConjunctionDay + 1;
    else
        AlternativeDay = ConjunctionDay;

    if (((AlternativeDay % 7) == 0)// If Rosh HaShanah would occur on Sunday,
          || ((AlternativeDay % 7) == 3)     // or Wednesday,
          || ((AlternativeDay % 7) == 5))    // or Friday
        // Then postpone it one (more) day
        return (1+ AlternativeDay);
    else
        return AlternativeDay;
}

// Number of days in Hebrew year.
sal_Int32 DaysInHebrewYear(sal_Int32 year) {
    return ((HebrewCalendarElapsedDays(year + 1)) -
          (HebrewCalendarElapsedDays(year)));
}

// True if Heshvan is long in Hebrew year.
sal_Bool LongHeshvan(sal_Int32 year) {
    return ((DaysInHebrewYear(year) % 10) == 5);
}

// True if Kislev is short in Hebrew year.
sal_Bool ShortKislev(sal_Int32 year) {
    return ((DaysInHebrewYear(year) % 10) == 3);
}

// Last day of month in Hebrew year.
sal_Int32 LastDayOfHebrewMonth(sal_Int32 month, sal_Int32 year) {
    if ((month == 2)
        || (month == 4)
        || (month == 6)
        || ((month == 8) && !(LongHeshvan(year)))
        || ((month == 9) && ShortKislev(year))
        || (month == 10)
        || ((month == 12) && !(HebrewLeapYear(year)))
        || (month == 13))
        return 29;
    else
        return 30;
}

class HebrewDate {
private:
    sal_Int32 year;   // 1...
    sal_Int32 month;  // 1..LastMonthOfHebrewYear(year)
    sal_Int32 day;    // 1..LastDayOfHebrewMonth(month, year)

public:
    HebrewDate(sal_Int32 m, sal_Int32 d, sal_Int32 y) { month = m; day = d; year = y; }

    HebrewDate(sal_Int32 d) { // Computes the Hebrew date from the absolute date.
    year = (d + HebrewEpoch) / 366; // Approximation from below.
    // Search forward for year from the approximation.
    while (d >= HebrewDate(7,1,year + 1))
      year++;
    // Search forward for month from either Tishri or Nisan.
    if (d < HebrewDate(1, 1, year))
      month = 7;  //  Start at Tishri
    else
      month = 1;  //  Start at Nisan
    while (d > HebrewDate(month, (LastDayOfHebrewMonth(month,year)), year))
      month++;
    // Calculate the day by subtraction.
    day = d - HebrewDate(month, 1, year) + 1;
    }

    operator int() { // Computes the absolute date of Hebrew date.
    sal_Int32 DayInYear = day; // Days so far this month.
    if (month < 7) { // Before Tishri, so add days in prior months
             // this year before and after Nisan.
      sal_Int32 m = 7;
      while (m <= (LastMonthOfHebrewYear(year))) {
        DayInYear = DayInYear + LastDayOfHebrewMonth(m, year);
        m++;
      };
      m = 1;
      while (m < month) {
        DayInYear = DayInYear + LastDayOfHebrewMonth(m, year);
        m++;
      }
    }
    else { // Add days in prior months this year
      sal_Int32 m = 7;
      while (m < month) {
        DayInYear = DayInYear + LastDayOfHebrewMonth(m, year);
        m++;
      }
    }
    return (DayInYear +
        (HebrewCalendarElapsedDays(year)// Days in prior years.
         + HebrewEpoch));         // Days elapsed before absolute date 1.
    }

    sal_Int32 GetMonth() { return month; }
    sal_Int32 GetDay() { return day; }
    sal_Int32 GetYear() { return year; }

};

//  Gregorian dates

int LastDayOfGregorianMonth(int month, int year) {
// Compute the last date of the month for the Gregorian calendar.

    switch (month) {
    case 2:
    if ((((year % 4) == 0) && ((year % 100) != 0))
        || ((year % 400) == 0))
      return 29;
    else
      return 28;
    case 4:
    case 6:
    case 9:
    case 11: return 30;
    default: return 31;
    }
}

class GregorianDate {
private:
    int year;   // 1...
    int month;  // 1 == January, ..., 12 == December
    int day;    // 1..LastDayOfGregorianMonth(month, year)

public:
    GregorianDate(int m, int d, int y) { month = m; day = d; year = y; }

    GregorianDate(int d) { // Computes the Gregorian date from the absolute date.
        // Search forward year by year from approximate year
        year = d/366;
        while (d >= GregorianDate(1,1,year+1))
          year++;
        // Search forward month by month from January
        month = 1;
        while (d > GregorianDate(month, LastDayOfGregorianMonth(month,year), year))
          month++;
        day = d - GregorianDate(month,1,year) + 1;
    }

    operator int() { // Computes the absolute date from the Gregorian date.
        int N = day;           // days this month
        for (int m = month - 1;  m > 0; m--) // days in prior months this year
          N = N + LastDayOfGregorianMonth(m, year);
        return
          (N                    // days this year
           + 365 * (year - 1)   // days in previous years ignoring leap days
           + (year - 1)/4       // Julian leap days before this year...
           - (year - 1)/100     // ...minus prior century years...
           + (year - 1)/400);   // ...plus prior years divisible by 400
    }

    int GetMonth() { return month; }
    int GetDay() { return day; }
    int GetYear() { return year; }

};

// map field value from gregorian calendar to other calendar, it can be overwritten by derived class.
void Calendar_jewish::mapFromGregorian() throw(RuntimeException)
{
    int y = fieldValue[CalendarFieldIndex::YEAR];
    if (fieldValue[CalendarFieldIndex::ERA] == 0)
        y = 1 - y;
    GregorianDate Temp(fieldValue[CalendarFieldIndex::MONTH] + 1, fieldValue[CalendarFieldIndex::DAY_OF_MONTH], y);
    HebrewDate hd(Temp);

    fieldValue[CalendarFieldIndex::ERA] = hd.GetYear() <= 0 ? 0 : 1;
    fieldValue[CalendarFieldIndex::MONTH] = sal::static_int_cast<sal_Int16>( hd.GetMonth() - 1 );
    fieldValue[CalendarFieldIndex::DAY_OF_MONTH] = (sal_Int16)hd.GetDay();
    fieldValue[CalendarFieldIndex::YEAR] = (sal_Int16)(hd.GetYear() <= 0 ? 1 - hd.GetYear() : hd.GetYear());
}

#define FIELDS  ((1 << CalendarFieldIndex::ERA) | (1 << CalendarFieldIndex::YEAR) | (1 << CalendarFieldIndex::MONTH) | (1 << CalendarFieldIndex::DAY_OF_MONTH))
// map field value from other calendar to gregorian calendar, it should be implemented.
void Calendar_jewish::mapToGregorian() throw(RuntimeException)
{
    if (fieldSet & FIELDS) {
        sal_Int16 y = fieldSetValue[CalendarFieldIndex::YEAR];
        if (fieldSetValue[CalendarFieldIndex::ERA] == 0)
        y = 1 - y;
        HebrewDate Temp(fieldSetValue[CalendarFieldIndex::MONTH] + 1, fieldSetValue[CalendarFieldIndex::DAY_OF_MONTH], y);
        GregorianDate gd(Temp);

        fieldSetValue[CalendarFieldIndex::ERA] = gd.GetYear() <= 0 ? 0 : 1;
        fieldSetValue[CalendarFieldIndex::MONTH] = sal::static_int_cast<sal_Int16>( gd.GetMonth() - 1 );
        fieldSetValue[CalendarFieldIndex::DAY_OF_MONTH] = (sal_Int16)gd.GetDay();
        fieldSetValue[CalendarFieldIndex::YEAR] = (sal_Int16)(gd.GetYear() <= 0 ? 1 - gd.GetYear() : gd.GetYear());
        fieldSet |= FIELDS;
    }
}

// Methods in XExtendedCalendar
OUString SAL_CALL
Calendar_jewish::getDisplayString( sal_Int32 nCalendarDisplayCode, sal_Int16 nNativeNumberMode )
    throw (RuntimeException)
{
    nNativeNumberMode = NativeNumberMode::NATNUM2;  // make Hebrew number for Jewish calendar

    if (nCalendarDisplayCode == CalendarDisplayCode::SHORT_YEAR) {
        sal_Int32 value = getValue(CalendarFieldIndex::YEAR) % 1000; // take last 3 digits
        return aNatNum.getNativeNumberString(OUString::valueOf(value), aLocale, nNativeNumberMode );
    }
    else
        return Calendar_gregorian::getDisplayString(nCalendarDisplayCode, nNativeNumberMode );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>cppcheck: methods can be const<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_i18npool.hxx"

#include <math.h>
#include <stdio.h>

#include "calendar_jewish.hxx"

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::i18n;
using namespace ::rtl;

#define ERROR RuntimeException()

// not used
//static UErrorCode status; // status is shared in all calls to Calendar, it has to be reset for each call.

Calendar_jewish::Calendar_jewish()
{
    cCalendar = "com.sun.star.i18n.Calendar_jewish";
}

// The following C++ code is translated from the Lisp code in
// ``Calendrical Calculations'' by Nachum Dershowitz and Edward M. Reingold,
// Software---Practice & Experience, vol. 20, no. 9 (September, 1990),
// pp. 899--928.

// This code is in the public domain, but any use of it
// should acknowledge its source.
// http://www.ntu.edu.sg/home/ayxyan/date1.txt

// Hebrew dates

const int HebrewEpoch = -1373429; // Absolute date of start of Hebrew calendar

// True if year is an Hebrew leap year
sal_Bool HebrewLeapYear(sal_Int32 year) {
    return ((((7 * year) + 1) % 19) < 7);
}

// Last month of Hebrew year.
sal_Int32 LastMonthOfHebrewYear(sal_Int32 year) {
    return  (HebrewLeapYear(year)) ? 13 : 12;
}

// Number of days elapsed from the Sunday prior to the start of the
// Hebrew calendar to the mean conjunction of Tishri of Hebrew year.
sal_Int32 HebrewCalendarElapsedDays(sal_Int32 year) {
    sal_Int32 MonthsElapsed =
        (235 * ((year - 1) / 19))           // Months in complete cycles so far.
        + (12 * ((year - 1) % 19))          // Regular months in this cycle.
        + (7 * ((year - 1) % 19) + 1) / 19; // Leap months this cycle
    sal_Int32 PartsElapsed = 204 + 793 * (MonthsElapsed % 1080);
    int HoursElapsed =
        5 + 12 * MonthsElapsed + 793 * (MonthsElapsed  / 1080)
        + PartsElapsed / 1080;
    sal_Int32 ConjunctionDay = 1 + 29 * MonthsElapsed + HoursElapsed / 24;
    sal_Int32 ConjunctionParts = 1080 * (HoursElapsed % 24) + PartsElapsed % 1080;
    sal_Int32 AlternativeDay;

    if ((ConjunctionParts >= 19440)        // If new moon is at or after midday,
          || (((ConjunctionDay % 7) == 2)    // ...or is on a Tuesday...
          && (ConjunctionParts >= 9924)  // at 9 hours, 204 parts or later...
          && !(HebrewLeapYear(year)))   // ...of a common year,
          || (((ConjunctionDay % 7) == 1)    // ...or is on a Monday at...
          && (ConjunctionParts >= 16789) // 15 hours, 589 parts or later...
          && (HebrewLeapYear(year - 1))))// at the end of a leap year
        // Then postpone Rosh HaShanah one day
        AlternativeDay = ConjunctionDay + 1;
    else
        AlternativeDay = ConjunctionDay;

    if (((AlternativeDay % 7) == 0)// If Rosh HaShanah would occur on Sunday,
          || ((AlternativeDay % 7) == 3)     // or Wednesday,
          || ((AlternativeDay % 7) == 5))    // or Friday
        // Then postpone it one (more) day
        return (1+ AlternativeDay);
    else
        return AlternativeDay;
}

// Number of days in Hebrew year.
sal_Int32 DaysInHebrewYear(sal_Int32 year) {
    return ((HebrewCalendarElapsedDays(year + 1)) -
          (HebrewCalendarElapsedDays(year)));
}

// True if Heshvan is long in Hebrew year.
sal_Bool LongHeshvan(sal_Int32 year) {
    return ((DaysInHebrewYear(year) % 10) == 5);
}

// True if Kislev is short in Hebrew year.
sal_Bool ShortKislev(sal_Int32 year) {
    return ((DaysInHebrewYear(year) % 10) == 3);
}

// Last day of month in Hebrew year.
sal_Int32 LastDayOfHebrewMonth(sal_Int32 month, sal_Int32 year) {
    if ((month == 2)
        || (month == 4)
        || (month == 6)
        || ((month == 8) && !(LongHeshvan(year)))
        || ((month == 9) && ShortKislev(year))
        || (month == 10)
        || ((month == 12) && !(HebrewLeapYear(year)))
        || (month == 13))
        return 29;
    else
        return 30;
}

class HebrewDate {
private:
    sal_Int32 year;   // 1...
    sal_Int32 month;  // 1..LastMonthOfHebrewYear(year)
    sal_Int32 day;    // 1..LastDayOfHebrewMonth(month, year)

public:
    HebrewDate(sal_Int32 m, sal_Int32 d, sal_Int32 y) { month = m; day = d; year = y; }

    HebrewDate(sal_Int32 d) { // Computes the Hebrew date from the absolute date.
    year = (d + HebrewEpoch) / 366; // Approximation from below.
    // Search forward for year from the approximation.
    while (d >= HebrewDate(7,1,year + 1))
      year++;
    // Search forward for month from either Tishri or Nisan.
    if (d < HebrewDate(1, 1, year))
      month = 7;  //  Start at Tishri
    else
      month = 1;  //  Start at Nisan
    while (d > HebrewDate(month, (LastDayOfHebrewMonth(month,year)), year))
      month++;
    // Calculate the day by subtraction.
    day = d - HebrewDate(month, 1, year) + 1;
    }

    operator int() { // Computes the absolute date of Hebrew date.
    sal_Int32 DayInYear = day; // Days so far this month.
    if (month < 7) { // Before Tishri, so add days in prior months
             // this year before and after Nisan.
      sal_Int32 m = 7;
      while (m <= (LastMonthOfHebrewYear(year))) {
        DayInYear = DayInYear + LastDayOfHebrewMonth(m, year);
        m++;
      };
      m = 1;
      while (m < month) {
        DayInYear = DayInYear + LastDayOfHebrewMonth(m, year);
        m++;
      }
    }
    else { // Add days in prior months this year
      sal_Int32 m = 7;
      while (m < month) {
        DayInYear = DayInYear + LastDayOfHebrewMonth(m, year);
        m++;
      }
    }
    return (DayInYear +
        (HebrewCalendarElapsedDays(year)// Days in prior years.
         + HebrewEpoch));         // Days elapsed before absolute date 1.
    }

    sal_Int32 GetMonth() const { return month; }
    sal_Int32 GetDay() const { return day; }
    sal_Int32 GetYear() const { return year; }

};

//  Gregorian dates

int LastDayOfGregorianMonth(int month, int year) {
// Compute the last date of the month for the Gregorian calendar.

    switch (month) {
    case 2:
    if ((((year % 4) == 0) && ((year % 100) != 0))
        || ((year % 400) == 0))
      return 29;
    else
      return 28;
    case 4:
    case 6:
    case 9:
    case 11: return 30;
    default: return 31;
    }
}

class GregorianDate {
private:
    int year;   // 1...
    int month;  // 1 == January, ..., 12 == December
    int day;    // 1..LastDayOfGregorianMonth(month, year)

public:
    GregorianDate(int m, int d, int y) { month = m; day = d; year = y; }

    GregorianDate(int d) { // Computes the Gregorian date from the absolute date.
        // Search forward year by year from approximate year
        year = d/366;
        while (d >= GregorianDate(1,1,year+1))
          year++;
        // Search forward month by month from January
        month = 1;
        while (d > GregorianDate(month, LastDayOfGregorianMonth(month,year), year))
          month++;
        day = d - GregorianDate(month,1,year) + 1;
    }

    operator int() { // Computes the absolute date from the Gregorian date.
        int N = day;           // days this month
        for (int m = month - 1;  m > 0; m--) // days in prior months this year
          N = N + LastDayOfGregorianMonth(m, year);
        return
          (N                    // days this year
           + 365 * (year - 1)   // days in previous years ignoring leap days
           + (year - 1)/4       // Julian leap days before this year...
           - (year - 1)/100     // ...minus prior century years...
           + (year - 1)/400);   // ...plus prior years divisible by 400
    }

    int GetMonth() const { return month; }
    int GetDay() const { return day; }
    int GetYear() const { return year; }

};

// map field value from gregorian calendar to other calendar, it can be overwritten by derived class.
void Calendar_jewish::mapFromGregorian() throw(RuntimeException)
{
    int y = fieldValue[CalendarFieldIndex::YEAR];
    if (fieldValue[CalendarFieldIndex::ERA] == 0)
        y = 1 - y;
    GregorianDate Temp(fieldValue[CalendarFieldIndex::MONTH] + 1, fieldValue[CalendarFieldIndex::DAY_OF_MONTH], y);
    HebrewDate hd(Temp);

    fieldValue[CalendarFieldIndex::ERA] = hd.GetYear() <= 0 ? 0 : 1;
    fieldValue[CalendarFieldIndex::MONTH] = sal::static_int_cast<sal_Int16>( hd.GetMonth() - 1 );
    fieldValue[CalendarFieldIndex::DAY_OF_MONTH] = (sal_Int16)hd.GetDay();
    fieldValue[CalendarFieldIndex::YEAR] = (sal_Int16)(hd.GetYear() <= 0 ? 1 - hd.GetYear() : hd.GetYear());
}

#define FIELDS  ((1 << CalendarFieldIndex::ERA) | (1 << CalendarFieldIndex::YEAR) | (1 << CalendarFieldIndex::MONTH) | (1 << CalendarFieldIndex::DAY_OF_MONTH))
// map field value from other calendar to gregorian calendar, it should be implemented.
void Calendar_jewish::mapToGregorian() throw(RuntimeException)
{
    if (fieldSet & FIELDS) {
        sal_Int16 y = fieldSetValue[CalendarFieldIndex::YEAR];
        if (fieldSetValue[CalendarFieldIndex::ERA] == 0)
        y = 1 - y;
        HebrewDate Temp(fieldSetValue[CalendarFieldIndex::MONTH] + 1, fieldSetValue[CalendarFieldIndex::DAY_OF_MONTH], y);
        GregorianDate gd(Temp);

        fieldSetValue[CalendarFieldIndex::ERA] = gd.GetYear() <= 0 ? 0 : 1;
        fieldSetValue[CalendarFieldIndex::MONTH] = sal::static_int_cast<sal_Int16>( gd.GetMonth() - 1 );
        fieldSetValue[CalendarFieldIndex::DAY_OF_MONTH] = (sal_Int16)gd.GetDay();
        fieldSetValue[CalendarFieldIndex::YEAR] = (sal_Int16)(gd.GetYear() <= 0 ? 1 - gd.GetYear() : gd.GetYear());
        fieldSet |= FIELDS;
    }
}

// Methods in XExtendedCalendar
OUString SAL_CALL
Calendar_jewish::getDisplayString( sal_Int32 nCalendarDisplayCode, sal_Int16 nNativeNumberMode )
    throw (RuntimeException)
{
    nNativeNumberMode = NativeNumberMode::NATNUM2;  // make Hebrew number for Jewish calendar

    if (nCalendarDisplayCode == CalendarDisplayCode::SHORT_YEAR) {
        sal_Int32 value = getValue(CalendarFieldIndex::YEAR) % 1000; // take last 3 digits
        return aNatNum.getNativeNumberString(OUString::valueOf(value), aLocale, nNativeNumberMode );
    }
    else
        return Calendar_gregorian::getDisplayString(nCalendarDisplayCode, nNativeNumberMode );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include "ideutils.h"

#include <QDir>
#include <QFileInfo>
#include <QCheckBox>
#include <QLineEdit>
#include <QSpinBox>
#include <QDoubleSpinBox>
#include <QComboBox>
#include <QGroupBox>
#include <QTableWidget>
#include <QPlainTextEdit>

namespace IDEUtils {

QString formatTime(qint64 time) {
    int hours =  time / 3600000;
    int minutes = (time % 3600000) / 60000;
    int seconds = (time % 60000) / 1000;
    int msec = (time % 1000);
    QString elapsed;
    if (hours > 0) {
        elapsed += QString("%1h ").arg(hours);
    }
    if (hours > 0 || minutes > 0) {
        elapsed += QString("%1m ").arg(minutes);
    }
    if (hours > 0 || minutes > 0 || seconds > 0) {
        elapsed += QString("%1s").arg(seconds);
    }
    if (hours==0 && minutes==0) {
        if (seconds > 0) {
            elapsed += " ";
        }
        elapsed += QString("%1msec").arg(msec);
    }
    return elapsed;
}

bool isChildPath(const QString& parent, const QString& child)
{
    return !QDir(parent).relativeFilePath(child).startsWith(".");
}

void watchChildChanges(QWidget* target, QObject* receiver, std::function<void()> action)
{
    for (auto widget : target->findChildren<QWidget*>()) {
        QCheckBox* checkBox;
        QLineEdit* lineEdit;
        QSpinBox* spinBox;
        QDoubleSpinBox* doubleSpinBox;
        QComboBox* comboBox;
        QGroupBox* groupBox;
        QTableWidget* tableWidget;
        QPlainTextEdit* plainTextEdit;

        if ((checkBox = qobject_cast<QCheckBox*>(widget))) {
            QObject::connect(checkBox, &QCheckBox::stateChanged, receiver, [=] (int) { action(); });
        } else if ((lineEdit = qobject_cast<QLineEdit*>(widget))) {
            QObject::connect(lineEdit, &QLineEdit::textChanged, receiver, [=] (const QString&) { action(); });
        } else if ((spinBox = qobject_cast<QSpinBox*>(widget))) {
            QObject::connect(spinBox, QOverload<int>::of(&QSpinBox::valueChanged), receiver, [=] (int) { action(); });
        } else if ((doubleSpinBox = qobject_cast<QDoubleSpinBox*>(widget))) {
            QObject::connect(doubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), receiver, [=] (double) { action(); });
        } else if ((comboBox = qobject_cast<QComboBox*>(widget))) {
            QObject::connect(comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), receiver, [=] (int) { action(); });
        } else if ((groupBox = qobject_cast<QGroupBox*>(widget))) {
            QObject::connect(groupBox, &QGroupBox::toggled, receiver, [=] (bool) { action(); });
        } else if ((tableWidget = qobject_cast<QTableWidget*>(widget))) {
            QObject::connect(tableWidget, &QTableWidget::cellChanged, receiver, [=] (int, int) { action(); });
        } else if ((plainTextEdit = qobject_cast<QPlainTextEdit*>(widget))) {
            QObject::connect(plainTextEdit, &QPlainTextEdit::textChanged,receiver, [=] () { action(); });
        }
    }
}

QFont fontFromString(const QString& s)
{
    QStringList families({"Menlo", "Consolas", "Courier New"});

    QFont font;
    font.setPointSize(13);
    font.setStyleHint(QFont::TypeWriter);
    for (auto& family : families) {
        font.setFamily(family);
        if (font.exactMatch()) {
            break;
        }
    }
    font.fromString(s);
    return font;
}

}
<commit_msg>Fix loading of default fonts<commit_after>#include "ideutils.h"

#include <QDir>
#include <QFileInfo>
#include <QCheckBox>
#include <QLineEdit>
#include <QSpinBox>
#include <QDoubleSpinBox>
#include <QComboBox>
#include <QGroupBox>
#include <QTableWidget>
#include <QPlainTextEdit>

namespace IDEUtils {

QString formatTime(qint64 time) {
    int hours =  time / 3600000;
    int minutes = (time % 3600000) / 60000;
    int seconds = (time % 60000) / 1000;
    int msec = (time % 1000);
    QString elapsed;
    if (hours > 0) {
        elapsed += QString("%1h ").arg(hours);
    }
    if (hours > 0 || minutes > 0) {
        elapsed += QString("%1m ").arg(minutes);
    }
    if (hours > 0 || minutes > 0 || seconds > 0) {
        elapsed += QString("%1s").arg(seconds);
    }
    if (hours==0 && minutes==0) {
        if (seconds > 0) {
            elapsed += " ";
        }
        elapsed += QString("%1msec").arg(msec);
    }
    return elapsed;
}

bool isChildPath(const QString& parent, const QString& child)
{
    return !QDir(parent).relativeFilePath(child).startsWith(".");
}

void watchChildChanges(QWidget* target, QObject* receiver, std::function<void()> action)
{
    for (auto widget : target->findChildren<QWidget*>()) {
        QCheckBox* checkBox;
        QLineEdit* lineEdit;
        QSpinBox* spinBox;
        QDoubleSpinBox* doubleSpinBox;
        QComboBox* comboBox;
        QGroupBox* groupBox;
        QTableWidget* tableWidget;
        QPlainTextEdit* plainTextEdit;

        if ((checkBox = qobject_cast<QCheckBox*>(widget))) {
            QObject::connect(checkBox, &QCheckBox::stateChanged, receiver, [=] (int) { action(); });
        } else if ((lineEdit = qobject_cast<QLineEdit*>(widget))) {
            QObject::connect(lineEdit, &QLineEdit::textChanged, receiver, [=] (const QString&) { action(); });
        } else if ((spinBox = qobject_cast<QSpinBox*>(widget))) {
            QObject::connect(spinBox, QOverload<int>::of(&QSpinBox::valueChanged), receiver, [=] (int) { action(); });
        } else if ((doubleSpinBox = qobject_cast<QDoubleSpinBox*>(widget))) {
            QObject::connect(doubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), receiver, [=] (double) { action(); });
        } else if ((comboBox = qobject_cast<QComboBox*>(widget))) {
            QObject::connect(comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), receiver, [=] (int) { action(); });
        } else if ((groupBox = qobject_cast<QGroupBox*>(widget))) {
            QObject::connect(groupBox, &QGroupBox::toggled, receiver, [=] (bool) { action(); });
        } else if ((tableWidget = qobject_cast<QTableWidget*>(widget))) {
            QObject::connect(tableWidget, &QTableWidget::cellChanged, receiver, [=] (int, int) { action(); });
        } else if ((plainTextEdit = qobject_cast<QPlainTextEdit*>(widget))) {
            QObject::connect(plainTextEdit, &QPlainTextEdit::textChanged,receiver, [=] () { action(); });
        }
    }
}

QFont fontFromString(const QString& s)
{
    QFont font;
    if (font.fromString(s)) {
        return font;
    }

    QStringList families({"Menlo", "Consolas", "Courier New"});

    font.setPointSize(13);
    font.setStyleHint(QFont::TypeWriter);
    for (auto& family : families) {
        font.setFamily(family);
        if (font.exactMatch()) {
            break;
        }
    }
    return font;
}

}
<|endoftext|>


<commit_before>#include <sys/stat.h>
#include "storing.hh"
#include "StoreTarget.h"
#include "../Util2.h"
#include "../InputFileStream.h"

namespace Moses2
{

BinaryFileWriter::BinaryFileWriter (std::string basepath) : os ((basepath + "/binfile.dat").c_str(), std::ios::binary)
{
  binfile.reserve(10000); //Reserve part of the vector to avoid realocation
  it = binfile.begin();
  dist_from_start = 0; //Initialize variables
  extra_counter = 0;
}

void BinaryFileWriter::write (std::vector<unsigned char> * bytes)
{
  binfile.insert(it, bytes->begin(), bytes->end()); //Insert the bytes
  //Keep track of the offsets
  it += bytes->size();
  dist_from_start = distance(binfile.begin(),it);
  //Flush the vector to disk every once in a while so that we don't consume too much ram
  if (dist_from_start > 9000) {
    flush();
  }
}

void BinaryFileWriter::flush ()
{
  //Cast unsigned char to char before writing...
  os.write((char *)&binfile[0], dist_from_start);
  //Clear the vector:
  binfile.clear();
  binfile.reserve(10000);
  extra_counter += dist_from_start; //Keep track of the total number of bytes.
  it = binfile.begin(); //Reset iterator
  dist_from_start = distance(binfile.begin(),it); //Reset dist from start
}

BinaryFileWriter::~BinaryFileWriter ()
{
  os.close();
  binfile.clear();
}

void createProbingPT(
		const std::string &phrasetable_path,
		const std::string &basepath,
        int num_scores,
		int num_lex_scores,
		bool log_prob,
		int max_cache_size)
{
  std::cerr << "Starting..." << std::endl;

  //Get basepath and create directory if missing
  mkdir(basepath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

  //Set up huffman and serialize decoder maps.
  Huffman huffmanEncoder(phrasetable_path.c_str()); //initialize
  huffmanEncoder.assign_values();
  huffmanEncoder.produce_lookups();
  huffmanEncoder.serialize_maps(basepath.c_str());

  StoreTarget storeTarget(basepath);

  //Get uniq lines:
  unsigned long uniq_entries = countUniqueSource(phrasetable_path);

  //Source phrase vocabids
  std::map<uint64_t, std::string> source_vocabids;

  //Read the file
  util::FilePiece filein(phrasetable_path.c_str());

  //Init the probing hash table
  size_t size = Table::Size(uniq_entries, 1.2);
  char * mem = new char[size];
  memset(mem, 0, size);
  Table table(mem, size);

  BinaryFileWriter binfile(basepath); //Init the binary file writer.

  std::priority_queue<CacheItem*, std::vector<CacheItem*>, CacheItemOrderer> cache;
  float totalSourceCount = 0;

  line_text prev_line; //Check if the source phrase of the previous line is the same

  //Keep track of the size of each group of target phrases
  uint64_t entrystartidx = 0;
  size_t line_num = 0;

  //Read everything and processs
  while(true) {
    try {
      //Process line read
      line_text line;
      line = splitLine(filein.ReadLine());

      ++line_num;
      if (line_num % 1000000 == 0) {
    	  std::cerr << line_num << " " << std::flush;
      }

      //Add source phrases to vocabularyIDs
      add_to_map(&source_vocabids, line.source_phrase);

      if ((binfile.dist_from_start + binfile.extra_counter) == 0) {
        prev_line = line; //For the first iteration assume the previous line is
      } //The same as this one.

      if (line.source_phrase != prev_line.source_phrase) {

        //Create a new entry even

        // save
        uint64_t targetInd = storeTarget.Save();

          // next line
      	storeTarget.Append(line, log_prob);

        //Create an entry for the previous source phrase:
        Entry pesho;
        pesho.value = entrystartidx;
        pesho.targetInd = targetInd;
        //The key is the sum of hashes of individual words bitshifted by their position in the phrase.
        //Probably not entirerly correct, but fast and seems to work fine in practise.
        pesho.key = 0;
        std::vector<uint64_t> vocabid_source = getVocabIDs(prev_line.source_phrase);
        for (int i = 0; i < vocabid_source.size(); i++) {
          pesho.key += (vocabid_source[i] << i);
        }
        pesho.bytes_toread = binfile.dist_from_start + binfile.extra_counter - entrystartidx;

        //Put into table
        table.Insert(pesho);

        entrystartidx = binfile.dist_from_start + binfile.extra_counter; //Designate start idx for new entry

        //Encode a line and write it to disk.
        std::vector<unsigned char> encoded_line = huffmanEncoder.full_encode_line(line, log_prob);
        binfile.write(&encoded_line);

        // update cache
        if (max_cache_size) {
			std::string countStr = line.counts.as_string();
			countStr = Trim(countStr);
			if (!countStr.empty()) {
				std::vector<float> toks = Tokenize<float>(countStr);

				if (toks.size() >= 2) {
					totalSourceCount += toks[1];
					CacheItem *item = new CacheItem(Trim(line.source_phrase.as_string()), toks[1]);
					cache.push(item);

					if (max_cache_size > 0 && cache.size() > max_cache_size) {
						cache.pop();
					}
				}
			}
        }

        //Set prevLine
        prev_line = line;

      } else {
        //If we still have the same line, just append to it:
    	storeTarget.Append(line, log_prob);

        std::vector<unsigned char> encoded_line = huffmanEncoder.full_encode_line(line, log_prob);
        binfile.write(&encoded_line);
      }

    } catch (util::EndOfFileException e) {
      std::cerr << "Reading phrase table finished, writing remaining files to disk." << std::endl;
      binfile.flush();

      //After the final entry is constructed we need to add it to the phrase_table
      //Create an entry for the previous source phrase:
      uint64_t targetInd = storeTarget.Save();

      Entry pesho;
      pesho.value = entrystartidx;
      pesho.targetInd = targetInd;

      //The key is the sum of hashes of individual words. Probably not entirerly correct, but fast
      pesho.key = 0;
      std::vector<uint64_t> vocabid_source = getVocabIDs(prev_line.source_phrase);
      for (int i = 0; i < vocabid_source.size(); i++) {
        pesho.key += (vocabid_source[i] << i);
      }
      pesho.bytes_toread = binfile.dist_from_start + binfile.extra_counter - entrystartidx;
      //Put into table
      table.Insert(pesho);

      break;
    }
  }

  serialize_table(mem, size, (basepath + "/probing_hash.dat"));

  serialize_map(&source_vocabids, (basepath + "/source_vocabids"));

  serialize_cache(cache, (basepath + "/cache"), totalSourceCount);

  delete[] mem;

  //Write configfile
  std::ofstream configfile;
  configfile.open((basepath + "/config").c_str());
  configfile << API_VERSION << '\n';
  configfile << uniq_entries << '\n';
  configfile << num_scores << '\n';
  configfile << num_lex_scores << '\n';
  configfile << log_prob << '\n';
  configfile.close();
}

size_t countUniqueSource(const std::string &path)
{
	size_t ret = 0;
	InputFileStream strme(path);

	std::string line, prevSource;
	while (std::getline(strme, line)) {
		std::vector<std::string> toks = TokenizeMultiCharSeparator(line, "|||");
		assert(toks.size() == 0);

		if (prevSource != toks[0]) {
			prevSource = toks[0];
			++ret;
		}
	}

	return ret;
}

void serialize_cache(std::priority_queue<CacheItem*, std::vector<CacheItem*>, CacheItemOrderer> &cache,
		const std::string &path,
		float totalSourceCount)
{
  std::vector<const CacheItem*> vec(cache.size());

  size_t ind = cache.size() - 1;
  while (!cache.empty()) {
	  const CacheItem *item = cache.top();
	  vec[ind] = item;
	  cache.pop();
	  --ind;
  }

  std::ofstream os (path.c_str());

  os << totalSourceCount << std::endl;
  for (size_t i = 0; i < vec.size(); ++i) {
	  const CacheItem *item = vec[i];
	  os << item->count << "\t" << item->source << std::endl;
	  delete item;
  }

  os.close();
}

}

<commit_msg>just store prev source, not whole line<commit_after>#include <sys/stat.h>
#include "storing.hh"
#include "StoreTarget.h"
#include "../Util2.h"
#include "../InputFileStream.h"

namespace Moses2
{

BinaryFileWriter::BinaryFileWriter (std::string basepath) : os ((basepath + "/binfile.dat").c_str(), std::ios::binary)
{
  binfile.reserve(10000); //Reserve part of the vector to avoid realocation
  it = binfile.begin();
  dist_from_start = 0; //Initialize variables
  extra_counter = 0;
}

void BinaryFileWriter::write (std::vector<unsigned char> * bytes)
{
  binfile.insert(it, bytes->begin(), bytes->end()); //Insert the bytes
  //Keep track of the offsets
  it += bytes->size();
  dist_from_start = distance(binfile.begin(),it);
  //Flush the vector to disk every once in a while so that we don't consume too much ram
  if (dist_from_start > 9000) {
    flush();
  }
}

void BinaryFileWriter::flush ()
{
  //Cast unsigned char to char before writing...
  os.write((char *)&binfile[0], dist_from_start);
  //Clear the vector:
  binfile.clear();
  binfile.reserve(10000);
  extra_counter += dist_from_start; //Keep track of the total number of bytes.
  it = binfile.begin(); //Reset iterator
  dist_from_start = distance(binfile.begin(),it); //Reset dist from start
}

BinaryFileWriter::~BinaryFileWriter ()
{
  os.close();
  binfile.clear();
}

void createProbingPT(
		const std::string &phrasetable_path,
		const std::string &basepath,
        int num_scores,
		int num_lex_scores,
		bool log_prob,
		int max_cache_size)
{
  std::cerr << "Starting..." << std::endl;

  //Get basepath and create directory if missing
  mkdir(basepath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

  //Set up huffman and serialize decoder maps.
  Huffman huffmanEncoder(phrasetable_path.c_str()); //initialize
  huffmanEncoder.assign_values();
  huffmanEncoder.produce_lookups();
  huffmanEncoder.serialize_maps(basepath.c_str());

  StoreTarget storeTarget(basepath);

  //Get uniq lines:
  unsigned long uniq_entries = countUniqueSource(phrasetable_path);

  //Source phrase vocabids
  std::map<uint64_t, std::string> source_vocabids;

  //Read the file
  util::FilePiece filein(phrasetable_path.c_str());

  //Init the probing hash table
  size_t size = Table::Size(uniq_entries, 1.2);
  char * mem = new char[size];
  memset(mem, 0, size);
  Table table(mem, size);

  BinaryFileWriter binfile(basepath); //Init the binary file writer.

  std::priority_queue<CacheItem*, std::vector<CacheItem*>, CacheItemOrderer> cache;
  float totalSourceCount = 0;

  //Keep track of the size of each group of target phrases
  uint64_t entrystartidx = 0;
  size_t line_num = 0;

  //Read everything and processs
  std::string prevSource;
  while(true) {
    try {
      //Process line read
      line_text line;
      line = splitLine(filein.ReadLine());

      ++line_num;
      if (line_num % 1000000 == 0) {
    	  std::cerr << line_num << " " << std::flush;
      }

      //Add source phrases to vocabularyIDs
      add_to_map(&source_vocabids, line.source_phrase);

      if ((binfile.dist_from_start + binfile.extra_counter) == 0) {
    	prevSource = line.source_phrase.as_string(); //For the first iteration assume the previous line is
      } //The same as this one.

      if (line.source_phrase != prevSource) {

        //Create a new entry even

        // save
        uint64_t targetInd = storeTarget.Save();

          // next line
      	storeTarget.Append(line, log_prob);

        //Create an entry for the previous source phrase:
        Entry pesho;
        pesho.value = entrystartidx;
        pesho.targetInd = targetInd;
        //The key is the sum of hashes of individual words bitshifted by their position in the phrase.
        //Probably not entirerly correct, but fast and seems to work fine in practise.
        pesho.key = 0;
        std::vector<uint64_t> vocabid_source = getVocabIDs(prevSource);
        for (int i = 0; i < vocabid_source.size(); i++) {
          pesho.key += (vocabid_source[i] << i);
        }
        pesho.bytes_toread = binfile.dist_from_start + binfile.extra_counter - entrystartidx;

        //Put into table
        table.Insert(pesho);

        entrystartidx = binfile.dist_from_start + binfile.extra_counter; //Designate start idx for new entry

        //Encode a line and write it to disk.
        std::vector<unsigned char> encoded_line = huffmanEncoder.full_encode_line(line, log_prob);
        binfile.write(&encoded_line);

        // update cache
        if (max_cache_size) {
			std::string countStr = line.counts.as_string();
			countStr = Trim(countStr);
			if (!countStr.empty()) {
				std::vector<float> toks = Tokenize<float>(countStr);

				if (toks.size() >= 2) {
					totalSourceCount += toks[1];
					CacheItem *item = new CacheItem(Trim(line.source_phrase.as_string()), toks[1]);
					cache.push(item);

					if (max_cache_size > 0 && cache.size() > max_cache_size) {
						cache.pop();
					}
				}
			}
        }

        //Set prevLine
        prevSource = line.source_phrase.as_string();

      } else {
        //If we still have the same line, just append to it:
    	storeTarget.Append(line, log_prob);

        std::vector<unsigned char> encoded_line = huffmanEncoder.full_encode_line(line, log_prob);
        binfile.write(&encoded_line);
      }

    } catch (util::EndOfFileException e) {
      std::cerr << "Reading phrase table finished, writing remaining files to disk." << std::endl;
      binfile.flush();

      //After the final entry is constructed we need to add it to the phrase_table
      //Create an entry for the previous source phrase:
      uint64_t targetInd = storeTarget.Save();

      Entry pesho;
      pesho.value = entrystartidx;
      pesho.targetInd = targetInd;

      //The key is the sum of hashes of individual words. Probably not entirerly correct, but fast
      pesho.key = 0;
      std::vector<uint64_t> vocabid_source = getVocabIDs(prevSource);
      for (int i = 0; i < vocabid_source.size(); i++) {
        pesho.key += (vocabid_source[i] << i);
      }
      pesho.bytes_toread = binfile.dist_from_start + binfile.extra_counter - entrystartidx;
      //Put into table
      table.Insert(pesho);

      break;
    }
  }

  serialize_table(mem, size, (basepath + "/probing_hash.dat"));

  serialize_map(&source_vocabids, (basepath + "/source_vocabids"));

  serialize_cache(cache, (basepath + "/cache"), totalSourceCount);

  delete[] mem;

  //Write configfile
  std::ofstream configfile;
  configfile.open((basepath + "/config").c_str());
  configfile << API_VERSION << '\n';
  configfile << uniq_entries << '\n';
  configfile << num_scores << '\n';
  configfile << num_lex_scores << '\n';
  configfile << log_prob << '\n';
  configfile.close();
}

size_t countUniqueSource(const std::string &path)
{
	size_t ret = 0;
	InputFileStream strme(path);

	std::string line, prevSource;
	while (std::getline(strme, line)) {
		std::vector<std::string> toks = TokenizeMultiCharSeparator(line, "|||");
		assert(toks.size() == 0);

		if (prevSource != toks[0]) {
			prevSource = toks[0];
			++ret;
		}
	}

	return ret;
}

void serialize_cache(std::priority_queue<CacheItem*, std::vector<CacheItem*>, CacheItemOrderer> &cache,
		const std::string &path,
		float totalSourceCount)
{
  std::vector<const CacheItem*> vec(cache.size());

  size_t ind = cache.size() - 1;
  while (!cache.empty()) {
	  const CacheItem *item = cache.top();
	  vec[ind] = item;
	  cache.pop();
	  --ind;
  }

  std::ofstream os (path.c_str());

  os << totalSourceCount << std::endl;
  for (size_t i = 0; i < vec.size(); ++i) {
	  const CacheItem *item = vec[i];
	  os << item->count << "\t" << item->source << std::endl;
	  delete item;
  }

  os.close();
}

}

<|endoftext|>


<commit_before>/*!
 * \file painter_attribute.hpp
 * \brief file painter_attribute.hpp
 *
 * Copyright 2016 by Intel.
 *
 * Contact: kevin.rogovin@intel.com
 *
 * This Source Code Form is subject to the
 * terms of the Mozilla Public License, v. 2.0.
 * If a copy of the MPL was not distributed with
 * this file, You can obtain one at
 * http://mozilla.org/MPL/2.0/.
 *
 * \author Kevin Rogovin <kevin.rogovin@intel.com>
 *
 */

#pragma once

#include <fastuidraw/util/vecN.hpp>
namespace fastuidraw
{
/*!\addtogroup Painter
 * @{
 */

  /*!
   * \brief
   * The attribute data generated/filled by \ref Painter.
   * Attribute data is sent to 3D API as raw bits with
   * the expectation that shaders will cast the bits
   * to the appropiate types for themselves.
   */
  class PainterAttribute
  {
  public:
    /*!
     * Generic attribute data
     */
    uvec4 m_attrib0;

    /*!
     * Generic attribute data
     */
    uvec4 m_attrib1;

    /*!
     * Generic attribute data
     */
    uvec4 m_attrib2;
  };

  /*!
   * \brief
   * Typedef for the index type used by \ref Packer
   */
  typedef uint32_t PainterIndex;

/*! @} */
}
<commit_msg>fastuidraw/painter/painter_attribute: doxytag fix<commit_after>/*!
 * \file painter_attribute.hpp
 * \brief file painter_attribute.hpp
 *
 * Copyright 2016 by Intel.
 *
 * Contact: kevin.rogovin@intel.com
 *
 * This Source Code Form is subject to the
 * terms of the Mozilla Public License, v. 2.0.
 * If a copy of the MPL was not distributed with
 * this file, You can obtain one at
 * http://mozilla.org/MPL/2.0/.
 *
 * \author Kevin Rogovin <kevin.rogovin@intel.com>
 *
 */

#pragma once

#include <fastuidraw/util/vecN.hpp>
namespace fastuidraw
{
/*!\addtogroup Painter
 * @{
 */

  /*!
   * \brief
   * The attribute data generated/filled by \ref Painter.
   * Attribute data is sent to 3D API as raw bits with
   * the expectation that shaders will cast the bits
   * to the appropiate types for themselves.
   */
  class PainterAttribute
  {
  public:
    /*!
     * Generic attribute data
     */
    uvec4 m_attrib0;

    /*!
     * Generic attribute data
     */
    uvec4 m_attrib1;

    /*!
     * Generic attribute data
     */
    uvec4 m_attrib2;
  };

  /*!
   * \brief
   * Typedef for the index type used by \ref Painter
   */
  typedef uint32_t PainterIndex;

/*! @} */
}
<|endoftext|>


<commit_before>// This file is distributed under the BSD License.
// See "license.txt" for details.
// Copyright 2009-2012, Jonathan Turner (jonathan@emptycrate.com)
// Copyright 2009-2015, Jason Turner (jason@emptycrate.com)
// http://www.chaiscript.com

#ifndef CHAISCRIPT_TYPE_INFO_HPP_
#define CHAISCRIPT_TYPE_INFO_HPP_

#include <memory>
#include <type_traits>
#include <typeinfo>
#include <string>

namespace chaiscript
{

  namespace detail
  {
    template<typename T>
      struct Bare_Type
      {
        typedef typename std::remove_cv<typename std::remove_pointer<typename std::remove_reference<T>::type>::type>::type type;
      };
  }

  /// \brief Compile time deduced information about a type
  class Type_Info
  {
    public:
       Type_Info(bool t_is_const, bool t_is_reference, bool t_is_pointer, bool t_is_void,
          bool t_is_arithmetic, const std::type_info *t_ti, const std::type_info *t_bare_ti)
        : m_type_info(t_ti), m_bare_type_info(t_bare_ti),
        m_is_const(t_is_const), m_is_reference(t_is_reference), m_is_pointer(t_is_pointer),
        m_is_void(t_is_void), m_is_arithmetic(t_is_arithmetic),
        m_is_undef(false)
      {
      }

       Type_Info()
        : m_type_info(nullptr), m_bare_type_info(nullptr),
        m_is_const(false), m_is_reference(false), m_is_pointer(false),
        m_is_void(false), m_is_arithmetic(false),
        m_is_undef(true)
      {
      }

#if !defined(_MSC_VER) || _MSC_VER != 1800
      Type_Info(Type_Info&&) = default;
      Type_Info& operator=(Type_Info&&) = default;
#endif

      Type_Info(const Type_Info&) = default;
      Type_Info& operator=(const Type_Info&) = default;

       bool operator<(const Type_Info &ti) const CHAISCRIPT_NOEXCEPT
      {
        return m_type_info < ti.m_type_info;
      }

       bool operator==(const Type_Info &ti) const CHAISCRIPT_NOEXCEPT
      {
        return ti.m_type_info == m_type_info
          || (ti.m_type_info && m_type_info && *ti.m_type_info == *m_type_info);
      }

       bool operator==(const std::type_info &ti) const CHAISCRIPT_NOEXCEPT
      {
        return m_type_info != nullptr && (*m_type_info) == ti;
      }

       bool bare_equal(const Type_Info &ti) const CHAISCRIPT_NOEXCEPT
      {
        return ti.m_bare_type_info == m_bare_type_info
          || (ti.m_bare_type_info && m_bare_type_info && *ti.m_bare_type_info == *m_bare_type_info);
      }

       bool bare_equal_type_info(const std::type_info &ti) const CHAISCRIPT_NOEXCEPT
      {
        return m_bare_type_info != nullptr
          && (*m_bare_type_info) == ti;
      }

       bool is_const() const CHAISCRIPT_NOEXCEPT { return m_is_const; }
       bool is_reference() const CHAISCRIPT_NOEXCEPT { return m_is_reference; }
       bool is_void() const CHAISCRIPT_NOEXCEPT { return m_is_void; }
       bool is_arithmetic() const CHAISCRIPT_NOEXCEPT { return m_is_arithmetic; }
       bool is_undef() const CHAISCRIPT_NOEXCEPT { return m_is_undef || m_bare_type_info == nullptr; }
       bool is_pointer() const CHAISCRIPT_NOEXCEPT { return m_is_pointer; }

      std::string name() const
      {
        if (m_type_info)
        {
          return m_type_info->name();
        } else {
          return "";
        }
      }

      std::string bare_name() const
      {
        if (m_bare_type_info)
        {
          return m_bare_type_info->name();
        } else {
          return "";
        }
      }

       const std::type_info *bare_type_info() const
      {
        return m_bare_type_info;
      }

    private:
      const std::type_info *m_type_info;
      const std::type_info *m_bare_type_info;
      bool m_is_const;
      bool m_is_reference;
      bool m_is_pointer;
      bool m_is_void;
      bool m_is_arithmetic;
      bool m_is_undef;
  };

  namespace detail
  {
    /// Helper used to create a Type_Info object
    template<typename T>
      struct Get_Type_Info
      {
        typedef T type;

         static Type_Info get()
        {
          return Type_Info(std::is_const<typename std::remove_pointer<typename std::remove_reference<T>::type>::type>::value, std::is_reference<T>::value, std::is_pointer<T>::value,
              std::is_void<T>::value,
              std::is_arithmetic<T>::value && !std::is_same<typename std::remove_const<T>::type, bool>::value,
              &typeid(T),
              &typeid(typename Bare_Type<T>::type));
        }
      };

    template<typename T>
      struct Get_Type_Info<std::shared_ptr<T> >
      {
        typedef T type;

         static Type_Info get()
        {
          return Type_Info(std::is_const<T>::value, std::is_reference<T>::value, std::is_pointer<T>::value,
              std::is_void<T>::value,
              std::is_arithmetic<T>::value && !std::is_same<typename std::remove_const<T>::type, bool>::value,
              &typeid(std::shared_ptr<T> ),
              &typeid(typename Bare_Type<T>::type));
        }
      };

    template<typename T>
      struct Get_Type_Info<const std::shared_ptr<T> &>
      {
        typedef T type;

         static Type_Info get()
        {
          return Type_Info(std::is_const<T>::value, std::is_reference<T>::value, std::is_pointer<T>::value,
              std::is_void<T>::value,
              std::is_arithmetic<T>::value && !std::is_same<typename std::remove_const<T>::type, bool>::value,
              &typeid(const std::shared_ptr<T> &),
              &typeid(typename Bare_Type<T>::type));
        }
      };

    template<typename T>
      struct Get_Type_Info<std::reference_wrapper<T> >
      {
        typedef T type;

         static Type_Info get()
        {
          return Type_Info(std::is_const<T>::value, std::is_reference<T>::value, std::is_pointer<T>::value,
              std::is_void<T>::value,
              std::is_arithmetic<T>::value && !std::is_same<typename std::remove_const<T>::type, bool>::value,
              &typeid(std::reference_wrapper<T> ),
              &typeid(typename Bare_Type<T>::type));
        }
      };

    template<typename T>
      struct Get_Type_Info<const std::reference_wrapper<T> &>
      {
        typedef T type;

         static Type_Info get()
        {
          return Type_Info(std::is_const<T>::value, std::is_reference<T>::value, std::is_pointer<T>::value,
              std::is_void<T>::value,
              std::is_arithmetic<T>::value && !std::is_same<typename std::remove_const<T>::type, bool>::value,
              &typeid(const std::reference_wrapper<T> &),
              &typeid(typename Bare_Type<T>::type));
        }
      };

  }

  /// \brief Creates a Type_Info object representing the type passed in
  /// \tparam T Type of object to get a Type_Info for, derived from the passed in parameter
  /// \return Type_Info for T
  ///
  /// \b Example:
  /// \code
  /// int i;
  /// chaiscript::Type_Info ti = chaiscript::user_type(i);
  /// \endcode
  template<typename T>
   Type_Info user_type(const T &/*t*/)
  {
    return detail::Get_Type_Info<T>::get();
  }

  /// \brief Creates a Type_Info object representing the templated type
  /// \tparam T Type of object to get a Type_Info for
  /// \return Type_Info for T
  ///
  /// \b Example:
  /// \code
  /// chaiscript::Type_Info ti = chaiscript::user_type<int>();
  /// \endcode
  template<typename T>
   Type_Info user_type()
  {
    return detail::Get_Type_Info<T>::get();
  }

}

#endif

<commit_msg>Add back CONSTEXPR for Type_Info<commit_after>// This file is distributed under the BSD License.
// See "license.txt" for details.
// Copyright 2009-2012, Jonathan Turner (jonathan@emptycrate.com)
// Copyright 2009-2015, Jason Turner (jason@emptycrate.com)
// http://www.chaiscript.com

#ifndef CHAISCRIPT_TYPE_INFO_HPP_
#define CHAISCRIPT_TYPE_INFO_HPP_

#include <memory>
#include <type_traits>
#include <typeinfo>
#include <string>

namespace chaiscript
{

  namespace detail
  {
    template<typename T>
      struct Bare_Type
      {
        typedef typename std::remove_cv<typename std::remove_pointer<typename std::remove_reference<T>::type>::type>::type type;
      };
  }

  /// \brief Compile time deduced information about a type
  class Type_Info
  {
    public:
       CHAISCRIPT_CONSTEXPR Type_Info(bool t_is_const, bool t_is_reference, bool t_is_pointer, bool t_is_void,
          bool t_is_arithmetic, const std::type_info *t_ti, const std::type_info *t_bare_ti)
        : m_type_info(t_ti), m_bare_type_info(t_bare_ti),
        m_is_const(t_is_const), m_is_reference(t_is_reference), m_is_pointer(t_is_pointer),
        m_is_void(t_is_void), m_is_arithmetic(t_is_arithmetic),
        m_is_undef(false)
      {
      }

       CHAISCRIPT_CONSTEXPR Type_Info()
        : m_type_info(nullptr), m_bare_type_info(nullptr),
        m_is_const(false), m_is_reference(false), m_is_pointer(false),
        m_is_void(false), m_is_arithmetic(false),
        m_is_undef(true)
      {
      }

#if !defined(_MSC_VER) || _MSC_VER != 1800
      Type_Info(Type_Info&&) = default;
      Type_Info& operator=(Type_Info&&) = default;
#endif

      Type_Info(const Type_Info&) = default;
      Type_Info& operator=(const Type_Info&) = default;

      CHAISCRIPT_CONSTEXPR bool operator<(const Type_Info &ti) const CHAISCRIPT_NOEXCEPT
      {
        return m_type_info < ti.m_type_info;
      }

      CHAISCRIPT_CONSTEXPR bool operator==(const Type_Info &ti) const CHAISCRIPT_NOEXCEPT
      {
        return ti.m_type_info == m_type_info
          || (ti.m_type_info && m_type_info && *ti.m_type_info == *m_type_info);
      }

      CHAISCRIPT_CONSTEXPR bool operator==(const std::type_info &ti) const CHAISCRIPT_NOEXCEPT
      {
        return m_type_info != nullptr && (*m_type_info) == ti;
      }

      CHAISCRIPT_CONSTEXPR bool bare_equal(const Type_Info &ti) const CHAISCRIPT_NOEXCEPT
      {
        return ti.m_bare_type_info == m_bare_type_info
          || (ti.m_bare_type_info && m_bare_type_info && *ti.m_bare_type_info == *m_bare_type_info);
      }

      CHAISCRIPT_CONSTEXPR bool bare_equal_type_info(const std::type_info &ti) const CHAISCRIPT_NOEXCEPT
      {
        return m_bare_type_info != nullptr
          && (*m_bare_type_info) == ti;
      }

      CHAISCRIPT_CONSTEXPR bool is_const() const CHAISCRIPT_NOEXCEPT { return m_is_const; }
      CHAISCRIPT_CONSTEXPR bool is_reference() const CHAISCRIPT_NOEXCEPT { return m_is_reference; }
      CHAISCRIPT_CONSTEXPR bool is_void() const CHAISCRIPT_NOEXCEPT { return m_is_void; }
      CHAISCRIPT_CONSTEXPR bool is_arithmetic() const CHAISCRIPT_NOEXCEPT { return m_is_arithmetic; }
      CHAISCRIPT_CONSTEXPR bool is_undef() const CHAISCRIPT_NOEXCEPT { return m_is_undef || m_bare_type_info == nullptr; }
      CHAISCRIPT_CONSTEXPR bool is_pointer() const CHAISCRIPT_NOEXCEPT { return m_is_pointer; }

      std::string name() const
      {
        if (m_type_info)
        {
          return m_type_info->name();
        } else {
          return "";
        }
      }

      std::string bare_name() const
      {
        if (m_bare_type_info)
        {
          return m_bare_type_info->name();
        } else {
          return "";
        }
      }

      CHAISCRIPT_CONSTEXPR const std::type_info *bare_type_info() const
      {
        return m_bare_type_info;
      }

    private:
      const std::type_info *m_type_info;
      const std::type_info *m_bare_type_info;
      bool m_is_const;
      bool m_is_reference;
      bool m_is_pointer;
      bool m_is_void;
      bool m_is_arithmetic;
      bool m_is_undef;
  };

  namespace detail
  {
    /// Helper used to create a Type_Info object
    template<typename T>
      struct Get_Type_Info
      {
        typedef T type;

         static Type_Info get()
        {
          return Type_Info(std::is_const<typename std::remove_pointer<typename std::remove_reference<T>::type>::type>::value, std::is_reference<T>::value, std::is_pointer<T>::value,
              std::is_void<T>::value,
              std::is_arithmetic<T>::value && !std::is_same<typename std::remove_const<T>::type, bool>::value,
              &typeid(T),
              &typeid(typename Bare_Type<T>::type));
        }
      };

    template<typename T>
      struct Get_Type_Info<std::shared_ptr<T> >
      {
        typedef T type;

         static Type_Info get()
        {
          return Type_Info(std::is_const<T>::value, std::is_reference<T>::value, std::is_pointer<T>::value,
              std::is_void<T>::value,
              std::is_arithmetic<T>::value && !std::is_same<typename std::remove_const<T>::type, bool>::value,
              &typeid(std::shared_ptr<T> ),
              &typeid(typename Bare_Type<T>::type));
        }
      };

    template<typename T>
      struct Get_Type_Info<const std::shared_ptr<T> &>
      {
        typedef T type;

         static Type_Info get()
        {
          return Type_Info(std::is_const<T>::value, std::is_reference<T>::value, std::is_pointer<T>::value,
              std::is_void<T>::value,
              std::is_arithmetic<T>::value && !std::is_same<typename std::remove_const<T>::type, bool>::value,
              &typeid(const std::shared_ptr<T> &),
              &typeid(typename Bare_Type<T>::type));
        }
      };

    template<typename T>
      struct Get_Type_Info<std::reference_wrapper<T> >
      {
        typedef T type;

         static Type_Info get()
        {
          return Type_Info(std::is_const<T>::value, std::is_reference<T>::value, std::is_pointer<T>::value,
              std::is_void<T>::value,
              std::is_arithmetic<T>::value && !std::is_same<typename std::remove_const<T>::type, bool>::value,
              &typeid(std::reference_wrapper<T> ),
              &typeid(typename Bare_Type<T>::type));
        }
      };

    template<typename T>
      struct Get_Type_Info<const std::reference_wrapper<T> &>
      {
        typedef T type;

         static Type_Info get()
        {
          return Type_Info(std::is_const<T>::value, std::is_reference<T>::value, std::is_pointer<T>::value,
              std::is_void<T>::value,
              std::is_arithmetic<T>::value && !std::is_same<typename std::remove_const<T>::type, bool>::value,
              &typeid(const std::reference_wrapper<T> &),
              &typeid(typename Bare_Type<T>::type));
        }
      };

  }

  /// \brief Creates a Type_Info object representing the type passed in
  /// \tparam T Type of object to get a Type_Info for, derived from the passed in parameter
  /// \return Type_Info for T
  ///
  /// \b Example:
  /// \code
  /// int i;
  /// chaiscript::Type_Info ti = chaiscript::user_type(i);
  /// \endcode
  template<typename T>
   Type_Info user_type(const T &/*t*/)
  {
    return detail::Get_Type_Info<T>::get();
  }

  /// \brief Creates a Type_Info object representing the templated type
  /// \tparam T Type of object to get a Type_Info for
  /// \return Type_Info for T
  ///
  /// \b Example:
  /// \code
  /// chaiscript::Type_Info ti = chaiscript::user_type<int>();
  /// \endcode
  template<typename T>
   Type_Info user_type()
  {
    return detail::Get_Type_Info<T>::get();
  }

}

#endif

<|endoftext|>


<commit_before>// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2013 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

#include "config.h"

#include "D4Group.h"
#include "D4EnumDefs.h"

#include <sstream>

#include "dods-limits.h"
#include "util.h"

namespace libdap {

/** Test if a particular value is legal for a given type. In a D4EnumDef,
 * all values are actually stored in a long long, but the different
 * enumerations can specify different types like Byte, Int32, ..., and this
 * method is used to test that the values match those types.
 */
bool
D4EnumDef::is_valid_enum_value(long long value)
{
    switch (type()) {
        case dods_int8_c:
            return (value >= DODS_SCHAR_MIN && value <= DODS_SCHAR_MAX);
        case dods_byte_c:
        case dods_uint8_c:
            return (value >= 0 && static_cast<unsigned long long>(value) <= DODS_UCHAR_MAX);
        case dods_int16_c:
            return (value >= DODS_SHRT_MIN && value <= DODS_SHRT_MAX);
        case dods_uint16_c:
            return (value >= 0 && static_cast<unsigned long long>(value) <= DODS_USHRT_MAX);
        case dods_int32_c:
            return (value >= DODS_INT_MIN && value <= DODS_INT_MAX);
        case dods_uint32_c:
            return (value >= 0 && static_cast<unsigned long long>(value) <= DODS_UINT_MAX);
        case dods_int64_c:
            return true; // This is always true: (value >= DODS_LLONG_MIN && value <= DODS_LLONG_MAX);
        case dods_uint64_c:
            return (value >= 0 && static_cast<unsigned long long>(value) <= DODS_ULLONG_MAX);
        default:
            return false;
    }
}

// Note that in order for this to work the second argument must not be a reference.
// jhrg 8/20/13
static bool
enum_def_name_eq(D4EnumDef *d, const string name)
{
    return d->name() == name;
}

D4EnumDef *
D4EnumDefs::find_enum_def(const string &name)
{
    D4EnumDefIter d = find_if(d_enums.begin(), d_enums.end(), bind2nd(ptr_fun(enum_def_name_eq), name));
    return (d != d_enums.end()) ? *d: 0;
}

void D4EnumDef::print_value(XMLWriter &xml, const D4EnumDef::tuple &tuple) const
{
    if (xmlTextWriterStartElement(xml.get_writer(), (const xmlChar*)"EnumConst") < 0)
        throw InternalErr(__FILE__, __LINE__, "Could not write EnumConst element");

    if (xmlTextWriterWriteAttribute(xml.get_writer(), (const xmlChar*) "name", (const xmlChar*)tuple.label.c_str()) < 0)
        throw InternalErr(__FILE__, __LINE__, "Could not write attribute for name");

    ostringstream oss;
    oss << tuple.value;
    if (xmlTextWriterWriteAttribute(xml.get_writer(), (const xmlChar*) "value", (const xmlChar*)oss.str().c_str()) < 0)
        throw InternalErr(__FILE__, __LINE__, "Could not write attribute for value");

    if (xmlTextWriterEndElement(xml.get_writer()) < 0)
        throw InternalErr(__FILE__, __LINE__, "Could not end EnumConst element");
}

void D4EnumDef::print_dap4(XMLWriter &xml) const
{
    vector<D4EnumDef::tuple>::const_iterator i = d_tuples.begin();
    while(i != d_tuples.end()) {
        print_value(xml, *i++);
    }
}

void D4EnumDefs::m_print_enum(XMLWriter &xml, D4EnumDef *e) const
{
    if (xmlTextWriterStartElement(xml.get_writer(), (const xmlChar*)"Enumeration") < 0)
        throw InternalErr(__FILE__, __LINE__, "Could not write Enumeration element");

    if (xmlTextWriterWriteAttribute(xml.get_writer(), (const xmlChar*) "name", (const xmlChar*)e->name().c_str()) < 0)
        throw InternalErr(__FILE__, __LINE__, "Could not write attribute for name");

    if (xmlTextWriterWriteAttribute(xml.get_writer(), (const xmlChar*) "basetype", (const xmlChar*)D4type_name(e->type()).c_str()) < 0)
        throw InternalErr(__FILE__, __LINE__, "Could not write attribute for name");

    // print each of e.values
    e->print_dap4(xml);

    if (xmlTextWriterEndElement(xml.get_writer()) < 0)
        throw InternalErr(__FILE__, __LINE__, "Could not end Enumeration element");
}

void D4EnumDefs::print_dap4(XMLWriter &xml, bool constrained) const
{
    D4EnumDefCIter i = d_enums.begin();
    while (i != d_enums.end()) {
        if (!constrained || parent()->find_first_var_that_uses_enumeration(*i))
            m_print_enum(xml, *i);
        ++i;
    }
}

} /* namespace libdap */
<commit_msg>Minor issue in D4EnumDefs.cc with range checking<commit_after>// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2013 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

#include "config.h"

#include "D4Group.h"
#include "D4EnumDefs.h"

#include <sstream>

#include "dods-limits.h"
#include "util.h"

namespace libdap {

/** Test if a particular value is legal for a given type. In a D4EnumDef,
 * all values are actually stored in a long long, but the different
 * enumerations can specify different types like Byte, Int32, ..., and this
 * method is used to test that the values match those types.
 */
bool
D4EnumDef::is_valid_enum_value(long long value)
{
    switch (type()) {
        case dods_int8_c:
            return (value >= DODS_SCHAR_MIN && value <= DODS_SCHAR_MAX);
        case dods_byte_c:
        case dods_uint8_c:
            return (value >= 0 && static_cast<unsigned long long>(value) <= DODS_UCHAR_MAX);
        case dods_int16_c:
            return (value >= DODS_SHRT_MIN && value <= DODS_SHRT_MAX);
        case dods_uint16_c:
            return (value >= 0 && static_cast<unsigned long long>(value) <= DODS_USHRT_MAX);
        case dods_int32_c:
            return (value >= DODS_INT_MIN && value <= DODS_INT_MAX);
        case dods_uint32_c:
            return (value >= 0 && static_cast<unsigned long long>(value) <= DODS_UINT_MAX);
        case dods_int64_c:
            return true; // This is always true: (value >= DODS_LLONG_MIN && value <= DODS_LLONG_MAX);
        case dods_uint64_c:
            return (value >= 0 /*Always true: && static_cast<unsigned long long>(value) <= DODS_ULLONG_MAX*/);
        default:
            return false;
    }
}

// Note that in order for this to work the second argument must not be a reference.
// jhrg 8/20/13
static bool
enum_def_name_eq(D4EnumDef *d, const string name)
{
    return d->name() == name;
}

D4EnumDef *
D4EnumDefs::find_enum_def(const string &name)
{
    D4EnumDefIter d = find_if(d_enums.begin(), d_enums.end(), bind2nd(ptr_fun(enum_def_name_eq), name));
    return (d != d_enums.end()) ? *d: 0;
}

void D4EnumDef::print_value(XMLWriter &xml, const D4EnumDef::tuple &tuple) const
{
    if (xmlTextWriterStartElement(xml.get_writer(), (const xmlChar*)"EnumConst") < 0)
        throw InternalErr(__FILE__, __LINE__, "Could not write EnumConst element");

    if (xmlTextWriterWriteAttribute(xml.get_writer(), (const xmlChar*) "name", (const xmlChar*)tuple.label.c_str()) < 0)
        throw InternalErr(__FILE__, __LINE__, "Could not write attribute for name");

    ostringstream oss;
    oss << tuple.value;
    if (xmlTextWriterWriteAttribute(xml.get_writer(), (const xmlChar*) "value", (const xmlChar*)oss.str().c_str()) < 0)
        throw InternalErr(__FILE__, __LINE__, "Could not write attribute for value");

    if (xmlTextWriterEndElement(xml.get_writer()) < 0)
        throw InternalErr(__FILE__, __LINE__, "Could not end EnumConst element");
}

void D4EnumDef::print_dap4(XMLWriter &xml) const
{
    vector<D4EnumDef::tuple>::const_iterator i = d_tuples.begin();
    while(i != d_tuples.end()) {
        print_value(xml, *i++);
    }
}

void D4EnumDefs::m_print_enum(XMLWriter &xml, D4EnumDef *e) const
{
    if (xmlTextWriterStartElement(xml.get_writer(), (const xmlChar*)"Enumeration") < 0)
        throw InternalErr(__FILE__, __LINE__, "Could not write Enumeration element");

    if (xmlTextWriterWriteAttribute(xml.get_writer(), (const xmlChar*) "name", (const xmlChar*)e->name().c_str()) < 0)
        throw InternalErr(__FILE__, __LINE__, "Could not write attribute for name");

    if (xmlTextWriterWriteAttribute(xml.get_writer(), (const xmlChar*) "basetype", (const xmlChar*)D4type_name(e->type()).c_str()) < 0)
        throw InternalErr(__FILE__, __LINE__, "Could not write attribute for name");

    // print each of e.values
    e->print_dap4(xml);

    if (xmlTextWriterEndElement(xml.get_writer()) < 0)
        throw InternalErr(__FILE__, __LINE__, "Could not end Enumeration element");
}

void D4EnumDefs::print_dap4(XMLWriter &xml, bool constrained) const
{
    D4EnumDefCIter i = d_enums.begin();
    while (i != d_enums.end()) {
        if (!constrained || parent()->find_first_var_that_uses_enumeration(*i))
            m_print_enum(xml, *i);
        ++i;
    }
}

} /* namespace libdap */
<|endoftext|>


<commit_before>#include "include/ViewerPageWidget.h"
#include "ui_ViewerPageWidget.h"
#include <QMenu>
#include <QToolTip>
#include <QMessageBox>
#include <QPointer>

const int ViewerPageWidget::EXIT_NEXT = 0;

/**
 * @brief ViewerPageWidget::ViewerPageWidget Constructs a ViewerPageWidget.
 */
ViewerPageWidget::ViewerPageWidget() :
    ui(new Ui::ViewerPageWidget), mIndex(0), mImage(nullptr), mSelectionPen(QColor(0,255,230)),
    mCurrentSelection(nullptr), mAnnotationDrawer(&mGraphicsScene), mSelectedAnnotation(nullptr),
    mAlgorithmList(nullptr), mDataset(nullptr), mROIIsChosen(false), mZoomLevel(1.0)
{
    ui->setupUi(this);
    ui->mViewerListView->setResizeMode(QListView::Adjust);
    ui->mGraphicsView->setScene(&mGraphicsScene);
    ui->mViewerListView->setModel(&mModel);

    connect(ui->mViewerListView->selectionModel(), SIGNAL(currentChanged(const QModelIndex&, const QModelIndex&)), this,
        SLOT(selectionChanged(const QModelIndex&, const QModelIndex&)));
    connect(ui->mNextButton, SIGNAL(clicked()), this, SLOT(next()));
    connect(ui->mBeforeButton, SIGNAL(clicked()), this, SLOT(before()));
    connect(ui->mROIButton, SIGNAL(clicked()), this, SLOT(roiClicked()));
    connect(&mAnnotationDrawer, SIGNAL(selected(Annotation*, const QPointF&)), this, SLOT(annotationSelected(Annotation*, const QPointF&)));
    connect(ui->mZoomIn, SIGNAL(clicked()), this, SLOT(zoomIn()));
    connect(ui->mZoomOut, SIGNAL(clicked()), this, SLOT(zoomOut()));
    connect(ui->mGraphicsView, SIGNAL(zoomed(double)), this, SLOT(zoomed(double)));
    connect(ui->mGraphicsView, SIGNAL(resize()), this, SLOT(resize()));

    Q_INIT_RESOURCE(application);
    ui->mBeforeButton->setIcon(QIcon(":/before.png"));
    ui->mNextButton->setIcon(QIcon(":/next.png"));
}

/**
 * @brief ViewerPageWidget::~ViewerPageWidget Deletes the ViewerPageWidget.
 */
ViewerPageWidget::~ViewerPageWidget()
{
    delete ui;
}

/**
 * @brief ViewerPageWidget::resizeEvent Resizes the widget.
 * @param event The QResizeEvent.
 */
void ViewerPageWidget::resizeEvent(QResizeEvent *event) {
    resize();
}

/**
 * @brief ViewerPageWidget::resize Resizes the displayed Medium.
 */
void ViewerPageWidget::resize() {
    ui->mGraphicsView->fitInView(mImage, Qt::KeepAspectRatio);
}

/**
 * @brief ViewerPageWidget::zoomIn Zooms in the Medium.
 */
void ViewerPageWidget::zoomIn() {
    ui->mGraphicsView->scale(2,2);
    zoomed(2);
}

/**
 * @brief ViewerPageWidget::zoomOut Zooms the Medium out.
 */
void ViewerPageWidget::zoomOut() {
    ui->mGraphicsView->scale(0.5,0.5);
    zoomed(0.5);
}

void ViewerPageWidget::zoomed(double factor) {
    mZoomLevel *= factor;
    ui->mZoom->setText(QString::number(mZoomLevel*100) + " %");
}

/**
 * @brief ViewerPageWidget::annotationSelected Sets the selected annotation and shows a context menu to select an Algorithm.
 * @param annotation The selected Annotation.
 * @param pos The mouse position.
 */
void ViewerPageWidget::annotationSelected(Annotation* annotation, const QPointF& pos) {
    mSelectedAnnotation = annotation->copy();
    contextMenu(pos);
}

/**
 * @brief ViewerPageWidget::contextMenu Shows a context menu to select an Algorithm.
 * @param pos The mouse position.
 */
void ViewerPageWidget::contextMenu(const QPointF &pos) {
    SearchObject searchObject;
    searchObject.setMedium(getSearchMedium());
    if(mCurrentSelection != nullptr && mCurrentSelection->contains(pos)) {
        mROI = mCurrentSelection->rect().toRect();
        searchObject.setROI(mROI);
        searchObject.setType(SearchObject::Type::ROI);
    } else if(mSelectedAnnotation != nullptr) {
        searchObject.setAnnotation(mSelectedAnnotation);
        searchObject.setType(SearchObject::Type::ANNOTATION);
    } else {
        searchObject.setType(SearchObject::Type::MEDIUM);
    }
    searchObject.setSourceDataset(mDataset->getPath());
    mSearchQuery = std::make_shared<SearchQuery>();
    mSearchQuery->setSearchObject(searchObject);
    QList<QString> datasetList;
    datasetList.push_back(mDataset->getPath());
    mSearchQuery->setDatasets(datasetList);

    QList<Algorithm*> algoList = mAlgorithmList ? mAlgorithmList->findCompatibleAlgorithms(QList<DataPacket*>({mSearchQuery.get()})) : QList<Algorithm*>();

    QMenu contextMenu(this);
    if(algoList.isEmpty()) {
        QMessageBox msgBox(QMessageBox::Information, "", "Found no fitting algorithm.", QMessageBox::Ok, this);
        msgBox.exec();
        return;
    }
    switch(searchObject.getType()) {
        case SearchObject::Type::ROI:
            contextMenu.setTitle("ROI");
            break;
        case SearchObject::Type::ANNOTATION:
            contextMenu.setTitle("Annotation");
            break;
        case  SearchObject::Type::MEDIUM:
        default:
            contextMenu.setTitle("Medium");
    }
    for(Algorithm* iter: algoList) {
        mAlgorithms.insert(iter->getName(), iter);
        QAction* action = new QAction(iter->getName(), this);
        action->setToolTip(iter->getDescription());
        contextMenu.addAction(action);
    }
    connect(&contextMenu, SIGNAL(triggered(QAction*)), this, SLOT(nextWidget(QAction*)));
    connect(&contextMenu, SIGNAL(hovered(QAction*)), this, SLOT(showToolTip(QAction*)));
    contextMenu.exec(QCursor::pos());
}

/**
 * @brief ViewerPageWidget::showToolTip Shows tooltips for the algorithms.
 * @param action The QAction of the algorithm in the context menu.
 */
void ViewerPageWidget::showToolTip(QAction* action) {
    QToolTip::showText(QCursor::pos(), action->toolTip());
}

/**
 * @brief ViewerPageWidget::selectionChanged Updates the displayed Medium when the selection changed.
 * @param index The new QModelIndex.
 * @param previousIndex The previous QModelIndex.
 */
void ViewerPageWidget::selectionChanged(const QModelIndex &index, const QModelIndex &previousIndex) {
    mIndex = index.row();
    display();
}

/**
 * @brief ViewerPageWidget::next Shows the next Medium in the ListView.
 */
void ViewerPageWidget::next() {
    mIndex++;
    mIndex%=mDataset->getNumberOfMedia();
    ui->mViewerListView->selectionModel()->setCurrentIndex(mModel.index(mIndex), QItemSelectionModel::ClearAndSelect);
    display();
}

/**
 * @brief ViewerPageWidget::before Shows the Medium before in the ListView.
 */
void ViewerPageWidget::before() {
    if(mIndex <= 0) {
        mIndex = mDataset->getNumberOfMedia();
    }
    mIndex--;
    ui->mViewerListView->selectionModel()->setCurrentIndex(mModel.index(mIndex), QItemSelectionModel::ClearAndSelect);
    display();
}

/**
 * @brief ViewerPageWidget::display Displays a Medium.
 */
void ViewerPageWidget::display() {
    mZoomLevel = 1.0;
    ui->mZoom->setText("100 %");
}

/**
 * @brief ViewerPageWidget::reset Resets the ViewerPageWidget.
 */
void ViewerPageWidget::reset()
{
    QVariant var;
    emit readFromStack(0, var);
    if(var.canConvert<int>()){
        QVariant var2;
        emit readFromStack(-2, var2);
        if(var2.canConvert<std::shared_ptr<DatasetList>>()) {
            if(mDataset != nullptr) {
                delete mDataset;
            }
            mDataset = new Dataset(var2.value<std::shared_ptr<DatasetList>>()->getDatasetList().at(var.value<int>()));
            mModel.setDataset(*mDataset);
            mIndex = 0;
            if(mImage != nullptr) {
                delete mImage;
                mImage = nullptr;
            }
            if(mCurrentSelection != nullptr) {
                delete mCurrentSelection;
                mCurrentSelection = nullptr;
            }
            if(mSelectedAnnotation != nullptr) {
                delete mSelectedAnnotation;
                mSelectedAnnotation = nullptr;
            }

            display();
        }
    }

    QVariant algoListVariant;
    emit readFromStack(-1, algoListVariant);
    if(algoListVariant.canConvert<std::shared_ptr<AlgorithmList>>()){
        mAlgorithmList = algoListVariant.value<std::shared_ptr<AlgorithmList>>().get();
    } else {
        mAlgorithmList = nullptr;
    }
}

/**
 * @brief ViewerPageWidget::nextWidget Switches to the next widget.
 * @param action The QAction of the selected Algorithm.
 */
void ViewerPageWidget::nextWidget(QAction* action) {
    delete mDataset;
    mDataset = nullptr;
    delete mSelectedAnnotation;
    mSelectedAnnotation = nullptr;
    delete mCurrentSelection;
    mCurrentSelection = nullptr;
    delete mImage;
    mImage = nullptr;

    QVariant query;
    query.setValue(mSearchQuery);
    pushToStack(query);

    // todo: push actual, user-chosen algorithm
    QPointer<Algorithm> algo(mAlgorithms.value(action->text()));
    //std::shared_ptr<Algorithm> algo = std::make_shared<TestAlgorithm>("id123");
    QVariant varAlgo;
    varAlgo.setValue(algo);
    pushToStack(varAlgo);

    exit(EXIT_NEXT);
}

/**
 * @brief ViewerPageWidget::on_mGraphicsView_rubberBandChanged Selects a ROI.
 * @param viewportRect unused
 * @param fromScenePoint The starting point of the selection.
 * @param toScenePoint The ending point of the selection.
 */
void ViewerPageWidget::on_mGraphicsView_rubberBandChanged(const QRect &viewportRect, const QPointF &fromScenePoint,
                                                          const QPointF &toScenePoint)
{
    Q_UNUSED(viewportRect);
    if(mImage == nullptr) {
        return;
    }
    if(fromScenePoint.x() == 0 && fromScenePoint.y() == 0){
        if(mCurrentSelection != nullptr){
            mGraphicsScene.removeItem(mCurrentSelection);
            delete mCurrentSelection;
        }
        mCurrentSelection = mGraphicsScene.addRect(mCurrentRubberBand, mSelectionPen);
    } else {
        int width = mImage->boundingRect().width();
        int height = mImage->boundingRect().height();

        if(fromScenePoint.x() >= 0 && fromScenePoint.x() < width
                && fromScenePoint.y() >= 0 && fromScenePoint.y() < height) {
            mCurrentRubberBand.setLeft(fromScenePoint.x());
            mCurrentRubberBand.setTop(fromScenePoint.y());
            mCurrentRubberBand.setRight(toScenePoint.x());
            mCurrentRubberBand.setBottom(toScenePoint.y());

            if(toScenePoint.x() < 0)
                mCurrentRubberBand.setRight(0);
            if(toScenePoint.x() >= width)
                mCurrentRubberBand.setRight(width-1);
            if(toScenePoint.y() < 0)
                mCurrentRubberBand.setBottom(0);
            if(toScenePoint.y() >= height)
                mCurrentRubberBand.setBottom(height-1);
            mCurrentRubberBand = mCurrentRubberBand.normalized();
        }
    }
}

/**
 * @brief ViewerPageWidget::roiClicked En-/Disables the selection mode of a ROI, when the ROI button was clicked.
 */
void ViewerPageWidget::roiClicked() {
    if(!mROIIsChosen) {
        ui->mGraphicsView->setDragMode(QGraphicsView::DragMode::RubberBandDrag);
        ui->mROIButton->setText(tr("Bereich entfernen"));
        mROIIsChosen = true;
    } else {
        ui->mGraphicsView->setDragMode(QGraphicsView::DragMode::NoDrag);
        ui->mROIButton->setText(tr("Bereich auswählen"));
        mROIIsChosen = false;
        if(mCurrentSelection != nullptr) {
            mGraphicsScene.removeItem(mCurrentSelection);
            mCurrentSelection = nullptr;
            mCurrentRubberBand.setRect(0,0,0,0);
        }
    }
}

/**
 * @brief ViewerPageWidget::retranslateUi Translates the GUI.
 */
void ViewerPageWidget::retranslateUi() {
    if(mROIIsChosen) {
        ui->mROIButton->setText(tr("Bereich entfernen"));
    } else {
        ui->mROIButton->setText(tr("Bereich auswählen"));
    }
}

QString ViewerPageWidget::getName() {
    return tr("CoBaB - Viewer");
}

<commit_msg>Corrected zooming level.<commit_after>#include "include/ViewerPageWidget.h"
#include "ui_ViewerPageWidget.h"
#include <QMenu>
#include <QToolTip>
#include <QMessageBox>
#include <QPointer>

const int ViewerPageWidget::EXIT_NEXT = 0;

/**
 * @brief ViewerPageWidget::ViewerPageWidget Constructs a ViewerPageWidget.
 */
ViewerPageWidget::ViewerPageWidget() :
    ui(new Ui::ViewerPageWidget), mIndex(0), mImage(nullptr), mSelectionPen(QColor(0,255,230)),
    mCurrentSelection(nullptr), mAnnotationDrawer(&mGraphicsScene), mSelectedAnnotation(nullptr),
    mAlgorithmList(nullptr), mDataset(nullptr), mROIIsChosen(false), mZoomLevel(1.0)
{
    ui->setupUi(this);
    ui->mViewerListView->setResizeMode(QListView::Adjust);
    ui->mGraphicsView->setScene(&mGraphicsScene);
    ui->mViewerListView->setModel(&mModel);

    connect(ui->mViewerListView->selectionModel(), SIGNAL(currentChanged(const QModelIndex&, const QModelIndex&)), this,
        SLOT(selectionChanged(const QModelIndex&, const QModelIndex&)));
    connect(ui->mNextButton, SIGNAL(clicked()), this, SLOT(next()));
    connect(ui->mBeforeButton, SIGNAL(clicked()), this, SLOT(before()));
    connect(ui->mROIButton, SIGNAL(clicked()), this, SLOT(roiClicked()));
    connect(&mAnnotationDrawer, SIGNAL(selected(Annotation*, const QPointF&)), this, SLOT(annotationSelected(Annotation*, const QPointF&)));
    connect(ui->mZoomIn, SIGNAL(clicked()), this, SLOT(zoomIn()));
    connect(ui->mZoomOut, SIGNAL(clicked()), this, SLOT(zoomOut()));
    connect(ui->mGraphicsView, SIGNAL(zoomed(double)), this, SLOT(zoomed(double)));
    connect(ui->mGraphicsView, SIGNAL(resize()), this, SLOT(resize()));

    Q_INIT_RESOURCE(application);
    ui->mBeforeButton->setIcon(QIcon(":/before.png"));
    ui->mNextButton->setIcon(QIcon(":/next.png"));
}

/**
 * @brief ViewerPageWidget::~ViewerPageWidget Deletes the ViewerPageWidget.
 */
ViewerPageWidget::~ViewerPageWidget()
{
    delete ui;
}

/**
 * @brief ViewerPageWidget::resizeEvent Resizes the widget.
 * @param event The QResizeEvent.
 */
void ViewerPageWidget::resizeEvent(QResizeEvent *event) {
    resize();
}

/**
 * @brief ViewerPageWidget::resize Resizes the displayed Medium.
 */
void ViewerPageWidget::resize() {
    ui->mGraphicsView->fitInView(mImage, Qt::KeepAspectRatio);
    mZoomLevel = 1.0;
    ui->mZoom->setText("100 %");
}

/**
 * @brief ViewerPageWidget::zoomIn Zooms in the Medium.
 */
void ViewerPageWidget::zoomIn() {
    ui->mGraphicsView->scale(2,2);
    zoomed(2);
}

/**
 * @brief ViewerPageWidget::zoomOut Zooms the Medium out.
 */
void ViewerPageWidget::zoomOut() {
    ui->mGraphicsView->scale(0.5,0.5);
    zoomed(0.5);
}

void ViewerPageWidget::zoomed(double factor) {
    mZoomLevel *= factor;
    ui->mZoom->setText(QString::number(mZoomLevel*100) + " %");
}

/**
 * @brief ViewerPageWidget::annotationSelected Sets the selected annotation and shows a context menu to select an Algorithm.
 * @param annotation The selected Annotation.
 * @param pos The mouse position.
 */
void ViewerPageWidget::annotationSelected(Annotation* annotation, const QPointF& pos) {
    mSelectedAnnotation = annotation->copy();
    contextMenu(pos);
}

/**
 * @brief ViewerPageWidget::contextMenu Shows a context menu to select an Algorithm.
 * @param pos The mouse position.
 */
void ViewerPageWidget::contextMenu(const QPointF &pos) {
    SearchObject searchObject;
    searchObject.setMedium(getSearchMedium());
    if(mCurrentSelection != nullptr && mCurrentSelection->contains(pos)) {
        mROI = mCurrentSelection->rect().toRect();
        searchObject.setROI(mROI);
        searchObject.setType(SearchObject::Type::ROI);
    } else if(mSelectedAnnotation != nullptr) {
        searchObject.setAnnotation(mSelectedAnnotation);
        searchObject.setType(SearchObject::Type::ANNOTATION);
    } else {
        searchObject.setType(SearchObject::Type::MEDIUM);
    }
    searchObject.setSourceDataset(mDataset->getPath());
    mSearchQuery = std::make_shared<SearchQuery>();
    mSearchQuery->setSearchObject(searchObject);
    QList<QString> datasetList;
    datasetList.push_back(mDataset->getPath());
    mSearchQuery->setDatasets(datasetList);

    QList<Algorithm*> algoList = mAlgorithmList ? mAlgorithmList->findCompatibleAlgorithms(QList<DataPacket*>({mSearchQuery.get()})) : QList<Algorithm*>();

    QMenu contextMenu(this);
    if(algoList.isEmpty()) {
        QMessageBox msgBox(QMessageBox::Information, "", "Found no fitting algorithm.", QMessageBox::Ok, this);
        msgBox.exec();
        return;
    }
    switch(searchObject.getType()) {
        case SearchObject::Type::ROI:
            contextMenu.setTitle("ROI");
            break;
        case SearchObject::Type::ANNOTATION:
            contextMenu.setTitle("Annotation");
            break;
        case  SearchObject::Type::MEDIUM:
        default:
            contextMenu.setTitle("Medium");
    }
    for(Algorithm* iter: algoList) {
        mAlgorithms.insert(iter->getName(), iter);
        QAction* action = new QAction(iter->getName(), this);
        action->setToolTip(iter->getDescription());
        contextMenu.addAction(action);
    }
    connect(&contextMenu, SIGNAL(triggered(QAction*)), this, SLOT(nextWidget(QAction*)));
    connect(&contextMenu, SIGNAL(hovered(QAction*)), this, SLOT(showToolTip(QAction*)));
    contextMenu.exec(QCursor::pos());
}

/**
 * @brief ViewerPageWidget::showToolTip Shows tooltips for the algorithms.
 * @param action The QAction of the algorithm in the context menu.
 */
void ViewerPageWidget::showToolTip(QAction* action) {
    QToolTip::showText(QCursor::pos(), action->toolTip());
}

/**
 * @brief ViewerPageWidget::selectionChanged Updates the displayed Medium when the selection changed.
 * @param index The new QModelIndex.
 * @param previousIndex The previous QModelIndex.
 */
void ViewerPageWidget::selectionChanged(const QModelIndex &index, const QModelIndex &previousIndex) {
    mIndex = index.row();
    display();
}

/**
 * @brief ViewerPageWidget::next Shows the next Medium in the ListView.
 */
void ViewerPageWidget::next() {
    mIndex++;
    mIndex%=mDataset->getNumberOfMedia();
    ui->mViewerListView->selectionModel()->setCurrentIndex(mModel.index(mIndex), QItemSelectionModel::ClearAndSelect);
    display();
}

/**
 * @brief ViewerPageWidget::before Shows the Medium before in the ListView.
 */
void ViewerPageWidget::before() {
    if(mIndex <= 0) {
        mIndex = mDataset->getNumberOfMedia();
    }
    mIndex--;
    ui->mViewerListView->selectionModel()->setCurrentIndex(mModel.index(mIndex), QItemSelectionModel::ClearAndSelect);
    display();
}

/**
 * @brief ViewerPageWidget::display Displays a Medium.
 */
void ViewerPageWidget::display() {
    mZoomLevel = 1.0;
    ui->mZoom->setText("100 %");
}

/**
 * @brief ViewerPageWidget::reset Resets the ViewerPageWidget.
 */
void ViewerPageWidget::reset()
{
    QVariant var;
    emit readFromStack(0, var);
    if(var.canConvert<int>()){
        QVariant var2;
        emit readFromStack(-2, var2);
        if(var2.canConvert<std::shared_ptr<DatasetList>>()) {
            if(mDataset != nullptr) {
                delete mDataset;
            }
            mDataset = new Dataset(var2.value<std::shared_ptr<DatasetList>>()->getDatasetList().at(var.value<int>()));
            mModel.setDataset(*mDataset);
            mIndex = 0;
            if(mImage != nullptr) {
                delete mImage;
                mImage = nullptr;
            }
            if(mCurrentSelection != nullptr) {
                delete mCurrentSelection;
                mCurrentSelection = nullptr;
            }
            if(mSelectedAnnotation != nullptr) {
                delete mSelectedAnnotation;
                mSelectedAnnotation = nullptr;
            }

            display();
        }
    }

    QVariant algoListVariant;
    emit readFromStack(-1, algoListVariant);
    if(algoListVariant.canConvert<std::shared_ptr<AlgorithmList>>()){
        mAlgorithmList = algoListVariant.value<std::shared_ptr<AlgorithmList>>().get();
    } else {
        mAlgorithmList = nullptr;
    }
}

/**
 * @brief ViewerPageWidget::nextWidget Switches to the next widget.
 * @param action The QAction of the selected Algorithm.
 */
void ViewerPageWidget::nextWidget(QAction* action) {
    delete mDataset;
    mDataset = nullptr;
    delete mSelectedAnnotation;
    mSelectedAnnotation = nullptr;
    delete mCurrentSelection;
    mCurrentSelection = nullptr;
    delete mImage;
    mImage = nullptr;

    QVariant query;
    query.setValue(mSearchQuery);
    pushToStack(query);

    // todo: push actual, user-chosen algorithm
    QPointer<Algorithm> algo(mAlgorithms.value(action->text()));
    //std::shared_ptr<Algorithm> algo = std::make_shared<TestAlgorithm>("id123");
    QVariant varAlgo;
    varAlgo.setValue(algo);
    pushToStack(varAlgo);

    exit(EXIT_NEXT);
}

/**
 * @brief ViewerPageWidget::on_mGraphicsView_rubberBandChanged Selects a ROI.
 * @param viewportRect unused
 * @param fromScenePoint The starting point of the selection.
 * @param toScenePoint The ending point of the selection.
 */
void ViewerPageWidget::on_mGraphicsView_rubberBandChanged(const QRect &viewportRect, const QPointF &fromScenePoint,
                                                          const QPointF &toScenePoint)
{
    Q_UNUSED(viewportRect);
    if(mImage == nullptr) {
        return;
    }
    if(fromScenePoint.x() == 0 && fromScenePoint.y() == 0){
        if(mCurrentSelection != nullptr){
            mGraphicsScene.removeItem(mCurrentSelection);
            delete mCurrentSelection;
        }
        mCurrentSelection = mGraphicsScene.addRect(mCurrentRubberBand, mSelectionPen);
    } else {
        int width = mImage->boundingRect().width();
        int height = mImage->boundingRect().height();

        if(fromScenePoint.x() >= 0 && fromScenePoint.x() < width
                && fromScenePoint.y() >= 0 && fromScenePoint.y() < height) {
            mCurrentRubberBand.setLeft(fromScenePoint.x());
            mCurrentRubberBand.setTop(fromScenePoint.y());
            mCurrentRubberBand.setRight(toScenePoint.x());
            mCurrentRubberBand.setBottom(toScenePoint.y());

            if(toScenePoint.x() < 0)
                mCurrentRubberBand.setRight(0);
            if(toScenePoint.x() >= width)
                mCurrentRubberBand.setRight(width-1);
            if(toScenePoint.y() < 0)
                mCurrentRubberBand.setBottom(0);
            if(toScenePoint.y() >= height)
                mCurrentRubberBand.setBottom(height-1);
            mCurrentRubberBand = mCurrentRubberBand.normalized();
        }
    }
}

/**
 * @brief ViewerPageWidget::roiClicked En-/Disables the selection mode of a ROI, when the ROI button was clicked.
 */
void ViewerPageWidget::roiClicked() {
    if(!mROIIsChosen) {
        ui->mGraphicsView->setDragMode(QGraphicsView::DragMode::RubberBandDrag);
        ui->mROIButton->setText(tr("Bereich entfernen"));
        mROIIsChosen = true;
    } else {
        ui->mGraphicsView->setDragMode(QGraphicsView::DragMode::NoDrag);
        ui->mROIButton->setText(tr("Bereich auswählen"));
        mROIIsChosen = false;
        if(mCurrentSelection != nullptr) {
            mGraphicsScene.removeItem(mCurrentSelection);
            mCurrentSelection = nullptr;
            mCurrentRubberBand.setRect(0,0,0,0);
        }
    }
}

/**
 * @brief ViewerPageWidget::retranslateUi Translates the GUI.
 */
void ViewerPageWidget::retranslateUi() {
    if(mROIIsChosen) {
        ui->mROIButton->setText(tr("Bereich entfernen"));
    } else {
        ui->mROIButton->setText(tr("Bereich auswählen"));
    }
}

QString ViewerPageWidget::getName() {
    return tr("CoBaB - Viewer");
}

<|endoftext|>