Example #1
0
// Convert simple DOM types
QVariant domPropertyToVariant(const DomProperty *p)
{
    // requires non-const virtual nameToIcon, etc.
    switch(p->kind()) {
    case DomProperty::Bool:
        return QVariant(p->elementBool() == QFormBuilderStrings::instance().trueValue);

    case DomProperty::Cstring:
        return QVariant(p->elementCstring().toUtf8());

    case DomProperty::Point: {
        const DomPoint *point = p->elementPoint();
        return QVariant(QPoint(point->elementX(), point->elementY()));
    }

    case DomProperty::PointF: {
        const DomPointF *pointf = p->elementPointF();
        return QVariant(QPointF(pointf->elementX(), pointf->elementY()));
    }

    case DomProperty::Size: {
        const DomSize *size = p->elementSize();
        return QVariant(QSize(size->elementWidth(), size->elementHeight()));
    }

    case DomProperty::SizeF: {
        const DomSizeF *sizef = p->elementSizeF();
        return QVariant(QSizeF(sizef->elementWidth(), sizef->elementHeight()));
    }

    case DomProperty::Rect: {
        const DomRect *rc = p->elementRect();
        const QRect g(rc->elementX(), rc->elementY(), rc->elementWidth(), rc->elementHeight());
        return QVariant(g);
    }

    case DomProperty::RectF: {
        const DomRectF *rcf = p->elementRectF();
        const QRectF g(rcf->elementX(), rcf->elementY(), rcf->elementWidth(), rcf->elementHeight());
        return QVariant(g);
    }

    case DomProperty::String:
        return QVariant(p->elementString()->text());

    case DomProperty::Number:
        return QVariant(p->elementNumber());

    case DomProperty::UInt:
        return QVariant(p->elementUInt());

    case DomProperty::LongLong:
        return QVariant(p->elementLongLong());

    case DomProperty::ULongLong:
        return QVariant(p->elementULongLong());

    case DomProperty::Double:
        return QVariant(p->elementDouble());

    case DomProperty::Char: {
        const DomChar *character = p->elementChar();
        const QChar c(character->elementUnicode());
        return QVariant::fromValue(c);
    }

    case DomProperty::Color: {
        const DomColor *color = p->elementColor();
        QColor c(color->elementRed(), color->elementGreen(), color->elementBlue());
        if (color->hasAttributeAlpha())
            c.setAlpha(color->attributeAlpha());
        return QVariant::fromValue(c);
    }

    case DomProperty::Font: {
        const DomFont *font = p->elementFont();

        QFont f;
        if (font->hasElementFamily() && !font->elementFamily().isEmpty())
            f.setFamily(font->elementFamily());
        if (font->hasElementPointSize() && font->elementPointSize() > 0)
            f.setPointSize(font->elementPointSize());
        if (font->hasElementWeight() && font->elementWeight() > 0)
            f.setWeight(font->elementWeight());
        if (font->hasElementItalic())
            f.setItalic(font->elementItalic());
        if (font->hasElementBold())
            f.setBold(font->elementBold());
        if (font->hasElementUnderline())
            f.setUnderline(font->elementUnderline());
        if (font->hasElementStrikeOut())
            f.setStrikeOut(font->elementStrikeOut());
        if (font->hasElementKerning())
            f.setKerning(font->elementKerning());
        if (font->hasElementAntialiasing())
            f.setStyleStrategy(font->elementAntialiasing() ? QFont::PreferDefault : QFont::NoAntialias);
        if (font->hasElementStyleStrategy()) {
            f.setStyleStrategy(enumKeyOfObjectToValue<QAbstractFormBuilderGadget, QFont::StyleStrategy>("styleStrategy", font->elementStyleStrategy().toLatin1()));
        }
        return QVariant::fromValue(f);
    }

    case DomProperty::Date: {
        const DomDate *date = p->elementDate();
        return QVariant(QDate(date->elementYear(), date->elementMonth(), date->elementDay()));
    }

    case DomProperty::Time: {
        const DomTime *t = p->elementTime();
        return QVariant(QTime(t->elementHour(), t->elementMinute(), t->elementSecond()));
    }

    case DomProperty::DateTime: {
        const DomDateTime *dateTime = p->elementDateTime();
        const QDate d(dateTime->elementYear(), dateTime->elementMonth(), dateTime->elementDay());
        const QTime tm(dateTime->elementHour(), dateTime->elementMinute(), dateTime->elementSecond());
        return QVariant(QDateTime(d, tm));
    }

    case DomProperty::Url: {
        const DomUrl *url = p->elementUrl();
        return QVariant(QUrl(url->elementString()->text()));
    }

#ifndef QT_NO_CURSOR
    case DomProperty::Cursor:
        return QVariant::fromValue(QCursor(static_cast<Qt::CursorShape>(p->elementCursor())));

    case DomProperty::CursorShape:
        return QVariant::fromValue(QCursor(enumKeyOfObjectToValue<QAbstractFormBuilderGadget, Qt::CursorShape>("cursorShape", p->elementCursorShape().toLatin1())));
#endif

    case DomProperty::Locale: {
        const DomLocale *locale = p->elementLocale();
        return QVariant::fromValue(QLocale(enumKeyOfObjectToValue<QAbstractFormBuilderGadget, QLocale::Language>("language", locale->attributeLanguage().toLatin1()),
                    enumKeyOfObjectToValue<QAbstractFormBuilderGadget, QLocale::Country>("country", locale->attributeCountry().toLatin1())));
    }
    case DomProperty::SizePolicy: {
        const DomSizePolicy *sizep = p->elementSizePolicy();

        QSizePolicy sizePolicy;
        sizePolicy.setHorizontalStretch(sizep->elementHorStretch());
        sizePolicy.setVerticalStretch(sizep->elementVerStretch());

        const QMetaEnum sizeType_enum = metaEnum<QAbstractFormBuilderGadget>("sizeType");

        if (sizep->hasElementHSizeType()) {
            sizePolicy.setHorizontalPolicy((QSizePolicy::Policy) sizep->elementHSizeType());
        } else if (sizep->hasAttributeHSizeType()) {
            const QSizePolicy::Policy sp = enumKeyToValue<QSizePolicy::Policy>(sizeType_enum, sizep->attributeHSizeType().toLatin1());
            sizePolicy.setHorizontalPolicy(sp);
        }

        if (sizep->hasElementVSizeType()) {
            sizePolicy.setVerticalPolicy((QSizePolicy::Policy) sizep->elementVSizeType());
        } else if (sizep->hasAttributeVSizeType()) {
            const  QSizePolicy::Policy sp = enumKeyToValue<QSizePolicy::Policy>(sizeType_enum, sizep->attributeVSizeType().toLatin1());
            sizePolicy.setVerticalPolicy(sp);
        }

        return QVariant::fromValue(sizePolicy);
    }

    case DomProperty::StringList:
        return QVariant(p->elementStringList()->elementString());

    default:
        uiLibWarning(QCoreApplication::translate("QFormBuilder", "Reading properties of the type %1 is not supported yet.").arg(p->kind()));
        break;
    }

    return QVariant();
}
Example #2
0
	MapAdapter::MapAdapter(const QString& host, const QString& serverPath, int tilesize, int minZoom, int maxZoom)
	:myhost(host), serverPath(serverPath), mytilesize(tilesize), min_zoom(minZoom), max_zoom(maxZoom)
	{	
		current_zoom = min_zoom;
		loc = QLocale(QLocale::English);
	}
Example #3
0
int refresh_qimage( producer_qimage self, mlt_frame frame )
{
	// Obtain properties of frame and producer
	mlt_properties properties = MLT_FRAME_PROPERTIES( frame );
	mlt_producer producer = &self->parent;
	mlt_properties producer_props = MLT_PRODUCER_PROPERTIES( producer );

	// Check if user wants us to reload the image
	if ( mlt_properties_get_int( producer_props, "force_reload" ) )
	{
		self->qimage = NULL;
		self->current_image = NULL;
		mlt_properties_set_int( producer_props, "force_reload", 0 );
	}

	// Get the time to live for each frame
	double ttl = mlt_properties_get_int( producer_props, "ttl" );

	// Get the original position of this frame
	mlt_position position = mlt_frame_original_position( frame );
	position += mlt_producer_get_in( producer );

	// Image index
	int image_idx = ( int )floor( ( double )position / ttl ) % self->count;

	// Key for the cache
	char image_key[ 10 ];
	sprintf( image_key, "%d", image_idx );

	int disable_exif = mlt_properties_get_int( producer_props, "disable_exif" );
	
	
	if ( app == NULL ) 
	{
		if ( qApp ) 
		{
			app = qApp;
		}
		else 
		{
#ifdef linux
			if ( getenv("DISPLAY") == 0 )
			{
				mlt_log_panic( MLT_PRODUCER_SERVICE( producer ), "Error, cannot render titles without an X11 environment.\nPlease either run melt from an X session or use a fake X server like xvfb:\nxvfb-run -a melt (...)\n" );
				return -1;
			}
#endif
			int argc = 1;
			char* argv[1];
			argv[0] = (char*) "xxx";
			app = new QApplication( argc, argv );
			const char *localename = mlt_properties_get_lcnumeric( MLT_SERVICE_PROPERTIES( MLT_PRODUCER_SERVICE( producer ) ) );
			QLocale::setDefault( QLocale( localename ) );
		}
	}

	if ( image_idx != self->qimage_idx )
		self->qimage = NULL;
	if ( !self->qimage || mlt_properties_get_int( producer_props, "_disable_exif" ) != disable_exif )
	{
		self->current_image = NULL;
		QImage *qimage = new QImage( QString::fromUtf8( mlt_properties_get_value( self->filenames, image_idx ) ) );
		self->qimage = qimage;

		if ( !qimage->isNull( ) )
		{
			// Read the exif value for this file
			if ( !disable_exif )
				qimage = reorient_with_exif( self, image_idx, qimage );

			// Register qimage for destruction and reuse
			mlt_cache_item_close( self->qimage_cache );
			mlt_service_cache_put( MLT_PRODUCER_SERVICE( producer ), "qimage.qimage", qimage, 0, ( mlt_destructor )qimage_delete );
			self->qimage_cache = mlt_service_cache_get( MLT_PRODUCER_SERVICE( producer ), "qimage.qimage" );
			self->qimage_idx = image_idx;

			// Store the width/height of the qimage
			self->current_width = qimage->width( );
			self->current_height = qimage->height( );

			mlt_events_block( producer_props, NULL );
			mlt_properties_set_int( producer_props, "meta.media.width", self->current_width );
			mlt_properties_set_int( producer_props, "meta.media.height", self->current_height );
			mlt_properties_set_int( producer_props, "_disable_exif", disable_exif );
			mlt_events_unblock( producer_props, NULL );
		}
		else
		{
			delete qimage;
			self->qimage = NULL;
		}
	}

	// Set width/height of frame
	mlt_properties_set_int( properties, "width", self->current_width );
	mlt_properties_set_int( properties, "height", self->current_height );

	return image_idx;
}
Example #4
0
	void AcceptLangWidget::on_Add__released ()
	{
		const auto country = GetValue<QLocale::Country> (Ui_.Country_);
		const auto lang = GetValue<QLocale::Language> (Ui_.Language_);
		AddLocale (QLocale (lang, country));
	}
