//-----------------------------------------------------------------------------
//!
//-----------------------------------------------------------------------------
void tRadarSettingsMenuCommon::CreateActions()
{
    m_pTargetExpChkAct = new tAction( tr( "Target expansion" ), this );
    m_pTargetExpChkAct->setCheckable( true );
    m_pTargetExpChkAct->setChecked( m_pRadarDevice->TargetExpansion() != 0 );
    Connect(m_pTargetExpChkAct, SIGNAL(toggled(bool)), this, SLOT(OnTEChangeRequested(bool)));
    Connect(m_pRadarDevice, SIGNAL(TargetExpansionChanged(int)), this, SLOT(OnTEChanged(int)));

    QStringList trailOptions;
    trailOptions 
        << tr( "Off", "list item - radar trails" ) 
        << QString( "15 " + tr( "sec", "abbrev - seconds" )  )
        << QString( "30 " + tr( "sec", "abbrev - seconds" )  )
        << QString( "1 " + tr( "min", "abbrev - minute" )  )
        << QString( "3 " + tr( "min", "abbrev - minute" )  )
        << tr( "Continuous", "list item - radar trails" );
    m_pTrailsListAct = new tListAction( 
        tr( "Target trails", "button" ),
        trailOptions,
        m_pClientSettings->TargetTrailsValue(),
        Action::AutoShowPopup,
        this );
    Connect( m_pTrailsListAct, SIGNAL(ValueChanged(int)), m_pClientSettings, SLOT(SetTargetTrailsValue(int)));

    int colorScheme = m_pClientSettings->RadarCurrentColorScheme();

    QStringList dataPaletteOptions;
    dataPaletteOptions << "1" << "2" << "3" << "4";
    QList<QIcon> paletteIcons;
    paletteIcons
        << QIcon( tPath::ResourceFile( "radar/radar_black.png" ) )
        << QIcon( tPath::ResourceFile( "radar/radar_white.png" ) )
        << QIcon( tPath::ResourceFile( "radar/radar_green.png" ) )
        << QIcon( tPath::ResourceFile( "radar/radar_yellow.png" ) );

    m_pDataPaletteListAct = new tListAction( 
        tr( "Palette", "button" ),
        dataPaletteOptions,
        paletteIcons,
        colorScheme,
        Action::AutoShowPopup,
        this );
    Connect( m_pDataPaletteListAct, SIGNAL(ValueChanged(int)), this, SLOT(ColorSchemeChanged(int)));
    m_pDataPaletteListAct->SetIconSize( QSize( 100, 32 ) ); // the icon sizes are 100x32.

    QStringList orientationOptions;
    orientationOptions 
        << tr( "Heading up", "list item - radar orienation" ) 
        << tr( "North up", "list item - radar orienation" ) 
        << tr( "Course up", "list item - radar orienation" );
    m_pOrientationListAct = new tListAction( 
        tr( "Orientation", "button" ),
        orientationOptions,
        m_pClientSettings->RadarOrientationMode(),
        Action::AutoShowPopup,
        this );
    Connect( m_pOrientationListAct, SIGNAL(ValueChanged(int)), this, SLOT(OnOrientationChangeRequested(int)));
    Connect( m_pClientSettings, SIGNAL(RadarOrientationModeChanged(tRadarOrientationMode)), this, SLOT(OnOrientationChanged(tRadarOrientationMode)));

    m_pThresholdSliderAct = new tSliderAction(
        tr("Threshold", "button - radar sample level threshold"),
        0,
        100,
        m_pClientSettings->ThresholdPercent(),
        true,
        "%p%",
        this );
    m_pThresholdSliderAct->SetSingleStep( 10 );
    Connect( m_pThresholdSliderAct, SIGNAL(ValueChanged(int)), m_pClientSettings, SLOT(SetThresholdPercent(int)));

    m_pNorthMarkChkAct = new tAction( tr( "North indicator", "button - radar north indicator" ), this );
    m_pNorthMarkChkAct->setWhatsThis( HelpText( tr( "Shows the north indicator on the radar panel", "'What's this' help text" ),
                                                QString("<p>%1</p>").arg(BUTTON_HTML(tNOSStyle::FP_HelpImageNorthInd, "")) ) );


    m_pNorthMarkChkAct->setCheckable( true );
    m_pNorthMarkChkAct->setChecked( tRadarSettings::Instance()->NorthIndicatorEnabled() );
    Connect( m_pNorthMarkChkAct, SIGNAL(toggled(bool)), tRadarSettings::Instance(), SLOT(SetNorthIndicatorEnabled(bool)));
    Connect( tRadarSettings::Instance(), SIGNAL(NorthIndicatorEnabledChanged(bool)), m_pNorthMarkChkAct, SLOT(setChecked(bool)));

    m_pRangeRingsChkAct = new tAction( tr( "Range rings", "button - radar range rings" ), this );
    m_pRangeRingsChkAct->setWhatsThis( HelpText( tr( "Shows the range rings on the radar panel", "'What's this' help text" ),
                                                 QString("<p>%1</p>").arg(BUTTON_HTML(tNOSStyle::FP_HelpImageRangeRings, "") ) ) );
    m_pRangeRingsChkAct->setCheckable( true );
    m_pRangeRingsChkAct->setChecked( tRadarSettings::Instance()->RangeRingsEnabled() );
    Connect( m_pRangeRingsChkAct, SIGNAL(toggled(bool)), this, SLOT(OnRangeRingsChangeRequested(bool)));
    Connect( tRadarSettings::Instance(), SIGNAL(RangeRingsEnabledChanged(bool)), m_pRangeRingsChkAct, SLOT(setChecked(bool)));

    m_pRangeMarkersChkAct = new tAction( tr( "Range markers", "button - radar range markers" ), this );
    m_pRangeMarkersChkAct->setWhatsThis( HelpText( tr( "Shows the range markers on the radar panel", "'What's this' help text" ), 
                                                   QString("<p>%1</p>").arg(BUTTON_HTML(tNOSStyle::FP_HelpImageRangeMarkers, "") ) ) );
    m_pRangeMarkersChkAct->setCheckable( true );
    m_pRangeMarkersChkAct->setChecked( tRadarSettings::Instance()->RangeMarkersEnabled() );
    Connect( m_pRangeMarkersChkAct, SIGNAL(toggled(bool)), tRadarSettings::Instance(), SLOT(SetRangeMarkersEnabled(bool)));
    m_pRangeMarkersChkAct->setEnabled( tRadarSettings::Instance()->RangeRingsEnabled() );
    Connect( tRadarSettings::Instance(), SIGNAL(RangeMarkersEnabledChanged(bool)), m_pRangeMarkersChkAct, SLOT(setChecked(bool)));

    m_pCompassChkAct = new tAction( tr( "Compass", "button - radar compass" ), this );
    m_pCompassChkAct->setWhatsThis( HelpText( tr( "Shows the compass on the radar panel", "'What's this' help text" ),
                                              QString("<p>%1</p>").arg(BUTTON_HTML(tNOSStyle::FP_HelpImageCompass, "")) ) );
    m_pCompassChkAct->setCheckable( true );
    m_pCompassChkAct->setChecked( tRadarSettings::Instance()->CompassEnabled() );
    Connect( m_pCompassChkAct, SIGNAL(toggled(bool)), tRadarSettings::Instance(), SLOT(SetCompassEnabled(bool)));
    Connect( tRadarSettings::Instance(), SIGNAL(CompassEnabledChanged(bool)), m_pCompassChkAct, SLOT(setChecked(bool)));

    m_pHeadingLineChkAct = new tAction( tr( "Heading line", "button" ), this );
    m_pHeadingLineChkAct->setWhatsThis( HelpText( tr( "Shows the heading line on the radar panel", "'What's this' help text" ),
                                                  QString("<p>%1</p>").arg(BUTTON_HTML(tNOSStyle::FP_HelpImageHeadingLine, "")) ) );
    m_pHeadingLineChkAct->setCheckable( true );
    m_pHeadingLineChkAct->setChecked( tRadarSettings::Instance()->HeadingLineEnabled() );
    Connect( m_pHeadingLineChkAct, SIGNAL(toggled(bool)), tRadarSettings::Instance(), SLOT(SetHeadingLineEnabled(bool)) );

    QString trR = tr("R", "list item abbrev for relative (bearings) on radar max(1)" );
    QString trT = tr("T", "list item abbrev for true (bearings) on radar max(1)" );
    QString trM = tr("M", "abbrev for magnetic (bearings) on radar max(1)" );
    if( trR.size() > 1 )
        trR.truncate(1);
    if( trT.size() > 1 )
        trT.truncate(1);
    if( trM.size() > 1 )
        trM.truncate(1);
    
    QStringList bearingOptions;
    bearingOptions 
        << QString( "°" + trR )
        << QString( "°" + trT + "/°" + trM );
    m_pBearingListAct = new tListAction(
        tr( "Bearings", "button - radar bearings options" ),
        bearingOptions,
        tRadarSettings::Instance()->RadarAngleRef(),
        Action::AutoShowPopup,
        this );
    m_pBearingListAct->setWhatsThis( tr( "Controls whether bearings are displayed as an angle relative to this vessel's heading (°R), or as an absolute bearing (°T/°M)", "'What's this' help text" ) );
    Connect( m_pBearingListAct, SIGNAL(ValueChanged(int)), this, SLOT(OnAngleRefChangeRequested(int)));
    Connect( tRadarSettings::Instance(), SIGNAL(RadarAngleRefChanged(tRadarAngleRef)), this, SLOT(OnAngleRefChanged(tRadarAngleRef)));

    m_pInstallationAct = new tAction(
        QString(tr( "Installation", "button - radar installation dialog" ) + "..."),
        this );
    m_pInstallationAct->setWhatsThis( tr( "Shows controls for initial setting and calibration of the radar", "'What's this' help text" ) );
    Connect( m_pInstallationAct, SIGNAL(triggered()), this, SLOT(ShowInstallation()));

    ///////////////////////////////
    //MARPA Submenu
    ///////////////////////////////
    if ( tProductSettings::Instance().MARPAAllowed() )
    {
        QStringList historyLengthOptions;
        historyLengthOptions 
            << tr( "off", "list item - radar history length" ) 
            << tr( "30 secs", "list item - radar history length" ) 
            << tr( "1 min", "list item - radar history length" )
            << tr( "3 min", "list item - radar history length" )
            << tr( "6 min", "list item - radar history length" )
            << tr( "15 min", "list item - radar history length" )
            << tr( "30 min", "list item - radar history length" );
        m_pHistoryLengthListAct = new tListAction( 
            tr( "History length", "button" ),
            historyLengthOptions,
            tMarpaSettings::Instance()->HistoryLengthSecsIndex(),
            Action::AutoShowPopup,
            this );
        Connect( m_pHistoryLengthListAct, SIGNAL(ValueChanged(int)), this, SLOT(OnHistoryLengthChangeRequested(int)));

        QString cpaLabel = "%v " + tConvert::Instance()->GetUnitsString( UNITS_SMALL_DISTANCE );

        m_pSafeRingChkAct = new tAction( tr( "Safe ring", "button - radar range markers" ), this );
        m_pSafeRingChkAct->setCheckable( true );
        m_pSafeRingChkAct->setChecked( tMarpaSettings::Instance()->ShowSafeRing() );
        Connect( m_pSafeRingChkAct, SIGNAL(toggled(bool)), this, SLOT(OnSafeRingToggled(bool)));
    }
Example #2
0
QString Value::toString() const
{
    if (! isValid()) {
        return QLatin1String("nan");
    }

    // use C locale with out thousand-',' separators
    QLocale locale = QLocale::c();
    locale.setNumberOptions(QLocale::OmitGroupSeparator);
    QString number = locale.toString(m_value, 'f', 20);

    // TikZ doesn't allow commas as separator
    Q_ASSERT(! number.contains(QLatin1Char(',')));

    // allow only a single '.' as floating point separator
    Q_ASSERT(number.count(QLatin1Char('.')) <= 1);

    int dotIndex = number.indexOf(QLatin1Char('.'));

    // Rounding errors typically result in several consecutive '9' chars.
    // Catch this case and fix it to get a nice reacable number.
    int nineIndex;
    if ((nineIndex = number.indexOf(QLatin1String("099999"))) > dotIndex) {
        number.truncate(nineIndex + 1);
        number.replace(nineIndex, 1, "1");
    } else if ((nineIndex = number.indexOf(QLatin1String("199999"))) > dotIndex) {
        number.truncate(nineIndex + 1);
        number.replace(nineIndex, 1, "2");
    } else if ((nineIndex = number.indexOf(QLatin1String("299999"))) > dotIndex) {
        number.truncate(nineIndex + 1);
        number.replace(nineIndex, 1, "3");
    } else if ((nineIndex = number.indexOf(QLatin1String("399999"))) > dotIndex) {
        number.truncate(nineIndex + 1);
        number.replace(nineIndex, 1, "4");
    } else if ((nineIndex = number.indexOf(QLatin1String("499999"))) > dotIndex) {
        number.truncate(nineIndex + 1);
        number.replace(nineIndex, 1, "5");
    } else if ((nineIndex = number.indexOf(QLatin1String("599999"))) > dotIndex) {
        number.truncate(nineIndex + 1);
        number.replace(nineIndex, 1, "6");
    } else if ((nineIndex = number.indexOf(QLatin1String("699999"))) > dotIndex) {
        number.truncate(nineIndex + 1);
        number.replace(nineIndex, 1, "7");
    } else if ((nineIndex = number.indexOf(QLatin1String("799999"))) > dotIndex) {
        number.truncate(nineIndex + 1);
        number.replace(nineIndex, 1, "8");
    } else if ((nineIndex = number.indexOf(QLatin1String("899999"))) > dotIndex) {
        number.truncate(nineIndex + 1);
        number.replace(nineIndex, 1, "9");
    } else if ((nineIndex = number.indexOf(QLatin1String(".999999"))) == dotIndex) {
        number.truncate(nineIndex);
        number = QString::number(number.toInt() + 1);
        dotIndex = -1;
    }

    // we have 20 digits after the '.', which is usually too much.
    // Therefore, search for '00000' after the '.', and if we find these
    // 5 consecutive zeros, just kill the rest.
    // Example: the number 3.567 turns into 3.56700000000000017053. After
    //          the truncation, it'll be '3.5670000000'
    if (dotIndex >= 0) {
        const int indexOfZeros = number.lastIndexOf(QLatin1String("00000"));
        if (indexOfZeros > dotIndex) {
            number.truncate(indexOfZeros);
        }
    }

    // beautify step I: remove trailing zeros, e.g. 3.5670000000 -> 3.567
    while (dotIndex >= 0 && number.endsWith(QLatin1Char('0'))) {
        number.truncate(number.length() - 1);
    }

    // beautify step II: remove trailing dot, if applicable, e.g. 3. -> 3
    if (number.endsWith(QLatin1Char('.'))) {
        number.truncate(number.length() - 1);
    }

    QString suffix;
    switch (m_unit) {
        case Unit::Point: suffix = "pt"; break;
        case Unit::Millimeter: suffix = "mm"; break;
        case Unit::Centimeter: suffix = "cm"; break;
        case Unit::Inch: suffix = "in"; break;
        default: Q_ASSERT(false);
    }

    return number + suffix;
}
Example #3
0
static QString const settingsPath() {
	QString path = QSettings(QSettings::IniFormat, QSettings::UserScope,
		QCoreApplication::organizationName(), QCoreApplication::applicationName()).fileName();
	path.truncate(path.lastIndexOf('/'));
	return path;
}
void PlaylistItemDelegate::paintBody( QPainter* painter,
                                      const QStyleOptionViewItem& option,
                                      const QModelIndex& index ) const {
    painter->save();
    painter->translate( option.rect.topLeft() );

    QRect line(0, 0, option.rect.width(), option.rect.height());
    if (downloadInfo) line.setWidth(line.width() / 2);

    const bool isActive = index.data( ActiveTrackRole ).toBool();
    const bool isSelected = option.state & QStyle::State_Selected;

    // draw the "current track" highlight underneath the text
    if (isActive && !isSelected)
        paintActiveOverlay(painter, line);

    // get the video metadata
    const VideoPointer videoPointer = index.data( VideoRole ).value<VideoPointer>();
    const Video *video = videoPointer.data();

    // thumb
    painter->drawPixmap(0, 0, video->thumbnail());

    // play icon overlayed on the thumb
    if (isActive)
        painter->drawPixmap(playIcon.rect(), playIcon);

    // time
    if (video->duration() > 0)
        drawTime(painter, video->formattedDuration(), line);

    // separator
    painter->setPen(option.palette.color(QPalette::Midlight));
    painter->drawLine(THUMB_WIDTH, THUMB_HEIGHT, option.rect.width(), THUMB_HEIGHT);
    if (!video->thumbnail().isNull())
        painter->setPen(Qt::black);
    painter->drawLine(0, THUMB_HEIGHT, THUMB_WIDTH-1, THUMB_HEIGHT);

    if (line.width() > THUMB_WIDTH + 60) {

        // if (isActive) painter->setFont(boldFont);

        // text color
        if (isSelected)
            painter->setPen(QPen(option.palette.highlightedText(), 0));
        else
            painter->setPen(QPen(option.palette.text(), 0));

        // title
        QString videoTitle = video->title();
        QString v = videoTitle;
        const int flags = Qt::AlignTop | Qt::TextWordWrap;
        QRect textBox = line.adjusted(PADDING+THUMB_WIDTH, PADDING, 0, 0);
        textBox = painter->boundingRect(textBox, flags, v);
        while (textBox.height() > 55 && v.length() > 10) {
            videoTitle.truncate(videoTitle.length() - 1);
            v = videoTitle;
            v = v.trimmed().append("...");
            textBox = painter->boundingRect(textBox, flags, v);
        }
        painter->drawText(textBox, flags, v);

        painter->setFont(smallerFont);

        // published date
        QString publishedString = video->published().date().toString(Qt::DefaultLocaleShortDate);
        QSize stringSize(QFontMetrics(painter->font()).size( Qt::TextSingleLine, publishedString ) );
        QPoint textLoc(PADDING+THUMB_WIDTH, PADDING*2 + textBox.height());
        QRect publishedTextBox(textLoc , stringSize);
        painter->drawText(publishedTextBox, Qt::AlignLeft | Qt::AlignTop, publishedString);

        if (line.width() > publishedTextBox.x() + publishedTextBox.width()*2) {

            // author
            bool authorHovered = false;
            bool authorPressed = false;
            const bool isHovered = index.data(HoveredItemRole).toBool();
            if (isHovered) {
                authorHovered = index.data(AuthorHoveredRole).toBool();
                authorPressed = index.data(AuthorPressedRole).toBool();
            }

            painter->save();
            painter->setFont(smallerBoldFont);
            if (!isSelected) {
                if (authorHovered)
                    painter->setPen(QPen(option.palette.brush(QPalette::Highlight), 0));
                else
                    painter->setOpacity(.5);
            }
            QString authorString = video->channelTitle();
            textLoc.setX(textLoc.x() + stringSize.width() + PADDING);
            stringSize = QSize(QFontMetrics(painter->font()).size( Qt::TextSingleLine, authorString ) );
            QRect authorTextBox(textLoc , stringSize);
            authorRects.insert(index.row(), authorTextBox);
            painter->drawText(authorTextBox, Qt::AlignLeft | Qt::AlignTop, authorString);
            painter->restore();

            if (line.width() > authorTextBox.x() + 50) {

                // view count
                if (video->viewCount() >= 0) {
                    QLocale locale;
                    QString viewCountString = tr("%1 views").arg(locale.toString(video->viewCount()));
                    textLoc.setX(textLoc.x() + stringSize.width() + PADDING);
                    stringSize = QSize(QFontMetrics(painter->font()).size( Qt::TextSingleLine, viewCountString ) );
                    QRect viewCountTextBox(textLoc , stringSize);
                    painter->drawText(viewCountTextBox, Qt::AlignLeft | Qt::AlignBottom, viewCountString);
                }

                if (downloadInfo) {
                    const QString definitionString = VideoDefinition::getDefinitionFor(video->getDefinitionCode()).getName();
                    textLoc.setX(textLoc.x() + stringSize.width() + PADDING);
                    stringSize = QSize(QFontMetrics(painter->font()).size( Qt::TextSingleLine, definitionString ) );
                    QRect viewCountTextBox(textLoc , stringSize);
                    painter->drawText(viewCountTextBox, Qt::AlignLeft | Qt::AlignBottom, definitionString);
                }

            }

        }

    } else {

        const bool isHovered = index.data(HoveredItemRole).toBool();
        if (!isActive && isHovered) {
            painter->setFont(smallerFont);
            painter->setPen(Qt::white);
            QString videoTitle = video->title();
            QString v = videoTitle;
            const int flags = Qt::AlignTop | Qt::TextWordWrap;
            QRect textBox(PADDING, PADDING, THUMB_WIDTH - PADDING*2, THUMB_HEIGHT - PADDING*2);
            textBox = painter->boundingRect(textBox, flags, v);
            while (textBox.height() > THUMB_HEIGHT && v.length() > 10) {
                videoTitle.truncate(videoTitle.length() - 1);
                v = videoTitle;
                v = v.trimmed().append("...");
                textBox = painter->boundingRect(textBox, flags, v);
            }
            painter->fillRect(QRect(0, 0, THUMB_WIDTH, textBox.height() + PADDING*2), QColor(0, 0, 0, 128));
            painter->drawText(textBox, flags, v);
        }

    }

    painter->restore();

    if (downloadInfo) paintDownloadInfo(painter, option, index);

}
Example #5
0
static inline QString removeTrailingSlash(QString path)
{
    Q_ASSERT(path.endsWith(QLatin1Char('/')));
    path.truncate(path.length()-1);
    return path;
}
Example #6
0
static void myth_av_log(void *ptr, int level, const char* fmt, va_list vl)
{
    if (VERBOSE_LEVEL_NONE)
        return;

    static QString full_line("");
    static const int msg_len = 255;
    static QMutex string_lock;
    uint64_t   verbose_mask  = VB_GENERAL;
    LogLevel_t verbose_level = LOG_DEBUG;

    // determine mythtv debug level from av log level
    switch (level)
    {
        case AV_LOG_PANIC:
            verbose_level = LOG_EMERG;
            break;
        case AV_LOG_FATAL:
            verbose_level = LOG_CRIT;
            break;
        case AV_LOG_ERROR:
            verbose_level = LOG_ERR;
            verbose_mask |= VB_LIBAV;
            break;
        case AV_LOG_DEBUG:
        case AV_LOG_VERBOSE:
        case AV_LOG_INFO:
            verbose_level = LOG_DEBUG;
            verbose_mask |= VB_LIBAV;
            break;
        case AV_LOG_WARNING:
            verbose_mask |= VB_LIBAV;
            break;
        default:
            return;
    }

    if (!VERBOSE_LEVEL_CHECK(verbose_mask, verbose_level))
        return;

    string_lock.lock();
    if (full_line.isEmpty() && ptr) {
        AVClass* avc = *(AVClass**)ptr;
        full_line.sprintf("[%s @ %p] ", avc->item_name(ptr), avc);
    }

    char str[msg_len+1];
    int bytes = vsnprintf(str, msg_len+1, fmt, vl);

    // check for truncated messages and fix them
    if (bytes > msg_len)
    {
        LOG(VB_GENERAL, LOG_WARNING,
            QString("Libav log output truncated %1 of %2 bytes written")
                .arg(msg_len).arg(bytes));
        str[msg_len-1] = '\n';
    }

    full_line += QString(str);
    if (full_line.endsWith("\n"))
    {
        LOG(verbose_mask, verbose_level, full_line.trimmed());
        full_line.truncate(0);
    }
    string_lock.unlock();
}
Example #7
0
void PathChooser::slotBrowse()
{
    emit beforeBrowsing();

    QString predefined = path();
    QFileInfo fi(predefined);

    if (!predefined.isEmpty() && !fi.isDir()) {
        predefined = fi.path();
        fi.setFile(predefined);
    }

    if ((predefined.isEmpty() || !fi.isDir())
            && !d->m_initialBrowsePathOverride.isNull()) {
        predefined = d->m_initialBrowsePathOverride;
        fi.setFile(predefined);
        if (!fi.isDir()) {
            predefined.clear();
            fi.setFile(QString());
        }
    }

    // Prompt for a file/dir
    QString newPath;
    switch (d->m_acceptingKind) {
    case PathChooser::Directory:
    case PathChooser::ExistingDirectory:
        newPath = QFileDialog::getExistingDirectory(this,
                makeDialogTitle(tr("Choose Directory")), predefined);
        break;
    case PathChooser::ExistingCommand:
    case PathChooser::Command:
        newPath = QFileDialog::getOpenFileName(this,
                makeDialogTitle(tr("Choose Executable")), predefined,
                d->m_dialogFilter);
        newPath = appBundleExpandedPath(newPath);
        break;
    case PathChooser::File: // fall through
        newPath = QFileDialog::getOpenFileName(this,
                makeDialogTitle(tr("Choose File")), predefined,
                d->m_dialogFilter);
        newPath = appBundleExpandedPath(newPath);
        break;
    case PathChooser::SaveFile:
        newPath = QFileDialog::getSaveFileName(this,
                makeDialogTitle(tr("Choose File")), predefined,
                d->m_dialogFilter);
        break;
    case PathChooser::Any: {
        QFileDialog dialog(this);
        dialog.setFileMode(QFileDialog::AnyFile);
        dialog.setWindowTitle(makeDialogTitle(tr("Choose File")));
        if (fi.exists())
            dialog.setDirectory(fi.absolutePath());
        // FIXME: fix QFileDialog so that it filters properly: lib*.a
        dialog.setNameFilter(d->m_dialogFilter);
        if (dialog.exec() == QDialog::Accepted) {
            // probably loop here until the *.framework dir match
            QStringList paths = dialog.selectedFiles();
            if (!paths.isEmpty())
                newPath = paths.at(0);
        }
        break;
        }

    default:
        break;
    }

    // Delete trailing slashes unless it is "/"|"\\", only
    if (!newPath.isEmpty()) {
        newPath = QDir::toNativeSeparators(newPath);
        if (newPath.size() > 1 && newPath.endsWith(QDir::separator()))
            newPath.truncate(newPath.size() - 1);
        setPath(newPath);
    }

    emit browsingFinished();
    triggerChanged();
}
Example #8
0
void ProgDetails::loadPage(void)
{
    MSqlQuery query(MSqlQuery::InitCon());
    QString category_type, showtype, year, syndicatedEpisodeNum;
    QString rating, colorcode, title_pronounce;
    float stars = 0.0;
    int partnumber = 0, parttotal = 0;
    int audioprop = 0, videoprop = 0, subtype = 0, generic = 0;
    bool recorded = false;

    RecordingRule* record = nullptr;
    if (m_progInfo.GetRecordingRuleID())
    {
        record = new RecordingRule();
        record->LoadByProgram(&m_progInfo);
    }

    if (m_progInfo.GetFilesize())
        recorded = true;

    QString ptable = recorded ? "recordedprogram" : "program";

    if (m_progInfo.GetScheduledEndTime() != m_progInfo.GetScheduledStartTime())
    {
        query.prepare(QString("SELECT category_type, airdate, stars,"
                      " partnumber, parttotal, audioprop+0, videoprop+0,"
                      " subtitletypes+0, syndicatedepisodenumber, generic,"
                      " showtype, colorcode, title_pronounce"
                      " FROM %1 WHERE chanid = :CHANID AND"
                      " starttime = :STARTTIME ;").arg(ptable));

        query.bindValue(":CHANID",    m_progInfo.GetChanID());
        query.bindValue(":STARTTIME", m_progInfo.GetScheduledStartTime());

        if (query.exec() && query.next())
        {
            category_type = query.value(0).toString();
            year = query.value(1).toString();
            stars = query.value(2).toFloat();
            partnumber = query.value(3).toInt();
            parttotal = query.value(4).toInt();
            audioprop = query.value(5).toInt();
            videoprop = query.value(6).toInt();
            subtype = query.value(7).toInt();
            syndicatedEpisodeNum = query.value(8).toString();
            generic = query.value(9).toInt();
            showtype = query.value(10).toString();
            colorcode = query.value(11).toString();
            title_pronounce = query.value(12).toString();
        }
        else if (!query.isActive())
            MythDB::DBError("ProgDetails", query);

        rating = getRatings(
            recorded, m_progInfo.GetChanID(),
            m_progInfo.GetScheduledStartTime());
    }

    if (category_type.isEmpty() && !m_progInfo.GetProgramID().isEmpty())
    {
        QString prefix = m_progInfo.GetProgramID().left(2);

        if (prefix == "MV")
           category_type = "movie";
        else if (prefix == "EP")
           category_type = "series";
        else if (prefix == "SP")
           category_type = "sports";
        else if (prefix == "SH")
           category_type = "tvshow";
    }

    addItem(tr("Title"),
            m_progInfo.toString(ProgramInfo::kTitleSubtitle, " - "),
            ProgInfoList::kLevel1);

    addItem(tr("Title Pronounce"), title_pronounce, ProgInfoList::kLevel2);

    QString s = m_progInfo.GetDescription();

    QString attr;

    if (partnumber > 0)
        attr += tr("Part %1 of %2, ").arg(partnumber).arg(parttotal);

    if (!rating.isEmpty() && rating != "NR")
        attr += rating + ", ";
    if (category_type == "movie")
    {
        if (!year.isEmpty())
            attr += year + ", ";

    /* see #7810, was hardcoded to 4 star system, when every theme
     * uses 10 stars / 5 stars with half stars
     */
        if (stars > 0.0f)
            attr += tr("%n star(s)", "", roundf(stars * 10.0f)) + ", ";
    }
    if (!colorcode.isEmpty())
        attr += colorcode + ", ";

    if (audioprop & AUD_MONO)
        attr += tr("Mono") + ", ";
    if (audioprop & AUD_STEREO)
        attr += tr("Stereo") + ", ";
    if (audioprop & AUD_SURROUND)
        attr += tr("Surround Sound") + ", ";
    if (audioprop & AUD_DOLBY)
        attr += tr("Dolby Sound") + ", ";
    if (audioprop & AUD_HARDHEAR)
        attr += tr("Audio for Hearing Impaired") + ", ";
    if (audioprop & AUD_VISUALIMPAIR)
        attr += tr("Audio for Visually Impaired") + ", ";

    if (videoprop & VID_HDTV)
        attr += tr("HDTV") + ", ";
    if  (videoprop & VID_WIDESCREEN)
        attr += tr("Widescreen") + ", ";
    if  (videoprop & VID_AVC)
        attr += tr("AVC/H.264") + ", ";
    if  (videoprop & VID_720)
        attr += tr("720p Resolution") + ", ";
    if  (videoprop & VID_1080)
        attr += tr("1080i/p Resolution") + ", ";
    if  (videoprop & VID_DAMAGED)
        attr += tr("Damaged") + ", ";

    if (subtype & SUB_HARDHEAR)
        attr += tr("CC","Closed Captioned") + ", ";
    if (subtype & SUB_NORMAL)
        attr += tr("Subtitles Available") + ", ";
    if (subtype & SUB_ONSCREEN)
        attr += tr("Subtitled") + ", ";
    if (subtype & SUB_SIGNED)
        attr += tr("Deaf Signing") + ", ";

    if (generic && category_type == "series")
        attr += tr("Unidentified Episode") + ", ";
    else if (m_progInfo.IsRepeat())
        attr += tr("Repeat") + ", ";

    if (!attr.isEmpty())
    {
        attr.truncate(attr.lastIndexOf(','));
        s += " (" + attr + ")";
    }

    addItem(tr("Description"), s, ProgInfoList::kLevel1);

    QString actors, directors, producers, execProducers;
    QString writers, guestStars, hosts, adapters;
    QString presenters, commentators, guests;

    if (m_progInfo.GetScheduledEndTime() != m_progInfo.GetScheduledStartTime())
    {
        if (recorded)
            query.prepare("SELECT role,people.name FROM recordedcredits"
                          " AS credits"
                          " LEFT JOIN people ON credits.person = people.person"
                          " WHERE credits.chanid = :CHANID"
                          " AND credits.starttime = :STARTTIME"
                          " ORDER BY role;");
        else
            query.prepare("SELECT role,people.name FROM credits"
                          " LEFT JOIN people ON credits.person = people.person"
                          " WHERE credits.chanid = :CHANID"
                          " AND credits.starttime = :STARTTIME"
                          " ORDER BY role;");
        query.bindValue(":CHANID",    m_progInfo.GetChanID());
        query.bindValue(":STARTTIME", m_progInfo.GetScheduledStartTime());

        if (query.exec() && query.size() > 0)
        {
            QStringList plist;
            QString rstr, role, pname;

            while(query.next())
            {
                role = query.value(0).toString();
                /* The people.name column uses utf8_bin collation.
                 * Qt-MySQL drivers use QVariant::ByteArray for string-type
                 * MySQL fields marked with the BINARY attribute (those using a
                 * *_bin collation) and QVariant::String for all others.
                 * Since QVariant::toString() uses QString::fromAscii()
                 * (through QVariant::convert()) when the QVariant's type is
                 * QVariant::ByteArray, we have to use QString::fromUtf8()
                 * explicitly to prevent corrupting characters.
                 * The following code should be changed to use the simpler
                 * toString() approach, as above, if we do a DB update to
                 * coalesce the people.name values that differ only in case and
                 * change the collation to utf8_general_ci, to match the
                 * majority of other columns, or we'll have the same problem in
                 * reverse.
                 */
                pname = QString::fromUtf8(query.value(1)
                                          .toByteArray().constData());

                if (rstr != role)
                {
                    if (rstr == "actor")
                        actors = plist.join(", ");
                    else if (rstr == "director")
                        directors = plist.join(", ");
                    else if (rstr == "producer")
                        producers = plist.join(", ");
                    else if (rstr == "executive_producer")
                        execProducers = plist.join(", ");
                    else if (rstr == "writer")
                        writers = plist.join(", ");
                    else if (rstr == "guest_star")
                        guestStars = plist.join(", ");
                    else if (rstr == "host")
                        hosts = plist.join(", ");
                    else if (rstr == "adapter")
                        adapters = plist.join(", ");
                    else if (rstr == "presenter")
                        presenters = plist.join(", ");
                    else if (rstr == "commentator")
                        commentators = plist.join(", ");
                    else if (rstr == "guest")
                        guests =  plist.join(", ");

                    rstr = role;
                    plist.clear();
                }

                plist.append(pname);
            }
            if (rstr == "actor")
                actors = plist.join(", ");
            else if (rstr == "director")
                directors = plist.join(", ");
            else if (rstr == "producer")
                producers = plist.join(", ");
            else if (rstr == "executive_producer")
                execProducers = plist.join(", ");
            else if (rstr == "writer")
                writers = plist.join(", ");
            else if (rstr == "guest_star")
                guestStars = plist.join(", ");
            else if (rstr == "host")
                hosts = plist.join(", ");
            else if (rstr == "adapter")
                adapters = plist.join(", ");
            else if (rstr == "presenter")
                presenters = plist.join(", ");
            else if (rstr == "commentator")
                commentators = plist.join(", ");
            else if (rstr == "guest")
                guests =  plist.join(", ");
        }
    }
    addItem(tr("Actors"), actors, ProgInfoList::kLevel1);
    addItem(tr("Guest Star"), guestStars, ProgInfoList::kLevel1);
    addItem(tr("Guest"), guests, ProgInfoList::kLevel1);
    addItem(tr("Host"), hosts, ProgInfoList::kLevel1);
    addItem(tr("Presenter"), presenters, ProgInfoList::kLevel1);
    addItem(tr("Commentator"), commentators, ProgInfoList::kLevel1);
    addItem(tr("Director"), directors, ProgInfoList::kLevel1);
    addItem(tr("Producer"), producers, ProgInfoList::kLevel2);
    addItem(tr("Executive Producer"), execProducers, ProgInfoList::kLevel2);
    addItem(tr("Writer"), writers, ProgInfoList::kLevel2);
    addItem(tr("Adapter"), adapters, ProgInfoList::kLevel2);

    addItem(tr("Category"), m_progInfo.GetCategory(), ProgInfoList::kLevel1);

    query.prepare("SELECT genre FROM programgenres "
                  "WHERE chanid = :CHANID AND starttime = :STARTTIME "
                  "AND relevance > 0 ORDER BY relevance;");
    query.bindValue(":CHANID",    m_progInfo.GetChanID());
    query.bindValue(":STARTTIME", m_progInfo.GetScheduledStartTime());

    if (query.exec())
    {
        s.clear();
        while (query.next())
        {
            if (!s.isEmpty())
                s += ", ";
            s += query.value(0).toString();
        }
        addItem(tr("Genre"), s, ProgInfoList::kLevel1);
    }

    s.clear();
    if (!category_type.isEmpty())
    {
        s = category_type;
        if (!m_progInfo.GetSeriesID().isEmpty())
            s += "  (" + m_progInfo.GetSeriesID() + ")";
        if (!showtype.isEmpty())
            s += "  " + showtype;
    }
    addItem(tr("Type", "category_type"), s, ProgInfoList::kLevel1);

    s.clear();
    if (m_progInfo.GetSeason() > 0)
        s = QString::number(m_progInfo.GetSeason());
    addItem(tr("Season"), s, ProgInfoList::kLevel1);

    s.clear();
    if (m_progInfo.GetEpisode() > 0)
    {
        if (m_progInfo.GetEpisodeTotal() > 0)
            s = tr("%1 of %2").arg(m_progInfo.GetEpisode())
                              .arg(m_progInfo.GetEpisodeTotal());
        else
            s = QString::number(m_progInfo.GetEpisode());

    }
    addItem(tr("Episode"), s, ProgInfoList::kLevel1);

    addItem(tr("Syndicated Episode Number"), syndicatedEpisodeNum,
            ProgInfoList::kLevel1);

    s.clear();
    if (m_progInfo.GetOriginalAirDate().isValid() &&
        category_type != "movie")
    {
        s = MythDate::toString(m_progInfo.GetOriginalAirDate(),
                               MythDate::kDateFull | MythDate::kAddYear);
    }
    addItem(tr("Original Airdate"), s, ProgInfoList::kLevel1);

    addItem(tr("Program ID"), m_progInfo.GetProgramID(), ProgInfoList::kLevel1);

    // Begin MythTV information not found in the listings info
    QDateTime statusDate;
    if (m_progInfo.GetRecordingStatus() == RecStatus::WillRecord ||
        m_progInfo.GetRecordingStatus() == RecStatus::Pending)
        statusDate = m_progInfo.GetScheduledStartTime();

    RecordingType rectype = kSingleRecord; // avoid kNotRecording
    RecStatus::Type recstatus = m_progInfo.GetRecordingStatus();

    if (recstatus == RecStatus::PreviousRecording ||
        recstatus == RecStatus::NeverRecord ||
        recstatus == RecStatus::Unknown)
    {
        query.prepare("SELECT recstatus, starttime "
                      "FROM oldrecorded WHERE duplicate > 0 AND "
                      "future = 0 AND "
                      "((programid <> '' AND programid = :PROGRAMID) OR "
                      " (title <> '' AND title = :TITLE AND "
                      "  subtitle <> '' AND subtitle = :SUBTITLE AND "
                      "  description <> '' AND description = :DECRIPTION));");

        query.bindValue(":PROGRAMID",  m_progInfo.GetProgramID());
        query.bindValue(":TITLE",      m_progInfo.GetTitle());
        query.bindValue(":SUBTITLE",   m_progInfo.GetSubtitle());
        query.bindValue(":DECRIPTION", m_progInfo.GetDescription());

        if (!query.exec())
        {
            MythDB::DBError("showDetails", query);
        }
        else if (query.next())
        {
            if (recstatus == RecStatus::Unknown)
                recstatus = RecStatus::Type(query.value(0).toInt());

            if (recstatus == RecStatus::PreviousRecording ||
                recstatus == RecStatus::NeverRecord ||
                recstatus == RecStatus::Recorded)
            {
                statusDate = MythDate::as_utc(query.value(1).toDateTime());
            }
        }
    }

    if (recstatus == RecStatus::Unknown)
    {
        if (recorded)
        {
            recstatus = RecStatus::Recorded;
            statusDate = m_progInfo.GetScheduledStartTime();
        }
        else
        {
            // re-enable "Not Recording" status text
            rectype = m_progInfo.GetRecordingRuleType();
        }
    }

    s = RecStatus::toString(recstatus, rectype);

    if (statusDate.isValid())
        s += " " + MythDate::toString(statusDate, MythDate::kDateFull |
                                      MythDate::kAddYear);

    addItem(tr("MythTV Status"), s, ProgInfoList::kLevel1);

    QString recordingRule;
    QString lastRecorded;
    QString nextRecording;
    QString averageTimeShift;
    QString watchListScore;
    QString watchListStatus;
    QString searchPhrase;

    if (m_progInfo.GetRecordingRuleID())
    {
        recordingRule = QString("%1, ").arg(m_progInfo.GetRecordingRuleID());
        if (m_progInfo.GetRecordingRuleType() != kNotRecording)
            recordingRule += toString(m_progInfo.GetRecordingRuleType());
        if (!(record->m_title.isEmpty()))
            recordingRule += QString(" \"%2\"").arg(record->m_title);

        query.prepare("SELECT last_record, next_record, avg_delay "
                      "FROM record WHERE recordid = :RECORDID");
        query.bindValue(":RECORDID", m_progInfo.GetRecordingRuleID());

        if (query.exec() && query.next())
        {
            if (query.value(0).toDateTime().isValid())
                lastRecorded = MythDate::toString(
                    MythDate::as_utc(query.value(0).toDateTime()),
                    MythDate::kDateFull | MythDate::kAddYear);
            if (query.value(1).toDateTime().isValid())
                nextRecording = MythDate::toString(
                    MythDate::as_utc(query.value(1).toDateTime()),
                    MythDate::kDateFull | MythDate::kAddYear);
            if (query.value(2).toInt() > 0)
                averageTimeShift = tr("%n hour(s)", "",
                                                query.value(2).toInt());
        }
        if (recorded)
        {
            if (m_progInfo.GetRecordingPriority2() > 0)
                watchListScore =
                    QString::number(m_progInfo.GetRecordingPriority2());

            if (m_progInfo.GetRecordingPriority2() < 0)
            {
                switch (m_progInfo.GetRecordingPriority2())
                {
                    case wlExpireOff:
                        watchListStatus = tr("Auto-expire off");
                        break;
                    case wlWatched:
                        watchListStatus = tr("Marked as 'watched'");
                        break;
                    case wlEarlier:
                        watchListStatus = tr("Not the earliest episode");
                        break;
                    case wlDeleted:
                        watchListStatus = tr("Recently deleted episode");
                        break;
                }
            }
        }
        if (record->m_searchType != kManualSearch &&
            record->m_description != m_progInfo.GetDescription())
            searchPhrase = record->m_description;
    }
    addItem(tr("Recording Rule"), recordingRule, ProgInfoList::kLevel1);
    addItem(tr("Search Phrase"), searchPhrase, ProgInfoList::kLevel1);

    s.clear();
    if (m_progInfo.GetFindID())
    {
        QDateTime fdate(QDate(1970, 1, 1),QTime(12,0,0));
        fdate = fdate.addDays((int)m_progInfo.GetFindID() - 719528);
        s = QString("%1 (%2)").arg(m_progInfo.GetFindID())
            .arg(MythDate::toString(
                     fdate, MythDate::kDateFull | MythDate::kAddYear));
    }
    addItem(tr("Find ID"), s, ProgInfoList::kLevel2);

    addItem(tr("Last Recorded"), lastRecorded, ProgInfoList::kLevel2);
    addItem(tr("Next Recording"), nextRecording, ProgInfoList::kLevel2);
    addItem(tr("Average Time Shift"), averageTimeShift, ProgInfoList::kLevel2);
    addItem(tr("Watch List Score"), watchListScore, ProgInfoList::kLevel2);
    addItem(tr("Watch List Status"), watchListStatus, ProgInfoList::kLevel2);

    QString recordingHost;
    QString recordingInput;
    QString recordedFilename;
    QString recordedFileSize;
    QString recordingGroup;
    QString storageGroup;
    QString playbackGroup;
    QString recordingProfile;

    recordingHost = m_progInfo.GetHostname();
    recordingInput = m_progInfo.GetInputName();

    if (recorded)
    {
        recordedFilename = m_progInfo.GetBasename();
        recordedFileSize = QString("%1 ")
            .arg(m_progInfo.GetFilesize()/((double)(1<<30)),0,'f',2);
        recordedFileSize += tr("GB", "GigaBytes");

        query.prepare("SELECT profile FROM recorded"
                      " WHERE chanid = :CHANID"
                      " AND starttime = :STARTTIME;");
        query.bindValue(":CHANID",    m_progInfo.GetChanID());
        query.bindValue(":STARTTIME", m_progInfo.GetRecordingStartTime());

        if (query.exec() && query.next())
        {
            recordingProfile = m_progInfo.i18n(query.value(0).toString());
        }
        recordingGroup = m_progInfo.i18n(m_progInfo.GetRecordingGroup());
        storageGroup   = m_progInfo.i18n(m_progInfo.GetStorageGroup());
        playbackGroup  = m_progInfo.i18n(m_progInfo.GetPlaybackGroup());
    }
    else if (m_progInfo.GetRecordingRuleID())
    {
        recordingProfile =  record->m_recProfile;
    }
    addItem(tr("Recording Host"), recordingHost, ProgInfoList::kLevel2);
    addItem(tr("Recording Input"), recordingInput, ProgInfoList::kLevel2);
    addItem(tr("Recorded File Name"), recordedFilename, ProgInfoList::kLevel1);
    addItem(tr("Recorded File Size"), recordedFileSize, ProgInfoList::kLevel1);
    addItem(tr("Recording Profile"), recordingProfile, ProgInfoList::kLevel2);
    addItem(tr("Recording Group"), recordingGroup, ProgInfoList::kLevel1);
    addItem(tr("Storage Group"), storageGroup, ProgInfoList::kLevel2);
    addItem(tr("Playback Group"),  playbackGroup, ProgInfoList::kLevel2);

    PowerPriorities(ptable);

    delete record;
}
Example #9
0
collectedSCProjects& wcsClient::parse(QString file)
{
	collectedSCProjects* jobs = new collectedSCProjects;
	QFile infile(file);
	//	int startFrame, endFrame, frameInterval;
	QString line;
	QString summaryStream;
	QString JobNameTemp, CamNameTemp, OptNameTemp;
	int JobEnabledTemp, FrameIntervalTemp, StartFrameTemp, EndFrameTemp;
	int WidthTemp, HeightTemp, SegmentsTemp, JobPriTemp;
	double JobFrameRateTemp, StartTimeTemp, EndTimeTemp;
	QTextStream* summary;
	QString piece;
	char *temp;
	unsigned long size;
	bool *ok, swapped;
	int version, revision;

	ok = new bool;
	if(infile.open(IO_ReadOnly))
	{
		QTextStream info(&infile);
		
		//reads in the first 8 bytes as first file format checking method
		temp = new char[8];
		info.readRawBytes(temp, 8);
		line.sprintf(temp);
		line.truncate(8);
		
		//if the first 8 bytes of the file are not the string
		//"WCS File" then the format is incorrect and 2 is returned
		if(line != "WCS File")
		{
			infile.close();
			return *jobs;
		}
		
		
		delete [] temp;
		line.truncate(0);
		
		//takes in the file version and revision bytes
		temp = new char[2];
		info.readRawBytes(temp, 2);
		
		version = temp[0];
		revision = temp[1];
		
		if(version < 4) {
			infile.close();
			// return 5;
			return *jobs;
		}
		
		delete [] temp;
		line.truncate(0);
		
		//reads in the 4 byte, byte swapping constant
		//if no swapping occurs, the value will be 0xaabbccdd
		temp = new char[4];
		info.readRawBytes(temp, 4);
		getSize(temp, size);
		
		
		//checks the byteswapping of the system
		//if the bytes are not swapped, then swapped = false
		//if the bytes are Endian swapped, then swapped is true
		//if the bytes are neither, 3 is returned as error message
		if(size == 0xaabbccdd)
		{
			swapped = false;
		}
		else if(size == 0xddccbbaa)
		{
			swapped = true;
		}
		else
		{
			infile.close();
			// return 3;
			return *jobs;
		}
		
		delete [] temp;
		line.truncate(0);
		
		
		//takes in the name of the first chunk
		temp = new char[8];
		info.readRawBytes(temp, 8);
		line.sprintf(temp);
		line.truncate(8);
		
		delete [] temp;
		
		//goes through the chunks until the summary chunk is found
		while(line != "Summary\0" && !info.atEnd())
		{
			temp = new char[4];
			info.readRawBytes(temp, 4);
			getSize(temp, size);
			if(swapped == true)
				byteSwap(size);
			
			goToNextChunk(info, size);
			
			delete [] temp;
			line.truncate(0);
			
			temp = new char[8];
			info.readRawBytes(temp, 8);
			line.sprintf(temp);
			line.truncate(8);
			
			
			if((line == "ÍÍÍÍÍÍÍÍ") || (info.atEnd())) {
				infile.close();
				// return 4;
			    return *jobs;
			}
			
			delete [] temp;
		}
		
		line.truncate(0);
		
		temp = new char[4];                     //reads in size of Summary
		info.readRawBytes(temp, 4);             //not necessary to save
		getSize(temp, size);					//get the size of the summary chunk
		delete [] temp;
		temp = new char[size];					// reallocate temp to hold whole array
		info.readRawBytes(temp, size);			// read the whole summary chunk into temp
		summaryStream = temp;					// make a string from the summary
		summary = new QTextStream(&summaryStream, IO_ReadOnly);
		
		// we need to parse according to value, not simply order
		// set a loop here, parse the lines, evaluate according to
		// their value
		// line = QString, info = QTextStream
		line = summary->readLine();
		// this first loop reads in all the options lines, deals with what they have
		while (line != "") {
			// we got a new line
			line = summary->readLine();
			// now figure out what is in it (no endline on string)
			// if the line is empty (but not null) then it is the break between the
			// two "sections", so just get the next two lines after that
		}
		// Now read one or more lines.  Parse the
		// project data, including things like frames, size, etc.
		// put them into the "incoming" parameters
		// int& startFrame, int& endFrame, int& frameInterval, int& port, QString &job
		
		// when we hit a blank line we're done
		for(line = summary->readLine(); line != "";) {
			int ThisField = 0;
			piece = line.section(",", ThisField, ThisField);
			JobNameTemp = piece.section("\"", 1, 1);
			ThisField++;
			
			piece = line.section(",", ThisField, ThisField);
			CamNameTemp = piece.section("\"", 1, 1);
			ThisField++;
			
			piece = line.section(",", ThisField, ThisField);
			OptNameTemp = piece.section("\"", 1, 1);
			ThisField++;
			
			piece = line.section(",", ThisField, ThisField);
			JobPriTemp = piece.toInt();
			ThisField++;
			
			piece = line.section(",", ThisField, ThisField);
			JobEnabledTemp = piece.toInt();
			ThisField++;
			
			piece = line.section(",", ThisField, ThisField);
			JobFrameRateTemp = piece.toDouble();
			ThisField++;
			
			piece = line.section(",", ThisField, ThisField);
			FrameIntervalTemp = piece.toInt();
			ThisField++;
			
			piece = line.section(",", ThisField, ThisField);
			StartFrameTemp = piece.toInt();
			ThisField++;
			
			piece = line.section(",", ThisField, ThisField);
			EndFrameTemp = piece.toInt();
			ThisField++;
			
			piece = line.section(",", ThisField, ThisField);
			StartTimeTemp = piece.toDouble();
			ThisField++;
			
			piece = line.section(",", ThisField, ThisField);
			EndTimeTemp = piece.toDouble();
			ThisField++;
			
			piece = line.section(",", ThisField, ThisField);
			WidthTemp = piece.toInt();
			ThisField++;
			
			piece = line.section(",", ThisField, ThisField);
			HeightTemp = piece.toInt();
			ThisField++;
			
			piece = line.section(",", ThisField, ThisField);
			SegmentsTemp = piece.toInt();
			ThisField++;
			
			// read zero or more lines corresponding to output events
			for(line = summary->readLine(); line[0] == 0x09; line = summary->readLine())
			{
				// Output Event line (7 fields)
				// Output Format type, Enabled State, Path and File text
				// Number frame digits, Extension text (if used)
				// Temp Path, Save Before Post
				// ignored for now as we are not doing any sort of output validation
			} // for
			// 	renderInfo(int pri, int fi, int sf, int ef, QString jn, renderInfo* nextRI=NULL)
			if(JobEnabledTemp == 1) {
				jobs->addSCProject(*(new renderInfo(JobPriTemp, FrameIntervalTemp, StartFrameTemp, EndFrameTemp, JobNameTemp)));
			} // if
		} // for
	} // if infile close
	else {
		infile.close();
		return *jobs;
	}
	infile.close();
	return *jobs;                               //returns 0 if no problems with parsing
}
Example #10
0
static void fromXMLTVDate(QString &timestr, QDateTime &dt)
{
    // The XMLTV spec requires dates to either be in UTC/GMT or to specify a
    // valid timezone. We are sticking to the spec and require all grabbers
    // to comply.

    if (timestr.isEmpty())
    {
        LOG(VB_XMLTV, LOG_ERR, "Found empty Date/Time in XMLTV data, ignoring");
        return;
    }

    QStringList split = timestr.split(" ");
    QString ts = split[0];
    QDateTime tmpDT;
    tmpDT.setTimeSpec(Qt::LocalTime);

    // UTC/GMT, just strip
    if (ts.endsWith('Z'))
        ts.truncate(ts.length()-1);
    
    if (ts.length() == 14)
    {
        tmpDT = QDateTime::fromString(ts, "yyyyMMddHHmmss");
    }
    else if (ts.length() == 12)
    {
        tmpDT = QDateTime::fromString(ts, "yyyyMMddHHmm");
    }
    else if (ts.length() == 8)
    {
        tmpDT = QDateTime::fromString(ts, "yyyyMMdd");
    }
    else if (ts.length() == 6)
    {
        tmpDT = QDateTime::fromString(ts, "yyyyMM");
    }
    else if (ts.length() == 4)
    {
        tmpDT = QDateTime::fromString(ts, "yyyy");
    }

    if (!tmpDT.isValid())
    {
        LOG(VB_GENERAL, LOG_ERR,
            QString("Ignoring unknown timestamp format: %1")
                .arg(ts));
        return;
    }
    
    if (split.size() > 1)
    {
        QString tmp = split[1].trimmed();
        
        // These shouldn't be required and they aren't ISO 8601 but the
        // xmltv spec mentions these and just these so handle them just in
        // case
        if (tmp == "GMT" || tmp == "UTC")
            tmp = "+0000";
        else if (tmp == "BST")
            tmp = "+0100";
        
        // While this seems like a hack, it's better than what was done before
        QString isoDateString = QString("%1 %2").arg(tmpDT.toString(Qt::ISODate))
                                                .arg(tmp);
        // Work around Qt bug where zero offset dates are flagged as LocalTime
        tmpDT = QDateTime::fromString(isoDateString, Qt::ISODate);
        if (tmpDT.timeSpec() == Qt::LocalTime)
            tmpDT.setTimeSpec(Qt::UTC);
        dt = tmpDT.toUTC();
    }
    
    if (!dt.isValid())
    {
        static bool warned_once_on_implicit_utc = false;
        if (!warned_once_on_implicit_utc)
        {
            LOG(VB_XMLTV, LOG_ERR, "No explicit time zone found, "
                "guessing implicit UTC! Please consider enhancing "
                "the guide source to provice explicit UTC or local "
                "time instead.");
            warned_once_on_implicit_utc = true;
        }
        dt = tmpDT;
    }

    dt.setTimeSpec(Qt::UTC);
    
    timestr = MythDate::toString(dt, MythDate::kFilename);
}
Example #11
0
//---------------------------------------------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
    Q_INIT_RESOURCE(cursor);
    Q_INIT_RESOURCE(icon);
    Q_INIT_RESOURCE(schema);
    Q_INIT_RESOURCE(theme);

    QT_REQUIRE_VERSION(argc, argv, "5.2.1");

    VApplication app(argc, argv);
#ifdef QT_DEBUG
    // Because our "noisy" message handler uses the GUI subsystem for message
    // boxes, we can't install it until after the QApplication is constructed.  But it
    // is good to be the very next thing to run, to start catching warnings ASAP.
    {
        qInstallMessageHandler(noisyFailureMsgHandler);
    }
#endif
    app.setApplicationDisplayName(VER_PRODUCTNAME_STR);
    app.setApplicationName(VER_INTERNALNAME_STR);
    app.setOrganizationName(VER_COMPANYNAME_STR);
    app.setOrganizationDomain(VER_COMPANYDOMAIN_STR);
    // Setting the Application version
    app.setApplicationVersion(APP_VERSION);

    QSettings settings(QSettings::IniFormat, QSettings::UserScope, QApplication::organizationName(),
                       QApplication::applicationName());
    QString defaultLocale = QLocale::system().name();       // e.g. "de_DE"
    defaultLocale.truncate(defaultLocale.lastIndexOf('_')); // e.g. "de"
    QString checkedLocale = settings.value("configuration/locale", defaultLocale).toString();

    QTranslator qtTranslator;
    qtTranslator.load("qt_" + checkedLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    app.installTranslator(&qtTranslator);

    QTranslator appTranslator;
    appTranslator.load("valentina_" + checkedLocale, qApp->translationsPath());
    app.installTranslator(&appTranslator);

    static const char * GENERIC_ICON_TO_CHECK = "document-open";
    if (QIcon::hasThemeIcon(GENERIC_ICON_TO_CHECK) == false)
    {
        //If there is no default working icon theme then we should
        //use an icon theme that we provide via a .qrc file
        //This case happens under Windows and Mac OS X
        //This does not happen under GNOME or KDE
        QIcon::setThemeName("win.icon.theme");
    }

    MainWindow w;
    w.setWindowState(w.windowState() ^ Qt::WindowMaximized);
    app.setWindowIcon(QIcon(":/icon/64x64/icon64x64.png"));
    TableWindow table;
    QObject::connect(&w, &MainWindow::ModelChosen, &table, &TableWindow::ModelChosen);
    QObject::connect(&table, &TableWindow::closed, &w, &MainWindow::tableClosed);

    QCommandLineParser parser;
    parser.setApplicationDescription(QCoreApplication::translate("main", "Pattern making program."));
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument("filename", QCoreApplication::translate("main", "Pattern file."));
    parser.process(app);
    const QStringList args = parser.positionalArguments();
    if (args.size() > 0)
    {
        w.LoadPattern(args.at(0));

    }
    w.show();
    return app.exec();
}
Example #12
0
QString LayoutTestController::decodeHostName(const QString& host)
{
    QString decoded = QUrl::fromAce(host.toLatin1() + QByteArray(".no"));
    decoded.truncate(decoded.length() - 3);
    return decoded;
}
Example #13
0
QString LayoutTestController::encodeHostName(const QString& host)
{
    QString encoded = QString::fromLatin1(QUrl::toAce(host + QLatin1String(".no")));
    encoded.truncate(encoded.length() - 3); // strip .no
    return encoded;
}
Example #14
0
void FITSViewer::fileSave()
{
  
  FITS_FILE *ifp;
  QString recordList;
  KURL backupCurrent = currentURL;
  QString bitpixRec;
  FITS_BITPIX16  pixval_16  =0;
  FITS_BITPIX32  pixval_32  =0;
  FITS_BITPIXM32 pixval_m32 =0;
  FITS_BITPIXM64 pixval_m64 =0;
  unsigned char *transData;
  int index=0, i=0, transCount = 0, totalCount= image->width * image->height;
  
  QString currentDir = Options::fitsSaveDirectory();
  
  //kdDebug() << "We doing stats BEFORE we save!! " << endl;
  //calculateStats();
  
  // If no changes made, return.
  if (Dirty == 0 && !currentURL.isEmpty())
    return;
  
  if (currentURL.isEmpty())
  {
  	currentURL = KFileDialog::getSaveURL( currentDir, "*.fits |Flexible Image Transport System");
	// if user presses cancel
	if (currentURL.isEmpty())
	{
	  currentURL = backupCurrent;
	  return;
	}
	if (currentURL.path().contains('.') == 0) currentURL.setPath(currentURL.path() + ".fits");
	
	if (QFile::exists(currentURL.path()))
        {
            int r=KMessageBox::warningContinueCancel(static_cast<QWidget *>(parent()),
            i18n( "A file named \"%1\" already exists. "
                  "Overwrite it?" ).arg(currentURL.fileName()),
            i18n( "Overwrite File?" ),
            i18n( "&Overwrite" ) );
  
             if(r==KMessageBox::Cancel) return;
         }
   }

  if ( currentURL.isValid() )
  {
        transData = (unsigned char *) malloc (sizeof(unsigned char) * totalCount * image->bpp);
	if (transData == NULL)
	{
  		KMessageBox::error(0, i18n("Error: Low memory. Saving is aborted."));
		return;
  	}
  
  	ifp = fits_open (currentURL.path().ascii(), "w");
        if (ifp == NULL)
        {
          KMessageBox::error(0, i18n("Error during open of FITS file."));
          return;
        }
    	
	setbuf(ifp->fp, NULL);
	
	bitpixRec.sprintf("BITPIX  =                    %d /Modified by KStars                               ", image->bitpix);
	bitpixRec.truncate(80);
	
	for (unsigned int j=0; j < record.count(); j++)
	{
	  recordList = record[j];
	  
	  if ( (index = recordList.find("BITPIX")) != -1)
	  	recordList.replace(index, FITS_CARD_SIZE, bitpixRec);
	
	  fwrite(recordList.ascii(), 1, FITS_RECORD_SIZE, ifp->fp);
        }
	
	switch (image->bitpix)
	{
	   case 8:
		for (i= image->height - 1; i >= 0; i--)
		fwrite(image->displayImage->scanLine(i), 1, image->width, ifp->fp);
		break;
		
		
	   case 16:
    		for (i= 0, transCount = 0 ; i < totalCount ; i++, transCount += 2)
    		{
       			pixval_16 = (unsigned short) imgBuffer[i];
			transData[transCount]   = ((unsigned char*) &pixval_16)[1];
			transData[transCount+1] = ((unsigned char*) &pixval_16)[0];
		}
		// Now we need to write all uchars to file. We have 2 bytes per pixel
		transCount = 0;
		totalCount *= 2;
		
		for (i=0, transCount = 0; i < totalCount; i += transCount)
		   transCount = fwrite( transData + i , 1, totalCount - i, ifp->fp);
       			
     		break;
      
   	  case 32:
	        for (i=0, transCount = 0 ; i < totalCount ; i++, transCount += 4)
    		{
       			pixval_32 = (unsigned int) imgBuffer[i];
			transData[transCount]       = ((unsigned char*) &pixval_32)[3];
			transData[transCount+1]     = ((unsigned char*) &pixval_32)[2];
			transData[transCount+2]     = ((unsigned char*) &pixval_32)[1];
			transData[transCount+3]     = ((unsigned char*) &pixval_32)[0];
		}
		
		// Now we need to write all uchars to file. We have 4 bytes per pixel
		transCount = 0;
		totalCount *= 4;
		
		for (i=0, transCount = 0; i < totalCount; i += transCount)
		   transCount = fwrite( transData + i , 1, totalCount - i, ifp->fp);
    		break;
    
   	case -32:
		for (i=0, transCount = 0 ; i < totalCount ; i++, transCount += 4)
    		{
       			pixval_m32 = imgBuffer[i];
			transData[transCount]       = ((unsigned char*) &pixval_m32)[3];
			transData[transCount+1]     = ((unsigned char*) &pixval_m32)[2];
			transData[transCount+2]     = ((unsigned char*) &pixval_m32)[1];
			transData[transCount+3]     = ((unsigned char*) &pixval_m32)[0];
			
		}
		
		// Now we need to write all uchars to file. We have 4 bytes per pixel
		transCount = 0;
		totalCount *= 4;
		
		for (i=0, transCount = 0; i < totalCount; i += transCount)
		   transCount = fwrite( transData + i , 1, totalCount - i, ifp->fp);
   		
    		break;
    
    	case -64:
    		for (i=0, transCount = 0 ; i < totalCount ; i++, transCount += 8)
    		{
       			pixval_m64 = imgBuffer[i];
			transData[transCount]   = 0;
			transData[transCount+1] = 0;
			transData[transCount+2] = 0;
			transData[transCount+3] = 0;
			transData[transCount+4] = ((unsigned char*) &pixval_m32)[3];
			transData[transCount+5] = ((unsigned char*) &pixval_m32)[2];
			transData[transCount+6] = ((unsigned char*) &pixval_m32)[1];
			transData[transCount+7] = ((unsigned char*) &pixval_m32)[0];
			
		}
		
		// Now we need to write all uchars to file. We have 4 bytes per pixel
		transCount = 0;
		totalCount *= 8;
		
		for (i=0, transCount = 0; i < totalCount; i += transCount)
		   transCount = fwrite( transData + i , 1, totalCount - i, ifp->fp);
	        break;	
	}
		
	fits_close(ifp);
	
	statusBar()->changeItem(i18n("File saved."), 3);
	
	free(transData);
	Dirty = 0;
	history->clear();
	fitsRestore();
	//updateImgBuffer();
  }
  else
  {
		QString message = i18n( "Invalid URL: %1" ).arg( currentURL.url() );
		KMessageBox::sorry( 0, message, i18n( "Invalid URL" ) );
  }
	

}
Example #15
0
bool KstEqDialogI::newObject() {
  QString tag_name = _tagName->text();
  QString etext = _w->_equation->text();
  etext.remove(QRegExp("[^a-zA-Z0-9\\(\\)\\+\\-\\*/\\%\\^\\|\\&\\!<>=_.]"));
  if (etext.length() > 12) {
    etext.truncate(12);
    etext += "...";
  }

  if (tag_name == defaultTag) {
    tag_name = KST::suggestEQName(etext);
  }

  /* verify that the curve name is unique */
  if (KstData::self()->dataTagNameNotUnique(tag_name)) {
    _tagName->setFocus();
    return false;
  }

  if (!checkEntries()) {
    return false;
  }

  KST::vectorList.lock().readLock();
  /* find *V */
  KstVectorPtr vp = *KST::vectorList.findTag(_w->_xVectors->selectedVector());
  if (!vp) {
    kstdFatal() << "Bug in kst: the Vector field in plotDialog (Eq) "
                << "refers to a non-existent vector..." << endl;
  }
  KST::vectorList.lock().unlock();

  /** Create the equation here */
  vp->readLock();
  KstEquationPtr eq = new KstEquation(tag_name, _w->_equation->text(), vp, _w->_doInterpolation->isChecked());
  vp->unlock();

  if (!eq->isValid()) {
    eq = 0L;
    QString parseErrors;
    for (QStringList::ConstIterator i = Equation::errorStack.begin(); i != Equation::errorStack.end(); ++i) {
      parseErrors += *i;
      parseErrors += "\n";
    }

    KMessageBox::detailedSorry(this, i18n("There is an error in the equation you entered."), parseErrors);
    return false;
  }

  KstVCurvePtr vc = new KstVCurve(KST::suggestCurveName(tag_name, true), eq->vX(), eq->vY(), 0L, 0L, 0L, 0L, _w->_curveAppearance->color());
  vc->setHasPoints(_w->_curveAppearance->showPoints());
  vc->setHasLines(_w->_curveAppearance->showLines());
  vc->setHasBars(_w->_curveAppearance->showBars());
  vc->setLineWidth(_w->_curveAppearance->lineWidth());
  vc->setLineStyle(_w->_curveAppearance->lineStyle());
  vc->pointType = _w->_curveAppearance->pointType();
  vc->setPointDensity(_w->_curveAppearance->pointDensity());
  vc->setBarStyle(_w->_curveAppearance->barStyle());
  
  QString legend_text = _legendText->text();
  if (legend_text == defaultTag) {
    vc->setLegendText(QString(""));
  } else {
    vc->setLegendText(legend_text);
  }

  KstViewWindow *w = dynamic_cast<KstViewWindow*>(KstApp::inst()->findWindow(_w->_curvePlacement->_plotWindow->currentText()));
  if (!w) {
    QString n = KstApp::inst()->newWindow(KST::suggestWinName());
    w = dynamic_cast<KstViewWindow*>(KstApp::inst()->findWindow(n));
  }

  if (w) {
    Kst2DPlotPtr plot;
    if (_w->_curvePlacement->existingPlot()) {
      /* assign curve to plot */
      plot = kst_cast<Kst2DPlot>(w->view()->findChild(_w->_curvePlacement->plotName()));
      if (plot) {
        plot->addCurve(vc.data());
      }
    }

    if (_w->_curvePlacement->newPlot()) {
      /* assign curve to plot */
      QString name = w->createObject<Kst2DPlot>(KST::suggestPlotName());
      if (_w->_curvePlacement->reGrid()) {
        w->view()->cleanup(_w->_curvePlacement->columns());
      }
      plot = kst_cast<Kst2DPlot>(w->view()->findChild(name));
      if (plot) {
        _w->_curvePlacement->update();
        _w->_curvePlacement->setCurrentPlot(plot->tagName());
        plot->addCurve(vc.data());
        plot->generateDefaultLabels();
      }
    }
  }

  KST::dataObjectList.lock().writeLock();
  KST::dataObjectList.append(eq.data());
  KST::dataObjectList.append(vc.data());
  KST::dataObjectList.lock().unlock();

  eq = 0L; // drop the reference before we update
  vc = 0L;
  emit modified();
  return true;
}
Example #16
0
int KST::vectorsToFile(const KstVectorList& vl, QFile *f, bool interpolate) {
  KstApp *app = KstApp::inst();
  int maxlen = -1;

  if (interpolate) { // code duplication is faster
    maxlen = 0;
    for (KstVectorList::ConstIterator v = vl.begin(); v != vl.end(); ++v) {
      (*v)->readLock();
      maxlen = KMAX(maxlen, (*v)->length());
    }
  } else {
    for (KstVectorList::ConstIterator v = vl.begin(); v != vl.end(); ++v) {
      (*v)->readLock();
      if (maxlen == -1) {
        maxlen = (*v)->length();
      } else {
        maxlen = KMIN(maxlen, (*v)->length());
      }
    }
  }

  QString saving = i18n("Saving vectors...");
  register int modval = QMAX(maxlen/100, 100);
  app->slotUpdateProgress(maxlen, 0, QString::null);

  bool first = true;
  QString ltxt = ";";
  for (KstVectorList::ConstIterator v = vl.begin(); v != vl.end(); ++v) {
    ltxt += ' ';
    ltxt += (*v)->tagName();
  }
  ltxt += '\n';

  f->writeBlock(ltxt.ascii(), ltxt.length());
  ltxt.fill('-');
  ltxt[0] = ';';
  ltxt[1] = ' ';
  ltxt[ltxt.length() - 1] = '\n';
  f->writeBlock(ltxt.ascii(), ltxt.length());
#if QT_VERSION >= 0x030200
  ltxt.reserve(vl.count()*17);
#endif
  for (int line = 0; line < maxlen; ++line) {
    ltxt.truncate(0);
    first = true;
    for (KstVectorList::ConstIterator v = vl.begin(); v != vl.end(); ++v) {
      if (!first) {
        ltxt += ' ';
      } else {
        first = false;
      }
      double val;
      if (interpolate) {  // might be faster to put this outside the for loops
        val = (*v)->interpolate(line, maxlen);
      } else {
        val = (*v)->value()[line];
      } 
      ltxt += QString::number(val, 'g', 15);
    }
    ltxt += "\n";
    f->writeBlock(ltxt.ascii(), ltxt.length());
    if (line % modval == 0) {
      app->slotUpdateProgress(maxlen, line, saving);
    }
  }

  for (KstVectorList::ConstIterator v = vl.begin(); v != vl.end(); ++v) {
    (*v)->readUnlock();
  }

  app->slotUpdateProgress(0, 0, QString::null);

  return 0;
}
Example #17
0
int main(int argc, char *argv[])
{
    QCoreApplication::setOrganizationName("SRFGames");
    QCoreApplication::setOrganizationDomain("sol-online.org"),
    QCoreApplication::setApplicationName("TrackYourTime");

#ifdef Q_OS_MAC
    QDir dir(argv[0]);
    dir.cdUp();
    QString currentDir = dir.absolutePath();
    dir.cdUp();
    dir.cd("PlugIns");
    QCoreApplication::setLibraryPaths(QStringList(dir.absolutePath()));
#endif

    QApplication a(argc, argv);
    QApplication::setQuitOnLastWindowClosed(false);

#ifdef Q_OS_MAC
    QDir::setCurrent(currentDir);
#endif



    QSettings settings;
    QString Language = QLocale::system().name();
    Language.truncate(Language.lastIndexOf('_'));
    Language = settings.value(cDataManager::CONF_LANGUAGE_ID,Language).toString();
    if (settings.value(cDataManager::CONF_FIRST_LAUNCH_ID,true).toBool()){
        settings.setValue(cDataManager::CONF_FIRST_LAUNCH_ID,false);
        settings.setValue(cDataManager::CONF_LANGUAGE_ID,Language);
        settings.setValue(cDataManager::CONF_AUTORUN_ID,true);
        setAutorun();
        settings.sync();
    }

    QTranslator translator;
    translator.load("lang_" + Language,QDir::currentPath()+"/data/languages");
    QApplication::installTranslator(&translator);

    cDataManager datamanager;

    cTrayIcon trIcon(&datamanager);
    QObject::connect(&datamanager, SIGNAL(trayActive()), &trIcon, SLOT(setActive()));
    QObject::connect(&datamanager, SIGNAL(traySleep()), &trIcon, SLOT(setInactive()));
    QObject::connect(&datamanager, SIGNAL(trayShowHint(QString)), &trIcon, SLOT(showHint(QString)));
    QObject::connect(&datamanager, SIGNAL(profilesChanged()), &trIcon, SLOT(onProfilesChange()));

    ApplicationsWindow applicationsWindow(&datamanager);
    QObject::connect(&trIcon, SIGNAL(showApplications()), &applicationsWindow, SLOT(show()));
    QObject::connect(&datamanager, SIGNAL(profilesChanged()), &applicationsWindow, SLOT(onProfilesChange()));
    QObject::connect(&datamanager, SIGNAL(applicationsChanged()), &applicationsWindow, SLOT(onApplicationsChange()));

    ProfilesWindow profilesWindow(&datamanager);
    QObject::connect(&applicationsWindow, SIGNAL(showProfiles()), &profilesWindow, SLOT(show()));

    App_SettingsWindow app_settingsWindow(&datamanager);
    QObject::connect(&applicationsWindow, SIGNAL(showAppSettings(int)), &app_settingsWindow, SLOT(showApp(int)));
    QObject::connect(&datamanager, SIGNAL(debugScriptResult(QString,sSysInfo)), &app_settingsWindow, SLOT(onScriptResult(QString,sSysInfo)));

    SettingsWindow settingsWindow(&datamanager);
    QObject::connect(&trIcon, SIGNAL(showSettings()), &settingsWindow, SLOT(show()));
    QObject::connect(&settingsWindow, SIGNAL(preferencesChange()), &datamanager, SLOT(onPreferencesChanged()));

    StatisticWindow statisticWindow(&datamanager);
    QObject::connect(&trIcon, SIGNAL(showStatistic()), &statisticWindow, SLOT(show()));

    AboutWindow aboutWindow;
    QObject::connect(&trIcon, SIGNAL(showAbout()), &aboutWindow, SLOT(show()));

    int result = a.exec();

    return result;
}
Example #18
0
Q_DECL_EXPORT int main(int argc, char *argv[])
{
    int currentExitCode = 0;

    QScopedPointer<QSymbianApplication> app(new QSymbianApplication(argc, argv));

    // Set App Info:
    app->setApplicationName("Battery Status");
    app->setOrganizationName("Motaz Alnuweiri");
    app->setApplicationVersion(APP_Version);

    // QT_DEBUG or QT_NO_DEBUG
//    #ifdef QT_DEBUG
//        // Install Debug Msgs Handler:
//        ClearDebugFile();
//        qInstallMsgHandler(DebugFileHandler);
//    #endif

    // Install EventFilter in QApplication:
    //app->installEventFilter(new myEventFilter);

    // Set App Splash Screen:
    QSplashScreen *splash = new QSplashScreen(QPixmap(":qml/Images/JPG/Splash_Screen.jpg"),
                                              Qt::WindowStaysOnTopHint);
    splash->show();

    // Check System Language & Load App Translator:
    QString systemLang = QLocale::system().name();
    QTranslator appTranslator;

    systemLang.truncate(2); //truncate(2) to ignore the country code

    if (QFile::exists("Languages/batterystatus_" + systemLang + ".qm")) {
        appTranslator.load("batterystatus_" + systemLang, "Languages");
    } else {
        appTranslator.load("batterystatus_en", "Languages");
    }

    // Install QTranslator to QApplication:
    app->installTranslator(&appTranslator);

    // Hide The App If Deactive:
    if (!app->foreground())
        QSymbianHelper::hideInBackground();

    // Register QSettings:
    QAppSettings appSettings;

    // Register QmlApplicationViewer:
    QmlApplicationViewer *viewer = new QmlApplicationViewer();
    //viewer.setResizeMode(QmlApplicationViewer::SizeRootObjectToView);
    //viewer.setAutoFillBackground(false);
    //viewer.setOrientation(QmlApplicationViewer::ScreenOrientationLockPortrait);

    // Register App HSWidget:
    QBatteryHSWidget *batteryHSWidget = new QBatteryHSWidget();
    batteryHSWidget->setBackgroundOpacity(appSettings.getWidgetOpacity());

    // Register QDeviceName:
    QDeviceName deviceName;

    // Register Class to QML:
    qmlRegisterType<QPSMode>("PSMode", 1, 0, "PSMode");
    qmlRegisterType<QGlobalNote>("GlobalNote", 1, 0, "GlobalNote");
    qmlRegisterType<QCBatteryInfo>("CBatteryInfo", 1, 0, "CBatteryInfo");
    qmlRegisterType<CommonType>("CommonType", 1, 0, "CommonType");

    // Set Propertys to QML:
    viewer->rootContext()->setContextProperty("APPName", QObject::tr("Battery Status"));
    viewer->rootContext()->setContextProperty("APPVersion", app->applicationVersion());
    viewer->rootContext()->setContextProperty("AppPath", app->applicationDirPath());
    viewer->rootContext()->setContextProperty("SymbianHelper", new QSymbianHelper);
    viewer->rootContext()->setContextProperty("AppSettings", &appSettings);
    viewer->rootContext()->setContextProperty("HSWidget", batteryHSWidget);
    viewer->rootContext()->setContextProperty("DeviceName", &deviceName);
    viewer->rootContext()->setContextProperty("QApp", app->instance());

    viewer->setSource(QUrl(QLatin1String("qrc:qml/main.qml")));
    //viewer.setSource(QUrl::fromLocalFile("qrc:qml/main.qml"));

    // Lock screen orientation in portrait only
    //viewer.setOrientation(QmlApplicationViewer::ScreenOrientationLockPortrait);

    //viewer.setGeometry(app->desktop()->screenGeometry());
    viewer->showFullScreen();

    // Stop Splash Screen & Delete It:
    splash->finish(viewer);
    splash->deleteLater();

    //viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);

    // Enter App Event Loop:
    currentExitCode = app->exec();

    // Cleun Pointers:
    delete viewer;
    delete batteryHSWidget;

    // Check If App Is Restarting:
    if(app->isRestarting()) {
        // Workround for my app to restart it self
        QProcess::startDetached(qApp->applicationFilePath());
    }

    return currentExitCode;
}
Example #19
0
void AppendCommand::undo()
{
    QCOMPARE(m_str->mid(m_str->length() - m_text.length()), m_text);

    m_str->truncate(m_str->length() - m_text.length());
}
Example #20
0
bool BulkHeaderGroup::BulkHeaderGroupBody()
{
    // belt and braces
    key.set_data(keymem);
    data.set_data(datamem);

    if (m_cancel)
    {
        emit updateJob(JobList::BulkHeaderGroup, JobList::Cancelled, job->seq);
        return false;
    }

    emit updateJob(JobList::BulkHeaderGroup, JobList::Running, job->seq);

    NewsGroup* ng = job->ng;
    Db* db = ng->getDb();

    MultiPartHeader mph;
    SinglePartHeader sph;
    HeaderBase* hb = 0;
    HeaderGroup* headerGroup = 0;
    HeaderGroup* advancedHeaderGroup = 0;

    // typedef QMap<QString, QString> HeaderGroupIndexes; // subj, headerGroup index
    // typedef QMap<QString, HeaderGroup*> HeaderGroups; //  headerGroup index, headerGroup *

    HeaderGroupIndexes headerGroupIndexes;
    HeaderGroups       headerGroups;

    DBC *dbcp = 0;
    DBT ckey, cdata;

    memset(&ckey, 0, sizeof(ckey));
    memset(&cdata, 0, sizeof(cdata));

    size_t retklen, retdlen;
    void *retkey = 0, *retdata = 0;
    int ret, t_ret;
    void *p = 0;

    quint64 count=0;

    cdata.data = (void *) new char[HEADER_BULK_BUFFER_LENGTH];
    cdata.ulen = HEADER_BULK_BUFFER_LENGTH;
    cdata.flags = DB_DBT_USERMEM;

    ckey.data = (void *) new char[HEADER_BULK_BUFFER_LENGTH];
    ckey.ulen = HEADER_BULK_BUFFER_LENGTH;
    ckey.flags = DB_DBT_USERMEM;

    /* Acquire a cursor for the database. */
    if ((ret = db->get_DB()->cursor(db->get_DB(), NULL, &dbcp, DB_CURSOR_BULK)) != 0)
    {
        db->err(ret, "DB->cursor");
        char* ptr = 0;

        ptr = (char*)(ckey.data);
        Q_DELETE_ARRAY(ptr);
        ptr = (char*)(cdata.data);
        Q_DELETE_ARRAY(ptr);
        return false;
    }

    // To save the group records
    ng->articlesNeedDeleting(false);

    // Store the data in the database - flush first ...

    u_int32_t delCount;

    uchar keymem[KEYMEM_SIZE];
    uchar datamem[DATAMEM_SIZE];
    Dbt key, data;
    char* p2 = 0;
    QByteArray ba;
    const char *k = 0;

    key.set_flags(DB_DBT_USERMEM);
    key.set_data(&keymem);
    key.set_ulen(KEYMEM_SIZE);

    data.set_flags(DB_DBT_USERMEM);
    data.set_ulen(DATAMEM_SIZE);
    data.set_data(&datamem);

    QString subj =  "MDQuban", from = "MDQuban";

    //QString rs1 = "^(.*)(\".*\")";
    //QString rs2 = "^(.*)\\s-\\s(.*)$";
    //QString rs3 = "^(\\S+.*)\\[.*\\].*(\".*\")";

    //QString rs3 = "^(.*)\\s-\\s.*\\s-\\s(.*)$";
    QRegExp rx[3];
    bool    rxPosBack[3];
    bool    noRegexpGrouping;

    QString recKey, storeIndex;
    QString prevSubj = "MDQuban", prevFrom = "MDQuban";

    int pos;
    bool newGroup = false;

    bool mphFound = false;

    quint32 grouped = 0,
            single = 0,
            numGroups = 0;

    qint16 stringDiff = -1;

    bool prevGroup = false;
    bool advancedPlacement = false;
    bool skipAdvanced = false;

    noRegexpGrouping = ng->isThereNoRegexOnGrouping();

    if (noRegexpGrouping == false) // need regex for grouping
    {
        rx[0].setPattern(ng->getGroupRE1());
        rx[1].setPattern(ng->getGroupRE2());
        rx[2].setPattern(ng->getGroupRE3());

        rxPosBack[0] = ng->getGroupRE1Back();
        rxPosBack[1] = ng->getGroupRE2Back();
        rxPosBack[2] = ng->getGroupRE3Back();
    }

    ng->getGroupingDb()->truncate(0, &delCount, 0);
    qDebug() << "Deleted " << delCount << " records from group db";

    QMapIterator<QString, QString> it(headerGroupIndexes);
    QString advancedIndex;

    for (;;)
    {
        /*
         * Acquire the next set of key/data pairs.  This code
         * does not handle single key/data pairs that won't fit
         * in a BUFFER_LENGTH size buffer, instead returning
         * DB_BUFFER_SMALL to our caller.
         */
        if ((ret = dbcp->get(dbcp, &ckey, &cdata, DB_MULTIPLE_KEY | DB_NEXT)) != 0)
        {
            if (ret != DB_NOTFOUND)
                db->err(ret, "DBcursor->get");
            break;
        }

        for (DB_MULTIPLE_INIT(p, &cdata);;)
        {
            DB_MULTIPLE_KEY_NEXT(p, &cdata, retkey, retklen, retdata, retdlen);
            if (p == NULL)
                break;

            if (retdlen){;} // MD TODO compiler .... unused variable

            recKey = QString::fromLocal8Bit((char*)retkey, retklen);

            if (*((char *)retdata) == 'm')
            {
                MultiPartHeader::getMultiPartHeader((unsigned int)retklen, (char *)retkey, (char *)retdata, &mph);
                hb = (HeaderBase*)&mph;
                mphFound = true;
            }
            else if (*((char *)retdata) == 's')
            {
                SinglePartHeader::getSinglePartHeader((unsigned int)retklen, (char *)retkey, (char *)retdata, &sph);
                hb = (HeaderBase*)&sph;
                mphFound = false;
            }
            else
            {
                // What have we found ?????
                qDebug() << "Found unexpected identifier for header : " << (char)*((char *)retdata);
                continue;
            }

            ++count;

            prevSubj = subj;

            prevFrom = from;

            subj = hb->getSubj();
            from = hb->getFrom();

            if (noRegexpGrouping == false) // need regex for grouping
            {
                for (int i=0; i<3; ++i)
                {
                    if (rx[i].isEmpty() == false)
                    {
                        if (rxPosBack[i] == true) // from the back
                        {
                            pos = subj.lastIndexOf(rx[i]);
                            if (pos != -1)
                                subj.truncate(pos);
                        }
                        else // from the front
                        {
                            pos = rx[i].indexIn(subj);
                            if (pos > -1)
                                subj = rx[i].cap(0);
                        }
                    }
                }
            }

            //qDebug() << "Stripped down to: " << subj;

            stringDiff = -1;

            if (prevFrom != from) // change of contributor
            {
                newGroup = true;
            }
            else // same contributor
            {
               if ((stringDiff = levenshteinDistance(prevSubj, subj)) > ng->getMatchDistance()) // no match ...
                   newGroup = true;
               else
                   newGroup = false;

               //qDebug() << "Diff between " << prevSubj << " and " << subj << " is " << stringDiff;
            }

            if (newGroup)
            {
                if (ng->isThereAdvancedGrouping())
                {
                    it.toFront();

                    // decide if we can match to a previous group
                    while (it.hasNext())
                    {
                        it.next();
                        if ((stringDiff = levenshteinDistance(it.key(), subj)) <= ng->getMatchDistance()) // match ...
                        {
                            // The index for this group is in it.value()
                            // See if we have the HeaderGroup in our cache headerGroups)

                            if (headerGroups.contains(it.value()))
                            {
                                advancedHeaderGroup = headerGroups.value(it.value());
                            }
                            else // not in cache
                            {
                                advancedIndex = it.value();
                                advancedHeaderGroup = getGroup(ng, advancedIndex);
                                if (advancedHeaderGroup)
                                {
                                    headerGroups.insert(advancedIndex, advancedHeaderGroup);
                                }
                                else // db read failed ..
                                {
                                    skipAdvanced = true;
                                }
                            }

                            if (skipAdvanced == false)
                            {
                                if (mphFound)
                                    advancedHeaderGroup->addMphKey(recKey);
                                else
                                    advancedHeaderGroup->addSphKey(recKey);

                                advancedPlacement = true;
                                subj = prevSubj; // ignore this header as it's been placed out of sequence
                                from = prevFrom;
                                newGroup = false; // as we managed to relocate to an existing group

                                break; // stop looking at previous groups
                            }
                            else
                                skipAdvanced = false;
                        }
                    }
                }
            }

            if (newGroup)
            {
                if (prevGroup) // save before moving on
                {
                    ba = storeIndex.toLocal8Bit();
                    k= ba.constData();
                    memcpy(keymem, k, storeIndex.length());
                    key.set_size(storeIndex.length());

                    p2=headerGroup->data();
                    data.set_data(p2);
                    data.set_size(headerGroup->getRecordSize());
                    ret=ng->getGroupingDb()->put(NULL, &key, &data, 0);
                    if (ret!=0)
                        qDebug("Error updating record: %d", ret);

                    if (ng->isThereAdvancedGrouping())
                        headerGroupIndexes.insert(storeIndex.section('\n', 0, 0), storeIndex);

                    Q_DELETE_ARRAY(p2);
                    Q_DELETE(headerGroup);
                    numGroups++;
                }

                prevGroup = true;

                storeIndex = subj % "\n" % from;

                headerGroup = new HeaderGroup();

                headerGroup->setDisplayName(subj);
                headerGroup->setPostingDate(hb->getPostingDate());
                headerGroup->setDownloadDate(hb->getDownloadDate());
                headerGroup->setStatus(hb->getStatus());
                headerGroup->setNextDistance(stringDiff);
            }

            // if we've found somewhere else to place this header then don't add again
            if (!advancedPlacement)
            {
                if (mphFound)
                    headerGroup->addMphKey(recKey);
                else
                    headerGroup->addSphKey(recKey);
            }
            else
                advancedPlacement = false;

            if (count % 250 == 0)
            {
                QCoreApplication::processEvents();

                emit updateJob(JobList::BulkHeaderGroup, tr("Header bulk grouping for newsgroup ") + job->ng->getAlias() + ": " +
                    QString::number(count) + " out of " + QString::number(ng->getTotal()) + tr(" grouped"), job->seq);
            }

            if (m_cancel)
            {
                emit updateJob(JobList::BulkHeaderGroup, JobList::Cancelled, job->seq);
                return false;
            }
        }

        if (m_cancel)
        {
            emit updateJob(JobList::BulkHeaderGroup, JobList::Cancelled, job->seq);
            return false;
        }
    }

    if ((t_ret = dbcp->close(dbcp)) != 0)
    {
        db->err(ret, "DBcursor->close");
        if (ret == 0)
            ret = t_ret;
    }

    char* ptr = ((char*)ckey.data);
    Q_DELETE_ARRAY(ptr);
    ptr = ((char*)cdata.data);
    Q_DELETE_ARRAY(ptr);
    if (headerGroups.count())
    {
        qDeleteAll(headerGroups);
        headerGroups.clear();
    }

    qDebug() << "Multi = " << grouped << ", single = " << single;

    ng->setHeadersNeedGrouping(false);
    // Finally update the newsgroup
    emit saveGroup(ng);

    emit updateJob(JobList::BulkHeaderGroup, tr("Header bulk grouping for newsgroup ") + job->ng->getAlias() + ": " +
                  QString::number(count) + " out of " + QString::number(ng->getTotal()) + tr(" grouped"), job->seq);

    if (m_cancel)
    {
        emit updateJob(JobList::BulkHeaderGroup, JobList::Cancelled, job->seq);
        return false;
    }

    emit logEvent(tr("Bulk grouping of ") + ng->getTotal() + tr(" articles completed successfully."));

    emit updateJob(JobList::BulkHeaderGroup, JobList::Finished_Ok, job->seq);

    ng->setTotalGroups(numGroups);

    Q_DELETE(headerGroup);

    return true;
}
Example #21
0
int main(int argc, char ** argv)
{
    QStringList in;
    for(int i=1; i<argc; i++){ //skip the first arg (app binary)
      in << QString(argv[i]);
    }
    if(in.isEmpty()){ in << QDir::homePath(); }
    #ifdef __linux
    QApplication a(argc, argv);
    #else
    QtSingleApplication a(argc, argv);
    if( a.isRunning() ){
      return !(a.sendMessage(in.join("\n")));
    }
    #endif
    QTranslator translator;
    QLocale mylocale;
    QString langCode = mylocale.name();
    
    if ( ! QFile::exists(PREFIX + "/share/Lumina-DE/i18n/lumina-config_" + langCode + ".qm" ) )  langCode.truncate(langCode.indexOf("_"));
    translator.load( QString("lumina-config_") + langCode, PREFIX + "/share/i18n/Lumina-DE/" );
    a.installTranslator( &translator );
    qDebug() << "Locale:" << langCode;
    
    MainUI w;
    QObject::connect(&a, SIGNAL(messageReceived(const QString&)), &w, SLOT(slotSingleInstance(const QString&)) );
    w.OpenDirs(in);
    w.show();

    int retCode = a.exec();
    return retCode;
}
Example #22
0
void CSV::parse ()
{
  Setting rule;
  getRule(rule);

  if (! rule.count())
  {
    QString s(tr("Empty rule"));
    printStatusLogMessage(s);
    downloadComplete();
    return;
  }

  QString ts = "Rule";
  QString ts2, s;
  rule.getData(ts, ts2);
  if (! ts2.contains("Date:"))
  {
    QString ss(tr("Rule missing Date field"));
    printStatusLogMessage(ss);
    downloadComplete();
    return;
  }

  ts = "Delimiter";
  rule.getData(ts, s);
  if (! s.length())
  {
    QString ss(tr("Delimiter not found"));
    printStatusLogMessage(ss);
    downloadComplete();
    return;
  }
  setDelimiter(s);

  if (dateRange->isChecked())
  {
    if (sdate->date() >= edate->date() || edate->date() <= sdate->date())
    {
      QString ss = stringDone + " " + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
      printStatusLogMessage(ss);
      downloadComplete();
      return;
    }
  }

  QString type;
  ts = "Type";
  rule.getData(ts, type);
  if (! type.length())
  {
    QString ss(tr("Type not found"));
    printStatusLogMessage(ss);
    downloadComplete();
    return;
  }

  ts = "Rule";
  rule.getData(ts, ts2);
  QStringList fieldList = QStringList::split(",", ts2, FALSE);
  if (! fieldList.count())
  {
    QString ss(tr("No rule found"));
    printStatusLogMessage(ss);
    downloadComplete();
    return;
  }

  // get the directory path offset
  ts = "Directory";
  QString directory;
  rule.getData(ts, directory);
  if (! directory.length())
  {
    QString ss(tr("Directory not found"));
    printStatusLogMessage(ss);
    downloadComplete();
    return;
  }

  // get the symbol filter
  ts = "SymbolFilter";
  rule.getData(ts, ts2);
  QStringList symbolFilter = QStringList::split(",", ts2, FALSE);

  // check for time field and set the tickflag
  bool tickFlag = FALSE;
  ts = "Rule";
  rule.getData(ts, ts2);
  if (ts2.contains("Time"))
    tickFlag = TRUE;
  else
  {
    if (ts2.contains("HHMMSS"))
      tickFlag = TRUE;
  }

  QStringList list;
  file->getFile(list);

  int loop;
  for (loop = 0; loop < (int) list.count(); loop++)
  {
    if (cancelFlag)
      break;

    QFile f(list[loop]);
    if (! f.open(QIODevice::ReadOnly))
      continue;
    Q3TextStream stream(&f);

    QString symbol = symbolOveride;
    if (! symbol.length() && fieldList.findIndex("Symbol") == -1)
    {
      QStringList l = QStringList::split("/", list[loop], FALSE);
      symbol = l[l.count() - 1];

      if (symbol.right(4).contains(".txt"))
        symbol.truncate(symbol.length() - 4);

      if (symbol.right(4).contains(".TXT"))
        symbol.truncate(symbol.length() - 4);

      while (symbol.contains("_"))
        symbol = symbol.remove(symbol.find("_", 0, TRUE), 1);
    }

    QString path;
    if (! type.compare("Stocks"))
    {
      QString tmp = "Stocks/" + directory;
      createDirectory(tmp, path);
      if (! path.length())
      {
        QString ss(tr("CSVPlugin::Unable to create directory"));
        printStatusLogMessage(ss);
        downloadComplete();
        f.close();
        return;
      }
    }
    else
    {
      if (! type.compare("Futures"))
      {
        QString tmp = "Futures/" + directory;
        createDirectory(tmp, path);
        if (! path.length())
        {
          QString ss(tr("CSVPlugin::Unable to create directory"));
          printStatusLogMessage(ss);
          downloadComplete();
          f.close();
          return;
        }
      }
    }

    path.append("/");

    if (symbol.length())
    {
      QString s = path;
      s.append(symbol);
      if (openDb(s, symbol, type, tickFlag))
        continue;
//      QString ss = tr("Updating") + " " + symbol;
//      printStatusLogMessage(ss);
        progressBar->setProgress(loop, (int) list.count());
    }

    int lineCount = 0;
    QFileInfo fi(f);
    QString fName = fi.fileName();
    while(stream.atEnd() == 0)
    {
      QString ts = stream.readLine();
      QStringList l = QStringList::split( '\n', substituteSeparator(ts, delim, '\n'), FALSE);

      lineCount++;
      if (l.count() != fieldList.count())
      {
        QString ss = QString().sprintf(
          "%s - %s - %s: %s Number of fields in file (%i) != rule format (%i)",
          fName.latin1(), symbol.latin1(), tr("Line").latin1(),
          QString::number(lineCount).latin1(),  l.count(), fieldList.count()
          );
        printStatusLogMessage(ss);
        continue;
      }

      int fieldLoop;
      bool flag = FALSE;
      Setting r;
      for (fieldLoop = 0; fieldLoop < (int) fieldList.count(); fieldLoop++)
      {
        QString listItem = l[fieldLoop].stripWhiteSpace();
        if (fieldList[fieldLoop].contains("Date:"))
	{
          QDate dt;
          getDate(fieldList[fieldLoop], listItem, r, dt);
          if (! dt.isValid())
	  {
            QString ss = QString().sprintf("%s - %s - %s: %s %s: %s",
              fName.latin1(), symbol.latin1(), tr("Line").latin1(), QString::number(lineCount).latin1(),
              tr("Bad date").latin1(), listItem.latin1()
              );
            printStatusLogMessage(ss);
	    flag = TRUE;
	    break;
	  }

          if (dateRange->isChecked())
          {
            if (dt < sdate->date() || dt > edate->date())
	    {
	      flag = TRUE;
	      break;
	    }
          }
          ts = "Date";
          ts2 = dt.toString("yyyyMMdd");
	  r.setData(ts, ts2);
	  continue;
	}

        if (! fieldList[fieldLoop].compare("Time"))
	{
          getTime(listItem, s);
          if (! s.length())
	  {
            QString ss = QString().sprintf("%s - %s - %s: %s %s: %s",
              fName.latin1(), symbol.latin1(), tr("Line").latin1(), QString::number(lineCount).latin1(),
              tr("Bad time").latin1(), listItem.latin1()
              );
            printStatusLogMessage(ss);
	    flag = TRUE;
	    break;
	  }
          ts = "Time";
	  r.setData(ts, s);
	  continue;
	}

        if (! fieldList[fieldLoop].compare("Symbol"))
	{
	  if (symbolFilter.count())
	  {
	    if (symbolFilter.findIndex(listItem) == -1)
	    {
	      flag = TRUE;
	      break;
	    }
	  }

          ts = "Symbol";
	  r.setData(ts, listItem);
	  continue;
	}

        if (! fieldList[fieldLoop].compare("Name"))
	{
          ts = "Name";
	  r.setData(ts, listItem);
	  continue;
	}

	if (! fieldList[fieldLoop].compare("Open") ||
	    ! fieldList[fieldLoop].compare("High") ||
	    ! fieldList[fieldLoop].compare("Low") ||
	    ! fieldList[fieldLoop].compare("Close"))
	{
          if (setTFloat(listItem, TRUE))
	  {
            QString ss = QString().sprintf("%s - %s - %s: %i %s: %s",
              fName.latin1(), symbol.latin1(), tr("Line").latin1(), lineCount,
              tr("Bad value").latin1(), tr(fieldList[fieldLoop]).latin1()
              );
            printStatusLogMessage(ss);
	    flag = TRUE;
	    break;
	  }
          ts = QString::number(tfloat);
	  r.setData(fieldList[fieldLoop], ts);
	  continue;
	}

	if (! fieldList[fieldLoop].compare("Volume") ||
	    ! fieldList[fieldLoop].compare("OI"))
	{
          if (setTFloat(listItem, FALSE))
	  {
            QString ss = QString().sprintf("%s - %s - %s: %s %s: %s",
              fName.latin1(), symbol.latin1(), tr("Line").latin1(), QString::number(lineCount).latin1(),
              tr("Bad value").latin1(), tr(fieldList[fieldLoop]).latin1()
              );
            printStatusLogMessage(ss);
	    flag = TRUE;
	    break;
	  }
          ts = QString::number(tfloat);
	  r.setData(fieldList[fieldLoop], ts);
	  continue;
	}
      }

      if (flag)
	continue;

      ts = "Date";
      r.getData(ts, s);
      if (! s.length())
	continue;

      ts = "Time";
      r.getData(ts, ts2);
      if (ts2.length())
        s.append(ts2);
      else
        s.append("000000");

      Bar bar;
      if (bar.setDate(s))
      {
        ts = "Date";
        r.getData(ts, ts2);
        QString ss = tr("Bad date") + " " + ts2;
        printStatusLogMessage(ss);
        continue;
      }
      bar.setTickFlag(tickFlag);
      ts = "Open";
      bar.setOpen(r.getDouble(ts));
      ts = "High";
      bar.setHigh(r.getDouble(ts));
      ts = "Low";
      bar.setLow(r.getDouble(ts));
      ts = "Close";
      bar.setClose(r.getDouble(ts));
      ts = "Volume";
      bar.setVolume(r.getDouble(ts));
      ts = "OI";
      bar.setOI(r.getInt(ts));

      DBIndexItem item;

      if (! symbol.length())
      {
        ts = "Symbol";
        QString t;
        r.getData(ts, t);
	s = path;
	s.append(t);
	if (openDb(s, t, type, tickFlag))
	  continue;

        ts = "Name";
	r.getData(ts, s);
	if (s.length())
        {
          chartIndex->getIndexItem(t, item);
          item.setTitle(s);
	  chartIndex->setIndexItem(t, item);
        }

        db.setBar(bar);

        ts = "Symbol";
        r.getData(ts, ts2);
//        QString ss = tr("Updating") + " " + ts2;
//        printStatusLogMessage(ss);
	config.closePlugin(type);

        db.close();

        emit signalWakeup();
      }
      else
      {
        ts = "Name";
	r.getData(ts, s);
	if (s.length())
        {
          chartIndex->getIndexItem(symbol, item);
          item.setTitle(s);
	  chartIndex->setIndexItem(symbol, item);
        }
        db.setBar(bar);

        emit signalWakeup();
      }
    }

    db.close();
    f.close();
  }

  progressBar->setProgress((int) list.count(), (int) list.count());
  downloadComplete();
  if (cancelFlag)
  {
    cancelFlag = FALSE;
    printStatusLogMessage(stringCanceled);
  }
  else {
    QString ss = stringDone + " " + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    printStatusLogMessage(ss);
  }
  progressBar->reset();
}
Example #23
0
bool QTranslator::load(const QString & filename, const QString & directory,
                       const QString & search_delimiters,
                       const QString & suffix)
{
    Q_D(QTranslator);
    d->clear();

    QString prefix;
    if (QFileInfo(filename).isRelative()) {
        prefix = directory;
	if (prefix.length() && !prefix.endsWith(QLatin1Char('/')))
	    prefix += QLatin1Char('/');
    }

    QString fname = filename;
    QString realname;
    QString delims;
    delims = search_delimiters.isNull() ? QString::fromLatin1("_.") : search_delimiters;

    for (;;) {
        QFileInfo fi;

        realname = prefix + fname + (suffix.isNull() ? QString::fromLatin1(".qm") : suffix);
        fi.setFile(realname);
        if (fi.isReadable() && fi.isFile())
            break;

        realname = prefix + fname;
        fi.setFile(realname);
        if (fi.isReadable() && fi.isFile())
            break;

        int rightmost = 0;
        for (int i = 0; i < (int)delims.length(); i++) {
            int k = fname.lastIndexOf(delims[i]);
            if (k > rightmost)
                rightmost = k;
        }

        // no truncations? fail
        if (rightmost == 0)
            return false;

        fname.truncate(rightmost);
    }

    // realname is now the fully qualified name of a readable file.

    bool ok = false;

#ifdef QT_USE_MMAP

#ifndef MAP_FILE
#define MAP_FILE 0
#endif
#ifndef MAP_FAILED
#define MAP_FAILED -1
#endif

    int fd = -1;
    if (!realname.startsWith(QLatin1Char(':')))
        fd = QT_OPEN(QFile::encodeName(realname), O_RDONLY,
#if defined(Q_OS_WIN)
                     _S_IREAD | _S_IWRITE
#else
                     0666
#endif
            );
    if (fd >= 0) {
        QT_STATBUF st;
        if (!QT_FSTAT(fd, &st)) {
            char *ptr;
            ptr = reinterpret_cast<char *>(
                mmap(0, st.st_size,             // any address, whole file
                     PROT_READ,                 // read-only memory
                     MAP_FILE | MAP_PRIVATE,    // swap-backed map from file
                     fd, 0));                   // from offset 0 of fd
            if (ptr && ptr != reinterpret_cast<char *>(MAP_FAILED)) {
                d->used_mmap = true;
                d->unmapPointer = ptr;
                d->unmapLength = st.st_size;
                ok = true;
            }
        }
        ::close(fd);
    }
#endif // QT_USE_MMAP

    if (!ok) {
        QFile file(realname);
        d->unmapLength = file.size();
        if (!d->unmapLength)
            return false;
        d->unmapPointer = new char[d->unmapLength];

        if (file.open(QIODevice::ReadOnly))
            ok = (d->unmapLength == (uint)file.read(d->unmapPointer, d->unmapLength));

        if (!ok) {
            delete [] d->unmapPointer;
            d->unmapPointer = 0;
            d->unmapLength = 0;
            return false;
        }
    }

    return d->do_load(reinterpret_cast<const uchar *>(d->unmapPointer), d->unmapLength);
}
Example #24
0
void KNewFileMenuSingleton::parseFiles()
{
    //kDebug(1203);
    filesParsed = true;
    KNewFileMenuSingleton::EntryList::iterator templ = templatesList->begin();
    const KNewFileMenuSingleton::EntryList::iterator templ_end = templatesList->end();
    for (; templ != templ_end; ++templ)
    {
        QString iconname;
        QString filePath = (*templ).filePath;
        if (!filePath.isEmpty())
        {
            QString text;
            QString templatePath;
            // If a desktop file, then read the name from it.
            // Otherwise (or if no name in it?) use file name
            if (KDesktopFile::isDesktopFile(filePath)) {
                KDesktopFile desktopFile( filePath);
                text = desktopFile.readName();
                (*templ).icon = desktopFile.readIcon();
                (*templ).comment = desktopFile.readComment();
                QString type = desktopFile.readType();
                if (type == "Link")
                {
                    templatePath = desktopFile.desktopGroup().readPathEntry("URL", QString());
                    if (templatePath[0] != '/' && !templatePath.startsWith("__"))
                    {
                        if (templatePath.startsWith("file:/"))
                            templatePath = KUrl(templatePath).toLocalFile();
                        else
                        {
                            // A relative path, then (that's the default in the files we ship)
                            QString linkDir = filePath.left(filePath.lastIndexOf('/') + 1 /*keep / */);
                            //kDebug(1203) << "linkDir=" << linkDir;
                            templatePath = linkDir + templatePath;
                        }
                    }
                }
                if (templatePath.isEmpty())
                {
                    // No URL key, this is an old-style template
                    (*templ).entryType = KNewFileMenuSingleton::Template;
                    (*templ).templatePath = (*templ).filePath; // we'll copy the file
                } else {
                    (*templ).entryType = KNewFileMenuSingleton::LinkToTemplate;
                    (*templ).templatePath = templatePath;
                }

            }
            if (text.isEmpty())
            {
                text = KUrl(filePath).fileName();
                if (text.endsWith(".desktop"))
                    text.truncate(text.length() - 8);
            }
            (*templ).text = text;
            /*kDebug(1203) << "Updating entry with text=" << text
                          << "entryType=" << (*templ).entryType
                          << "templatePath=" << (*templ).templatePath;*/
        }
        else {
            (*templ).entryType = KNewFileMenuSingleton::Separator;
        }
    }
}
Example #25
0
// ### AbanQ
static ulong embedData_MSB( QTextStream& out, const uchar* input, int nbytes ) {
#ifndef QT_NO_IMAGE_COLLECTION_COMPRESSION
  QByteArray bazip( qCompress( input, nbytes ) );
  ulong len = bazip.size();
#else
  ulong len = nbytes;
#endif
  static const char hexdigits[] = "0123456789abcdef";
  QString s;
  for ( int i = 0; i < ( int )len; i++ ) {
    if (( i % 14 ) == 0 ) {
      s += "\n    ";
      out << ( const char* )s;
      s.truncate( 0 );
    }
    uint v = ( uchar )
#ifndef QT_NO_IMAGE_COLLECTION_COMPRESSION
             bazip
#else
             input
#endif
             [i + 3];
    s += "0x";
    s += hexdigits[( v >> 4 ) & 15];
    s += hexdigits[v & 15];
    s += ',';

    v = ( uchar )
#ifndef QT_NO_IMAGE_COLLECTION_COMPRESSION
             bazip
#else
             input
#endif
             [i + 2];
    s += "0x";
    s += hexdigits[( v >> 4 ) & 15];
    s += hexdigits[v & 15];
    s += ',';

    v = ( uchar )
#ifndef QT_NO_IMAGE_COLLECTION_COMPRESSION
             bazip
#else
             input
#endif
             [i + 1];
    s += "0x";
    s += hexdigits[( v >> 4 ) & 15];
    s += hexdigits[v & 15];
    s += ',';

    v = ( uchar )
#ifndef QT_NO_IMAGE_COLLECTION_COMPRESSION
             bazip
#else
             input
#endif
             [i];
    s += "0x";
    s += hexdigits[( v >> 4 ) & 15];
    s += hexdigits[v & 15];

    i += 3;

    if ( i < ( int )len - 1 )
      s += ',';
  }
  if ( s.length() )
    out << ( const char* )s;
  return len;
}
Example #26
0
bool MneFiffExpSet::show_fiff_contents(FILE *out, const QString &name, bool verbose, const QList<int> &tags, int indent_step, bool long_strings, bool blocks_only)
{
    QFile file(name);
    FiffStream::SPtr stream(new FiffStream(&file));

    FiffDirEntry::SPtr this_ent;
    FiffTag::SPtr   tag;
    int             day,month,year;
    int             block;
    int             count = 0;
    int             prev_kind;
    int             indent = 0;
    bool            show_it = false;
    QString         s;
    bool            output_taginfo = false;
    QList<MneFiffExp>::const_iterator exp;

    if (!stream->open())
        return false;
    prev_kind = -1;

    if (blocks_only) {
        //        for (auto this_ent : stream->dir()) {//C++11
        for (int i = 0; i < stream->dir().size(); ++i) {
            this_ent = stream->dir()[i];
            if (this_ent->kind == FIFF_BLOCK_START || this_ent->kind == FIFF_BLOCK_END) {
                if (this_ent->kind == FIFF_BLOCK_END)
                    indent = indent - indent_step;
                if (this_ent->kind == FIFF_BLOCK_START) {
                    for (int k = 0; k < indent; k++)
                        fprintf(out," ");
                    if ( stream->read_tag(tag, this_ent->pos) ) {
                        block = *tag->toInt();
                        exp = this->find_fiff_explanation(CLASS_BLOCK,block);
                        if (exp != this->constEnd())
                            fprintf(out,"%-d = %-s\n",exp->kind,exp->text.toUtf8().constData());
                        else
                            fprintf(out,"%-d = %-s\n",block,"Not explained");
                    }
                }
                if (this_ent->kind == FIFF_BLOCK_START)
                    indent = indent + indent_step;
            }
        }
    }
    else {
        //        for (auto this_ent : stream->dir()) {//C++11
        for (int i = 0; i < stream->dir().size(); ++i) {
            this_ent = stream->dir()[i];
            if (tags.size() == 0)
                show_it = true;
            else {
                show_it = false;
                for (int k = 0; k < tags.size(); k++) {
                    if (this_ent->kind == tags[k]) {
                        show_it = true;
                        break;
                    }
                }
            }
            if (show_it) {
                if (this_ent->kind == FIFF_BLOCK_START || this_ent->kind == FIFF_BLOCK_END) {
                    if (!verbose) {
                        if (count > 1)
                            fprintf(out," [%d]\n",count);
                        else if (this_ent != stream->dir()[0])
                            fprintf(out,"\n");
                    }
                    if (this_ent->kind == FIFF_BLOCK_END)
                        indent = indent - indent_step;
                    for (int k = 0; k < indent; k++)
                        fprintf(out," ");
                    exp = this->find_fiff_explanation(CLASS_TAG,this_ent->kind);
                    if (exp != this->constEnd())
                        fprintf(out,"%4d = %-s",exp->kind,exp->text.toUtf8().constData());
                    else
                        fprintf(out,"%4d = %-s",this_ent->kind,"Not explained");
                    if ( stream->read_tag(tag,this_ent->pos)) {
                        block = *tag->toInt();
                        exp = this->find_fiff_explanation(CLASS_BLOCK,block);
                        if (exp != this->constEnd())
                            fprintf(out,"\t%-d = %-s",exp->kind,exp->text.toUtf8().constData());
                        else
                            fprintf(out,"\t%-d = %-s",block,"Not explained");
                    }
                    if ( this_ent->kind == FIFF_BLOCK_START)
                        indent = indent + indent_step;
                    count = 1;
                    if (verbose)
                        fprintf(out,"\n");
                }
                else if (verbose) {
                    for (int k = 0; k < indent; k++)
                        fprintf(out," ");
                    if (output_taginfo) {
                        fprintf(out,"%d %d ",this_ent->size,this_ent->type);
                    }
                    exp = this->find_fiff_explanation(CLASS_TAG,this_ent->kind);
                    if (exp != this->constEnd())
                        fprintf(out,"%4d = %-18s",exp->kind,exp->text.toUtf8().constData());
                    else
                        fprintf(out,"%4d = %-18s",this_ent->kind,"Not explained");
                    if (FiffTag::fiff_type_fundamental(this_ent->type) == FIFFTS_FS_MATRIX) {
                        fprintf(out,"TODO print_matrix");
                        //                        print_matrix(out,in,this_ent);
                    }
                    else {
                        switch (this_ent->type) {
                        case FIFFT_INT :
                            if (stream->read_tag(tag,this_ent->pos)) {
                                if (this_ent->kind == FIFF_BLOCK_START ||
                                        this_ent->kind == FIFF_BLOCK_END) {
                                    block = *tag->toInt();
                                    exp = this->find_fiff_explanation(CLASS_BLOCK,block);
                                    if (exp != this->constEnd())
                                        fprintf(out,"\t%-d = %s",exp->kind,exp->text.toUtf8().constData());
                                    else
                                        fprintf(out,"\t%-d = %-s",block,"Not explained");
                                }
                                else if (this_ent->kind == FIFF_MEAS_DATE) {
                                    QDateTime ltime;
                                    ltime.setTime_t(tag->toInt()[0]);
                                    fprintf(out,"\t%s",ltime.toString().toUtf8().constData());
                                }
                                else if (tag->size() == sizeof(fiff_int_t))
                                    fprintf(out,"\t%d",*tag->toInt());
                                else
                                    fprintf(out,"\t%d ints",(int)(tag->size()/sizeof(fiff_int_t)));
                            }
                            break;
                        case FIFFT_UINT :
                            if (stream->read_tag(tag,this_ent->pos)) {
                                if (tag->size() == sizeof(fiff_int_t))
                                    fprintf(out,"\t%d",*tag->toUnsignedInt());
                                else
                                    fprintf(out,"\t%d u_ints",(int)(tag->size()/sizeof(fiff_int_t)));
                            }
                            break;
                        case FIFFT_JULIAN :
                            if (stream->read_tag(tag,this_ent->pos)) {
                                fprintf(out,"TODO fiff_caldate");
                                //                                fiff_caldate (*(fiff_julian_t *)tag.data,&day,&month,&year);
                                fprintf(out,"\t%d.%d.%d",day,month,year);
                            }
                            break;
                        case FIFFT_STRING :
                            if (stream->read_tag(tag,this_ent->pos)) {
                                s = tag->toString();
                                if (long_strings)
                                    fprintf(out,"\t%s",tag->toString().toUtf8().constData());
                                else {
                                    if ((s.indexOf("\n")) != -1)
                                        s.replace(s.indexOf("\n"), 2, "\0");
                                    else if (s.size() > LONG_LINE) {
                                        s.truncate(LONG_LINE);
                                        s += "...";
                                    }
                                    fprintf(out,"\t%s",s.toUtf8().constData());
                                }
                            }
                            break;
                        case FIFFT_FLOAT :
                            if (stream->read_tag(tag,this_ent->pos)) {
                                if (tag->size() == sizeof(fiff_float_t))
                                    fprintf(out,"\t%g",*tag->toFloat());
                                else
                                    fprintf(out,"\t%d floats",(int)(tag->size()/sizeof(fiff_float_t)));
                            }
                            break;
                        case FIFFT_DOUBLE :
                            if (stream->read_tag(tag,this_ent->pos)) {
                                if (tag->size() == sizeof(fiff_double_t))
                                    fprintf(out,"\t%g",*tag->toDouble());
                                else
                                    fprintf(out,"\t%d doubles",(int)(tag->size()/sizeof(fiff_double_t)));
                            }
                            break;
                        case FIFFT_COMPLEX_FLOAT :
                            if (stream->read_tag(tag,this_ent->pos)) {
                                float *fdata = tag->toFloat();
                                if (tag->size() == 2*sizeof(fiff_float_t))
                                    fprintf(out,"\t(%g %g)",fdata[0],fdata[1]);
                                else
                                    fprintf(out,"\t%d complex numbers",
                                            (int)(tag->size()/(2*sizeof(fiff_float_t))));
                            }
                            break;
                        case FIFFT_COMPLEX_DOUBLE :
                            if (stream->read_tag(tag,this_ent->pos)) {
                                double *ddata = tag->toDouble();
                                if (tag->size() == 2*sizeof(fiff_double_t))
                                    fprintf(out,"\t(%g %g)",ddata[0],ddata[1]);
                                else
                                    fprintf(out,"\t%d double complex numbers",
                                            (int)(tag->size()/(2*sizeof(fiff_double_t))));
                            }
                            break;
                        case FIFFT_CH_INFO_STRUCT :
                            if (stream->read_tag(tag,this_ent->pos))
                                fprintf(out,"TODO print_ch_info");
                            //                                print_ch_info (out,set,(fiff_ch_info_t *)tag.data);
                            break;
                        case FIFFT_ID_STRUCT :
                            if (stream->read_tag(tag,this_ent->pos))
                                fprintf(out,"TODO print_file_id");
                            //                                if (tag.size == sizeof(fiff_id_t))
                            //                                    print_file_id (out,(fiff_id_t *)tag.data);
                            break;
                        case FIFFT_DIG_POINT_STRUCT :
                            if (stream->read_tag(tag,this_ent->pos))
                                fprintf(out,"TODO print_dig_point");
                            //                                if (tag.size == sizeof(fiff_dig_point_t))
                            //                                    print_dig_point (out,(fiff_dig_point_t *)tag.data);
                            break;
                        case FIFFT_DIG_STRING_STRUCT :
                            if (stream->read_tag(tag,this_ent->pos)) {
#ifdef FOO
                                if ((ds = decode_fiff_dig_string(&tag)) != NULL)
                                    print_dig_string (ds);
                                free_fiff_dig_string(ds);
#endif
                            }
                            break;
                        case FIFFT_COORD_TRANS_STRUCT :
                            if (stream->read_tag(tag,this_ent->pos))
                                fprintf(out,"TODO print_transform");
                            //                                if (tag.size == sizeof(fiff_coord_trans_t))
                            //                                    print_transform   (out,(fiff_coord_trans_t *)tag.data);
                            break;
                        default :
                            if (this_ent->kind == FIFF_DIG_STRING)
                                fprintf(out,"type = %d\n",this_ent->type);
                            if (this_ent->size > 0)
                                fprintf(out,"\t%d bytes",this_ent->size);
                            break;
                        }
                    }
                    fprintf(out,"\n");
                    prev_kind = this_ent->kind;
                }
                else {
                    if (this_ent->kind != prev_kind) {
                        if (count > 1)
                            fprintf(out," [%d]\n",count);
                        else if (this_ent != stream->dir()[0])
                            fprintf(out,"\n");
                        for (int k = 0; k < indent; k++)
                            fprintf(out," ");
                        exp = this->find_fiff_explanation(CLASS_TAG,this_ent->kind);
                        if (exp != this->constEnd())
                            fprintf(out,"%4d = %-s",exp->kind,exp->text.toUtf8().constData());
                        else
                            fprintf(out,"%4d = %-s",this_ent->kind,"Not explained");
                        count = 1;
                    }
                    else
                        count++;
                }
            }
            prev_kind = this_ent->kind;
        }
        if (!verbose) {
            if (count > 1)
                fprintf(out," [%d]\n",count);
            else
                fprintf(out,"\n");
        }
    }

    stream->close();

    return true;
}
Example #27
0
/*!
    Returns a string representation of the \a field value for the
    database. This is used, for example, when constructing INSERT and
    UPDATE statements.

    The default implementation returns the value formatted as a string
    according to the following rules:

    \list

    \i If \a field is character data, the value is returned enclosed
    in single quotation marks, which is appropriate for many SQL
    databases. Any embedded single-quote characters are escaped
    (replaced with two single-quote characters). If \a trimStrings is
    true (the default is false), all trailing whitespace is trimmed
    from the field.

    \i If \a field is date/time data, the value is formatted in ISO
    format and enclosed in single quotation marks. If the date/time
    data is invalid, "NULL" is returned.

    \i If \a field is \link QByteArray bytearray\endlink data, and the
    driver can edit binary fields, the value is formatted as a
    hexadecimal string.

    \i For any other field type, toString() is called on its value
    and the result of this is returned.

    \endlist

    \sa QVariant::toString()

*/
QString QSqlDriver::formatValue(const QSqlField &field, bool trimStrings) const
{
    const QLatin1String nullTxt("NULL");

    QString r;
    if (field.isNull())
        r = nullTxt;
    else {
        switch (field.type()) {
        case QVariant::Int:
        case QVariant::UInt:
            if (field.value().type() == QVariant::Bool)
                r = field.value().toBool() ? QLatin1String("1") : QLatin1String("0");
            else
                r = field.value().toString();
            break;
#ifndef QT_NO_DATESTRING
	case QVariant::Date:
            if (field.value().toDate().isValid())
                r = QLatin1Char('\'') + field.value().toDate().toString(Qt::ISODate)
                    + QLatin1Char('\'');
            else
                r = nullTxt;
            break;
        case QVariant::Time:
            if (field.value().toTime().isValid())
                r =  QLatin1Char('\'') + field.value().toTime().toString(Qt::ISODate)
                     + QLatin1Char('\'');
            else
                r = nullTxt;
            break;
        case QVariant::DateTime:
            if (field.value().toDateTime().isValid())
                r = QLatin1Char('\'') +
                    field.value().toDateTime().toString(Qt::ISODate) + QLatin1Char('\'');
            else
                r = nullTxt;
            break;
#endif
        case QVariant::String:
        case QVariant::Char:
        {
            QString result = field.value().toString();
            if (trimStrings) {
                int end = result.length();
                while (end && result.at(end-1).isSpace()) /* skip white space from end */
                    end--;
                result.truncate(end);
            }
            /* escape the "'" character */
            result.replace(QLatin1Char('\''), QLatin1String("''"));
            r = QLatin1Char('\'') + result + QLatin1Char('\'');
            break;
        }
        case QVariant::Bool:
            if (field.value().toBool())
                r = QLatin1String("1");
            else
                r = QLatin1String("0");
            break;
        case QVariant::ByteArray : {
            if (hasFeature(BLOB)) {
                QByteArray ba = field.value().toByteArray();
                QString res;
                static const char hexchars[] = "0123456789abcdef";
                for (int i = 0; i < ba.size(); ++i) {
                    uchar s = (uchar) ba[i];
                    res += QLatin1Char(hexchars[s >> 4]);
                    res += QLatin1Char(hexchars[s & 0x0f]);
                }
                r = QLatin1Char('\'') + res +  QLatin1Char('\'');
                break;
            }
        }
        default:
            r = field.value().toString();
            break;
        }
    }
    return r;
}
Example #28
0
void MatWindow::processMat(QTreeWidgetItem* currentItem)
{
    if(!currentItem)
        return;

    return;

    //clean old values
    strAllMat = "";
    matText->clear();
    textureLbl->setPixmap(QPixmap(""));
    textureLbl->setText("Texture Unavailable");

    //We'll seek for the material to include it in matText.
    QDir dir(scriptPath);
    QStringList listFiles(dir.entryList(QStringList() << "*.material", QDir::Files));

    for(int i = 0; i < listFiles.size(); i++)
    {
        QFile file(dir.path() + QDir::separator() + listFiles.at(i));
        if(file.open(QIODevice::ReadOnly))
        {
            QTextStream script(&file);
            //Search our mat
            QString strMat = script.readAll();
            QString nameMat("material "+currentItem->text(0));
            posMat = strMat.indexOf(nameMat);
            if(posMat != -1)
            {
                matText->setPlainText(strMat);//insert all the text and keep it in strAllMat
                strAllMat = matText->toPlainText();
                matText->clear();//clear it so the user don't see anything

                //Process: we cut the beginning of the string. Then we cut all others material
                //So we only have the material wich interest us
                strMat.remove(0, posMat);//we cut the firt part of the string
                nextMat = strMat.indexOf("material ", 8);//search the next material at pos 8 because we want the next material (not the first one)
                if(nextMat != -1)
                    strMat.remove(nextMat, strMat.size());//we cut from this next material to the end so we only have the material we want

                //Processing strMat
                for(int i=0; i<strMat.size(); ++i)
                {
                    if(strMat.at(i) == '\t')
                        strMat.replace(i, 1, "          ");
                }
                matText->setPlainText(strMat);
                QFont f("Arial", 8);
                matText->setFont(f);

                //Now we're looking for the texture
                int posText = strMat.indexOf("texture ");
                if(posText != -1)
                {
                    QString textureName;
                    for(int i=posText+8; i<strMat.size(); ++i)
                    {
                        textureName += strMat.at(i);
                    }
                    textureName.truncate(textureName.indexOf('.'));
                    QPixmap img;
                    if(img.load(texturePath+textureName))
                    {
                        img = img.scaled(150, 150);
                        textureLbl->setText(textureName);
                        textureLbl->setPixmap(img);
                    }
                    else
                    {
                        textureLbl->setText("Image Unavailable");
                    }
                }
                matFile.setFileName(file.fileName());//Finally we keep matFile in memory so that we can open the file later --> saveMat()
            }
        }
        file.close();
    }
}
Example #29
0
void BookmarksToolbar::refreshBookmarks()
{
    QSqlQuery query;
    query.exec("SELECT id, title, url, icon FROM bookmarks WHERE folder='bookmarksToolbar' ORDER BY toolbar_position");
    while (query.next()) {
        Bookmark bookmark;
        bookmark.id = query.value(0).toInt();
        bookmark.title = query.value(1).toString();
        bookmark.url = query.value(2).toUrl();
        bookmark.icon = IconProvider::iconFromBase64(query.value(3).toByteArray());
        bookmark.folder = "bookmarksToolbar";
        QString title = bookmark.title;
        if (title.length() > 15) {
            title.truncate(13);
            title += "..";
        }

        QVariant v;
        v.setValue<Bookmark>(bookmark);

        ToolButton* button = new ToolButton(this);
        button->setText(title);
        button->setData(v);
        button->setIcon(bookmark.icon);
        button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
        button->setToolTip(bookmark.url.toEncoded());
        button->setWhatsThis(bookmark.title);
        button->setAutoRaise(true);
        button->setContextMenuPolicy(Qt::CustomContextMenu);

        connect(button, SIGNAL(clicked()), this, SLOT(loadClickedBookmark()));
        connect(button, SIGNAL(middleMouseClicked()), this, SLOT(loadClickedBookmarkInNewTab()));
        connect(button, SIGNAL(controlClicked()), this, SLOT(loadClickedBookmarkInNewTab()));
        connect(button, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showBookmarkContextMenu(QPoint)));
        m_layout->addWidget(button);
    }

    query.exec("SELECT name FROM folders WHERE subfolder='yes'");
    while (query.next()) {
        ToolButton* b = new ToolButton(this);
        b->setPopupMode(QToolButton::InstantPopup);
        b->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
        b->setIcon(style()->standardIcon(QStyle::SP_DirIcon));
        b->setText(query.value(0).toString());

        Menu* menu = new Menu(query.value(0).toString());
        b->setMenu(menu);
        connect(menu, SIGNAL(aboutToShow()), this, SLOT(aboutToShowFolderMenu()));

        m_layout->addWidget(b);
    }

    m_mostVis = new ToolButton(this);
    m_mostVis->setPopupMode(QToolButton::InstantPopup);
    m_mostVis->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
    m_mostVis->setIcon(style()->standardIcon(QStyle::SP_DirIcon));
    m_mostVis->setText(tr("Most visited"));
    m_mostVis->setToolTip(tr("Sites you visited the most"));

    m_menuMostVisited = new Menu();
    m_mostVis->setMenu(m_menuMostVisited);
    connect(m_menuMostVisited, SIGNAL(aboutToShow()), this, SLOT(refreshMostVisited()));

    m_layout->addWidget(m_mostVis);
    m_layout->addStretch();

    m_mostVis->setVisible(m_bookmarksModel->isShowingMostVisited());
}
Example #30
0
void Smtp::readyRead() {
	
	 qDebug() << "readyRead";
	// SMTP is line-oriented

	QString responseLine;
	do {
		responseLine = socket->readLine();
		response += responseLine;
	}
	while(socket->canReadLine() && responseLine[3] != ' ');
	qDebug() << response;
	responseLine.truncate(3);

	if (state == Init && responseLine[0] == '2') {
		// banner was okay, let's go on

		*t << "Hello!\r\n";
		t->flush();
		
		state = Mail;
	}
	else if (state == Mail && responseLine[0] == '2') {
		// HELLO response was okay (well, it has to be)

		*t << "MAIL FROM: " << from << "\r\n";
		t->flush();
		state = Rcpt;
	}
	else if (state == Rcpt && responseLine[0] == '2') {
		*t << "RCPT TO: " << rcpt << "\r\n"; //r
		t->flush();
		state = Data;
	}
	else if (state == Data && responseLine[0] == '2') {
		*t << "DATA\r\n";
		t->flush();
		state = Body;
	}
	else if (state == Body && responseLine[0] == '3') {
		*t << message << "\r\n.\r\n";
		t->flush();
		state = Quit;
	}
	else if (state == Quit && responseLine[0] == '2') {

		*t << "QUIT\r\n";
		t->flush();
		// Here, we just close.
		state = Close;
		emit status(tr("Message sent"));
	}
	else if (state == Close) {
		deleteLater();
		return;
	}
	else {
		// something broke.
		QMessageBox::warning(0, tr("IP Checker"), tr("Unexpected reply from SMTP server:\n\n") + response);
		state = Close;
	}
	response = "";
}