Example #5
0
AppSettings::AppSettings()
{
    QCoreApplication::setOrganizationName("ghostwriter");
    QCoreApplication::setApplicationName("ghostwriter");
    QCoreApplication::setApplicationVersion(APPVERSION);

    // The following was lifted/modded from FocusWriter.
    // See GPL license at the beginning of this file.
    //
    QString appDir = qApp->applicationDirPath();

    // Set up portable settings directories.
#if defined(Q_OS_MAC)
    QFileInfo portable(appDir + "/../../../data");
#elif defined(Q_OS_UNIX)
    QFileInfo portable(appDir + "/data");
#else
    QFileInfo portable(appDir + "/data");
#endif

    // Handle portability
    QString userDir;

    if (portable.exists() && portable.isWritable())
    {
        userDir = portable.absoluteFilePath();
        QSettings::setDefaultFormat(QSettings::IniFormat);
        QSettings::setPath
        (
            QSettings::IniFormat,
            QSettings::UserScope,
            userDir + "/settings"
        );

        translationsPath = appDir + "/translations";
    }
    else
    {
#ifdef Q_OS_WIN32
        // On Windows, don't ever use the registry to store settings, for the
        // sake of cleanness, ability to load configuration files on other
        // machines, and also for the user's privacy.
        //
        QSettings::setDefaultFormat(QSettings::IniFormat);
#endif
        QSettings settings;
        userDir = QFileInfo(settings.fileName()).dir().absolutePath();

        QStringList translationPaths;
        translationPaths.append(appDir + "/translations");
        translationPaths.append(appDir + "/../share/" +
            QCoreApplication::applicationName().toLower() +
            "/translations");
        translationPaths.append(appDir + "/../Resources/translations");

        foreach (const QString& path, translationPaths)
        {
            if (QFile::exists(path))
            {
                translationsPath = path;
                break;
            }
        }
    }

    QDir themeDir(userDir + "/themes");

    if (!themeDir.exists())
    {
        themeDir.mkpath(themeDir.path());
    }

    themeDirectoryPath = themeDir.absolutePath();

    QDir dictionaryDir(userDir + "/dictionaries");

    if (!dictionaryDir.exists())
    {
        dictionaryDir.mkpath(dictionaryDir.path());
    }

    dictionaryPath = dictionaryDir.absolutePath();
    DictionaryManager::setPath(dictionaryPath);

    QStringList dictdirs;
    dictdirs.append(DictionaryManager::path());

    dictionaryDir = QDir(appDir + "/dictionaries");

    if (dictionaryDir.exists())
    {
        dictdirs.append(dictionaryDir.path());
    }

    QDir::setSearchPaths("dict", dictdirs);

    // End FocusWriter lift/mod

    // Depending on the OS and Qt version, the default monospaced font returned
    // by the Monospace style hint and/or font family tends to something not
    // even monospaced, or, at best "Courier".  QTBUG-34082 seems to be what is
    // causing the issue.  Regardless, we want the prettiest monospaced font
    // available, so see which preferred fonts are available on the system
    // before before resorting to style hints.
    //
    QFontDatabase fontDb;

    QStringList fontFamilies = fontDb.families();
    QStringList preferredFonts;

#ifdef Q_OS_MAC
    preferredFonts.append("Menlo");
#endif

    preferredFonts.append("DejaVu Sans Mono");

#ifdef Q_OS_MAC
    preferredFonts.append("Monaco");
#elif defined(Q_OS_LINUX)
    preferredFonts.append("Ubuntu Mono");
    preferredFonts.append("Liberation Mono");
#elif defined(Q_OS_WIN32)
    preferredFonts.append("Consolas");
    preferredFonts.append("Lucida Console");
#endif

    preferredFonts.append("Courier New");
    preferredFonts.append("Courier");

    // Pick the first font in the list of preferredFonts that is installed
    // (i.e., in the font database) to use as the default font on the very
    // first start up of this program.
    //
    bool fontMatchFound = false;

    for (int i = 0; i < preferredFonts.size(); i++)
    {
        fontMatchFound =
            std::binary_search
            (
                fontFamilies.begin(),
                fontFamilies.end(),
                preferredFonts[i]
            );

        if (fontMatchFound)
        {
            defaultFont = QFont(preferredFonts[i]);
            break;
        }
    }

    if (!fontMatchFound)
    {
        // This case should not really happen, since the Courier family is
        // cross-platform.  This is just a precaution.
        //
        qWarning() <<
            "No fixed-width fonts were found. Using sytem default...";
        defaultFont = QFont("");
        defaultFont.setFixedPitch(true);
        defaultFont.setStyleHint(QFont::Monospace);
    }

    // Last but not least, load some basic settings from the configuration file,
    // but only those that need special validation.  Things like window
    // dimensions and file history can be handled elsewhere.
    //
    QSettings appSettings;

    autoSaveEnabled = appSettings.value(GW_AUTOSAVE_KEY, QVariant(true)).toBool();
    backupFileEnabled = appSettings.value(GW_BACKUP_FILE_KEY, QVariant(true)).toBool();

    font = defaultFont;
    font.fromString(appSettings.value(GW_FONT_KEY, QVariant(defaultFont.toString())).toString());

    tabWidth = appSettings.value(GW_TAB_WIDTH_KEY, QVariant(DEFAULT_TAB_WIDTH)).toInt();

    if ((tabWidth < MIN_TAB_WIDTH) || (tabWidth > MAX_TAB_WIDTH))
    {
        tabWidth = DEFAULT_TAB_WIDTH;
    }

    insertSpacesForTabsEnabled = appSettings.value(GW_SPACES_FOR_TABS_KEY, QVariant(false)).toBool();
    useUnderlineForEmphasis = appSettings.value(GW_UNDERLINE_ITALICS_KEY, QVariant(false)).toBool();
    largeHeadingSizesEnabled = appSettings.value(GW_LARGE_HEADINGS_KEY, QVariant(true)).toBool();
    autoMatchEnabled = appSettings.value(GW_AUTO_MATCH_KEY, QVariant(true)).toBool();
    autoMatchDoubleQuotesEnabled = appSettings.value(GW_AUTO_MATCH_DOUBLE_QUOTES_KEY, QVariant(true)).toBool();
    autoMatchSingleQuotesEnabled = appSettings.value(GW_AUTO_MATCH_SINGLE_QUOTES_KEY, QVariant(true)).toBool();
    autoMatchParenthesesEnabled = appSettings.value(GW_AUTO_MATCH_PARENTHESES_KEY, QVariant(true)).toBool();
    autoMatchSquareBracketsEnabled = appSettings.value(GW_AUTO_MATCH_SQUARE_BRACKETS_KEY, QVariant(true)).toBool();
    autoMatchBracesEnabled = appSettings.value(GW_AUTO_MATCH_BRACES_KEY, QVariant(true)).toBool();
    autoMatchAsterisksEnabled = appSettings.value(GW_AUTO_MATCH_ASTERISKS_KEY, QVariant(true)).toBool();
    autoMatchUnderscoresEnabled = appSettings.value(GW_AUTO_MATCH_UNDERSCORES_KEY, QVariant(true)).toBool();
    autoMatchBackticksEnabled = appSettings.value(GW_AUTO_MATCH_BACKTICKS_KEY, QVariant(true)).toBool();
    autoMatchAngleBracketsEnabled = appSettings.value(GW_AUTO_MATCH_ANGLE_BRACKETS_KEY, QVariant(true)).toBool();
    bulletPointCyclingEnabled = appSettings.value(GW_BULLET_CYCLING_KEY, QVariant(true)).toBool();
    focusMode = (FocusMode) appSettings.value(GW_FOCUS_MODE_KEY, QVariant(FocusModeSentence)).toInt();

    if ((focusMode < FocusModeDisabled) || (focusMode > FocusModeParagraph))
    {
        focusMode = FocusModeSentence;
    }

    hideMenuBarInFullScreenEnabled = appSettings.value(GW_HIDE_MENU_BAR_IN_FULL_SCREEN_KEY, QVariant(true)).toBool();
    fileHistoryEnabled = appSettings.value(GW_REMEMBER_FILE_HISTORY_KEY, QVariant(true)).toBool();
    displayTimeInFullScreenEnabled = appSettings.value(GW_DISPLAY_TIME_IN_FULL_SCREEN_KEY, QVariant(true)).toBool();
    themeName = appSettings.value(GW_THEME_KEY, QVariant("Classic Light")).toString();
    dictionaryLanguage = appSettings.value(GW_DICTIONARY_KEY, QLocale().name()).toString();
    locale = appSettings.value(GW_LOCALE_KEY, QLocale().name()).toString();
    liveSpellCheckEnabled = appSettings.value(GW_LIVE_SPELL_CHECK_KEY, QVariant(true)).toBool();
    editorWidth = (EditorWidth) appSettings.value(GW_EDITOR_WIDTH_KEY, QVariant(EditorWidthMedium)).toInt();
    blockquoteStyle = (BlockquoteStyle) appSettings.value(GW_BLOCKQUOTE_STYLE_KEY, QVariant(BlockquoteStylePlain)).toInt();

    if ((editorWidth < EditorWidthNarrow) || (editorWidth > EditorWidthFull))
    {
        editorWidth = EditorWidthMedium;
    }


#ifdef Q_OS_MAC
    HudWindowButtonLayout defaultHudButtonLayout = HudWindowButtonLayoutLeft;
#else
    HudWindowButtonLayout defaultHudButtonLayout = HudWindowButtonLayoutRight;
#endif

    hudButtonLayout = (HudWindowButtonLayout) appSettings.value(GW_HUD_BUTTON_LAYOUT_KEY, QVariant(defaultHudButtonLayout)).toInt();
    alternateHudRowColorsEnabled = appSettings.value(GW_HUD_ROW_COLORS_KEY, QVariant(false)).toBool();
    desktopCompositingEnabled = appSettings.value(GW_DESKTOP_COMPOSITING_KEY, QVariant(true)).toBool();
    hudOpacity = appSettings.value(GW_HUD_OPACITY_KEY, QVariant(200)).toInt();
}
Example #6
0
std::string getLocale()
{
	return QLocale().name().toStdString();
}
Example #7
0
mainWindow::mainWindow() : QMainWindow(),
    ui(new Ui::MainWindow)
{
    this->setMinimumSize(1000,500);
    // Creating the general UI
    ui->setupUi(this);

    // Making last minute adjustments and
    // initializing some parts of the UI
    ui->tabWidget->setCurrentIndex(0);
    ui->fileName->setText("log_file");
    ui->actionDisconnect->setEnabled(false);

    // Creating the logger file instance
    log = new QFile();

    // Creating the session file instance
    session = new QFile("session.dat");


    // Creating the QVector of double needed to store the graphs
    // points
    y[0] = new QVector<double>(2);
    x[0] = new QVector<double>(2);

    x[1] = new QVector<double>(200);

    y[1] = new QVector<double>(200);
    y[2] = new QVector<double>(200);
    y[3] = new QVector<double>(200);

    y[4] = new QVector<double>(200);
    y[5] = new QVector<double>(200);
    y[6] = new QVector<double>(200);

    y[7] = new QVector<double>(200);

    // The SettingsDialog instance handles the serial port configuration
    // window
    settings = new SettingsDialog();
    file_viewer = new FileViewer();

    // The Protocole instance handles the communication through the selected
    // serial port and parses the data received through a RegEx string
    protocole = new Protocole();


    // Now that everything's ready, try restoring
    // an existing session
    restoreSession();

    // Connecting all the commands button
    QSignalMapper * cmdMap = new QSignalMapper(this);

    connect(ui->cmdFreq,SIGNAL(clicked()),cmdMap,SLOT(map()));
    connect(ui->cmdBurst,SIGNAL(clicked()),cmdMap,SLOT(map()));
    connect(ui->cmdStream,SIGNAL(clicked()),cmdMap,SLOT(map()));
    cmdMap -> setMapping (ui->cmdFreq, "FRQ") ;
    cmdMap -> setMapping (ui->cmdBurst, "BST") ;
    cmdMap -> setMapping (ui->cmdStream, "STR") ;
    connect(cmdMap,SIGNAL(mapped(QString)),this,SLOT(sendCommandBox(QString)));

    // Connecting the buttons for RTC sync
    connect(ui->sendTime,SIGNAL(clicked()),this,SLOT(sendRTCTime()));
    connect(ui->getTime,SIGNAL(clicked()),this,SLOT(getRTCTime()));
    connect(ui->syncSysTime,SIGNAL(clicked()),this,SLOT(getSysTime()));

    // Connecting the button to fetch the last logged frames
    // into the console
    connect(ui->logUpdate,SIGNAL(clicked()),this,SLOT(update_c()));

    // Connecting the buttons used to connect to and configure
    // the serial port
    connect(ui->actionConnect, SIGNAL(clicked()), this, SLOT(openSerialPort()));
    connect(ui->actionDisconnect, SIGNAL(clicked()), this, SLOT(closeSerialPort()));
    connect(ui->actionConfigure, SIGNAL(clicked()), settings, SLOT(show()));
    connect(ui->cmdCustomSend,SIGNAL(clicked()),this,SLOT(sendCustomCommand()));

    connect(ui->applyLog, SIGNAL(clicked()),this,SLOT(applyLog()));


    logMap = new QSignalMapper(this);
    logMap->setMapping(ui->viewLog,logDirectory);
    connect(ui->viewLog,SIGNAL(clicked()),logMap,SLOT(map()));
    connect(logMap,SIGNAL(mapped(QString)),file_viewer,SLOT(show_dialog(QString)));

    // Connectring the button to change the log directory
    connect(ui->changeDirectory,SIGNAL(clicked()),this,SLOT(changeLogDirectory()));

    // Creating graphs instances by linking them to UI elements
    graph[0] = ui->graphXY;
    graph[1] = ui->graphXAxis;
    graph[2] = ui->graphYAxis;
    graph[3] = ui->graphZAxis;
    graph[4] = ui->gyroX;
    graph[5] = ui->gyroY;
    graph[6] = ui->gyroZ;
    graph[7] = ui->weightGraph;

    // The pen is used to draw a dot on XY graphs
    QPen pen;
    pen.setColor(QColor(229,115,115,255));
    pen.setWidth(10);
    pen.setCapStyle(Qt::RoundCap);
    // The line is used to draw classic graphs
    QPen line;
    line.setColor(QColor(25,118,210,255));
    line.setWidth(1);
    QPen line_red;
    line_red.setColor(QColor(210,25,118,255));
    line_red.setWidth(1);
    QPen line_green;
    line_green.setColor(QColor(118,210,25,255));
    line_green.setWidth(1);


    // Graph 1 to 6 stores the accelerometer and gyroscope
    // axis, and share similar settings.
    // Their label can be set directly in the next array
    QString label[16] = {
        "",
        "X","Y","Z",    // Accelerometer's three axis
        "X","Y","Z"     // Gyroscope's three axis
    };
    for(int i=1;i<8;i++) {
        // Only one curve on those graphs : axis/time
        graph[i]->addGraph();
        // The datas are stored in x[1] (time) and y[i] vectors
        graph[i]->graph(0)->setData(*x[1],*y[i]);
        graph[i]->graph(0)->setPen(line);
        // Setting the labels of each axis, as well
        // as the range
        graph[i]->xAxis->setLabel("t");
        graph[i]->yAxis->setLabel(label[i]);
        graph[i]->yAxis->setRange(-32000,32000);
        // The X Axis should display time (text)
        graph[i]->setLocale(QLocale(QLocale::English, QLocale::Canada));
        graph[i]->xAxis->setTickLabelType(QCPAxis::ltDateTime);
        graph[i]->xAxis->setDateTimeFormat("hh:mm:ss");
        graph[i]->xAxis->setDateTimeSpec(Qt::OffsetFromUTC);
        // Activating the zoom and drag interraction in vertical mode
        graph[i]->setInteraction(QCP::iRangeDrag, true);
        graph[i]->setInteraction(QCP::iRangeZoom, true);
        graph[i]->yAxis->axisRect()->setRangeDrag(Qt::Vertical);
        graph[i]->yAxis->axisRect()->setRangeZoom(Qt::Vertical);
    }
    graph[2]->graph(0)->setPen(line_green);
    graph[3]->graph(0)->setPen(line_red);
    graph[5]->graph(0)->setPen(line_green);
    graph[6]->graph(0)->setPen(line_red);

    graph[7]->yAxis->setRange(0,150);

    // Populating the XY graph
    // Only one curve on this graph : X axis /Y axis of accelerometer
    graph[0]->addGraph();
    // The datas are stored in x[0] and y[0] vectors
    graph[0]->graph(0)->setData(*x[0],*y[0]);
    // Draw a red dot
    graph[0]->graph(0)->setPen(pen);
    // Setting the labels of each axis, as well
    // as the range
    graph[0]->xAxis->setLabel("X");
    graph[0]->yAxis->setLabel("Y");
    graph[0]->xAxis->setRange(-10000,10000);
    graph[0]->yAxis->setRange(-10000,10000);
    // Activating the zoom and drag interraction in vertical and horizontal mode
    graph[0]->setInteraction(QCP::iRangeDrag, true);
    graph[0]->setInteraction(QCP::iRangeZoom, true);

    // For each graph, making the lines lighter in order to clean up the view
    for(int i=0;i<8;i++) {
        graph[i]->xAxis->setBasePen(QPen(QColor(195,195,195)));
        graph[i]->xAxis->setTickPen(QPen(QColor(195,195,195)));
        graph[i]->xAxis->setSubTickPen(QPen(QColor(195,195,195)));
        graph[i]->yAxis->setBasePen(QPen(QColor(195,195,195)));
        graph[i]->yAxis->setTickPen(QPen(QColor(195,195,195)));
        graph[i]->yAxis->setSubTickPen(QPen(QColor(195,195,195)));
    }

    // For every setting that should be saved, connecting the saveSession slot to
    // the state change signal
    connect(ui->appendDate,SIGNAL(stateChanged(int)),this,SLOT(saveSession()));
    connect(ui->logToFile,SIGNAL(stateChanged(int)),this,SLOT(saveSession()));
    connect(ui->fileName,SIGNAL(textChanged(QString)),this,SLOT(saveSession()));
    connect(ui->cmdValue,SIGNAL(valueChanged(int)),this,SLOT(saveSession()));
    connect(settings,SIGNAL(updated()),this,SLOT(saveSession()));

    // Addding Window's title
    setWindowTitle("Doctor's Orders Data Logger");



    // Creating a Timer for frame fetching
    serialFetch = new QTimer();
    serialFetch->setInterval(2);
    connect(serialFetch,SIGNAL(timeout()),protocole,SLOT(fetch()));

    // Creating a Timer for GUI update
    guiUpdate = new QTimer();
    guiUpdate->setInterval(50);
    connect(guiUpdate,SIGNAL(timeout()),this,SLOT(update()));

    // Connecting the serial port to the updateData slot
    connect(protocole,SIGNAL(updateData()),this,SLOT(updateData()));
}
Example #8
0
ThemeDialog::ThemeDialog(Theme& theme, QWidget* parent)
	: QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint),
	m_theme(theme)
{
	setWindowTitle(tr("Edit Theme"));
	setWindowModality(Qt::WindowModal);

	// Create name edit
	m_name = new QLineEdit(this);
	m_name->setText(m_theme.name());
	connect(m_name, SIGNAL(textChanged(QString)), this, SLOT(checkNameAvailable()));

	QHBoxLayout* name_layout = new QHBoxLayout;
	name_layout->setMargin(0);
	name_layout->addWidget(new QLabel(tr("Name:"), this));
	name_layout->addWidget(m_name);


	// Create scrollarea
	QWidget* contents = new QWidget(this);

	QScrollArea* scroll = new QScrollArea(this);
	scroll->setWidget(contents);
	scroll->setWidgetResizable(true);


	// Create text group
	QGroupBox* text_group = new QGroupBox(tr("Text"), contents);

	m_text_color = new ColorButton(text_group);
	m_text_color->setColor(m_theme.textColor());
	connect(m_text_color, SIGNAL(changed(QColor)), this, SLOT(renderPreview()));

	m_font_names = new FontComboBox(text_group);
	m_font_names->setEditable(false);
	m_font_names->setCurrentFont(m_theme.textFont());
	connect(m_font_names, SIGNAL(activated(int)), this, SLOT(fontChanged()));
	connect(m_font_names, SIGNAL(activated(int)), this, SLOT(renderPreview()));

	m_font_sizes = new QComboBox(text_group);
	m_font_sizes->setEditable(true);
	m_font_sizes->setMinimumContentsLength(3);
	connect(m_font_sizes, SIGNAL(editTextChanged(QString)), this, SLOT(renderPreview()));
	fontChanged();

	m_misspelled_color = new ColorButton(text_group);
	m_misspelled_color->setColor(m_theme.misspelledColor());
	connect(m_misspelled_color, SIGNAL(changed(QColor)), this, SLOT(renderPreview()));

	QHBoxLayout* font_layout = new QHBoxLayout;
	font_layout->addWidget(m_font_names);
	font_layout->addWidget(m_font_sizes);

	QFormLayout* text_layout = new QFormLayout(text_group);
	text_layout->setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint);
	text_layout->addRow(tr("Color:"), m_text_color);
	text_layout->addRow(tr("Font:"), font_layout);
	text_layout->addRow(tr("Misspelled:"), m_misspelled_color);


	// Create background group
	QGroupBox* background_group = new QGroupBox(tr("Window Background"), contents);

	m_background_color = new ColorButton(background_group);
	m_background_color->setColor(m_theme.backgroundColor());
	connect(m_background_color, SIGNAL(changed(QColor)), this, SLOT(renderPreview()));

	m_background_image = new ImageButton(background_group);
	m_background_image->setImage(m_theme.backgroundImage(), m_theme.backgroundPath());
	connect(m_background_image, SIGNAL(changed(QString)), this, SLOT(imageChanged()));

	m_clear_image = new QPushButton(tr("Remove"), background_group);
	connect(m_clear_image, SIGNAL(clicked()), m_background_image, SLOT(unsetImage()));

	m_background_type = new QComboBox(background_group);
	m_background_type->addItems(QStringList() << tr("No Image") << tr("Tiled") << tr("Centered") << tr("Stretched") << tr("Scaled") << tr("Zoomed"));
	m_background_type->setCurrentIndex(m_theme.backgroundType());
	connect(m_background_type, SIGNAL(activated(int)), this, SLOT(renderPreview()));

	QVBoxLayout* image_layout = new QVBoxLayout;
	image_layout->setSpacing(0);
	image_layout->setMargin(0);
	image_layout->addWidget(m_background_image);
	image_layout->addWidget(m_clear_image);

	QFormLayout* background_layout = new QFormLayout(background_group);
	background_layout->setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint);
	background_layout->addRow(tr("Color:"), m_background_color);
	background_layout->addRow(tr("Image:"), image_layout);
	background_layout->addRow(tr("Type:"), m_background_type);


	// Create foreground group
	QGroupBox* foreground_group = new QGroupBox(tr("Text Background"), contents);

	m_foreground_color = new ColorButton(foreground_group);
	m_foreground_color->setColor(m_theme.foregroundColor());
	connect(m_foreground_color, SIGNAL(changed(QColor)), this, SLOT(renderPreview()));

	m_foreground_opacity = new QSpinBox(foreground_group);
	m_foreground_opacity->setCorrectionMode(QSpinBox::CorrectToNearestValue);
	m_foreground_opacity->setSuffix(QLocale().percent());
	m_foreground_opacity->setRange(theme.foregroundOpacity().minimumValue(), theme.foregroundOpacity().maximumValue());
	m_foreground_opacity->setValue(m_theme.foregroundOpacity());
	connect(m_foreground_opacity, SIGNAL(valueChanged(int)), this, SLOT(renderPreview()));

	m_foreground_position = new QComboBox(foreground_group);
	m_foreground_position->addItems(QStringList() << tr("Left") << tr("Centered") << tr("Right") << tr("Stretched"));
	m_foreground_position->setCurrentIndex(m_theme.foregroundPosition());
	connect(m_foreground_position, SIGNAL(currentIndexChanged(int)), this, SLOT(positionChanged(int)));

	m_foreground_width = new QSpinBox(foreground_group);
	m_foreground_width->setCorrectionMode(QSpinBox::CorrectToNearestValue);
	m_foreground_width->setSuffix(tr(" pixels"));
	m_foreground_width->setRange(theme.foregroundWidth().minimumValue(), theme.foregroundWidth().maximumValue());
	m_foreground_width->setValue(m_theme.foregroundWidth());
	m_foreground_width->setEnabled(m_theme.foregroundPosition() != 3);
	connect(m_foreground_width, SIGNAL(valueChanged(int)), this, SLOT(renderPreview()));

	QFormLayout* foreground_layout = new QFormLayout(foreground_group);
	foreground_layout->setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint);
	foreground_layout->addRow(tr("Color:"), m_foreground_color);
	foreground_layout->addRow(tr("Opacity:"), m_foreground_opacity);
	foreground_layout->addRow(tr("Position:"), m_foreground_position);
	foreground_layout->addRow(tr("Width:"), m_foreground_width);


	// Create rounding group
	m_round_corners = new QGroupBox(tr("Round Text Background Corners"), contents);
	m_round_corners->setCheckable(true);
	m_round_corners->setChecked(m_theme.roundCornersEnabled());
	connect(m_round_corners, SIGNAL(clicked()), this, SLOT(renderPreview()));

	m_corner_radius = new QSpinBox(m_round_corners);
	m_corner_radius->setCorrectionMode(QSpinBox::CorrectToNearestValue);
	m_corner_radius->setSuffix(tr(" pixels"));
	m_corner_radius->setRange(theme.cornerRadius().minimumValue(), theme.cornerRadius().maximumValue());
	m_corner_radius->setValue(m_theme.cornerRadius());
	connect(m_corner_radius, SIGNAL(valueChanged(int)), this, SLOT(renderPreview()));

	QFormLayout* corner_layout = new QFormLayout(m_round_corners);
	corner_layout->setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint);
	corner_layout->addRow(tr("Radius:"), m_corner_radius);


	// Create blur group
	m_blur = new QGroupBox(tr("Blur Text Background"), contents);
	m_blur->setCheckable(true);
	m_blur->setChecked(m_theme.blurEnabled());
	connect(m_blur, SIGNAL(clicked()), this, SLOT(renderPreview()));

	m_blur_radius = new QSpinBox(m_blur);
	m_blur_radius->setCorrectionMode(QSpinBox::CorrectToNearestValue);
	m_blur_radius->setSuffix(tr(" pixels"));
	m_blur_radius->setRange(theme.blurRadius().minimumValue(), theme.blurRadius().maximumValue());
	m_blur_radius->setValue(m_theme.blurRadius());
	connect(m_blur_radius, SIGNAL(valueChanged(int)), this, SLOT(renderPreview()));

	QFormLayout* blur_layout = new QFormLayout(m_blur);
	blur_layout->setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint);
	blur_layout->addRow(tr("Radius:"), m_blur_radius);


	// Create shadow group
	m_shadow = new QGroupBox(tr("Text Background Drop Shadow"), contents);
	m_shadow->setCheckable(true);
	m_shadow->setChecked(m_theme.shadowEnabled());
	connect(m_shadow, SIGNAL(clicked()), this, SLOT(renderPreview()));

	m_shadow_color = new ColorButton(m_shadow);
	m_shadow_color->setColor(m_theme.shadowColor());
	connect(m_shadow_color, SIGNAL(changed(QColor)), this, SLOT(renderPreview()));

	m_shadow_radius = new QSpinBox(m_shadow);
	m_shadow_radius->setCorrectionMode(QSpinBox::CorrectToNearestValue);
	m_shadow_radius->setSuffix(tr(" pixels"));
	m_shadow_radius->setRange(theme.shadowRadius().minimumValue(), theme.shadowRadius().maximumValue());
	m_shadow_radius->setValue(m_theme.shadowRadius());
	connect(m_shadow_radius, SIGNAL(valueChanged(int)), this, SLOT(renderPreview()));

	m_shadow_offset = new QSpinBox(m_shadow);
	m_shadow_offset->setCorrectionMode(QSpinBox::CorrectToNearestValue);
	m_shadow_offset->setSuffix(tr(" pixels"));
	m_shadow_offset->setRange(theme.shadowOffset().minimumValue(), theme.shadowOffset().maximumValue());
	m_shadow_offset->setValue(m_theme.shadowOffset());
	connect(m_shadow_offset, SIGNAL(valueChanged(int)), this, SLOT(renderPreview()));

	QFormLayout* shadow_layout = new QFormLayout(m_shadow);
	shadow_layout->setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint);
	shadow_layout->addRow(tr("Color:"), m_shadow_color);
	shadow_layout->addRow(tr("Radius:"), m_shadow_radius);
	shadow_layout->addRow(tr("Vertical Offset:"), m_shadow_offset);


	// Create margins group
	QGroupBox* margins_group = new QGroupBox(tr("Margins"), contents);

	m_foreground_margin = new QSpinBox(margins_group);
	m_foreground_margin->setCorrectionMode(QSpinBox::CorrectToNearestValue);
	m_foreground_margin->setSuffix(tr(" pixels"));
	m_foreground_margin->setRange(theme.foregroundMargin().minimumValue(), theme.foregroundMargin().maximumValue());
	m_foreground_margin->setValue(m_theme.foregroundMargin());
	connect(m_foreground_margin, SIGNAL(valueChanged(int)), this, SLOT(renderPreview()));

	m_foreground_padding = new QSpinBox(margins_group);
	m_foreground_padding->setCorrectionMode(QSpinBox::CorrectToNearestValue);
	m_foreground_padding->setSuffix(tr(" pixels"));
	m_foreground_padding->setRange(theme.foregroundPadding().minimumValue(), theme.foregroundPadding().maximumValue());
	m_foreground_padding->setValue(m_theme.foregroundPadding());
	connect(m_foreground_padding, SIGNAL(valueChanged(int)), this, SLOT(renderPreview()));

	QFormLayout* margins_layout = new QFormLayout(margins_group);
	margins_layout->setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint);
	margins_layout->addRow(tr("Window:"), m_foreground_margin);
	margins_layout->addRow(tr("Page:"), m_foreground_padding);


	// Create line spacing group
	QGroupBox* line_spacing = new QGroupBox(tr("Line Spacing"), contents);

	m_line_spacing_type = new QComboBox(line_spacing);
	m_line_spacing_type->setEditable(false);
	m_line_spacing_type->addItems(QStringList() << tr("Single") << tr("1.5 Lines") << tr("Double") << tr("Proportional"));
	m_line_spacing_type->setCurrentIndex(3);

	m_line_spacing = new QSpinBox(line_spacing);
	m_line_spacing->setSuffix(QLocale().percent());
	m_line_spacing->setRange(theme.lineSpacing().minimumValue(), theme.lineSpacing().maximumValue());
	m_line_spacing->setValue(m_theme.lineSpacing());
	m_line_spacing->setEnabled(false);

	switch (m_theme.lineSpacing()) {
	case 100: m_line_spacing_type->setCurrentIndex(0); break;
	case 150: m_line_spacing_type->setCurrentIndex(1); break;
	case 200: m_line_spacing_type->setCurrentIndex(2); break;
	default: m_line_spacing->setEnabled(true); break;
	}
	connect(m_line_spacing_type, SIGNAL(currentIndexChanged(int)), this, SLOT(lineSpacingChanged(int)));
	connect(m_line_spacing_type, SIGNAL(currentIndexChanged(int)), this, SLOT(renderPreview()));
	connect(m_line_spacing, SIGNAL(valueChanged(int)), this, SLOT(renderPreview()));

	QFormLayout* line_spacing_layout = new QFormLayout(line_spacing);
	line_spacing_layout->setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint);
	line_spacing_layout->addRow(tr("Type:"), m_line_spacing_type);
	line_spacing_layout->addRow(tr("Height:"), m_line_spacing);


	// Create paragraph spacing group
	QGroupBox* paragraph_spacing = new QGroupBox(tr("Paragraph Spacing"), contents);

	m_tab_width = new QSpinBox(paragraph_spacing);
	m_tab_width->setSuffix(tr(" pixels"));
	m_tab_width->setRange(theme.tabWidth().minimumValue(), theme.tabWidth().maximumValue());
	m_tab_width->setValue(m_theme.tabWidth());
	connect(m_tab_width, SIGNAL(valueChanged(int)), this, SLOT(renderPreview()));

	m_spacing_above_paragraph = new QSpinBox(paragraph_spacing);
	m_spacing_above_paragraph->setSuffix(tr(" pixels"));
	m_spacing_above_paragraph->setRange(theme.spacingAboveParagraph().minimumValue(), theme.spacingAboveParagraph().maximumValue());
	m_spacing_above_paragraph->setValue(m_theme.spacingAboveParagraph());
	connect(m_spacing_above_paragraph, SIGNAL(valueChanged(int)), this, SLOT(renderPreview()));

	m_spacing_below_paragraph = new QSpinBox(paragraph_spacing);
	m_spacing_below_paragraph->setSuffix(tr(" pixels"));
	m_spacing_below_paragraph->setRange(theme.spacingBelowParagraph().minimumValue(), theme.spacingBelowParagraph().maximumValue());
	m_spacing_below_paragraph->setValue(m_theme.spacingBelowParagraph());
	connect(m_spacing_below_paragraph, SIGNAL(valueChanged(int)), this, SLOT(renderPreview()));

	m_indent_first_line = new QCheckBox(tr("Indent first line"), paragraph_spacing);
	m_indent_first_line->setChecked(m_theme.indentFirstLine());
	connect(m_indent_first_line, SIGNAL(toggled(bool)), this, SLOT(renderPreview()));

	QFormLayout* paragraph_spacing_layout = new QFormLayout(paragraph_spacing);
	paragraph_spacing_layout->setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint);
	paragraph_spacing_layout->addRow(tr("Tab Width:"), m_tab_width);
	paragraph_spacing_layout->addRow(tr("Above:"), m_spacing_above_paragraph);
	paragraph_spacing_layout->addRow(tr("Below:"), m_spacing_below_paragraph);
	paragraph_spacing_layout->addRow("", m_indent_first_line);


	// Create preview
	m_preview_text = new QTextEdit;
	m_preview_text->setFrameStyle(QFrame::NoFrame);
	m_preview_text->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	m_preview_text->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	QFile file(":/lorem.txt");
	if (file.open(QFile::ReadOnly)) {
		m_preview_text->setPlainText(QString::fromLatin1(file.readAll()));
		file.close();
	}

	m_preview = new QLabel(this);
	m_preview->setAlignment(Qt::AlignCenter);
	m_preview->setFrameStyle(QFrame::Sunken | QFrame::StyledPanel);

	QPixmap pixmap(480, 270);
	pixmap.fill(palette().window().color());
	m_preview->setPixmap(pixmap);

	m_theme_renderer = new ThemeRenderer(this);
	connect(m_theme_renderer, SIGNAL(rendered(QImage,QRect,Theme)), this, SLOT(renderPreview(QImage,QRect,Theme)));
	renderPreview();


	// Lay out dialog
	QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this);
	m_ok = buttons->button(QDialogButtonBox::Ok);
	connect(buttons, SIGNAL(accepted()), this, SLOT(accept()));
	connect(buttons, SIGNAL(rejected()), this, SLOT(reject()));

	QVBoxLayout* groups_layout = new QVBoxLayout(contents);
	groups_layout->addWidget(text_group);
	groups_layout->addWidget(background_group);
	groups_layout->addWidget(foreground_group);
	groups_layout->addWidget(m_round_corners);
	groups_layout->addWidget(m_blur);
	groups_layout->addWidget(m_shadow);
	groups_layout->addWidget(margins_group);
	groups_layout->addWidget(line_spacing);
	groups_layout->addWidget(paragraph_spacing);

	QGridLayout* layout = new QGridLayout(this);
	layout->setColumnStretch(0, 1);
	layout->setRowStretch(1, 1);
	layout->setRowMinimumHeight(2, layout->margin());
	layout->addLayout(name_layout, 0, 0, 1, 2);
	layout->addWidget(scroll, 1, 0, 1, 1);
	layout->addWidget(m_preview, 1, 1, 1, 1, Qt::AlignCenter);
	layout->addWidget(buttons, 3, 0, 1, 2);

	resize(QSettings().value("ThemeDialog/Size", sizeHint()).toSize());
}
Example #9
0
int main(int argc, char *argv[])
{
  Q_INIT_RESOURCE(guiclient);

  QString username;
  QString databaseURL;
  QString passwd;
  bool    haveUsername    = FALSE;
  bool    haveDatabaseURL = FALSE;
  bool    loggedIn        = FALSE;
  bool    haveEnhancedAuth= false;
  bool    _enhancedAuth   = false;
  bool    haveRequireSSL  = false;
  bool    _requireSSL     = false;
  bool    havePasswd      = false;

  QApplication app(argc, argv);

#if QT_VERSION >= 0x040400
  // This is the correct place for this call but on versions less
  // than 4.4 it causes a crash for an unknown reason so it is
  // called later on earlier versions.
  QCoreApplication::addLibraryPath(QString("."));
#endif

#ifndef Q_WS_MACX
  QApplication::setWindowIcon(QIcon(":/images/icon32x32.png"));
#endif

  // Try and load a default translation file and install it
  QTranslator defaultTranslator(&app);
  if (defaultTranslator.load("default.qm", app.applicationDirPath()))
    app.installTranslator(&defaultTranslator);

  app.processEvents();

  if (argc > 1)
  {
    for (int intCounter = 1; intCounter < argc; intCounter++)
    {
      QString argument(argv[intCounter]);

      if (argument.contains("-databaseURL=", Qt::CaseInsensitive))
      {
        haveDatabaseURL = TRUE;
        databaseURL = argument.right(argument.length() - 13);
      }
      else if (argument.contains("-username=", Qt::CaseInsensitive))
      {
        haveUsername = TRUE;
        username = argument.right(argument.length() - 10);
      }
      else if (argument.contains("-passwd=", Qt::CaseInsensitive))
      {
        havePasswd = TRUE;
        passwd     = argument.right(argument.length() - 8);
      }
      else if (argument.contains("-noAuth", Qt::CaseInsensitive))
      {
        haveUsername = TRUE;
        havePasswd   = TRUE;
      } 
      else if (argument.contains("-enhancedAuth", Qt::CaseInsensitive))
      {
        haveEnhancedAuth = true;
        _enhancedAuth = true;
        if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive))
          _enhancedAuth = false;
      }
      else if (argument.contains("-requireSSL", Qt::CaseInsensitive))
      {
        haveRequireSSL = true;
        _requireSSL = true;
        if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive))
          _requireSSL = false;
      }
    }
  }

  _splash = new QSplashScreen();
  _splash->setPixmap(QPixmap(":/images/splashEmpty.png"));

  _evaluation = FALSE;

  if (!loggedIn)
  {
    ParameterList params;
    params.append("copyright", _Copyright);
    params.append("version", _Version);
    params.append("build", QString("%1 %2").arg(__DATE__).arg(__TIME__));

    if (haveUsername)
      params.append("username", username);

    if (havePasswd)
      params.append("password", passwd);

    if (haveDatabaseURL)
      params.append("databaseURL", databaseURL);

    if (haveEnhancedAuth)
      params.append("enhancedAuth", _enhancedAuth);
    
    if (haveRequireSSL)
      params.append("requireSSL", _requireSSL);

    if (_evaluation)
      params.append("evaluation");

    if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) )
      params.append("login");

    login2 newdlg(0, "", TRUE);
    newdlg.set(params, _splash);

    if(newdlg.result() != QDialog::Accepted)
    {
      if (newdlg.exec() == QDialog::Rejected)
        return -1;
      else
      {
        databaseURL = newdlg._databaseURL;
        username = newdlg.username();
        __password = newdlg.password();
      }
    }
  }

  XSqlQuery metric;
  metric.exec("SELECT metric_value"
           "  FROM metric"
           " WHERE (metric_name = 'Application')" );
  if(!metric.first() || (metric.value("metric_value").toString() == "Standard"))
  {
    // check if the xtmfg package is installed
    metric.exec("SELECT pkghead_name FROM pkghead WHERE pkghead_name='xtmfg'");
    if(metric.first())
    {
      _splash->setPixmap(QPixmap(":/images/splashMfgEdition.png"));
      _Name = _Name.arg("Manufacturing");
    }
    else
    {
      _splash->setPixmap(QPixmap(":/images/splashStdEdition.png"));
      _Name = _Name.arg("Standard");
    }
  }
  else
  {
    _splash->setPixmap(QPixmap(":/images/splashPostBooks.png"));
    _Name = _Name.arg("PostBooks");
  }

  metric.exec("SELECT metric_value"
           "  FROM metric"
           " WHERE (metric_name = 'ServerVersion')" );
  if(!metric.first() || (metric.value("metric_value").toString() != _dbVersion))
  {
    bool disallowMismatch = false;
    metric.exec("SELECT metric_value FROM metric WHERE(metric_name='DisallowMismatchClientVersion')");
    if(metric.first() && (metric.value("metric_value").toString() == "t"))
      disallowMismatch = true;
    
    _splash->hide();
    int result;
    if(disallowMismatch)
      result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"),
        QObject::tr("<p>The version of the database you are connecting to is "
                    "not the version this client was designed to work against. "
                    "This client was designed to work against the database "
                    "version %1. The system has been configured to disallow "
                    "access in this case.<p>Please contact your systems "
                    "administrator.").arg(_dbVersion),
                 QMessageBox::Ok | QMessageBox::Escape | QMessageBox::Default );
    else
      result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"),
        QObject::tr("<p>The version of the database you are connecting to is "
                    "not the version this client was designed to work against. "
                    "This client was designed to work against the database "
                    "version %1. If you continue some or all functionality may "
                    "not work properly or at all. You may also cause other "
                    "problems on the database.<p>Do you want to continue "
                    "anyway?").arg(_dbVersion),
                 QMessageBox::Yes,
                 QMessageBox::No | QMessageBox::Escape | QMessageBox::Default );
    if(result != QMessageBox::Yes)
      return 0;
    _splash->show();
  }

  _splash->showMessage(QObject::tr("Loading Database Metrics"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  _metrics = new Metrics();

  _splash->showMessage(QObject::tr("Loading User Preferences"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  _preferences = new Preferences(username);

  _splash->showMessage(QObject::tr("Loading User Privileges"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  _privileges = new Privileges();

  // Load the translator and set the locale from the User's preferences
  _splash->showMessage(QObject::tr("Loading Translation Dictionary"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  XSqlQuery langq("SELECT * "
                  "FROM usr, locale LEFT OUTER JOIN"
                  "     lang ON (locale_lang_id=lang_id) LEFT OUTER JOIN"
                  "     country ON (locale_country_id=country_id) "
                  "WHERE ( (usr_username=CURRENT_USER)"
                  " AND (usr_locale_id=locale_id) );" );
  if (langq.first())
  {
    QStringList paths;
    paths << "dict";
    paths << "";
    paths << "../dict";
    paths << app.applicationDirPath() + "/dict";
    paths << app.applicationDirPath();
    paths << app.applicationDirPath() + "/../dict";
#if defined Q_WS_MACX
    paths << app.applicationDirPath() + "/../../../dict";
    paths << app.applicationDirPath() + "/../../..";
#endif
    
    QStringList files;
    if (!langq.value("locale_lang_file").toString().isEmpty())
      files << langq.value("locale_lang_file").toString();

    QString langext;
    if (!langq.value("lang_abbr2").toString().isEmpty() && 
        !langq.value("country_abbr").toString().isEmpty())
    {
      langext = langq.value("lang_abbr2").toString() + "_" +
                langq.value("country_abbr").toString().toLower();
    }
    else if (!langq.value("lang_abbr2").toString().isEmpty())
    {
      langext = langq.value("lang_abbr2").toString();
    }

    if(!langext.isEmpty())
    {
      files << "xTuple." + langext;
      files << "openrpt." + langext;

      XSqlQuery pkglist("SELECT pkghead_name FROM pkghead WHERE packageIsEnabled(pkghead_name);");
      while(pkglist.next())
      {
        files << pkglist.value("pkghead_name").toString() + "." + langext;
      }
    }

    if (files.size() > 0)
    {
      bool langFound = false;

      QTranslator *translator = new QTranslator(&app);
      for (QStringList::Iterator fit = files.begin(); fit != files.end(); ++fit)
      {
        for(QStringList::Iterator pit = paths.begin(); pit != paths.end(); ++pit)
        {
          if (DEBUG)
            qDebug("looking for %s in %s",
                   (*fit).toAscii().data(), (*pit).toAscii().data());
          if (translator->load(*fit, *pit))
          {
            app.installTranslator(translator);
            langFound = true;
            qDebug("installed %s/%s",
                   (*pit).toAscii().data(), (*fit).toAscii().data());
            translator = new QTranslator(&app);
            break;
          }
        }
      }

      if (!langFound && !_preferences->boolean("IngoreMissingTranslationFiles"))
        QMessageBox::warning( 0, QObject::tr("Cannot Load Dictionary"),
                              QObject::tr("<p>The Translation Dictionaries %1 "
                                          "cannot be loaded. Reverting "
                                          "to the default dictionary." )
                                       .arg(files.join(QObject::tr(", "))));
    }

    /* set the locale to langabbr_countryabbr, langabbr, {lang# country#}, or
       lang#, depending on what information is available
     */
    QString langAbbr = langq.value("lang_abbr2").toString();
    QString cntryAbbr = langq.value("country_abbr").toString().toUpper();
    if(cntryAbbr == "UK")
      cntryAbbr = "GB";
    if (! langAbbr.isEmpty() &&
        ! cntryAbbr.isEmpty())
      QLocale::setDefault(QLocale(langAbbr + "_" + cntryAbbr));
    else if (! langAbbr.isEmpty())
      QLocale::setDefault(QLocale(langq.value("lang_abbr2").toString()));
    else if (langq.value("lang_qt_number").toInt() &&
             langq.value("country_qt_number").toInt())
      QLocale::setDefault(
          QLocale(QLocale::Language(langq.value("lang_qt_number").toInt()),
                  QLocale::Country(langq.value("country_qt_number").toInt())));
    else
      QLocale::setDefault(QLocale::system());

    qDebug("Locale set to language %s and country %s",
           QLocale().languageToString(QLocale().language()).toAscii().data(),
           QLocale().countryToString(QLocale().country()).toAscii().data());

  }
  else if (langq.lastError().type() != QSqlError::NoError)
  {
    systemError(0, langq.lastError().databaseText(), __FILE__, __LINE__);
  }

  qApp->processEvents();
  QString key;

  // TODO: Add code to check a few locations - Hopefully done

  QString keypath;
  QString keyname;
  QString keytogether;
  
#ifdef Q_WS_WIN
  keypath = _metrics->value("CCWinEncKey");
#elif defined Q_WS_MACX
  keypath = _metrics->value("CCMacEncKey");
#elif defined Q_WS_X11
  keypath = _metrics->value("CCLinEncKey");
#endif
  
  if (keypath.isEmpty())
    keypath = app.applicationDirPath();

  if (! keypath.endsWith(QDir::separator()))
    keypath += QDir::separator();

  keyname = _metrics->value("CCEncKeyName");
  if (keyname.isEmpty())
  {
    keyname = "xTuple.key";
    keytogether = keypath + keyname;
    QFile kn(keytogether);
    if(!kn.exists())
      keyname = "OpenMFG.key";
  }
  
  keytogether = keypath + keyname;
  
  // qDebug("keytogether: %s", keytogether.toAscii().data());
  QFile keyFile(keytogether);

  if(keyFile.exists())
  {
    if(keyFile.open(QIODevice::ReadOnly))
    {
      key = keyFile.readLine(1024);
      // strip off any newline characters
      key = key.trimmed();
    }
  }

  omfgThis = 0;
  omfgThis = new GUIClient(databaseURL, username);
  omfgThis->_key = key;

// qDebug("Encryption Key: %s", key.toAscii().data() );
  
  if (key.length() > 0) {
	_splash->showMessage(QObject::tr("Loading Database Encryption Metrics"), SplashTextAlignment, SplashTextColor);
	qApp->processEvents();
	_metricsenc = new Metricsenc(key);
  }
  
  initializePlugin(_preferences, _metrics, _privileges, omfgThis->workspace());

// START code for updating the locale settings if they haven't been already
  XSqlQuery lc;
  lc.exec("SELECT count(*) FROM metric WHERE metric_name='AutoUpdateLocaleHasRun';");
  lc.first();
  if(lc.value(0).toInt() == 0)
  {
    lc.exec("INSERT INTO metric (metric_name, metric_value) values('AutoUpdateLocaleHasRun', 't');");
    lc.exec("SELECT locale_id from locale;");
    while(lc.next())
    {
      ParameterList params;
      params.append("mode","edit");
      params.append("locale_id", lc.value(0));
      sysLocale lcdlg;
      lcdlg.set(params);
      lcdlg.sSave();
    }
  }
// END code for updating locale settings

  QObject::connect(&app, SIGNAL(aboutToQuit()), &app, SLOT(closeAllWindows()));
  if (omfgThis->_singleWindow.isEmpty())
  {
    omfgThis->setAttribute(Qt::WA_DeleteOnClose);
    omfgThis->show();
  }
  // keep this synchronized with GUIClient and user.ui.h
  else if (omfgThis->_singleWindow == "woTimeClock")
  {
    ScriptToolbox sb(0);
    QWidget* newdlg = sb.openWindow("woTimeClock");
    if(newdlg)
    {
      XMainWindow *mw = qobject_cast<XMainWindow*>(newdlg);
      if(mw)
      {
        ParameterList params;
        params.append("captive");
        mw->set(params);
      }
      newdlg->setAttribute(Qt::WA_DeleteOnClose);
      QObject::connect(omfgThis, SIGNAL(destroyed(QObject*)), &app, SLOT(quit()));
      newdlg->show();
    }
    else
    {
Example #10
0
int main(int argc, char *argv[])
{
	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf8"));
	QTextCodec::setCodecForTr(QTextCodec::codecForName("utf8"));
	
	julyTranslator=new JulyTranslator;
	appDataDir_=new QByteArray();
	appVerIsBeta_=new bool(false);
	appVerStr_=new QByteArray("1.0707");
	appVerReal_=new double(appVerStr.toDouble());
	if(appVerStr.size()>4)
	{ 
		appVerStr.insert(4,".");
		if(appVerStr.at(appVerStr.size()-1)!='0')appVerIsBeta=true;
	}
	appVerLastReal_=new double(appVerReal);
	currencyBStr_=new QByteArray("USD");
	currencyBStrLow_=new QByteArray("usd");
	currencyBSign_=new QByteArray("USD");
	validKeySign_=new bool(false);
	currencyASign_=new QByteArray("BTC");
	currencyAStr_=new QByteArray("BTC");
	currencyAStrLow_=new QByteArray("btc");
	currencyRequest_=new QByteArray("BTCUSD");
	defaultLangFile_=new QString();pickDefaultLangFile();
	currencySignMap=new QMap<QByteArray,QByteArray>;
	currencyNamesMap=new QMap<QByteArray,QByteArray>;
	dateTimeFormat_=new QString(QLocale().dateTimeFormat(QLocale::ShortFormat));
	timeFormat_=new QString(QLocale().timeFormat(QLocale::ShortFormat));
	exchangeName_=new QString("Mt.Gox");
	btcDecimals_=new int(8);
	usdDecimals_=new int(5);
	priceDecimals_=new int(5);

	minTradePrice_=new double(0.01);
	minTradeVolume_=new double(0.01);
	currentTimeStamp_=new qint32(QDateTime::currentDateTime().toTime_t());
	httpRequestInterval_=new int(400);
	httpRequestTimeout_=new int(5);

	QString globalStyleSheet="QGroupBox {background: rgba(255,255,255,190); border: 1px solid gray;border-radius: 3px;margin-top: 7px;} QGroupBox:title {background: qradialgradient(cx: 0.5, cy: 0.5, fx: 0.5, fy: 0.5, radius: 0.7, stop: 0 #fff, stop: 1 transparent); border-radius: 2px; padding: 1 4px; top: -7; left: 7px;} QLabel {color: black;} QDoubleSpinBox {background: white;} QTextEdit {background: white;} QPlainTextEdit {background: white;} QCheckBox {color: black;} QLineEdit {color: black; background: white; border: 1px solid gray;}";

#ifdef Q_OS_WIN
	if(QFile::exists("./QtBitcoinTrader"))
	{
		appDataDir="./QtBitcoinTrader/";
		QDir().mkpath(appDataDir+"Language");
		if(!QFile::exists(appDataDir+"Language"))appDataDir.clear();
	}
	if(appDataDir.isEmpty())
	{
	appDataDir=QDesktopServices::storageLocation(QDesktopServices::DataLocation).replace("\\","/").toAscii()+"/QtBitcoinTrader/";
	if(!QFile::exists(appDataDir))QDir().mkpath(appDataDir);
	}
#else
	appDataDir=QDesktopServices::storageLocation(QDesktopServices::HomeLocation).toAscii()+"/.config/QtBitcoinTrader/";
	if(!QFile::exists(appDataDir))QDir().mkpath(appDataDir);
#endif
	
    if(argc>1)
	{
		QApplication a(argc,argv);
        if(a.arguments().last().startsWith("/checkupdate"))
		{
#ifndef Q_OS_WIN
			a.setStyle(new QPlastiqueStyle);
#endif
			a.setStyleSheet(globalStyleSheet);

			QSettings settings(appDataDir+"/Settings.set",QSettings::IniFormat);
			QString langFile=settings.value("LanguageFile","").toString();
			if(langFile.isEmpty()||!langFile.isEmpty()&&!QFile::exists(langFile))langFile=defaultLangFile;
			julyTranslator->loadFromFile(langFile);

			UpdaterDialog updater(a.arguments().last()!="/checkupdate");
			return a.exec();
		}
	}

	QApplication a(argc,argv);
#ifndef Q_OS_WIN
	a.setStyle(new QPlastiqueStyle);
#endif

#ifdef  Q_OS_WIN
	if(QFile::exists(a.applicationFilePath()+".upd"))QFile::remove(a.applicationFilePath()+".upd");
	if(QFile::exists(a.applicationFilePath()+".bkp"))QFile::remove(a.applicationFilePath()+".bkp");
#endif

#ifdef  Q_OS_MAC
	if(QFile::exists(a.applicationFilePath()+".upd"))QFile::remove(a.applicationFilePath()+".upd");
	if(QFile::exists(a.applicationFilePath()+".bkp"))QFile::remove(a.applicationFilePath()+".bkp");
#endif

	a.setWindowIcon(QIcon(":/Resources/QtBitcoinTrader.png"));
	QFile *lockFile=0;

	{
		QNetworkProxy proxy;
		QList<QNetworkProxy> proxyList=QNetworkProxyFactory::systemProxyForQuery(QNetworkProxyQuery(QUrl("https://")));
		if(proxyList.count())proxy=proxyList.first();
		QNetworkProxy::setApplicationProxy(proxy);

	logEnabled_=new bool(false);

	a.setStyleSheet(globalStyleSheet);

	logFileName_=new QString("QtBitcoinTrader.log");
	iniFileName_=new QString("QtBitcoinTrader.ini");

	restKey_=new QByteArray;
	restSign_=new QByteArray;
	{
		QFile currencyFile("://Resources/Currencies.map");
		currencyFile.open(QIODevice::ReadOnly);
		QStringList currencyList=QString(currencyFile.readAll().replace("\r","")).split("\n");
		currencyFile.close();
		for(int n=0;n<currencyList.count();n++)
		{
			QStringList currencyName=currencyList.at(n).split("=");
			if(currencyName.count()!=3)continue;
			currencyNamesMap->insert(currencyName.at(0).toAscii(),currencyName.at(1).toAscii());
			currencySignMap->insert(currencyName.at(0).toAscii(),currencyName.at(2).toAscii());
		}
		if(!QFile::exists(appDataDir+"Language"))QDir().mkpath(appDataDir+"Language");
		QSettings settings(appDataDir+"/Settings.set",QSettings::IniFormat);
		QString langFile=settings.value("LanguageFile","").toString();
		appVerLastReal=settings.value("Version",1.0).toDouble();
		settings.setValue("Version",appVerReal);
		if(langFile.isEmpty()||!langFile.isEmpty()&&!QFile::exists(langFile))langFile=defaultLangFile;
			julyTranslator->loadFromFile(langFile);
	}

	bool tryDecrypt=true;
	bool showNewPasswordDialog=false;
	while(tryDecrypt)
	{
		QString tryPassword;
		restKey.clear();
		restSign.clear();

		if(QDir(appDataDir,"*.ini").entryList().isEmpty()||showNewPasswordDialog)
		{
			NewPasswordDialog newPassword;
			if(newPassword.exec()==QDialog::Accepted)
			{
			tryPassword=newPassword.getPassword();
			newPassword.updateIniFileName();
			restKey=newPassword.getRestKey().toAscii();
			QSettings settings(iniFileName,QSettings::IniFormat);
			settings.setValue("ExchangeId",newPassword.getExchangeId());
			QByteArray cryptedData;
			if(newPassword.getExchangeId()==0)
			{
			restSign=QByteArray::fromBase64(newPassword.getRestSign().toAscii());
			cryptedData=JulyAES256::encrypt("Qt Bitcoin Trader\r\n"+restKey+"\r\n"+restSign.toBase64(),tryPassword.toAscii());
			}
			else
			if(newPassword.getExchangeId()==1)
			{
				restSign=newPassword.getRestSign().toAscii();
				cryptedData=JulyAES256::encrypt("Qt Bitcoin Trader\r\n"+restKey+"\r\n"+restSign.toBase64(),tryPassword.toAscii());
			}
			settings.setValue("CryptedData",QString(cryptedData.toBase64()));
			settings.setValue("ProfileName",newPassword.selectedProfileName());
			settings.remove("RestSign");
			settings.remove("RestKey");
			settings.sync();

			showNewPasswordDialog=false;
			}
		}
			PasswordDialog enterPassword;
			if(enterPassword.exec()==QDialog::Rejected)return 0;
			if(enterPassword.resetData)
			{
				if(QFile::exists(enterPassword.getIniFilePath()))
					QFile::remove(enterPassword.getIniFilePath());
				continue;
			}
			if(enterPassword.newProfile){showNewPasswordDialog=true;continue;}
			tryPassword=enterPassword.getPassword();

		if(!tryPassword.isEmpty())
		{
			iniFileName=enterPassword.getIniFilePath();
			bool profileLocked=enterPassword.isProfileLocked(iniFileName);
			if(profileLocked)
			{
				QMessageBox msgBox(0);
				msgBox.setIcon(QMessageBox::Question);
				msgBox.setWindowTitle("Qt Bitcoin Trader");
				msgBox.setText(julyTr("THIS_PROFILE_ALREADY_USED","This profile is already used by another instance.<br>API does not allow to run two instances with same key sign pair.<br>Please create new profile if you want to use two instances."));
#ifdef Q_OS_WIN
				msgBox.setStandardButtons(QMessageBox::Ok);
				msgBox.setDefaultButton(QMessageBox::Ok);
				msgBox.exec();
#else
				msgBox.setStandardButtons(QMessageBox::Ignore|QMessageBox::Ok);
				msgBox.setDefaultButton(QMessageBox::Ok);
				if(msgBox.exec()==QMessageBox::Ignore)profileLocked=false;
#endif
				if(profileLocked)tryPassword.clear();
			}
			if(!profileLocked)
			{
				QSettings settings(iniFileName,QSettings::IniFormat);
				QStringList decryptedList=QString(JulyAES256::decrypt(QByteArray::fromBase64(settings.value("CryptedData","").toString().toAscii()),tryPassword.toAscii())).split("\r\n");

				if(decryptedList.count()==3&&decryptedList.first()=="Qt Bitcoin Trader")
				{
					restKey=decryptedList.at(1).toAscii();
					restSign=QByteArray::fromBase64(decryptedList.last().toAscii());
                    tryDecrypt=false;
					lockFile=new QFile(enterPassword.lockFilePath(iniFileName));
                    lockFile->open(QIODevice::WriteOnly|QIODevice::Truncate);
					lockFile->write("Qt Bitcoin Trader Lock File");
				}
			}
		}
	}

	QSettings settings(iniFileName,QSettings::IniFormat);
	isLogEnabled=settings.value("LogEnabled",false).toBool();
	settings.setValue("LogEnabled",isLogEnabled);
	currencyASign=currencySignMap->value("BTC","BTC");
	currencyBStr=settings.value("Currency","USD").toString().toAscii();
	currencyBSign=currencySignMap->value(currencyBStr,"$");

	if(isLogEnabled)logThread=new LogThread;

	mainWindow_=new QtBitcoinTrader;
	QObject::connect(mainWindow_,SIGNAL(quit()),&a,SLOT(quit()));
	}
	mainWindow.loadUiSettings();
	a.exec();
	if(lockFile)
	{
		lockFile->close();
		lockFile->remove();
		delete lockFile;
	}
	return 0;
}
Example #11
0
void DrawPathTool::updateStatusText()
{
	QString text;
	static const QString text_more_shift_control_space(MapEditorTool::tr("More: %1, %2, %3").arg(ModifierKey::shift(), ModifierKey::control(), ModifierKey::space()));
	static const QString text_more_shift_space(MapEditorTool::tr("More: %1, %2").arg(ModifierKey::shift(), ModifierKey::space()));
	static const QString text_more_control_space(MapEditorTool::tr("More: %1, %2").arg(ModifierKey::control(), ModifierKey::space()));
	QString text_more(text_more_shift_control_space);
	
	if (editingInProgress() && preview_path && preview_path->getCoordinateCount() >= 2)
	{
		//Q_ASSERT(!preview_path->isDirty());
		float length = map()->getScaleDenominator() * preview_path->parts().front().path_coords.back().clen * 0.001f;
		text += tr("<b>Length:</b> %1 m ").arg(QLocale().toString(length, 'f', 1));
		text += "| ";
	}
	
	if (draw_dash_points && !is_helper_tool)
		text += DrawLineAndAreaTool::tr("<b>Dash points on.</b> ") + "| ";
	
	if (!editingInProgress())
	{
		if (shift_pressed)
		{
			text += DrawLineAndAreaTool::tr("<b>%1+Click</b>: Snap or append to existing objects. ").arg(ModifierKey::shift());
			text_more = text_more_control_space;
		}
		else if (ctrl_pressed)
		{
			text += DrawLineAndAreaTool::tr("<b>%1+Click</b>: Pick direction from existing objects. ").arg(ModifierKey::control());
			text_more = text_more_shift_space;
		}
		else
		{
			text += tr("<b>Click</b>: Start a straight line. <b>Drag</b>: Start a curve. ");
// 			text += DrawLineAndAreaTool::tr(draw_dash_points ? "<b>%1</b> Disable dash points. " : "<b>%1</b>: Enable dash points. ").arg(ModifierKey::space());
		}
	}
	else
	{
		if (shift_pressed)
		{
			text += DrawLineAndAreaTool::tr("<b>%1+Click</b>: Snap to existing objects. ").arg(ModifierKey::shift());
			text += tr("<b>%1+Drag</b>: Follow existing objects. ").arg(ModifierKey::shift());
			text_more = text_more_control_space;
		}
		else if (ctrl_pressed && angle_helper->isActive())
		{
			text += DrawLineAndAreaTool::tr("<b>%1</b>: Fixed angles. ").arg(ModifierKey::control());
			text_more = text_more_shift_space;
		}
		else
		{
			text += tr("<b>Click</b>: Draw a straight line. <b>Drag</b>: Draw a curve. "
			           "<b>Right or double click</b>: Finish the path. "
			           "<b>%1</b>: Close the path. ").arg(ModifierKey::return_key());
			text += DrawLineAndAreaTool::tr("<b>%1</b>: Undo last point. ").arg(ModifierKey::backspace());
			text += MapEditorTool::tr("<b>%1</b>: Abort. ").arg(ModifierKey::escape());
		}
	}
	
	text += "| " + text_more;
	
	setStatusBarText(text);
}
Example #12
0
QString TrackLayer::toHtml()
{
    QString S;

    int totSegment = 0;
    int totSec = 0;
    qreal totDistance = 0;
    for (int i=0; i < size(); ++i) {
        if (TrackSegment* S = CAST_SEGMENT(get(i))) {
            totSegment++;
            totSec += S->duration();
            totDistance += S->distance();
        }
    }

    S += "<i>"+QApplication::translate("TrackLayer", "# of track segments")+": </i>" + QApplication::translate("TrackLayer", "%1").arg(QLocale().toString(totSegment))+"<br/>";
    S += "<i>"+QApplication::translate("TrackLayer", "Total distance")+": </i>" + QApplication::translate("TrackLayer", "%1 km").arg(QLocale().toString(totDistance, 'g', 3))+"<br/>";
    S += "<i>"+QApplication::translate("TrackLayer", "Total duration")+": </i>" + QApplication::translate("TrackLayer", "%1h %2m").arg(QLocale().toString(totSec/3600)).arg(QLocale().toString((totSec%3600)/60))+"<br/>";

    return toMainHtml().arg(S);
}
QList<QVariantMap> DatabaseManager::getStartPageSeries()
{
    auto date = QDateTime::currentDateTime().date();
    auto locale  = QLocale(QLocale::English);
    auto firstAiredStart = date.addDays(1 - date.dayOfWeek()).toString(Qt::ISODate); // Monday == 1
    auto firstAiredEnd = date.addDays(7 - date.dayOfWeek()).toString(Qt::ISODate); // Sunday == 7
    auto status = "Continuing";
    const auto kTwelveHoursInSecs = 12 * 60 * 60;
    
    QList<QVariantMap> series;
    
    if (m_db.isOpen()) {
        
        QSqlQuery query(m_db);
        query.exec(QString("SELECT Series.seriesName, Series.network, Series.airsTime, Series.airsDayOfWeek, Series.status, Series.id, Episode.id, Episode.episodeName, Episode.episodeNumber, Episode.seasonNumber, Episode.firstAired, Episode.filename, Episode.overview, Episode.guestStars, Episode.writer, Episode.watched "
                           "FROM Series, Episode "
                           "WHERE Series.status = '%1' AND Episode.firstAired BETWEEN '%2' AND '%3' AND Series.id = Episode.seriesID AND Episode.seasonNumber != 0 "
                           "ORDER BY Episode.firstAired;").arg(status).arg(firstAiredStart).arg(firstAiredEnd));
        
        if (query.isSelect()) {
            
            while (query.next()) {
                
                QVariantMap temp;
                
                auto seriesName = query.value(0).toString();
                temp["seriesName"] = seriesName;
                
                auto network = query.value(1).toString();
                temp["network"] = network;
                
                auto airsTime = query.value(2).toString();
                QTime time;

                if (airsTime.contains("PM")) {
                    airsTime.resize(airsTime.indexOf("PM") - 1);
                    time = QTime::fromString(airsTime, "h:m").addSecs(kTwelveHoursInSecs);
                } else {
                    time = QTime::fromString(airsTime, "h:m");
                }
                
                temp["airsTime"] = time.toString("h:mm");
                
                auto airsDayOfWeek = query.value(3).toString();
                temp["airsDayOfWeek"] = airsDayOfWeek;
                
                auto status = query.value(4).toString();
                temp["status"] = status;
                
                auto id = query.value(5).toString();
                temp["id"] = id;
                
                auto episodeId = query.value(6).toString();
                temp["nextEpisodeId"] = episodeId;
                
                auto episodeName = query.value(7).toString();
                episodeName.replace("''", "'");
                temp["nextEpisodeName"] = episodeName;
                
                auto episodeNumber = query.value(8).toString();
                temp["nextEpisodeNumber"] = episodeNumber;
                
                auto seasonNumber = query.value(9).toString();
                temp["nextEpisodeSeasonNumber"] = seasonNumber;
                
                auto firstAired = query.value(10).toString();
                temp["nextEpisodeFirstAired"] = firstAired;
                
                // Sometimes the series info airsDayOfWeek is wrong so lets take it from the episode directly then
                auto airsDayOfWeekFromEpisode = locale.toString(QDate::fromString(firstAired, Qt::ISODate), "dddd");
                temp["airsDayOfWeek"] = airsDayOfWeek == airsDayOfWeekFromEpisode ? airsDayOfWeek : airsDayOfWeekFromEpisode;
                
                auto banner = query.value(11).toString();
                temp["nextEpisodeBanner"] = banner;
                
                auto overview = query.value(12).toString();
                overview.replace("''", "'");
                temp["nextEpisodeOverview"] = overview;
                
                auto guestStars = query.value(13).toString();
                temp["nextEpisodeGuestStars"] = guestStars;
                
                auto writer = query.value(14).toString();
                temp["nextEpisodeWriter"] = writer;
                
                auto watched = query.value(15).toString();
                temp["nextEpisodeWatched"] = watched;
                
                series.append(temp);
            }
        }
    }

    return series;
}
BehaviourSettingsPage::BehaviourSettingsPage(SettingsDialog* dialog)
    : SettingsPage(dialog), ui_(new Ui_BehaviourSettingsPage) {
  ui_->setupUi(this);

  connect(ui_->b_show_tray_icon_, SIGNAL(toggled(bool)),
          SLOT(ShowTrayIconToggled(bool)));

  ui_->doubleclick_addmode->setItemData(0, MainWindow::AddBehaviour_Append);
  ui_->doubleclick_addmode->setItemData(1, MainWindow::AddBehaviour_Load);
  ui_->doubleclick_addmode->setItemData(2, MainWindow::AddBehaviour_OpenInNew);
  ui_->doubleclick_addmode->setItemData(3, MainWindow::AddBehaviour_Enqueue);

  ui_->doubleclick_playmode->setItemData(0, MainWindow::PlayBehaviour_Never);
  ui_->doubleclick_playmode->setItemData(1,
                                         MainWindow::PlayBehaviour_IfStopped);
  ui_->doubleclick_playmode->setItemData(2, MainWindow::PlayBehaviour_Always);

  ui_->doubleclick_playlist_addmode->setItemData(
      0, MainWindow::PlaylistAddBehaviour_Play);
  ui_->doubleclick_playlist_addmode->setItemData(
      1, MainWindow::PlaylistAddBehaviour_Enqueue);

  ui_->menu_playmode->setItemData(0, MainWindow::PlayBehaviour_Never);
  ui_->menu_playmode->setItemData(1, MainWindow::PlayBehaviour_IfStopped);
  ui_->menu_playmode->setItemData(2, MainWindow::PlayBehaviour_Always);

  ui_->menu_previousmode->setItemData(0, Player::PreviousBehaviour_DontRestart);
  ui_->menu_previousmode->setItemData(1, Player::PreviousBehaviour_Restart);

  // Populate the language combo box.  We do this by looking at all the
  // compiled in translations.
  QDir dir(":/translations/");
  QStringList codes(dir.entryList(QStringList() << "*.qm"));
  QRegExp lang_re("^clementine_(.*).qm$");
  for (const QString& filename : codes) {
    // The regex captures the "ru" from "clementine_ru.qm"
    if (!lang_re.exactMatch(filename)) continue;

    QString code = lang_re.cap(1);
    QString lookup_code = QString(code)
                              .replace("@latin", "_Latn")
                              .replace("_CN", "_Hans_CN")
                              .replace("_TW", "_Hant_TW");
    QString language_name =
        QLocale::languageToString(QLocale(lookup_code).language());
#if QT_VERSION >= 0x040800
    QString native_name = QLocale(lookup_code).nativeLanguageName();
    if (!native_name.isEmpty()) {
      language_name = native_name;
    }
#endif
    QString name = QString("%1 (%2)").arg(language_name, code);

    language_map_[name] = code;
  }

  language_map_["English (en)"] = "en";

  // Sort the names and show them in the UI
  QStringList names = language_map_.keys();
  qStableSort(names.begin(), names.end(), LocaleAwareCompare);
  ui_->language->addItems(names);

#ifdef Q_OS_DARWIN
  ui_->b_show_tray_icon_->setEnabled(false);
  ui_->startup_group_->setEnabled(false);
#endif
}
Example #15
0
 void updateButton()
 {
     mDateButton->setText(QLocale().toString(mDate, QLocale::ShortFormat));
 }
Example #16
0
void SearchResultWidget::showSearchResult(int start)
{
    if (resultList.isEmpty()) {
        return;
    }
    if (start < 0) {
        start = 0;
    }
    int end = 0;
    if (SearchResultWidget::maxItemPerPage == 0 || SearchResultWidget::nonPagedSearch) {
        SearchResultWidget::nonPagedSearch = true;
        moreThanOnePage = false;
    }
    else {
        end = start + SearchResultWidget::maxItemPerPage - 1;

        if (end >= resultList.size()) {
            end = resultList.size() - 1;
        }
        if (start > end) {
            return;
        }
    }

    if (!moreThanOnePage) {
        start = 0;
        end = resultList.size() - 1;
        pageNumber = 1;
        pageCount = 1;
    }
    else {
        pageCount = resultList.size() / SearchResultWidget::maxItemPerPage;
        if (resultList.size() % SearchResultWidget::maxItemPerPage != 0) {
            ++pageCount;
        }
        if (end == resultList.size() - 1) {
            pageNumber = pageCount;
        }
        else if (start == 0) {
            pageNumber = 1;
        }
        else {
            pageNumber = (start + 1) / SearchResultWidget::maxItemPerPage; //'start' is started from 0
            if ((start + 1) % SearchResultWidget::maxItemPerPage != 0) {
                ++pageNumber;
            }
        }
    }
    //updatePageLabel(pageCount, pageNumber;
//  pageLabel->setText(tr("page %1 of %2 page(s)").arg(pageNumber).arg(pageCount));
    pageLabel->setText(tr("All: %1 - Filered: %2").arg(copyResultList.size()).arg(resultList.size()));
    QString dockTitle = sectionName + ":" + phrase;
    dockTitle.replace("==", tr("Radifs that contain: "));
    dockTitle.replace("=", tr("Rhymed by: "));
    dockTitle.append(" (" + tr("p: %1 of %2").arg(pageNumber).arg(pageCount) + ")");
    searchResultWidget->setWindowTitle(dockTitle);

    int count = end - start + 1;
    searchTable->clear();
    searchTable->setRowCount(count);
    searchTable->setHorizontalHeaderLabels(QStringList() << tr("#") << tr("Title") << tr("Verse"));

    navButtonsNeeded = moreThanOnePage;

    if (navButtonsNeeded) {
        //almost one of navigation button needs to be enabled
        searchNextPage->show();
        searchPreviousPage->show();
    }

    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

    QProgressDialog progress(tr("Initializing Results Table..."), tr("Cancel"), 0, count, this);
    progress.setWindowModality(Qt::WindowModal);
    progress.setMinimumDuration(3000);

    searchTable->setColumnWidth(0, searchTable->fontMetrics().boundingRect(QString::number((end + 1) * 100)).width());
    int maxPoemWidth = 0, maxVerseWidth = 0;

    QList<int> tmpList = resultList.keys();
    ////count = tmpList.size();
    //int progressBarIndex = 50;
    //const int step = count/20;

    //bool firstTimeUpdate = false;
    QMap<int, QString>::const_iterator it = resultList.constBegin();
    const QMap<int, QString>::const_iterator endIt = it + end + 1; //resultList.constEnd();
    it = it + start;
    int i = start;
    const QColor fisrtColor(235, 235, 230, 190);
    const QColor secondColor(249, 249, 228, 150);

    QColor color = fisrtColor;

    //for (int i = start; i < end+1; ++i)
    while (it != endIt) {
        /*if (i>progressBarIndex)
        {
            progress.setValue(i);
            progressBarIndex += step;
            if (!firstTimeUpdate)
            {
                searchTable->setUpdatesEnabled(false);
                firstTimeUpdate = true;
            }
        }*/

        if (count > 300) {
            progress.setValue(i - start);
        }

        if (progress.wasCanceled()) {
            break;
        }

        int poemId = it.key();// tmpList.at(i);
        //GanjoorPoem poem = SaagharWidget::ganjoorDataBase->getPoem(poemId/*resultList.at(i)*/);

        //poem._HighlightText = phrase;

        //we need a modified verion of showParentCategory
        //showParentCategory(SaagharWidget::ganjoorDataBase->getCategory(poem._CatID));
        //adding Numbers
        QLocale persianLocal = QLocale(QLocale::Persian, QLocale::Iran);
        persianLocal.setNumberOptions(QLocale::OmitGroupSeparator);
        QString localizedNumber = persianLocal.toString(i + 1);
        QTableWidgetItem* numItem = new QTableWidgetItem(localizedNumber);
        numItem->setFlags(Qt::NoItemFlags /*Qt::ItemIsEnabled*/);

        searchTable->setItem(i - start, 0, numItem);

        QString firstVerse = "", poemTiltle = "", poetName = "";
        //QStringList verseData = resultList.value(poemId, "").split("|", QString::SkipEmptyParts);
        QStringList verseData = it.value().split("|", QString::SkipEmptyParts);

        if (verseData.size() == 3) {
            firstVerse = verseData.at(0);
            firstVerse.remove("verseText=");

            poemTiltle = verseData.at(1);
            poemTiltle.remove("poemTitle=");

            poetName = verseData.at(2);
            poetName.remove("poetName=");
        }

        //add Items
        QString snippedPoemTitle = QGanjoorDbBrowser::snippedText(poemTiltle, "", 0, 5, true);
        if (sectionName == tr("All") || sectionName == tr("Titles")) {
            snippedPoemTitle.prepend(poetName + ": ");
        }
        QTableWidgetItem* poemItem = new QTableWidgetItem(snippedPoemTitle);
        poemItem->setFlags(Qt::ItemIsEnabled);
        poemItem->setData(Qt::UserRole, "PoemID=" + QString::number(poemId));

        int tmpWidth = searchTable->fontMetrics().boundingRect(snippedPoemTitle).width();
        if (tmpWidth > maxPoemWidth) {
            maxPoemWidth = tmpWidth;
        }

//      QString cleanedFirstVerse = QGanjoorDbBrowser::cleanString(firstVerse/*, false*/);
//      QString snippedFirstVerse = QGanjoorDbBrowser::snippedText(cleanedFirstVerse, phrase, 0, 8, true);
//      if (snippedFirstVerse.isEmpty())
//          snippedFirstVerse = QGanjoorDbBrowser::snippedText(cleanedFirstVerse, "", 0, 8, true);

        //change 'cleanedFirstVerse' to 'firstVerse' maybe this conflicts with 'snippedText()' algorithm!
        QString snippedFirstVerse = QGanjoorDbBrowser::snippedText(firstVerse, phrase, 0, 8, true);
        if (snippedFirstVerse.isEmpty()) {
            snippedFirstVerse = QGanjoorDbBrowser::snippedText(firstVerse, "", 0, 8, true);
        }

        QTableWidgetItem* verseItem = new QTableWidgetItem(snippedFirstVerse);
        verseItem->setFlags(Qt::ItemIsEnabled);
        verseItem->setData(Qt::UserRole, "PoemID=" + QString::number(poemId));
        //set search data
        verseItem->setData(ITEM_SEARCH_DATA, QStringList() << phrase << firstVerse);
        poemItem->setData(ITEM_SEARCH_DATA, QStringList() << phrase << firstVerse);

        if (viewedItems.contains(snippedFirstVerse)) {
            numItem->setBackgroundColor(QColor(Qt::green).lighter(170));
        }
        else {
            numItem->setBackgroundColor(color);
        }

        poemItem->setBackgroundColor(color);
        verseItem->setBackgroundColor(color);
        if (it + 1 != endIt) {
            if ((it + 1).key() != it.key()) {
                if (color == fisrtColor) {
                    color = secondColor;
                }
                else {
                    color = fisrtColor;
                }
            }
        }
        //insert items to table
        searchTable->setItem(i - start, 1, poemItem);
        searchTable->setItem(i - start, 2, verseItem);

        tmpWidth = searchTable->fontMetrics().boundingRect(snippedFirstVerse).width();
        if (tmpWidth > maxVerseWidth) {
            maxVerseWidth = tmpWidth;
        }

        ++it;
        ++i;
    }

    searchTable->setColumnWidth(1, maxPoemWidth + searchTable->fontMetrics().boundingRect("00").width());
    searchTable->setColumnWidth(2, maxVerseWidth + searchTable->fontMetrics().boundingRect("00").width());

    searchTable->setUpdatesEnabled(true);

    if (start > 0) {
        searchPreviousPage->setEnabled(true);
        actSearchPreviousPage->setData("actSearchPreviousPage|" + QString::number(start - SearchResultWidget::maxItemPerPage));
    }
    else {
        searchPreviousPage->setEnabled(false);
    }

    if (end < resultList.size() - 1) {
        searchNextPage->setEnabled(true);
        actSearchNextPage->setData("actSearchNextPage|" + QString::number(end + 1));
    }
    else {
        searchNextPage->setEnabled(false);
    }

    QApplication::restoreOverrideCursor();
}
Example #17
0
void Parser131500ComAu::parseSearchJourney(QNetworkReply *networkReply)
{
    lastJourneyResultList = new JourneyResultList();

    QBuffer *filebuffer = new QBuffer();
    filebuffer->setData(networkReply->readAll());

    QRegExp regexp = QRegExp("<div class=\"midcolumn3\">(.*)</div>(.*)</div>(.*)<div id=\"righttools\">");
    regexp.setMinimal(true);

    regexp.indexIn(filebuffer->buffer());

    QString element = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><html xmlns=\"http://www.w3.org/1999/xhtml\">\n<body>\n" + regexp.cap(0) + "\n</div></body>\n</html>\n";

    QRegExp imgReg = QRegExp("icon_(.*)_s.gif\" />");
    imgReg.setMinimal(true);
    element.replace(imgReg, "icon_" + QString("\\1") + "_s.gif\" />" + QString("\\1"));
    element.replace("am+", "am");
    element.replace("pm+", "pm");

    //qDebug()<<element;

    QBuffer readBuffer;
    readBuffer.setData(element.toAscii());
    readBuffer.open(QIODevice::ReadOnly);

    QXmlQuery query;
    query.bindVariable("path", &readBuffer);
    query.setQuery("declare default element namespace \"http://www.w3.org/1999/xhtml\"; declare variable $path external; doc($path)/html/body/div/div/table/tbody/tr/td[@id='header2']/string()");

    QStringList departResult;
    if (!query.evaluateTo(&departResult))
    {
        qDebug() << "parser131500ComAu::getJourneyData - Query 1 Failed";
    }

    query.setQuery("declare default element namespace \"http://www.w3.org/1999/xhtml\"; declare variable $path external; doc($path)/html/body/div/div/table/tbody/tr/td[@id='header3']/string()");

    QStringList arriveResult;
    if (!query.evaluateTo(&arriveResult))
    {
        qDebug() << "parser131500ComAu::getJourneyData - Query 2 Failed";
    }

    query.setQuery("declare default element namespace \"http://www.w3.org/1999/xhtml\"; declare variable $path external; doc($path)/html/body/div/div/table/tbody/tr/td[@id='header4']/string()");

    QStringList timeResult;
    if (!query.evaluateTo(&timeResult))
    {
        qDebug() << "parser131500ComAu::getJourneyData - Query 3 Failed";
    }

    query.setQuery("declare default element namespace \"http://www.w3.org/1999/xhtml\"; declare variable $path external; doc($path)/html/body/div/div/table/tbody/tr/td[@id='header5']/string()");

    QStringList trainResult;
    if (!query.evaluateTo(&trainResult))
    {
        qDebug() << "parser131500ComAu::getJourneyData - Query 4 Failed";
    }

    query.setQuery("declare default element namespace \"http://www.w3.org/1999/xhtml\"; declare variable $path external; doc($path)/html/body/div/div/div/string()");

    QStringList headerResult;
    if (!query.evaluateTo(&headerResult))
    {
        qDebug() << "parser131500ComAu::getJourneyData - Query 5 Failed";
    }

    for (int i = 0; i < headerResult.count(); i++) {
        QRegExp regexp = QRegExp("(From:|To:|When:)(.*)$");
        regexp.setMinimal(true);
        regexp.indexIn(headerResult[i].trimmed());
        if (regexp.cap(1) == "From:") {
            lastJourneyResultList->setDepartureStation(regexp.cap(2).trimmed());
        }
        if (regexp.cap(1) == "To:") {
            lastJourneyResultList->setArrivalStation(regexp.cap(2).trimmed());
        }
        if (regexp.cap(1) == "When:") {
            lastJourneyResultList->setTimeInfo(regexp.cap(2).trimmed());
        }
    }

    QRegExp regexp2 = QRegExp("(.*), (\\d\\d) (.*) (\\d\\d\\d\\d)");
    regexp2.setMinimal(true);
    regexp2.indexIn(lastJourneyResultList->timeInfo().trimmed());
    QLocale enLocale = QLocale(QLocale::English, QLocale::UnitedStates);
    int month = 1;
    for (month = 1; month < 10; month++) {
        if (regexp2.cap(3).trimmed() == enLocale.standaloneMonthName(month)) {
            break;
        }
    }

    QDate journeydate = QDate::fromString(regexp2.cap(2).trimmed() + " " + QString::number(month) + " " + regexp2.cap(4).trimmed(), "dd M yyyy");

    //Generate Details search results

    QStringList detailsResult;

    regexp = QRegExp("<table class=\"dataTbl widthcol2and3\" cellspacing=\"0\" style=\"margin:0px ! important;border-right:0px none;\" summary=\"Search Results Details\">(.*)</table>");
    regexp.setMinimal(true);
    int pos = 0;

    while ((pos = regexp.indexIn(filebuffer->buffer(), pos)) != -1) {
        QString element = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><html xmlns=\"http://www.w3.org/1999/xhtml\">\n<body><table>\n" + regexp.cap(1) + "\n</table></body>\n</html>\n";
        element.replace("&nbsp;", " ");
        element.replace("bulletin.gif\">", "bulletin.gif\" />");

        QBuffer readBuffer;
        readBuffer.setData(element.toAscii());
        readBuffer.open(QIODevice::ReadOnly);

        QXmlQuery query;
        query.bindVariable("path", &readBuffer);

        query.setQuery("declare default element namespace \"http://www.w3.org/1999/xhtml\"; declare variable $path external; doc($path)/html/body/table/tbody/tr/td[@headers='header2']/string()");

        QStringList detailsContentResult;
        if (!query.evaluateTo(&detailsContentResult))
        {
            qDebug() << "parser131500ComAu::getJourneyData - DetailsQuery 1 Failed";
        }

        detailsResult << detailsContentResult.join("<linesep>");

        pos += regexp.matchedLength();
    }

    //qDebug()<<departResult;

    //Create search result
    for (int i = 0; i < departResult.count(); i++) {

        //Parse transporttypes and changes
        QString tmp = trainResult[i].trimmed();
        tmp.replace("\t", " ");
        tmp.replace("\n", " ");
        tmp.replace("\r", " ");
        QStringList trains = tmp.split(" ", QString::SkipEmptyParts);
        int changes = trains.length() - 1;
        trains.removeDuplicates();

        //Parse travel time
        tmp = timeResult[i].trimmed();
        tmp.replace("mins", "");
        tmp.replace("min", "");
        tmp.replace("hrs ", ":");
        tmp.replace("hr ", ":");
        QStringList durationLst = tmp.split(":", QString::SkipEmptyParts);

        QString durationStr = "";
        if (durationLst.length() == 1) {
            durationStr.sprintf("00: %02d", durationLst[0].toInt());
        }
        if (durationLst.length() == 2) {
            durationStr.sprintf("%02d:%02d", durationLst[0].toInt(), durationLst[1].toInt());
        }

        JourneyResultItem *item = new JourneyResultItem();
        item->setDate(journeydate);
        item->setId(QString::number(i));
        item->setTransfers(QString::number(changes));
        item->setDuration(durationStr);
        item->setTrainType(trains.join(", "));
        item->setDepartureTime(QTime::fromString(departResult[i].trimmed(), "h:map").toString("hh:mm"));
        item->setArrivalTime(QTime::fromString(arriveResult[i].trimmed(), "h:map").toString("hh:mm"));
        item->setInternalData1(detailsResult[i]);

        lastJourneyResultList->appendItem(item);
    }

    emit journeyResult(lastJourneyResultList);
}
Example #18
0
void Settings::load()
{
	if(config.allKeys().size()) //if exist - reading settings
	{
		notes_path = config.value("NotesPath").toString();
		last_note = config.value("LastNote").toString();
		hide_start = config.value("HideStart").toBool();
		//
		dialog_geometry = config.value("DialogGeometry").toByteArray();
		dialog_state = config.value("DialogState").toByteArray();
		//
		tab_position = TabPosition(config.value("TabPosition").toInt());
		show_hidden = config.value("ShowHidden").toBool();
		show_extensions = config.value("ShowExtensions").toBool();
		//
		hide_frame = config.value("HideFrame").toBool();
		stay_top = config.value("StayTop").toBool();
		//
		single_instance = config.value("SingleInstance").toBool();
		copy_start_raise = config.value("CopyStartRaise").toBool();
		//
		note_font.fromString(config.value("NoteFont").toString());
		note_links_open = config.value("NoteLinksOpen").toBool();
		note_paste_plaintext = config.value("NotePastePlaintext").toBool();
		//
		int ScriptCount = config.value("ComandCount").toInt();
		for(int i=0; i<ScriptCount; ++i)
		{
			script_model.append(
				config.value(QString("ComandName%1").arg(i)).toString(),
				config.value(QString("ComandFile%1").arg(i)).toString(),
				config.value(QString("ComandIcon%1").arg(i)).toString());
		}
		note_highlight = config.value("NoteHighlight").toBool();

		int HighlightRuleCount = config.beginReadArray("HighlightRules");
		highlight_rules.resize(HighlightRuleCount);
		for(int i=0; i<highlight_rules.size(); ++i)
		{
			config.setArrayIndex(i);
			highlight_rules[i].enabled = config.value("enabled").toBool();
			highlight_rules[i].regexp = config.value("regexp").toString();
			highlight_rules[i].color = QColor(config.value("color").toString());
		}
		config.endArray();

		script_show_output = config.value("ScriptShowOutput").toBool();
		script_copy_output = config.value("ScriptCopyOutput").toBool();
		//
		language_custom = config.value("LanguageCustom").toBool();
		locale_current = QLocale(config.value("LanguageCurrent").toString());
		//
		if(config.contains("Toolbar/itemCount"))
		{
			tb_items.resize(config.value("Toolbar/itemCount").toInt());
			for(int i=itemAdd; i<itemMax; ++i)
			{
				int pos = config.value(ToolbarAction(item_enum(i)).pref_name(), tb_items.size()).toInt();
				if(pos<tb_items.size()) tb_items[pos] = i; //Item's position
			}
		}
	}
	/*
	* If settings don't exist - setup default settings
	*/
	//Setting default path to notes
	if(notes_path.isEmpty())
	{
#ifdef Q_WS_X11
	notes_path = QDir::homePath()+"/.local/share/notes";
#elif defined(Q_WS_WIN)
	QSettings win_settings("Microsoft", "Windows");
	QString mydocuments_path = win_settings.value("CurrentVersion/Explorer/Shell Folders/Personal", "").toString();
	if(!mydocuments_path.isEmpty()) notes_path = mydocuments_path+"/Notes";
	else if(!QDir::homePath().isEmpty()) notes_path = QDir::homePath()+"/Notes";
#else
	if(!QDir::homePath().isEmpty()) notes_path = QDir::homePath()+"\Notes";
#endif
		config.setValue("NotesPath", notes_path);
	}
	//Settings single instance options
	if(!config.contains("SingleInstance"))
	{
		single_instance = true;
		config.setValue("SingleInstance", single_instance);
		copy_start_raise = true;
		config.setValue("CopyStartRaise", copy_start_raise);
	}
	//Setting default note options
	if(!config.contains("NoteLinksOpen"))
	{
		note_links_open = true;
		config.setValue("NoteLinksOpen", note_links_open);
	}
	if(!config.contains("NotePastePlaintext"))
	{
		note_paste_plaintext = false;
		config.setValue("NotePastePlaintext", note_paste_plaintext);
	}
	//Setting default highlight rules
	if(!config.contains("NoteHighlight"))
	{
		if(config.contains("NoteLinksHighlight"))
			note_highlight = config.value("NoteLinksHighlight").toBool();
		else
			note_highlight = true;

		config.setValue("NoteHighlight", note_highlight);
		highlight_rules.append(HighlightRule(true, "(http|https|ftp)://\\S+", QColor(Qt::blue)));
		highlight_rules.append(HighlightRule(false, "(\\d{1,3}\\.){3,3}\\d{1,3}(\\:\\d+)?", QColor("#500000")));
		highlight_rules.append(HighlightRule(false, "(0x|)\\d+", QColor("#147E16")));
		highlight_rules.append(HighlightRule(false, "#[0-9a-fA-F]{6,6}", QColor("#CEC51B")));

		config.beginWriteArray("HighlightRules", highlight_rules.size());
		for(int i=0; i<highlight_rules.size(); ++i)
		{
			config.setArrayIndex(i);
			config.setValue("enabled", highlight_rules.at(i).enabled);
			config.setValue("regexp", highlight_rules.at(i).regexp);
			config.setValue("color", highlight_rules.at(i).color);
		}
		config.endArray();
	}
	//Setting default scripts
	if((script_model.rowCount()==0) && !config.contains("ComandCount"))
	{
	#ifdef unix
		script_model.append("Print note's content", "cat", "");
	#elif defined(Q_WS_WIN)
		//
	#endif
		config.setValue("ComandCount", script_model.rowCount());
		for(int i=0; i<script_model.rowCount(); ++i)
		{
			config.setValue(QString("ComandName%1").arg(i), script_model.getName(i));
			config.setValue(QString("ComandFile%1").arg(i), script_model.getFile(i));
			config.setValue(QString("ComandIcon%1").arg(i), script_model.getIcon(i));
		}
	}
	//Setting default tab position
	if(!config.contains("TabPosition"))
	{
		tab_position = West;
		config.setValue("TabPosition", tab_position);
	}
	//Setting default toolbar items
	if((tb_items.size()==0) && !config.contains("Toolbar/itemCount"))
	{
		tb_items.append(itemAdd);
		tb_items.append(itemRemove);
		tb_items.append(itemRename);
		tb_items.append(itemSeparator);
		tb_items.append(itemPrev);
		tb_items.append(itemNext);
		tb_items.append(itemSeparator);
		tb_items.append(itemCopy);
		tb_items.append(itemSeparator);
		tb_items.append(itemSetup);
		tb_items.append(itemInfo);
		tb_items.append(itemSeparator);
		tb_items.append(itemRun);
		tb_items.append(itemSearch);
		tb_items.append(itemSeparator);
		tb_items.append(itemExit);
		config.setValue("Toolbar/itemCount", tb_items.size());
		for(int i=0; i<tb_items.size(); ++i)
			if(tb_items[i]!=itemSeparator)
				config.setValue(ToolbarAction(item_enum(tb_items[i])).pref_name(), i);
	}

    // Build two dictionaries of translation files for the program:
    // 1) the program translation files;
    // 2) qt library translation files.
    loadLanguages();
	//
#ifdef unix
	//Fixing Qt's problem on unix systems...
	QString system_lang(qgetenv("LANG").constData());
	system_lang.truncate(system_lang.indexOf('.'));
	if(system_lang.size()) locale_system = QLocale(system_lang);
	else locale_system = QLocale::system().language();
#else
	locale_system = QLocale::system().language();
#endif
	locale = (language_custom)?locale_current:locale_system;

    // Define priority locale for user interface.
    // Analyze only the program translation files dictionary.
    QMap<int, QMap<int, QString> >::const_iterator it = translations.find(locale.language());
	if(it!=translations.end()) //if translation list has locale language
	{
		const QMap<int, QString>& country_list = it.value();
		if(!country_list.contains(locale.country()))
		{
			QList<QLocale::Country> language_countries = QLocale::countriesForLanguage(locale.language());
			if(!language_countries.empty() && country_list.contains(language_countries[0]))
			{
				QLocale::Country country = language_countries[0];
				locale = QLocale(locale.language(), country);
			}
			else if(!country_list.empty())
			{
				QLocale::Country country = QLocale::Country(country_list.begin().key());
				locale = QLocale(locale.language(), country);
			}
			else locale = QLocale::c();
		}
	}
	else locale = QLocale::c();

    // Load files from dictionary for defined locale.
    updateLocale();

	qApp->installTranslator(&qtranslator);
	qApp->installTranslator(&translator);
}
Example #19
0
int main(int argc, char *argv[]) {
    // Initialize application
    DrawpileApp app(argc,argv);

    icon::selectThemeVariant();

#ifdef Q_OS_MAC
    // Mac specific settings
    app.setAttribute(Qt::AA_DontShowIconsInMenus);
    app.setQuitOnLastWindowClosed(false);

    // Global menu bar that is shown when no windows are open
    MacMenu::instance();
#endif

    qsrand(QDateTime::currentMSecsSinceEpoch());

    Color_Wheel::setDefaultDisplayFlags(Color_Wheel::SHAPE_SQUARE | Color_Wheel::ANGLE_FIXED | Color_Wheel::COLOR_HSV);

    {
        // Set override locale from settings, or use system locale if no override is set
        QLocale locale = QLocale::c();
        QString overrideLang = QSettings().value("settings/language").toString();
        if(!overrideLang.isEmpty())
            locale = QLocale(overrideLang);

        if(locale == QLocale::c())
            locale = QLocale::system();

        initTranslations(locale);
    }

    const QStringList args = app.arguments();
    if(args.count()>1) {
        QUrl url(args.at(1));
        if(url.scheme().length() <= 1) {
            // no scheme (or a drive letter?) means this is probably a local file
            url = QUrl::fromLocalFile(args.at(1));
        }

        app.openUrl(url);
    } else {
        // No arguments, start with an empty document
        QSettings cfg;

        QSize maxSize = app.desktop()->screenGeometry().size();
        QSize size = cfg.value("history/newsize").toSize();
        if(size.width()<100 || size.height()<100) {
            // No previous size, or really small size
            size = QSize(800, 600);
        } else {
            // Make sure previous size is not ridiculously huge
            size = size.boundedTo(maxSize);
        }

        QColor color = cfg.value("history/newcolor").value<QColor>();
        if(!color.isValid())
            color = Qt::white;

        MainWindow *win = new MainWindow;
        win->newDocument(size, color);
    }

    return app.exec();
}
Example #20
0
HTMLParent &HTMLParent::operator<<(double value)
{
    children.append(new HTMLDataElement(QLocale().toString(FLOAT_ROUND(value), FLOAT_FORMAT, FLOAT_PRECISION)));
    return *this;
}
Example #21
0
void Plugin14CRefView::setDate(const Date& d, const ProjectSettings& settings)
{
    QLocale locale=QLocale();
    GraphViewRefAbstract::setDate(d, settings);
    Date date = d;
    
    mGraph->removeAllCurves();
    mGraph->clearInfos();
    mGraph->showInfos(true);
    mGraph->setRangeX(mSettings.mTmin, mSettings.mTmax);
    mGraph->setCurrentX(mSettings.mTmin, mSettings.mTmax);
    mGraph->setFormatFunctX(mFormatFuncX);
    
    if(!date.isNull())
    {
        double age = date.mData.value(DATE_14C_AGE_STR).toDouble();
        double error = date.mData.value(DATE_14C_ERROR_STR).toDouble();
        double delta_r = date.mData.value(DATE_14C_DELTA_R_STR).toDouble();
        double delta_r_error = date.mData.value(DATE_14C_DELTA_R_ERROR_STR).toDouble();
        QString ref_curve = date.mData.value(DATE_14C_REF_CURVE_STR).toString().toLower();
        
        // ----------------------------------------------
        //  Reference curve
        // ----------------------------------------------
        
        QColor color2(150, 150, 150);
        
        Plugin14C* plugin = (Plugin14C*)date.mPlugin;

        const QMap<QString, QMap<double, double> >& curves = plugin->getRefData(ref_curve);
        
        
        QMap<double, double> curveG;
        QMap<double, double> curveG95Sup;
        QMap<double, double> curveG95Inf;
        
        double yMin = curves["G95Inf"][mSettings.mTmin];
        double yMax = curves["G95Sup"][mSettings.mTmin];
        
        double tMinGraph=curves["G"].firstKey()>mSettings.mTmin ? curves["G"].firstKey(): mSettings.mTmin;
        double tMaxGraph=curves["G"].lastKey()<mSettings.mTmax ?  curves["G"].lastKey() : mSettings.mTmax;
        
        for(double t=tMinGraph; t<=tMaxGraph; ++t) {
            curveG[t] = curves["G"][t];
            curveG95Sup[t] = curves["G95Sup"][t];
            curveG95Inf[t] = curves["G95Inf"][t];
            
            yMin = qMin(yMin, curveG95Inf[t]);
            yMax = qMax(yMax, curveG95Sup[t]);
        }
        
        GraphCurve graphCurveG;
        graphCurveG.mName = "G";
        graphCurveG.mData = curveG;
        graphCurveG.mPen.setColor(Qt::blue);
        graphCurveG.mIsHisto = false;
        mGraph->addCurve(graphCurveG);
        
        GraphCurve graphCurveG95Sup;
        graphCurveG95Sup.mName = "G95Sup";
        graphCurveG95Sup.mData = curveG95Sup;
        graphCurveG95Sup.mPen.setColor(QColor(180, 180, 180));
        graphCurveG95Sup.mIsHisto = false;
        mGraph->addCurve(graphCurveG95Sup);
        
        GraphCurve graphCurveG95Inf;
        graphCurveG95Inf.mName = "G95Inf";
        graphCurveG95Inf.mData = curveG95Inf;
        graphCurveG95Inf.mPen.setColor(QColor(180, 180, 180));
        graphCurveG95Inf.mIsHisto = false;
        mGraph->addCurve(graphCurveG95Inf);
        
        // Display reference curve name
        mGraph->addInfo(tr("Ref : ") + ref_curve);
        
        // -------------------------------------------
        
        yMin = qMin(yMin, age);
        yMin = floor(yMin/10)*10;
        
        yMax = qMax(yMax, age);
        yMax = ceil(yMax/10)*10;
        
        mGraph->setRangeY(yMin, yMax);
        
        // ----------------------------------------------
        //  Measure curve
        // ----------------------------------------------
        GraphCurve curveMeasure;
        curveMeasure.mName = "Measure";
        
        QColor penColor(mMeasureColor);
        QColor brushColor(mMeasureColor);
        
        // Lower opacity in case of delta r not null
        if(delta_r != 0 && delta_r_error != 0){
            penColor.setAlpha(100);
            brushColor.setAlpha(15);
        }else{
            penColor.setAlpha(255);
            brushColor.setAlpha(50);
        }
        curveMeasure.mPen = penColor;
        curveMeasure.mBrush = brushColor;
        
        curveMeasure.mIsVertical = true;
        curveMeasure.mIsHisto = false;
        
        // 5000 pts are used on vertical measure
        // because the y scale auto adjusts depending on x zoom.
        // => the visible part of the measure may be very reduced !
        double step = (yMax - yMin) / 5000.;
        for(double t=yMin; t<yMax; t += step)
        {
            double v = exp(-0.5 * pow((age - t) / error, 2));
            curveMeasure.mData[t] = v;
        }
        curveMeasure.mData = normalize_map(curveMeasure.mData);
        mGraph->addCurve(curveMeasure);
        
        // Infos to write :
        QString info = tr("Age BP : ") + locale.toString(age) + " ± " + locale.toString(error);
        
        // ----------------------------------------------
        //  Delta R curve
        // ----------------------------------------------
        if(delta_r != 0 && delta_r_error != 0)
        {
            // Apply reservoir effect
            age = (age - delta_r);
            error = sqrt(error * error + delta_r_error * delta_r_error);
            
            GraphCurve curveDeltaR;
            curveDeltaR.mName = "Delta R";
            
            penColor = mMeasureColor;
            brushColor = mMeasureColor;
            brushColor.setAlpha(50);
            
            curveDeltaR.mPen = penColor;
            curveDeltaR.mBrush = brushColor;
            
            curveDeltaR.mIsVertical = true;
            curveDeltaR.mIsHisto = false;
            
            // 5000 pts are used on vertical measure
            // because the y scale auto adjusts depending on x zoom.
            // => the visible part of the measure may be very reduced !
            step = (yMax - yMin) / 5000.;
            for(double t=yMin; t<yMax; t += step)
            {
                double v = exp(-0.5 * pow((age - t) / error, 2));
                curveDeltaR.mData[t] = v;
            }
            curveDeltaR.mData = normalize_map(curveDeltaR.mData);
            mGraph->addCurve(curveDeltaR);
            
            info += tr(", ΔR : ") + locale.toString(delta_r) + " ± " + locale.toString(delta_r_error);
        }
        
        // ----------------------------------------------
        //  Sub-dates curves (combination)
        // ----------------------------------------------
        for(int i=0; i<date.mSubDates.size(); ++i){
            const Date& d = date.mSubDates[i];
            
            GraphCurve curveSubMeasure;
            curveSubMeasure.mName = "Sub-Measure " + QString::number(i);
            
            QColor penColor = QColor(167, 126, 73);
            QColor brushColor = QColor(167, 126, 73);
            
            double sub_age = d.mData.value(DATE_14C_AGE_STR).toDouble();
            double sub_error = d.mData.value(DATE_14C_ERROR_STR).toDouble();
            double sub_delta_r = d.mData.value(DATE_14C_DELTA_R_STR).toDouble();
            double sub_delta_r_error = d.mData.value(DATE_14C_DELTA_R_ERROR_STR).toDouble();
            
            // Apply reservoir effect
            sub_age = (sub_age - sub_delta_r);
            sub_error = sqrt(sub_error * sub_error + sub_delta_r_error * sub_delta_r_error);
            
            penColor.setAlpha(255);
            brushColor.setAlpha(50);
            
            curveSubMeasure.mPen = penColor;
            curveSubMeasure.mBrush = brushColor;
            
            curveSubMeasure.mIsVertical = true;
            curveSubMeasure.mIsHisto = false;
            
            // 5000 pts are used on vertical measure
            // because the y scale auto adjusts depending on x zoom.
            // => the visible part of the measure may be very reduced !
            double step = (yMax - yMin) / 5000.;
            for(double t=yMin; t<yMax; t += step)
            {
                double v = exp(-0.5 * pow((sub_age - t) / sub_error, 2));
                curveSubMeasure.mData[t] = v;
            }
            curveSubMeasure.mData = normalize_map(curveSubMeasure.mData);
            mGraph->addCurve(curveSubMeasure);
        }

        // ----------------------------------------------
        //  Textual info
        // ----------------------------------------------
        
        mGraph->addInfo(info);
        
        // ----------------------------------------------
        //  Error on measure (horizontal lines)
        // ----------------------------------------------
        
        GraphCurve curveMeasureAvg;
        curveMeasureAvg.mName = "MeasureAvg";
        curveMeasureAvg.mPen.setColor(mMeasureColor);
        curveMeasureAvg.mPen.setStyle(Qt::SolidLine);
        curveMeasureAvg.mIsHorizontalLine = true;
        
        GraphCurve curveMeasureSup;
        curveMeasureSup.mName = "MeasureSup";
        curveMeasureSup.mPen.setColor(mMeasureColor);
        curveMeasureSup.mPen.setStyle(Qt::DashLine);
        curveMeasureSup.mIsHorizontalLine = true;
        
        GraphCurve curveMeasureInf;
        curveMeasureInf.mName = "MeasureInf";
        curveMeasureInf.mPen.setColor(mMeasureColor);
        curveMeasureInf.mPen.setStyle(Qt::DashLine);
        curveMeasureInf.mIsHorizontalLine = true;
        
        curveMeasureAvg.mHorizontalValue = age;
        curveMeasureSup.mHorizontalValue = age + error;
        curveMeasureInf.mHorizontalValue = age - error;
        
        mGraph->addCurve(curveMeasureAvg);
        mGraph->addCurve(curveMeasureSup);
        mGraph->addCurve(curveMeasureInf);
    }
}
HomeApplication::HomeApplication(int &argc, char **argv, const QString &qmlPath)
    : QGuiApplication(argc, argv)
    , _mainWindowInstance(0)
    , _qmlPath(qmlPath)
    , originalSigIntHandler(signal(SIGINT, quitSignalHandler))
    , originalSigTermHandler(signal(SIGTERM, quitSignalHandler))
    , updatesEnabled(true)
    , homeReadySent(false)
    , onUpdatesDisabledUnfocusedWindowId(0)
{
    setApplicationName("Lipstick");
    // TODO: autogenerate this from tags
    setApplicationVersion(VERSION);

    QTranslator *engineeringEnglish = new QTranslator(this);
    engineeringEnglish->load("lipstick_eng_en", "/usr/share/translations");
    installTranslator(engineeringEnglish);
    QTranslator *translator = new QTranslator(this);
    translator->load(QLocale(), "lipstick", "-", "/usr/share/translations");
    installTranslator(translator);

    // Initialize the QML engine
    qmlEngine = new QQmlEngine(this);

    // Initialize the notification manager
    NotificationManager::instance();
    new NotificationPreviewPresenter(this);

    // Create screen lock logic - not parented to "this" since destruction happens too late in that case
    screenLock = new ScreenLock;
    LipstickSettings::instance()->setScreenLock(screenLock);
    new ScreenLockAdaptor(screenLock);

    deviceLock = new DeviceLock(this);
    new DeviceLockAdaptor(deviceLock);

    volumeControl = new VolumeControl;
    new BatteryNotifier(this);
    new DiskSpaceNotifier(this);
    new ThermalNotifier(this);
    usbModeSelector = new USBModeSelector(this);
    connect(usbModeSelector, SIGNAL(dialogShown()), screenLock, SLOT(unlockScreen()));
    shutdownScreen = new ShutdownScreen(this);
    new ShutdownScreenAdaptor(shutdownScreen);
    connectionSelector = new ConnectionSelector(this);

    // MCE and usb-moded expect services to be registered on the system bus
    QDBusConnection systemBus = QDBusConnection::systemBus();
    if (!systemBus.registerService(LIPSTICK_DBUS_SERVICE_NAME)) {
        qWarning("Unable to register D-Bus service %s: %s", LIPSTICK_DBUS_SERVICE_NAME, systemBus.lastError().message().toUtf8().constData());
    }

    new HomeApplicationAdaptor(this);

    registerDBusObject(systemBus, LIPSTICK_DBUS_PATH, this);
    registerDBusObject(systemBus, LIPSTICK_DBUS_SCREENLOCK_PATH, screenLock);
    registerDBusObject(systemBus, LIPSTICK_DBUS_DEVICELOCK_PATH, deviceLock);
    registerDBusObject(systemBus, LIPSTICK_DBUS_SHUTDOWN_PATH, shutdownScreen);

    ScreenshotService *screenshotService = new ScreenshotService(this);
    new ScreenshotServiceAdaptor(screenshotService);
    QDBusConnection sessionBus = QDBusConnection::sessionBus();

    registerDBusObject(sessionBus, LIPSTICK_DBUS_SCREENSHOT_PATH, screenshotService);

    connect(this, SIGNAL(homeReady()), this, SLOT(sendStartupNotifications()));
}
Example #23
0
void PimSettingsBackupRestore::addDate()
{
    const QDateTime now = QDateTime::currentDateTime();
    Q_EMIT addInfo(QLatin1Char('[') + QLocale().toString((now), QLocale::ShortFormat) + QLatin1Char(']'));
}
Example #24
0
void MathPlot::setupSincScatterDemo(QCustomPlot *customPlot)
{

  customPlot->legend->setVisible(true);
  customPlot->legend->setFont(QFont("Helvetica",9));
  // set locale to english, so we get english decimal separator:
  customPlot->setLocale(QLocale(QLocale::English, QLocale::UnitedKingdom));
  // add confidence band graphs:
  customPlot->addGraph();
  QPen pen;
  pen.setStyle(Qt::DotLine);
  pen.setWidth(1);
  pen.setColor(QColor(180,180,180));
  customPlot->graph(0)->setName("Confidence Band 68%");
  customPlot->graph(0)->setPen(pen);
  customPlot->graph(0)->setBrush(QBrush(QColor(255,50,30,20)));
  customPlot->addGraph();
  customPlot->legend->removeItem(customPlot->legend->itemCount()-1); // don't show two confidence band graphs in legend
  customPlot->graph(1)->setPen(pen);
  customPlot->graph(0)->setChannelFillGraph(customPlot->graph(1));
  // add theory curve graph:
  customPlot->addGraph();
  pen.setStyle(Qt::DashLine);
  pen.setWidth(2);
  pen.setColor(Qt::red);
  customPlot->graph(2)->setPen(pen);
  customPlot->graph(2)->setName("Theory Curve");
  // add data point graph:
  customPlot->addGraph();
  customPlot->graph(3)->setPen(QPen(Qt::blue));
  customPlot->graph(3)->setLineStyle(QCPGraph::lsNone);
  customPlot->graph(3)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCross, 4));
  customPlot->graph(3)->setErrorType(QCPGraph::etValue);
  customPlot->graph(3)->setErrorPen(QPen(QColor(180,180,180)));
  customPlot->graph(3)->setName("Measurement");

  // generate ideal sinc curve data and some randomly perturbed data for scatter plot:
  QVector<double> x0(250), y0(250);
  QVector<double> yConfUpper(250), yConfLower(250);
  for (int i=0; i<250; ++i)
  {
    x0[i] = (i/249.0-0.5)*30+0.01; // by adding a small offset we make sure not do divide by zero in next code line
    y0[i] = sin(x0[i])/x0[i]; // sinc function
    yConfUpper[i] = y0[i]+0.15;
    yConfLower[i] = y0[i]-0.15;
    x0[i] *= 1000;
  }
  QVector<double> x1(50), y1(50), y1err(50);
  for (int i=0; i<50; ++i)
  {
    // generate a gaussian distributed random number:
    double tmp1 = rand()/(double)RAND_MAX;
    double tmp2 = rand()/(double)RAND_MAX;
    double r = sqrt(-2*log(tmp1))*cos(2*M_PI*tmp2); // box-muller transform for gaussian distribution
    // set y1 to value of y0 plus a random gaussian pertubation:
    x1[i] = (i/50.0-0.5)*30+0.25;
    y1[i] = sin(x1[i])/x1[i]+r*0.15;
    x1[i] *= 1000;
    y1err[i] = 0.15;
  }
  // pass data to graphs and let QCustomPlot determine the axes ranges so the whole thing is visible:
  customPlot->graph(0)->setData(x0, yConfUpper);
  customPlot->graph(1)->setData(x0, yConfLower);
  customPlot->graph(2)->setData(x0, y0);
  customPlot->graph(3)->setDataValueError(x1, y1, y1err);
  customPlot->graph(2)->rescaleAxes();
  customPlot->graph(3)->rescaleAxes(true);
  // setup look of bottom tick labels:
  customPlot->xAxis->setTickLabelRotation(30);
  customPlot->xAxis->setAutoTickCount(9);
  customPlot->xAxis->setNumberFormat("ebc");
  customPlot->xAxis->setNumberPrecision(1);
  customPlot->xAxis->moveRange(-10);
  // make top right axes clones of bottom left axes. Looks prettier:
  customPlot->axisRect()->setupFullAxesBox();
}
Example #25
0
/*!
    Renders the delegate using the given \a painter and style \a option for
    the item specified by \a index.

    When reimplementing this function in a subclass, you should update the area
    held by the option's \l{QStyleOption::rect}{rect} variable, using the
    option's \l{QStyleOption::state}{state} variable to determine the state of
    the item to be displayed, and adjust the way it is painted accordingly.

    For example, a selected item may need to be displayed differently to
    unselected items, as shown in the following code:

    \snippet examples/itemviews/pixelator/pixeldelegate.cpp 2
    \dots

    After painting, you should ensure that the painter is returned to its
    the state it was supplied in when this function was called. For example,
    it may be useful to call QPainter::save() before painting and
    QPainter::restore() afterwards.

    \sa QStyle::State
*/
void QItemDelegate::paint(QPainter *painter,
                          const QStyleOptionViewItem &option,
                          const QModelIndex &index) const
{
    Q_D(const QItemDelegate);
    Q_ASSERT(index.isValid());

    QStyleOptionViewItemV4 opt = setOptions(index, option);

    const QStyleOptionViewItemV2 *v2 = qstyleoption_cast<const QStyleOptionViewItemV2 *>(&option);
    opt.features = v2 ? v2->features
                    : QStyleOptionViewItemV2::ViewItemFeatures(QStyleOptionViewItemV2::None);
    const QStyleOptionViewItemV3 *v3 = qstyleoption_cast<const QStyleOptionViewItemV3 *>(&option);
    opt.locale = v3 ? v3->locale : QLocale();
    opt.widget = v3 ? v3->widget : 0;

    // prepare
    painter->save();
    if (d->clipPainting)
        painter->setClipRect(opt.rect);

    // get the data and the rectangles

    QVariant value;

    QPixmap pixmap;
    QRect decorationRect;
    value = index.data(Qt::DecorationRole);
    if (value.isValid()) {
        // ### we need the pixmap to call the virtual function
        pixmap = decoration(opt, value);
        if (value.type() == QVariant::Icon) {
            d->tmp.icon = qvariant_cast<QIcon>(value);
            d->tmp.mode = d->iconMode(option.state);
            d->tmp.state = d->iconState(option.state);
            const QSize size = d->tmp.icon.actualSize(option.decorationSize,
                                                      d->tmp.mode, d->tmp.state);
            decorationRect = QRect(QPoint(0, 0), size);
        } else {
            d->tmp.icon = QIcon();
            decorationRect = QRect(QPoint(0, 0), pixmap.size());
        }
    } else {
        d->tmp.icon = QIcon();
        decorationRect = QRect();
    }

    QString text;
    QRect displayRect;
    value = index.data(Qt::DisplayRole);
    if (value.isValid() && !value.isNull()) {
        text = QItemDelegatePrivate::valueToText(value, opt);
        displayRect = textRectangle(painter, d->textLayoutBounds(opt), opt.font, text);
    }

    QRect checkRect;
    Qt::CheckState checkState = Qt::Unchecked;
    value = index.data(Qt::CheckStateRole);
    if (value.isValid()) {
        checkState = static_cast<Qt::CheckState>(value.toInt());
        checkRect = check(opt, opt.rect, value);
    }

    // do the layout

    doLayout(opt, &checkRect, &decorationRect, &displayRect, false);

    // draw the item

    drawBackground(painter, opt, index);
    drawCheck(painter, opt, checkRect, checkState);
    drawDecoration(painter, opt, decorationRect, pixmap);
    drawDisplay(painter, opt, displayRect, text);
    drawFocus(painter, opt, displayRect);

    // done
    painter->restore();
}
Example #26
0
void MathPlot::setupMultiAxisDemo(QCustomPlot *customPlot)
{
  customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);

  customPlot->setLocale(QLocale(QLocale::English, QLocale::UnitedKingdom)); // period as decimal separator and comma as thousand separator
  customPlot->legend->setVisible(true);
  QFont legendFont = font();  // start out with MainWindow's font..
  legendFont.setPointSize(9); // and make a bit smaller for legend
  customPlot->legend->setFont(legendFont);
  customPlot->legend->setBrush(QBrush(QColor(255,255,255,230)));
  // by default, the legend is in the inset layout of the main axis rect. So this is how we access it to change legend placement:
  customPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignBottom|Qt::AlignRight);

  // setup for graph 0: key axis left, value axis bottom
  // will contain left maxwell-like function
  customPlot->addGraph(customPlot->yAxis, customPlot->xAxis);
  customPlot->graph(0)->setPen(QPen(QColor(255, 100, 0)));
  customPlot->graph(0)->setBrush(QBrush(QPixmap("://skin/images/balboa.jpg"))); // fill with texture of specified image
  customPlot->graph(0)->setLineStyle(QCPGraph::lsLine);
  customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, 5));
  customPlot->graph(0)->setName("Left maxwell function");

  // setup for graph 1: key axis bottom, value axis left (those are the default axes)
  // will contain bottom maxwell-like function
  customPlot->addGraph();
  customPlot->graph(1)->setPen(QPen(Qt::red));
  customPlot->graph(1)->setBrush(QBrush(QPixmap("://skin/images/balboa.jpg"))); // same fill as we used for graph 0
  customPlot->graph(1)->setLineStyle(QCPGraph::lsStepCenter);
  customPlot->graph(1)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::red, Qt::white, 7));
  customPlot->graph(1)->setErrorType(QCPGraph::etValue);
  customPlot->graph(1)->setName("Bottom maxwell function");

  // setup for graph 2: key axis top, value axis right
  // will contain high frequency sine with low frequency beating:
  customPlot->addGraph(customPlot->xAxis2, customPlot->yAxis2);
  customPlot->graph(2)->setPen(QPen(Qt::blue));
  customPlot->graph(2)->setName("High frequency sine");

  // setup for graph 3: same axes as graph 2
  // will contain low frequency beating envelope of graph 2
  customPlot->addGraph(customPlot->xAxis2, customPlot->yAxis2);
  QPen blueDotPen;
  blueDotPen.setColor(QColor(30, 40, 255, 150));
  blueDotPen.setStyle(Qt::DotLine);
  blueDotPen.setWidthF(4);
  customPlot->graph(3)->setPen(blueDotPen);
  customPlot->graph(3)->setName("Sine envelope");

  // setup for graph 4: key axis right, value axis top
  // will contain parabolically distributed data points with some random perturbance
  customPlot->addGraph(customPlot->yAxis2, customPlot->xAxis2);
  customPlot->graph(4)->setPen(QColor(50, 50, 50, 255));
  customPlot->graph(4)->setLineStyle(QCPGraph::lsNone);
  customPlot->graph(4)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 4));
  customPlot->graph(4)->setName("Some random data around\na quadratic function");

  // generate data, just playing with numbers, not much to learn here:
  QVector<double> x0(25), y0(25);
  QVector<double> x1(15), y1(15), y1err(15);
  QVector<double> x2(250), y2(250);
  QVector<double> x3(250), y3(250);
  QVector<double> x4(250), y4(250);
  for (int i=0; i<25; ++i) // data for graph 0
  {
    x0[i] = 3*i/25.0;
    y0[i] = exp(-x0[i]*x0[i]*0.8)*(x0[i]*x0[i]+x0[i]);
  }
  for (int i=0; i<15; ++i) // data for graph 1
  {
    x1[i] = 3*i/15.0;;
    y1[i] = exp(-x1[i]*x1[i])*(x1[i]*x1[i])*2.6;
    y1err[i] = y1[i]*0.25;
  }
  for (int i=0; i<250; ++i) // data for graphs 2, 3 and 4
  {
    x2[i] = i/250.0*3*M_PI;
    x3[i] = x2[i];
    x4[i] = i/250.0*100-50;
    y2[i] = sin(x2[i]*12)*cos(x2[i])*10;
    y3[i] = cos(x3[i])*10;
    y4[i] = 0.01*x4[i]*x4[i] + 1.5*(rand()/(double)RAND_MAX-0.5) + 1.5*M_PI;
  }

  // pass data points to graphs:
  customPlot->graph(0)->setData(x0, y0);
  customPlot->graph(1)->setDataValueError(x1, y1, y1err);
  customPlot->graph(2)->setData(x2, y2);
  customPlot->graph(3)->setData(x3, y3);
  customPlot->graph(4)->setData(x4, y4);
  // activate top and right axes, which are invisible by default:
  customPlot->xAxis2->setVisible(true);
  customPlot->yAxis2->setVisible(true);
  // set ranges appropriate to show data:
  customPlot->xAxis->setRange(0, 2.7);
  customPlot->yAxis->setRange(0, 2.6);
  customPlot->xAxis2->setRange(0, 3.0*M_PI);
  customPlot->yAxis2->setRange(-70, 35);
  // set pi ticks on top axis:
  QVector<double> piTicks;
  QVector<QString> piLabels;
  piTicks << 0  << 0.5*M_PI << M_PI << 1.5*M_PI << 2*M_PI << 2.5*M_PI << 3*M_PI;
  piLabels << "0" << QString::fromUtf8("½π") << QString::fromUtf8("π") << QString::fromUtf8("1½π") << QString::fromUtf8("2π") << QString::fromUtf8("2½π") << QString::fromUtf8("3π");
  customPlot->xAxis2->setAutoTicks(false);
  customPlot->xAxis2->setAutoTickLabels(false);
  customPlot->xAxis2->setTickVector(piTicks);
  customPlot->xAxis2->setTickVectorLabels(piLabels);
  // add title layout element:
  customPlot->plotLayout()->insertRow(0);
  customPlot->plotLayout()->addElement(0, 0, new QCPPlotTitle(customPlot, "Way too many graphs in one plot"));
  // set labels:
  customPlot->xAxis->setLabel("Bottom axis with outward ticks");
  customPlot->yAxis->setLabel("Left axis label");
  customPlot->xAxis2->setLabel("Top axis label");
  customPlot->yAxis2->setLabel("Right axis label");
  // make ticks on bottom axis go outward:
  customPlot->xAxis->setTickLength(0, 5);
  customPlot->xAxis->setSubTickLength(0, 3);
  // make ticks on right axis go inward and outward:
  customPlot->yAxis2->setTickLength(3, 3);
  customPlot->yAxis2->setSubTickLength(1, 1);
}
Example #27
0
void EnrichmentDialog::initGeometryPage()
{
    geometryPage = new QWidget();

	QGridLayout *bl1 = new QGridLayout();

	attachToBox = new QComboBox();
	attachToBox->addItem(tr("Page"));
	attachToBox->addItem(tr("Layer Scales"));

	if (d_widget_type != MDIWindow)
		bl1->addWidget(new QLabel(tr( "Attach to" )), 0, 0);

	bl1->addWidget(attachToBox, 0, 1);
	if (d_widget_type == MDIWindow)
		attachToBox->hide();

	unitBox = new QComboBox();
	unitBox->insertItem(tr("inch"));
	unitBox->insertItem(tr("mm"));
	unitBox->insertItem(tr("cm"));
	unitBox->insertItem(tr("point"));
	unitBox->insertItem(tr("pixel"));
	if (d_widget_type != MDIWindow)
        unitBox->insertItem(tr("scale"));
	bl1->addWidget(unitBox, 1, 1);

	QLabel *l1 = new QLabel("&" + tr("Unit"));
	l1->setBuddy(unitBox);
	bl1->addWidget(l1, 1, 0);

	QLocale locale = QLocale();
	if (d_app)
		locale = d_app->locale();

    QGroupBox *gb1 = new QGroupBox(tr("Position"));
	xBox = new DoubleSpinBox();
	xBox->setLocale(locale);
	xBox->setDecimals(6);
	xBox->setMinimumWidth(80);
	yBox = new DoubleSpinBox();
	yBox->setLocale(locale);
	yBox->setDecimals(6);

    QGridLayout *gl1 = new QGridLayout();
    gl1->addWidget(new QLabel( tr("X")), 0, 0);
    gl1->addWidget(xBox, 0, 1);
    gl1->addWidget(new QLabel(tr("Y")), 1, 0);
    gl1->addWidget(yBox, 1, 1);
	gl1->setColumnStretch(1, 10);
	gl1->setRowStretch(2, 1);
    gb1->setLayout(gl1);

    QGroupBox *gb2 = new QGroupBox(tr("Size"));
    widthBox = new DoubleSpinBox();
	widthBox->setLocale(locale);
	widthBox->setDecimals(6);
	heightBox = new DoubleSpinBox();
	heightBox->setLocale(locale);
	heightBox->setDecimals(6);

    QGridLayout *gl2 = new QGridLayout();
    gl2->addWidget(new QLabel( tr("Width")), 0, 0);
    gl2->addWidget(widthBox, 0, 1);

    gl2->addWidget(new QLabel(tr("Height")), 1, 0);
    gl2->addWidget(heightBox, 1, 1);

	keepAspectBox = new QCheckBox(tr("&Keep aspect ratio"));
	if (d_app)
		keepAspectBox->setChecked(d_app->d_keep_aspect_ration);
	gl2->addWidget(keepAspectBox, 2, 1);

	bestSizeButton = new QPushButton(tr("&Best size"));
	bestSizeButton->hide();
	gl2->addWidget(bestSizeButton, 3, 1);

	gl2->setColumnStretch(1, 10);
	gl2->setRowStretch(4, 1);
    gb2->setLayout(gl2);

    QBoxLayout *bl2 = new QBoxLayout (QBoxLayout::LeftToRight);
	bl2->addWidget(gb1);
	bl2->addWidget(gb2);

	if (d_widget_type == Text)
		gb2->setEnabled(false);

	QVBoxLayout* vl = new QVBoxLayout(geometryPage);
    vl->addLayout(bl1);
    vl->addLayout(bl2);

	connect(unitBox, SIGNAL(activated(int)), this, SLOT(displayCoordinates(int)));
	connect(widthBox, SIGNAL(valueChanged(double)), this, SLOT(adjustHeight(double)));
	connect(heightBox, SIGNAL(valueChanged(double)), this, SLOT(adjustWidth(double)));
	connect(bestSizeButton, SIGNAL(clicked()), this, SLOT(setBestSize()));

	tabWidget->addTab(geometryPage, tr( "&Geometry" ) );
}
Example #28
0
void EditPointTool::updateStatusText()
{
	QString text;
	if (text_editor)
	{
		text = tr("<b>%1</b>: Finish editing. ").arg(ModifierKey::escape());
	}
	else if (editingInProgress())
	{
		MapCoordF drag_vector = constrained_pos_map - click_pos_map;
		text = EditTool::tr("<b>Coordinate offset:</b> %1, %2 mm  <b>Distance:</b> %3 m ").
		       arg(QLocale().toString(drag_vector.x(), 'f', 1)).
		       arg(QLocale().toString(-drag_vector.y(), 'f', 1)).
		       arg(QLocale().toString(0.001 * map()->getScaleDenominator() * drag_vector.length(), 'f', 1)) +
		       QLatin1String("| ");
		
		if (!angle_helper->isActive())
			text += EditTool::tr("<b>%1</b>: Fixed angles. ").arg(ModifierKey::control());
		
		if (!(active_modifiers & Qt::ShiftModifier))
		{
			if (hover_state == OverObjectNode &&
				hover_object->getType() == Object::Path &&
				hover_object->asPath()->isCurveHandle(hover_point))
			{
				text += tr("<b>%1</b>: Keep opposite handle positions. ").arg(ModifierKey::shift());
			}
			else
			{
				text += EditTool::tr("<b>%1</b>: Snap to existing objects. ").arg(ModifierKey::shift());
			}
		}
	}
	else
	{
		text = EditTool::tr("<b>Click</b>: Select a single object. <b>Drag</b>: Select multiple objects. <b>%1+Click</b>: Toggle selection. ").arg(ModifierKey::shift());
		if (map()->getNumSelectedObjects() > 0)
		{
			text += EditTool::tr("<b>%1</b>: Delete selected objects. ").arg(ModifierKey(delete_object_key));
			
			if (map()->selectedObjects().size() <= max_objects_for_handle_display)
			{
				// TODO: maybe show this only if at least one PathObject among the selected objects?
				if (active_modifiers & Qt::ControlModifier)
				{
					if (addDashPointDefault())
						text = tr("<b>%1+Click</b> on point: Delete it; on path: Add a new dash point; with <b>%2</b>: Add a normal point. ").
						       arg(ModifierKey::control(), ModifierKey::space());
					else
						text = tr("<b>%1+Click</b> on point: Delete it; on path: Add a new point; with <b>%2</b>: Add a dash point. ").
						       arg(ModifierKey::control(), ModifierKey::space());
				}
				else if (space_pressed)
					text = tr("<b>%1+Click</b> on point to switch between dash and normal point. ").arg(ModifierKey::space());
				else
					text += QLatin1String("| ") + MapEditorTool::tr("More: %1, %2").arg(ModifierKey::control(), ModifierKey::space());
			}
		}
	}
	setStatusBarText(text);
}
Example #29
0
void XDateEdit::parseDate()
{
  QString dateString = text().trimmed();
  bool    isNumeric;

  if (DEBUG)
    qDebug("%s::parseDate() with dateString %s, _currentDate %s, _allowNull %d",
           qPrintable(parent() ? parent()->objectName() : objectName()),
           qPrintable(dateString),
           qPrintable(_currentDate.toString()), _allowNull);

#ifdef GUIClient_h
  QDate today = ofmgThis->dbDate();
#else
  QDate today = QDate::currentDate();
#endif

  if (_parsed)
  {
    if (DEBUG)
      qDebug("%s::parseDate() looks like we've already parsed this string",
             qPrintable(parent() ? parent()->objectName() : objectName()));
    return;
  }

  _valid = false;

  if (dateString == _nullString || dateString.isEmpty())
    setNull();

  else if (dateString == "0")                           // today
    setDate(today, TRUE);

  else if (dateString.contains(QRegExp("^[+-][0-9]+"))) // offset from today
  {
    int offset = dateString.toInt(&isNumeric);
    if (isNumeric)
      setDate(today.addDays(offset), true);
  }

  else if (dateString[0] == '#')                        // julian day
  {
    int offset = dateString.right(dateString.length() - 1).toInt(&isNumeric);
    if (isNumeric)
      setDate(QDate(today.year(), 1, 1).addDays(offset - 1), TRUE);
  }

  else if (dateString.contains(QRegExp("^[0-9][0-9]?$"))) // date in month
  {
    int offset = dateString.toInt(&isNumeric, 10);
    if (isNumeric)
    {
      if (offset > today.daysInMonth())
        offset = today.daysInMonth();
 
      setDate(QDate(today.year(), today.month(), 1).addDays(offset - 1), TRUE);
    }
  }

  else                                                  // interpret with locale
  {
    QString dateFormatStr = QLocale().dateFormat(QLocale::ShortFormat);
    if (DEBUG)
      qDebug("%s::parseDate() trying to parse with %s",
             qPrintable(parent() ? parent()->objectName() : objectName()),
             qPrintable(dateFormatStr));

    QDate tmp = QDate::fromString(dateString, dateFormatStr);
    bool twodigitformat = !(dateFormatStr.indexOf(QRegExp("y{4}")) >= 0);
    if (tmp.isValid())
    {
      if (twodigitformat && tmp.year() < 1950) // Qt docs say 2-digit years are 1900-based so
      {
        qDebug("%s::parseDate() found valid 2-digit year %d",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               tmp.year());
        tmp = tmp.addYears(100); // add backwards-compat with pre-3.0 DLineEdit
        qDebug("%s::parseDate() altered year to %d",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               tmp.year());
      }
    }
    else if (twodigitformat)
    {
      // try 4 digits, ignoring the possibility of '-literals in the format str
      dateFormatStr.replace(QRegExp("y{2}"), "yyyy");
      if (DEBUG)
        qDebug("%s::parseDate() rewriting 2-digit year format string to %s",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               qPrintable(dateFormatStr));
      tmp = QDate::fromString(dateString, dateFormatStr);

      if (tmp.isValid())
      {
        if (tmp.year() < 10)
          tmp = tmp.addYears(today.year() - today.year() % 100);
        if (DEBUG)
          qDebug("%s::parseDate() after changing to 4-digit year, year = %d",
                 qPrintable(parent() ? parent()->objectName() : objectName()),
                 tmp.year());
      }
      else if (DEBUG)
        qDebug("%s::parseDate() after changing to 4-digit year, date still isn't valid",
               qPrintable(parent() ? parent()->objectName() : objectName()));

    }
    else
    {
      // try 2 digits, ignoring the possibility of '-literals in the format str
      dateFormatStr.replace(QRegExp("y{4}"), "yy");
      if (DEBUG)
        qDebug("%s::parseDate() rewriting 4-digit year format string to %s",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               qPrintable(dateFormatStr));
      tmp = QDate::fromString(dateString, dateFormatStr);
      if (tmp.isValid() && tmp.year() < 1950) // Qt docs say 2-digit years are 1900-based so
      {
        qDebug("%s::parseDate() found valid 2-digit year %d",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               tmp.year());
        tmp = tmp.addYears(100); // add backwards-compat with pre-3.0 DLineEdit
        qDebug("%s::parseDate() altered year to %d",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               tmp.year());
      }
    }
    if(!tmp.isValid())
    {
      // still no match -- we will decompose the format and input and
      // build a date based on that information
      QRegExp rx("(\\d+)");
      QRegExp rx2("(m+|y+|d+)");
      rx2.setCaseSensitivity(Qt::CaseInsensitive);
      QStringList numberList;
      QStringList formatList;
      int pos = 0;
      while ((pos = rx.indexIn(dateString, pos)) != -1)
      {
        numberList << rx.cap(1);
        pos += rx.matchedLength();
      }
      pos = 0;
      while((pos = rx2.indexIn(dateFormatStr, pos)) != -1)
      {
        formatList << rx2.cap(1);
        pos += rx2.matchedLength();
      }

      if (DEBUG)
        qDebug("%s::parseDate() aligning numberList %s with formatList %s",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               qPrintable(numberList.join(":")), qPrintable(formatList.join(":")));

      // if we don't have exactly 3 and the numberList is not 2 or 3 then don't bother
      if(formatList.size() == 3 && (numberList.size() == 2 || numberList.size() == 3))
      {
        int year = today.year();
        int day = -1;
        int month = -1;

        pos = 0;
        for (int i = 0; i < formatList.size(); ++i)
        {
          QChar ch = formatList.at(i).toLower().at(0);
          if(ch == 'y' && numberList.size() == 3)
          {
            year = numberList.at(pos).toInt();
            pos++;
          }
          else if(ch == 'm')
          {
            month = numberList.at(pos).toInt();
            pos++;
          }
          else if(ch == 'd')
          {
            day = numberList.at(pos).toInt();
            pos++;
          }
        }

        // if single digit year, move it to the current century
        if (year < 10)
          year += today.year() - today.year() % 100;

        if(day > 0 && month > 0 && year > 0)
          tmp = QDate(year, month, day);
      }
      else if(formatList.size() == 3 && numberList.size() == 1)
      {
        QString ns = numberList.at(0);
        bool isNumber = false;
        (void)ns.toInt(&isNumber);
        if(isNumber && (ns.length() == 6 || ns.length() == 8))
        {
          int year = today.year();
          int day = -1;
          int month = -1;

          pos = 0;
          for (int i = 0; i < formatList.size(); ++i)
          {
            QChar ch = formatList.at(i).toLower().at(0);
            if(ch == 'y')
            {
              if(ns.length() == 8)
              {
                year = ns.mid(pos, 4).toInt();
                pos+=4;
              }
              else
              {
                year = ns.mid(pos, 2).toInt(&isNumber);
                pos+=2;
                if(isNumber)
                {
                  if(year < 50)
                    year += 2000;
                  else
                    year += 1900;
                }
              }
            }
            else if(ch == 'm')
            {
              month = ns.mid(pos, 2).toInt();
              pos+=2;
            }
            else if(ch == 'd')
            {
              day = ns.mid(pos, 2).toInt();
              pos+=2;
            }
          }

          if(day > 0 && month > 0 && year > 0)
            tmp = QDate(year, month, day);
        }
      }
    }

    setDate(QDate(tmp.year(), tmp.month(), tmp.day()), true );
  }

  if (!_valid)
    setText("");

  _parsed = true;
}
Example #30
0
void sysLocale::sUpdateSamples()
{
  QLocale::Language localeLang = QLocale::C;
  QLocale::Country  localeCountry = QLocale::AnyCountry;

  if (_language->id() > 0)
  {
    q.prepare("SELECT lang_qt_number FROM lang WHERE (lang_id=:langid);");
    q.bindValue(":langid", _language->id());
    q.exec();
    if (q.first())
    {
      localeLang = QLocale::Language(q.value("lang_qt_number").toInt());
    }
    else if (q.lastError().type() != QSqlError::None)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
  }

  if (_country->id() > 0)
  {
    q.prepare("SELECT country_qt_number "
              "FROM country "
              "WHERE (country_id=:countryid);");
    q.bindValue(":countryid", _country->id());
    q.exec();
    if (q.first())
    {
      localeCountry = QLocale::Country(q.value("country_qt_number").toInt());
    }
    else if (q.lastError().type() != QSqlError::None)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
  }

  q.prepare("SELECT CURRENT_DATE AS dateSample, CURRENT_TIME AS timeSample,"
            "       CURRENT_TIMESTAMP AS timestampSample,"
            "       CURRENT_TIMESTAMP - CURRENT_DATE AS intervalSample,"
            "       987654321.987654321 AS doubleSample;");
  q.exec();
  if (q.first())
  {
    QLocale sampleLocale = QLocale(localeLang, localeCountry);
    _dateSample->setText(sampleLocale.toString(q.value("dateSample").toDate(), QLocale::ShortFormat));
    _timeSample->setText(sampleLocale.toString(q.value("timeSample").toTime(), QLocale::ShortFormat));
    _timestampSample->setText(sampleLocale.toString(q.value("timestampSample").toDate(), QLocale::ShortFormat) +
                              " " +
                              sampleLocale.toString(q.value("timestampSample").toTime(), QLocale::ShortFormat));
    _intervalSample->setText(sampleLocale.toString(q.value("intervalSample").toTime(), QLocale::ShortFormat));

    _currencySample->setText(sampleLocale.toString(q.value("doubleSample").toDouble(), 'f', _currencyScale->value()));
    _salesPriceSample->setText(sampleLocale.toString(q.value("doubleSample").toDouble(), 'f', _salesPriceScale->value()));
    _purchPriceSample->setText(sampleLocale.toString(q.value("doubleSample").toDouble(), 'f', _purchPriceScale->value()));
    _extPriceSample->setText(sampleLocale.toString(q.value("doubleSample").toDouble(), 'f', _extPriceScale->value()));
    _costSample->setText(sampleLocale.toString(q.value("doubleSample").toDouble(), 'f', _costScale->value()));
    _qtySample->setText(sampleLocale.toString(q.value("doubleSample").toDouble(), 'f', _qtyScale->value()));
    _qtyPerSample->setText(sampleLocale.toString(q.value("doubleSample").toDouble(), 'f', _qtyPerScale->value()));
    _uomRatioSample->setText(sampleLocale.toString(q.value("doubleSample").toDouble(), 'f', _uomRatioScale->value()));
  }
  else if (q.lastError().type() != QSqlError::None)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}