void GridSettingsDialog::updateInternalRepresentation() noexcept { QLocale locale; // this loads the application's default locale (defined in // WSI_AppLocale) mUi->lblIntervalNm->setText(QString("%1 nm").arg( locale.toString(mCurrentGrid.getInterval()->toNm()))); }
PreferencesDialog::PreferencesDialog(QWidget *parent, Profile *_profile) : QDialog(parent), ui(new Ui::PreferencesDialog), profile(_profile) { ui->setupUi(this); channeltype.clear(); channeltype[schema::FLAG] = tr("Flag"); channeltype[schema::MINOR_FLAG] = tr("Minor Flag"); channeltype[schema::SPAN] = tr("Span"); channeltype[schema::UNKNOWN] = tr("Always Minor"); //#ifdef LOCK_RESMED_SESSIONS // QList<Machine *> machines = p_profile->GetMachines(MT_CPAP); // for (QList<Machine *>::iterator it = machines.begin(); it != machines.end(); ++it) { // const QString & mclass=(*it)->loaderName(); // if (mclass == STR_MACH_ResMed) { // ui->combineSlider->setEnabled(false); // ui->IgnoreSlider->setEnabled(false); // ui->timeEdit->setEnabled(false); // break; // } // } //#endif QLocale locale = QLocale::system(); QString shortformat = locale.dateFormat(QLocale::ShortFormat); if (!shortformat.toLower().contains("yyyy")) { shortformat.replace("yy", "yyyy"); } // Qt::DayOfWeek dow = firstDayOfWeekFromLocale(); // QTextCharFormat format = ui->startedUsingMask->calendarWidget()->weekdayTextFormat(Qt::Saturday); // format.setForeground(QBrush(Qt::black, Qt::SolidPattern)); Q_ASSERT(profile != nullptr); ui->tabWidget->setCurrentIndex(0); //i=ui->timeZoneCombo->findText((*profile)["TimeZone"].toString()); //ui->timeZoneCombo->setCurrentIndex(i); ui->showLeakRedline->setChecked(profile->cpap->showLeakRedline()); ui->leakRedlineSpinbox->setValue(profile->cpap->leakRedline()); ui->oxiDesaturationThreshold->setValue(schema::channel[OXI_SPO2].lowerThreshold()); ui->flagPulseAbove->setValue(schema::channel[OXI_Pulse].upperThreshold()); ui->flagPulseBelow->setValue(schema::channel[OXI_Pulse].lowerThreshold()); ui->spo2Drop->setValue(profile->oxi->spO2DropPercentage()); ui->spo2DropTime->setValue(profile->oxi->spO2DropDuration()); ui->pulseChange->setValue(profile->oxi->pulseChangeBPM()); ui->pulseChangeTime->setValue(profile->oxi->pulseChangeDuration()); ui->oxiDiscardThreshold->setValue(profile->oxi->oxiDiscardThreshold()); ui->eventIndexCombo->setCurrentIndex(profile->general->calculateRDI() ? 1 : 0); ui->automaticImport->setChecked(profile->cpap->autoImport()); ui->timeEdit->setTime(profile->session->daySplitTime()); int val = profile->session->combineCloseSessions(); ui->combineSlider->setValue(val); if (val > 0) { ui->combineLCD->display(val); } else { ui->combineLCD->display(STR_TR_Off); } val = profile->session->ignoreShortSessions(); ui->IgnoreSlider->setValue(val); if (val > 0) { ui->IgnoreLCD->display(val); } else { ui->IgnoreLCD->display(STR_TR_Off); } ui->LockSummarySessionSplitting->setChecked(profile->session->lockSummarySessions()); ui->applicationFont->setCurrentFont(QApplication::font()); //ui->applicationFont->setFont(QApplication::font()); ui->applicationFontSize->setValue(QApplication::font().pointSize()); ui->applicationFontBold->setChecked(QApplication::font().weight() == QFont::Bold); ui->applicationFontItalic->setChecked(QApplication::font().italic()); ui->graphFont->setCurrentFont(*defaultfont); //ui->graphFont->setFont(*defaultfont); ui->graphFontSize->setValue(defaultfont->pointSize()); ui->graphFontBold->setChecked(defaultfont->weight() == QFont::Bold); ui->graphFontItalic->setChecked(defaultfont->italic()); ui->titleFont->setCurrentFont(*mediumfont); //ui->titleFont->setFont(*mediumfont); ui->titleFontSize->setValue(mediumfont->pointSize()); ui->titleFontBold->setChecked(mediumfont->weight() == QFont::Bold); ui->titleFontItalic->setChecked(mediumfont->italic()); ui->bigFont->setCurrentFont(*bigfont); //ui->bigFont->setFont(*bigfont); ui->bigFontSize->setValue(bigfont->pointSize()); ui->bigFontBold->setChecked(bigfont->weight() == QFont::Bold); ui->bigFontItalic->setChecked(bigfont->italic()); ui->lineThicknessSlider->setValue(profile->appearance->lineThickness()*2); ui->resyncMachineDetectedEvents->setChecked(profile->cpap->resyncFromUserFlagging()); ui->useAntiAliasing->setChecked(profile->appearance->antiAliasing()); ui->usePixmapCaching->setChecked(profile->appearance->usePixmapCaching()); ui->useSquareWavePlots->setChecked(profile->appearance->squareWavePlots()); ui->enableGraphSnapshots->setChecked(profile->appearance->graphSnapshots()); ui->graphTooltips->setChecked(profile->appearance->graphTooltips()); ui->allowYAxisScaling->setChecked(profile->appearance->allowYAxisScaling()); ui->skipLoginScreen->setChecked(PREF[STR_GEN_SkipLogin].toBool()); ui->allowEarlyUpdates->setChecked(PREF[STR_PREF_AllowEarlyUpdates].toBool()); int s = profile->cpap->clockDrift(); int m = (s / 60) % 60; int h = (s / 3600); s %= 60; ui->clockDriftHours->setValue(h); ui->clockDriftMinutes->setValue(m); ui->clockDriftSeconds->setValue(s); ui->skipEmptyDays->setChecked(profile->general->skipEmptyDays()); ui->showUnknownFlags->setChecked(profile->general->showUnknownFlags()); ui->enableMultithreading->setChecked(profile->session->multithreading()); ui->cacheSessionData->setChecked(profile->session->cacheSessions()); ui->preloadSummaries->setChecked(profile->session->preloadSummaries()); ui->animationsAndTransitionsCheckbox->setChecked(profile->appearance->animations()); ui->complianceCheckBox->setChecked(profile->cpap->showComplianceInfo()); ui->complianceHours->setValue(profile->cpap->complianceHours()); ui->prefCalcMiddle->setCurrentIndex(profile->general->prefCalcMiddle()); ui->prefCalcMax->setCurrentIndex(profile->general->prefCalcMax()); float f = profile->general->prefCalcPercentile(); ui->prefCalcPercentile->setValue(f); ui->tooltipTimeoutSlider->setValue(profile->general->tooltipTimeout() / 50); ui->tooltipMS->display(profile->general->tooltipTimeout()); ui->scrollDampeningSlider->setValue(profile->general->scrollDampening() / 10); if (profile->general->scrollDampening() > 0) { ui->scrollDampDisplay->display(profile->general->scrollDampening()); } else { ui->scrollDampDisplay->display(STR_TR_Off); } bool bcd = profile->session->backupCardData(); ui->createSDBackups->setChecked(bcd); ui->compressSDBackups->setEnabled(bcd); ui->compressSDBackups->setChecked(profile->session->compressBackupData()); ui->compressSessionData->setChecked(profile->session->compressSessionData()); ui->ignoreOlderSessionsCheck->setChecked(profile->session->ignoreOlderSessions()); ui->ignoreOlderSessionsDate->setDate(profile->session->ignoreOlderSessionsDate().date()); ui->graphHeight->setValue(profile->appearance->graphHeight()); ui->automaticallyCheckUpdates->setChecked(PREF[STR_GEN_UpdatesAutoCheck].toBool()); ui->updateCheckEvery->setValue(PREF[STR_GEN_UpdateCheckFrequency].toInt()); if (PREF.contains(STR_GEN_UpdatesLastChecked)) { RefreshLastChecked(); } else { ui->updateLastChecked->setText("Never"); } ui->allowEventRenaming->setChecked(PREF[STR_PREF_AllowEventRenaming].toBool()); ui->overlayFlagsCombo->setCurrentIndex(profile->appearance->overlayType()); ui->overviewLinecharts->setCurrentIndex(profile->appearance->overviewLinechartMode()); ui->ahiGraphWindowSize->setEnabled(false); ui->ahiGraphWindowSize->setValue(profile->cpap->AHIWindow()); ui->ahiGraphZeroReset->setChecked(profile->cpap->AHIReset()); ui->customEventGroupbox->setChecked(profile->cpap->userEventFlagging()); ui->apneaDuration->setValue(profile->cpap->userEventDuration()); ui->apneaFlowRestriction->setValue(profile->cpap->userFlowRestriction()); ui->apneaDuration2->setValue(profile->cpap->userEventDuration2()); ui->apneaFlowRestriction2->setValue(profile->cpap->userFlowRestriction2()); ui->userEventDuplicates->setChecked(profile->cpap->userEventDuplicates()); ui->userEventDuplicates->setVisible(false); ui->showUserFlagsInPie->setChecked(profile->cpap->userEventPieChart()); bool b; ui->calculateUnintentionalLeaks->setChecked(b=profile->cpap->calculateUnintentionalLeaks()); ui->maskLeaks4Slider->setValue(profile->cpap->custom4cmH2OLeaks()*10.0); ui->maskLeaks20Slider->setValue(profile->cpap->custom20cmH2OLeaks()*10.0); ui->maskLeaks4Label->setText(tr("%1 %2").arg(profile->cpap->custom4cmH2OLeaks(), 5, 'f', 1).arg(STR_UNIT_LPM)); ui->maskLeaks20Label->setText(tr("%1 %2").arg(profile->cpap->custom20cmH2OLeaks(), 5, 'f', 1).arg(STR_UNIT_LPM)); /* QLocale locale=QLocale::system(); QString shortformat=locale.dateFormat(QLocale::ShortFormat); if (!shortformat.toLower().contains("yyyy")) { shortformat.replace("yy","yyyy"); }*/ chanFilterModel = new MySortFilterProxyModel(this); chanModel = new QStandardItemModel(this); chanFilterModel->setSourceModel(chanModel); chanFilterModel->setFilterCaseSensitivity(Qt::CaseInsensitive); chanFilterModel->setFilterKeyColumn(0); ui->chanView->setModel(chanFilterModel); InitChanInfo(); waveFilterModel = new MySortFilterProxyModel(this); waveModel = new QStandardItemModel(this); waveFilterModel->setSourceModel(waveModel); waveFilterModel->setFilterCaseSensitivity(Qt::CaseInsensitive); waveFilterModel->setFilterKeyColumn(0); ui->waveView->setModel(waveFilterModel); InitWaveInfo(); ui->waveView->setSortingEnabled(true); ui->chanView->setSortingEnabled(true); ui->waveView->sortByColumn(0, Qt::AscendingOrder); ui->chanView->sortByColumn(0, Qt::AscendingOrder); }
EResumen::EResumen( QWidget *parent, tipo que ) : EVentana( parent ) { setObjectName( "selectorResumen" ); setWindowTitle( "Seleccione el Resumen" ); setAttribute( Qt::WA_DeleteOnClose ); generar = que; QVBoxLayout *layoutPrincipal = new QVBoxLayout( this ); layoutPrincipal->setMargin( 3 ); layoutPrincipal->setSpacing( 3 ); switch( que ) { case diario: { QGroupBox *g = new QGroupBox( this ); g->setTitle( "Elija la fecha del resumen" ); g->setAlignment( Qt::AlignHCenter ); g->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); QVBoxLayout *v = new QVBoxLayout( g ); CWfecha = new QCalendarWidget( g ); CWfecha->setGridVisible( false ); CWfecha->setMaximumDate( QDate::currentDate() ); CWfecha->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); v->addWidget( CWfecha ); g->adjustSize(); layoutPrincipal->addWidget( g ); break; } case mensual: { QGroupBox *groupBox = new QGroupBox( this ); groupBox->setObjectName(QString::fromUtf8("groupBox")); groupBox->setTitle( "Elija el mes para el resumen" ); groupBox->setAlignment( Qt::AlignCenter ); groupBox->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); QVBoxLayout *v = new QVBoxLayout(groupBox); v->setObjectName( "vLayout" ); QHBoxLayout *h1 = new QHBoxLayout(); h1->setObjectName("hLayout1"); QLabel *Lmes = new QLabel(groupBox); Lmes->setObjectName(QString::fromUtf8("labelMes")); Lmes->setText( tr( "Mes:" ) ); h1->addWidget(Lmes); CBMes = new QComboBox(groupBox); CBMes->setObjectName(QString::fromUtf8("CBMes")); // Inserto los meses QLocale locale; for( int i = 1; i<=12; i++ ) { CBMes->insertItem( i, locale.monthName( i ) ); } CBMes->setCurrentIndex( QDate::currentDate().month() ); h1->addWidget(CBMes); v->addLayout(h1); QHBoxLayout *horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2")); QLabel *Lano = new QLabel(groupBox); Lano->setObjectName(QString::fromUtf8("lano")); Lano->setText( tr( "Año:" ) ); horizontalLayout_2->addWidget(Lano); SBAno = new QSpinBox(groupBox); SBAno->setObjectName(QString::fromUtf8("SBAno")); SBAno->setMaximum( QDate::currentDate().year() ); SBAno->setSingleStep( 1 ); SBAno->setValue( QDate::currentDate().year() ); horizontalLayout_2->addWidget(SBAno); v->addLayout(horizontalLayout_2); layoutPrincipal->addWidget( groupBox ); break; } case anual: { QHBoxLayout *layout = new QHBoxLayout( this ); QLabel *etiqueta = new QLabel( this ); etiqueta->setText( QString( "Año:" ) ); seleccion = new QSpinBox( this ); seleccion->setRange( 0, QDate::currentDate().year() ); seleccion->setSingleStep( 1 ); seleccion->setValue( QDate::currentDate().year() ); layout->addWidget( etiqueta ); layout->addWidget( seleccion ); layoutPrincipal->addLayout( layout ); break; } case semanal: { QGroupBox *g = new QGroupBox( this ); g->setTitle( "Elija un dia de la semana para el resumen" ); g->setAlignment( Qt::AlignHCenter ); g->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); QVBoxLayout *v = new QVBoxLayout( g ); CWfecha = new QCalendarWidget( g ); CWfecha->setGridVisible( true ); CWfecha->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); v->addWidget( CWfecha ); g->adjustSize(); layoutPrincipal->addWidget( g ); break; } case entrefechas: { QHBoxLayout *horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName( "horizontalLayout" ); horizontalLayout->setContentsMargins(0, 0, 0, 0); QLabel *LInicio = new QLabel(this); LInicio->setObjectName( "LInicio" ); LInicio->setText( "Fecha de inicio:" ); horizontalLayout->addWidget(LInicio); DEInicio = new QDateEdit(this); DEInicio->setObjectName( "DEInicio" ); DEInicio->setCalendarPopup(true); horizontalLayout->addWidget(DEInicio); QHBoxLayout *horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setObjectName( "horizontalLayout_2" ); horizontalLayout_2->setContentsMargins(0, 0, 0, 0); QLabel *LFin = new QLabel(this); LFin->setObjectName( "LFin" ); LFin->setText( "Fecha de Fin:" ); horizontalLayout_2->addWidget(LFin); DEFin = new QDateEdit(this); DEFin->setObjectName( "DEFin" ); DEFin->setCalendarPopup(true); DEFin->setMaximumDate( QDate::currentDate() ); horizontalLayout_2->addWidget(DEFin); layoutPrincipal->addItem( horizontalLayout ); layoutPrincipal->addItem( horizontalLayout_2 ); } } QAction *ActGenerar = new QAction( "Generar Reporte", this ); ActGenerar->setIcon( QIcon( ":/imagenes/reporte.png" ) ); connect( ActGenerar, SIGNAL( triggered() ), this, SLOT( generarResumen() ) ); addAction( ActGenerar ); EActCerrar *ActCerrar = new EActCerrar( this ); connect( ActCerrar, SIGNAL( triggered() ), this, SLOT( close() ) ); addAction( ActCerrar ); this->adjustSize(); }
// update the dive and return the notes field, stripped of the HTML junk void QMLManager::commitChanges(QString diveId, QString date, QString location, QString gps, QString duration, QString depth, QString airtemp, QString watertemp, QString suit, QString buddy, QString diveMaster, QString weight, QString notes, QString startpressure, QString endpressure, QString gasmix) { #define DROP_EMPTY_PLACEHOLDER(_s) if ((_s) == QLatin1Literal("--")) (_s).clear() DROP_EMPTY_PLACEHOLDER(location); DROP_EMPTY_PLACEHOLDER(duration); DROP_EMPTY_PLACEHOLDER(depth); DROP_EMPTY_PLACEHOLDER(airtemp); DROP_EMPTY_PLACEHOLDER(watertemp); DROP_EMPTY_PLACEHOLDER(suit); DROP_EMPTY_PLACEHOLDER(buddy); DROP_EMPTY_PLACEHOLDER(diveMaster); DROP_EMPTY_PLACEHOLDER(weight); DROP_EMPTY_PLACEHOLDER(gasmix); DROP_EMPTY_PLACEHOLDER(startpressure); DROP_EMPTY_PLACEHOLDER(endpressure); DROP_EMPTY_PLACEHOLDER(notes); #undef DROP_EMPTY_PLACEHOLDER struct dive *d = get_dive_by_uniq_id(diveId.toInt()); // notes comes back as rich text - let's convert this into plain text QTextDocument doc; doc.setHtml(notes); notes = doc.toPlainText(); if (!d) { qDebug() << "don't touch this... no dive"; return; } bool diveChanged = false; bool needResort = false; invalidate_dive_cache(d); if (date != get_dive_date_string(d->when)) { diveChanged = needResort = true; QDateTime newDate; // what a pain - Qt will not parse dates if the day of the week is incorrect // so if the user changed the date but didn't update the day of the week (most likely behavior, actually), // we need to make sure we don't try to parse that QString format(QString(prefs.date_format) + QChar(' ') + prefs.time_format); if (format.contains(QLatin1String("ddd")) || format.contains(QLatin1String("dddd"))) { QString dateFormatToDrop = format.contains(QLatin1String("ddd")) ? QStringLiteral("ddd") : QStringLiteral("dddd"); QDateTime ts; QLocale loc = getLocale(); ts.setMSecsSinceEpoch(d->when * 1000L); QString drop = loc.toString(ts.toUTC(), dateFormatToDrop); format.replace(dateFormatToDrop, ""); date.replace(drop, ""); } newDate = QDateTime::fromString(date, format); if (!newDate.isValid()) { qDebug() << "unable to parse date" << date << "with the given format" << format; QRegularExpression isoDate("\\d+-\\d+-\\d+[^\\d]+\\d+:\\d+"); if (date.contains(isoDate)) { newDate = QDateTime::fromString(date, "yyyy-M-d h:m:s"); if (newDate.isValid()) goto parsed; newDate = QDateTime::fromString(date, "yy-M-d h:m:s"); if (newDate.isValid()) goto parsed; } QRegularExpression isoDateNoSecs("\\d+-\\d+-\\d+[^\\d]+\\d+"); if (date.contains(isoDateNoSecs)) { newDate = QDateTime::fromString(date, "yyyy-M-d h:m"); if (newDate.isValid()) goto parsed; newDate = QDateTime::fromString(date, "yy-M-d h:m"); if (newDate.isValid()) goto parsed; } QRegularExpression usDate("\\d+/\\d+/\\d+[^\\d]+\\d+:\\d+:\\d+"); if (date.contains(usDate)) { newDate = QDateTime::fromString(date, "M/d/yyyy h:m:s"); if (newDate.isValid()) goto parsed; newDate = QDateTime::fromString(date, "M/d/yy h:m:s"); if (newDate.isValid()) goto parsed; newDate = QDateTime::fromString(date.toLower(), "M/d/yyyy h:m:sap"); if (newDate.isValid()) goto parsed; newDate = QDateTime::fromString(date.toLower(), "M/d/yy h:m:sap"); if (newDate.isValid()) goto parsed; } QRegularExpression usDateNoSecs("\\d+/\\d+/\\d+[^\\d]+\\d+:\\d+"); if (date.contains(usDateNoSecs)) { newDate = QDateTime::fromString(date, "M/d/yyyy h:m"); if (newDate.isValid()) goto parsed; newDate = QDateTime::fromString(date, "M/d/yy h:m"); if (newDate.isValid()) goto parsed; newDate = QDateTime::fromString(date.toLower(), "M/d/yyyy h:map"); if (newDate.isValid()) goto parsed; newDate = QDateTime::fromString(date.toLower(), "M/d/yy h:map"); if (newDate.isValid()) goto parsed; } QRegularExpression leDate("\\d+\\.\\d+\\.\\d+[^\\d]+\\d+:\\d+:\\d+"); if (date.contains(leDate)) { newDate = QDateTime::fromString(date, "d.M.yyyy h:m:s"); if (newDate.isValid()) goto parsed; newDate = QDateTime::fromString(date, "d.M.yy h:m:s"); if (newDate.isValid()) goto parsed; } QRegularExpression leDateNoSecs("\\d+\\.\\d+\\.\\d+[^\\d]+\\d+:\\d+"); if (date.contains(leDateNoSecs)) { newDate = QDateTime::fromString(date, "d.M.yyyy h:m"); if (newDate.isValid()) goto parsed; newDate = QDateTime::fromString(date, "d.M.yy h:m"); if (newDate.isValid()) goto parsed; } } parsed: if (newDate.isValid()) { // stupid Qt... two digit years are always 19xx - WTF??? // so if adding a hundred years gets you into something before a year from now... // add a hundred years. if (newDate.addYears(100) < QDateTime::currentDateTime().addYears(1)) newDate = newDate.addYears(100); d->dc.when = d->when = newDate.toMSecsSinceEpoch() / 1000 + gettimezoneoffset(newDate.toMSecsSinceEpoch() / 1000); } else { qDebug() << "none of our parsing attempts worked for the date string"; } } struct dive_site *ds = get_dive_site_by_uuid(d->dive_site_uuid); char *locationtext = NULL; if (ds) locationtext = ds->name; if (!same_string(locationtext, qPrintable(location))) { diveChanged = true; // this is not ideal - and it's missing the gps information // but for now let's just create a new dive site ds = get_dive_site_by_uuid(create_dive_site(qPrintable(location), d->when)); d->dive_site_uuid = ds->uuid; } if (!gps.isEmpty()) { QString gpsString = getCurrentPosition(); if (gpsString != QString("waiting for the next gps location")) { qDebug() << "from commitChanges call to getCurrentPosition returns" << gpsString; double lat, lon; if (parseGpsText(qPrintable(gpsString), &lat, &lon)) { struct dive_site *ds = get_dive_site_by_uuid(d->dive_site_uuid); if (ds) { ds->latitude.udeg = lat * 1000000; ds->longitude.udeg = lon * 1000000; } else { degrees_t latData, lonData; latData.udeg = lat; lonData.udeg = lon; d->dive_site_uuid = create_dive_site_with_gps("new site", latData, lonData, d->when); } qDebug() << "set up dive site with new GPS data"; } } else { qDebug() << "still don't have a position - will need to implement some sort of callback"; } } if (get_dive_duration_string(d->duration.seconds, tr("h:"), tr("min")) != duration) { diveChanged = true; int h = 0, m = 0, s = 0; QRegExp r1(QStringLiteral("(\\d*)\\s*%1[\\s,:]*(\\d*)\\s*%2[\\s,:]*(\\d*)\\s*%3").arg(tr("h")).arg(tr("min")).arg(tr("sec")), Qt::CaseInsensitive); QRegExp r2(QStringLiteral("(\\d*)\\s*%1[\\s,:]*(\\d*)\\s*%2").arg(tr("h")).arg(tr("min")), Qt::CaseInsensitive); QRegExp r3(QStringLiteral("(\\d*)\\s*%1").arg(tr("min")), Qt::CaseInsensitive); QRegExp r4(QStringLiteral("(\\d*):(\\d*):(\\d*)")); QRegExp r5(QStringLiteral("(\\d*):(\\d*)")); QRegExp r6(QStringLiteral("(\\d*)")); if (r1.indexIn(duration) >= 0) { h = r1.cap(1).toInt(); m = r1.cap(2).toInt(); s = r1.cap(3).toInt(); } else if (r2.indexIn(duration) >= 0) { h = r2.cap(1).toInt(); m = r2.cap(2).toInt(); } else if (r3.indexIn(duration) >= 0) { m = r3.cap(1).toInt(); } else if (r4.indexIn(duration) >= 0) { h = r4.cap(1).toInt(); m = r4.cap(2).toInt(); s = r4.cap(3).toInt(); } else if (r5.indexIn(duration) >= 0) { h = r5.cap(1).toInt(); m = r5.cap(2).toInt(); } else if (r6.indexIn(duration) >= 0) { m = r6.cap(1).toInt(); } d->dc.duration.seconds = d->duration.seconds = h * 3600 + m * 60 + s; if (same_string(d->dc.model, "manually added dive")) { free(d->dc.sample); d->dc.sample = 0; d->dc.samples = 0; } else { qDebug() << "changing the duration on a dive that wasn't manually added - Uh-oh"; } } if (get_depth_string(d->maxdepth.mm, true, true) != depth) { int depthValue = parseLengthToMm(depth); // the QML code should stop negative depth, but massively huge depth can make // the profile extremely slow or even run out of memory and crash, so keep // the depth <= 500m if (0 <= depthValue && depthValue <= 500000) { diveChanged = true; d->maxdepth.mm = depthValue; if (same_string(d->dc.model, "manually added dive")) { d->dc.maxdepth.mm = d->maxdepth.mm; free(d->dc.sample); d->dc.sample = 0; d->dc.samples = 0; } } } if (get_temperature_string(d->airtemp, true) != airtemp) { diveChanged = true; d->airtemp.mkelvin = parseTemperatureToMkelvin(airtemp); } if (get_temperature_string(d->watertemp, true) != watertemp) { diveChanged = true; d->watertemp.mkelvin = parseTemperatureToMkelvin(watertemp); } // not sure what we'd do if there was more than one weight system // defined - for now just ignore that case if (weightsystem_none((void *)&d->weightsystem[1])) { if (get_weight_string(d->weightsystem[0].weight, true) != weight) { diveChanged = true; d->weightsystem[0].weight.grams = parseWeightToGrams(weight); } } // start and end pressures for first cylinder only if (get_pressure_string(d->cylinder[0].start, true) != startpressure || get_pressure_string(d->cylinder[0].end, true) != endpressure) { diveChanged = true; d->cylinder[0].start.mbar = parsePressureToMbar(startpressure); d->cylinder[0].end.mbar = parsePressureToMbar(endpressure); if (d->cylinder[0].end.mbar > d->cylinder[0].start.mbar) d->cylinder[0].end.mbar = d->cylinder[0].start.mbar; } // gasmix for first cylinder if (get_gas_string(d->cylinder[0].gasmix) != gasmix) { int o2 = parseGasMixO2(gasmix); int he = parseGasMixHE(gasmix); // the QML code SHOULD only accept valid gas mixes, but just to make sure if (o2 >= 0 && o2 <= 1000 && he >= 0 && he <= 1000 && o2 + he <= 1000) { diveChanged = true; d->cylinder[0].gasmix.o2.permille = o2; d->cylinder[0].gasmix.he.permille = he; } } if (!same_string(d->suit, qPrintable(suit))) { diveChanged = true; free(d->suit); d->suit = strdup(qPrintable(suit)); } if (!same_string(d->buddy, qPrintable(buddy))) { diveChanged = true; free(d->buddy); d->buddy = strdup(qPrintable(buddy)); } if (!same_string(d->divemaster, qPrintable(diveMaster))) { diveChanged = true; free(d->divemaster); d->divemaster = strdup(qPrintable(diveMaster)); } if (!same_string(d->notes, qPrintable(notes))) { diveChanged = true; free(d->notes); d->notes = strdup(qPrintable(notes)); } // now that we have it all figured out, let's see what we need // to update DiveListModel *dm = DiveListModel::instance(); int oldModelIdx = dm->getDiveIdx(d->id); int oldIdx = get_idx_by_uniq_id(d->id); if (needResort) { // we know that the only thing that might happen in a resort is that // this one dive moves to a different spot in the dive list sort_table(&dive_table); int newIdx = get_idx_by_uniq_id(d->id); if (newIdx != oldIdx) { DiveObjectHelper *newDive = new DiveObjectHelper(d); DiveListModel::instance()->removeDive(oldModelIdx); DiveListModel::instance()->insertDive(oldModelIdx - (newIdx - oldIdx), newDive); diveChanged = false; // because we already modified things } } if (diveChanged) { if (d->maxdepth.mm == d->dc.maxdepth.mm && d->maxdepth.mm > 0 && same_string(d->dc.model, "manually added dive") && d->dc.samples == 0) { // so we have depth > 0, a manually added dive and no samples // let's create an actual profile so the desktop version can work it // first clear out the mean depth (or the fake_dc() function tries // to be too clever d->meandepth.mm = d->dc.meandepth.mm = 0; d->dc = *fake_dc(&d->dc, true); } DiveListModel::instance()->updateDive(oldModelIdx, d); } if (diveChanged || needResort) changesNeedSaving(); }
void PrettyItemDelegate::paintBody( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { painter->save(); painter->translate( option.rect.topLeft() ); QRectF line(0, 0, option.rect.width(), option.rect.height()); if (downloadInfo) line.setWidth(line.width() / 2); painter->setClipRect(line); const bool isActive = index.data( ActiveTrackRole ).toBool(); const bool isSelected = option.state & QStyle::State_Selected; // draw the "current track" highlight underneath the text if (isActive && !isSelected) { paintActiveOverlay(painter, line.x(), line.y(), line.width(), line.height()); } // get the video metadata const VideoPointer videoPointer = index.data( VideoRole ).value<VideoPointer>(); const Video *video = videoPointer.data(); // thumb if (!video->thumbnail().isNull()) { painter->drawImage(QRect(0, 0, THUMB_WIDTH, THUMB_HEIGHT), video->thumbnail()); // play icon overlayed on the thumb if (isActive) paintPlayIcon(painter); // time QString timeString; int duration = video->duration(); if ( duration > 3600 ) timeString = QTime().addSecs(duration).toString("h:mm:ss"); else timeString = QTime().addSecs(duration).toString("m:ss"); drawTime(painter, timeString, line); } if (isActive) painter->setFont(boldFont); // text color if (isSelected) painter->setPen(QPen(option.palette.brush(QPalette::HighlightedText), 0)); else painter->setPen(QPen(option.palette.brush(QPalette::Text), 0)); // title QString videoTitle = video->title(); QRectF textBox = line.adjusted(PADDING+THUMB_WIDTH, PADDING, -2 * PADDING, -PADDING); textBox = painter->boundingRect( textBox, Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, videoTitle); painter->drawText(textBox, Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, videoTitle); painter->setFont(smallerFont); // published date QString publishedString = video->published().date().toString(Qt::DefaultLocaleShortDate); QSizeF stringSize(QFontMetrics(painter->font()).size( Qt::TextSingleLine, publishedString ) ); QPointF textLoc(PADDING+THUMB_WIDTH, PADDING*2 + textBox.height()); QRectF publishedTextBox(textLoc , stringSize); painter->drawText(publishedTextBox, Qt::AlignLeft | Qt::AlignTop, publishedString); // author bool authorHovered = false; bool authorPressed = false; const bool isHovered = index.data(HoveredItemRole).toBool(); if (isHovered) { authorHovered = index.data(AuthorHoveredRole).toBool(); authorPressed = index.data(AuthorPressedRole).toBool(); } painter->save(); painter->setFont(smallerBoldFont); if (!isSelected) { if (authorHovered) painter->setPen(QPen(option.palette.brush(QPalette::Highlight), 0)); else painter->setPen(QPen(option.palette.brush(QPalette::Mid), 0)); } QString authorString = video->author(); textLoc.setX(textLoc.x() + stringSize.width() + PADDING); stringSize = QSizeF(QFontMetrics(painter->font()).size( Qt::TextSingleLine, authorString ) ); QRectF authorTextBox(textLoc , stringSize); authorRects.insert(index.row(), authorTextBox.toRect()); painter->drawText(authorTextBox, Qt::AlignLeft | Qt::AlignTop, authorString); painter->restore(); // view count if (video->viewCount() >= 0) { painter->save(); QLocale locale; QString viewCountString = tr("%1 views").arg(locale.toString(video->viewCount())); textLoc.setX(textLoc.x() + stringSize.width() + PADDING); stringSize = QSizeF(QFontMetrics(painter->font()).size( Qt::TextSingleLine, viewCountString ) ); QRectF viewCountTextBox(textLoc , stringSize); painter->drawText(viewCountTextBox, Qt::AlignLeft | Qt::AlignBottom, viewCountString); painter->restore(); } if (downloadInfo) { painter->save(); QString definitionString = VideoDefinition::getDefinitionName(video->getDefinitionCode()); textLoc.setX(textLoc.x() + stringSize.width() + PADDING); stringSize = QSizeF(QFontMetrics(painter->font()).size( Qt::TextSingleLine, definitionString ) ); QRectF viewCountTextBox(textLoc , stringSize); painter->drawText(viewCountTextBox, Qt::AlignLeft | Qt::AlignBottom, definitionString); painter->restore(); } /* QLinearGradient myGradient; QPen myPen; QFont myFont; QPointF baseline(authorTextBox.x(), authorTextBox.y() + authorTextBox.height()); QPainterPath myPath; myPath.addText(baseline, boldFont, authorString); painter->setBrush(palette.color(QPalette::WindowText)); painter->setPen(palette.color(QPalette::Dark)); painter->setRenderHints (QPainter::Antialiasing, true); painter->drawPath(myPath); */ // separator painter->setClipping(false); painter->setPen(option.palette.color(QPalette::Midlight)); painter->drawLine(THUMB_WIDTH, THUMB_HEIGHT, option.rect.width(), THUMB_HEIGHT); if (!video->thumbnail().isNull()) painter->setPen(Qt::black); painter->drawLine(0, THUMB_HEIGHT, THUMB_WIDTH-1, THUMB_HEIGHT); painter->restore(); if (downloadInfo) paintDownloadInfo(painter, option, index); }
void init_ui(int *argcp, char ***argvp) { QVariant v; application = new QApplication(*argcp, *argvp); // tell Qt to use system proxies // note: on Linux, "system" == "environment variables" QNetworkProxyFactory::setUseSystemConfiguration(true); #if QT_VERSION < 0x050000 // ask QString in Qt 4 to interpret all char* as UTF-8, // like Qt 5 does. // 106 is "UTF-8", this is faster than lookup by name // [http://www.iana.org/assignments/character-sets/character-sets.xml] QTextCodec::setCodecForCStrings(QTextCodec::codecForMib(106)); #endif QCoreApplication::setOrganizationName("Subsurface"); QCoreApplication::setOrganizationDomain("subsurface.hohndel.org"); QCoreApplication::setApplicationName("Subsurface"); // find plugins installed in the application directory (without this SVGs don't work on Windows) QCoreApplication::addLibraryPath(QCoreApplication::applicationDirPath()); xslt_path = strdup(getSubsurfaceDataPath("xslt").toAscii().data()); QLocale loc; QString uiLang = loc.uiLanguages().first(); // there's a stupid Qt bug on MacOS where uiLanguages doesn't give us the country info if (!uiLang.contains('-') && uiLang != loc.bcp47Name()) { QLocale loc2(loc.bcp47Name()); loc = loc2; uiLang = loc2.uiLanguages().first(); } // we don't have translations for English - if we don't check for this // Qt will proceed to load the second language in preference order - not what we want // on Linux this tends to be en-US, but on the Mac it's just en if (!uiLang.startsWith("en")) { qtTranslator = new QTranslator; if (qtTranslator->load(loc,"qt", "_", QLibraryInfo::location(QLibraryInfo::TranslationsPath))) { application->installTranslator(qtTranslator); } else { qDebug() << "can't find Qt localization for locale" << uiLang << "searching in" << QLibraryInfo::location(QLibraryInfo::TranslationsPath); } ssrfTranslator = new QTranslator; if (ssrfTranslator->load(loc,"subsurface", "_") || ssrfTranslator->load(loc,"subsurface", "_", getSubsurfaceDataPath("translations")) || ssrfTranslator->load(loc,"subsurface", "_", getSubsurfaceDataPath("../translations"))) { application->installTranslator(ssrfTranslator); } else { qDebug() << "can't find Subsurface localization for locale" << uiLang; } } QSettings s; s.beginGroup("DiveComputer"); default_dive_computer_vendor = getSetting(s, "dive_computer_vendor"); default_dive_computer_product = getSetting(s,"dive_computer_product"); default_dive_computer_device = getSetting(s, "dive_computer_device"); s.endGroup(); window = new MainWindow(); window->show(); if (existing_filename && existing_filename[0] != '\0') window->setTitle(MWTF_FILENAME); else window->setTitle(MWTF_DEFAULT); return; }
int main(int argc, char *argv[]) { // This should be run as root since libparted requires it. if (getuid()) { // trying to obtain root UID setuid(0); if (getuid()) { string args; for (int i=1; i<argc; ++i) { args += string(argv[i]) + " "; } // Check if we can run via sudo if (system("[ \"`sudo -l | grep " + string(argv[0]) + " | grep NOPASSWD`\" = \"\" ]")) return system("sudo " + string(argv[0]) + " " + args); else return system("xdg-su -c \"" + string(argv[0]) + " " + args + "\""); } } if (FileExists("/var/run/guisetup_exec.pid")) { string pid_locked = ReadFile("/var/run/guisetup_exec.pid").c_str(); if (isProcessRunning(pid_locked)) { fprintf(stderr, "Another setup process %s is alrealy running.\n", pid_locked.c_str()); return 1; } } pid_t pid = getpid(); if (FileExists("/var/run/guisetup.pid")) { string pid_locked = ReadFile("/var/run/guisetup.pid").c_str(); if (isProcessRunning(pid_locked)) { fprintf(stderr, "Another setup process %s is alrealy running.\n", pid_locked.c_str()); return 1; } } WriteFile("/var/run/guisetup.pid", IntToStr(pid)); setlocale(LC_ALL, ""); bindtextdomain( "mpkg", "/usr/share/locale"); textdomain("mpkg"); // For mpkg, note that we copy config to temp directory CONFIG_FILE="/tmp/mpkg.xml"; mConfig.configName=CONFIG_FILE; unlink("/tmp/packages.db"); unlink("/tmp/mpkg.xml"); if (!FileExists("/usr/share/setup/packages.db")) { mError("Oops, no database template in /usr/share/setup/packages.db!"); return 1; } if (!FileExists("/usr/share/setup/mpkg-setup.xml")) { mError("Oops, no config template in /usr/share/setup/mpkg-setup.xml!"); return 1; } system("cp /usr/share/setup/packages.db /tmp/packages.db"); system("cp /usr/share/setup/mpkg-setup.xml /tmp/mpkg.xml"); QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QApplication a(argc, argv); QLocale lc; QTranslator translator; translator.load("guisetup_" + lc.name(), "/usr/share/setup/l10n"); a.installTranslator(&translator); MainWindow w; w.show(); return a.exec(); }
int main(int argc, char *argv[]) { //See http://doc.qt.io/qt-5/qopenglwidget.html#opengl-function-calls-headers-and-qopenglfunctions /** Calling QSurfaceFormat::setDefaultFormat() before constructing the QApplication instance is mandatory on some platforms (for example, OS X) when an OpenGL core profile context is requested. This is to ensure that resource sharing between contexts stays functional as all internal contexts are created using the correct version and profile. **/ { QSurfaceFormat format = QSurfaceFormat::defaultFormat(); format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); format.setStencilBufferSize(0); #ifdef CC_GL_WINDOW_USE_QWINDOW format.setStereo(true); #endif #ifdef Q_OS_MAC format.setStereo(false); format.setVersion( 2, 1 ); format.setProfile( QSurfaceFormat::CoreProfile ); #endif #ifdef QT_DEBUG format.setOption(QSurfaceFormat::DebugContext); #endif QSurfaceFormat::setDefaultFormat(format); } ccApplication a(argc, argv); //Locale management { //Force 'english' locale so as to get a consistent behavior everywhere QLocale locale = QLocale(QLocale::English); locale.setNumberOptions(QLocale::c().numberOptions()); QLocale::setDefault(locale); #ifdef Q_OS_UNIX //We reset the numeric locale for POSIX functions //See http://qt-project.org/doc/qt-5/qcoreapplication.html#locale-settings setlocale(LC_NUMERIC, "C"); #endif } #ifdef USE_VLD VLDEnable(); #endif #ifdef Q_OS_MAC // This makes sure that our "working directory" is not within the application bundle QDir appDir = QCoreApplication::applicationDirPath(); if ( appDir.dirName() == "MacOS" ) { appDir.cdUp(); appDir.cdUp(); appDir.cdUp(); QDir::setCurrent( appDir.absolutePath() ); } #endif if (!QGLFormat::hasOpenGL()) { QMessageBox::critical(0, "Error", "This application needs OpenGL to run!"); return EXIT_FAILURE; } if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_1) == 0) { QMessageBox::critical(0, "Error", "This application needs OpenGL 2.1 at least to run!"); return EXIT_FAILURE; } //common data initialization ccTimer::Init(); FileIOFilter::InitInternalFilters(); //load all known I/O filters (plugins will come later!) ccNormalVectors::GetUniqueInstance(); //force pre-computed normals array initialization ccColorScalesManager::GetUniqueInstance(); //force pre-computed color tables initialization ccViewer w/*(0,Qt::Window|Qt::CustomizeWindowHint)*/; #ifdef Q_OS_MAC a.setViewer( &w ); #endif //register minimal logger to display errors ccViewerLog logger(&w); ccLog::RegisterInstance(&logger); w.show(); //files to open are passed as argument if (argc > 1) { //parse arguments QStringList filenames; int i = 1; while ( i < argc) { QString argument = QString(argv[i++]).toUpper(); //Argument '-WIN X Y W H' (to set window size and position) if (argument.toUpper() == "-WIN") { bool ok = true; if (i+3 < argc) { bool converionOk; int x = QString(argv[i ]).toInt(&converionOk); ok &= converionOk; int y = QString(argv[i+1]).toInt(&converionOk); ok &= converionOk; int width = QString(argv[i+2]).toInt(&converionOk); ok &= converionOk; int height = QString(argv[i+3]).toInt(&converionOk); ok &= converionOk; i += 4; if (ok) { //change window position and size w.move(x,y); w.resize(width,height); } } if (!ok) { ccLog::Warning("Invalid arguments! 4 integer values are expected after '-win' (X Y W H)"); break; } } else if (argument == "-TOP") { w.setWindowFlags(w.windowFlags() | Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint); w.show(); } else //any other argument is assumed to be a filename (that will we try to load) { filenames << argument; } } if (!filenames.empty()) w.addToDB(filenames); } #ifdef Q_OS_MAC // process events to load any files on the command line QCoreApplication::processEvents(); #endif w.checkForLoadedEntities(); int result = a.exec(); //release global structures FileIOFilter::UnregisterAll(); return result; }
void tst_QLocale::toUpper_QLocale_2() { QString s = data(); QLocale l; QBENCHMARK { LOOP(l.toUpper(s)) } }
QString QtPropertyBrowserUtils::timeFormat() { QLocale loc; // ShortFormat is missing seconds on UNIX. return loc.timeFormat(QLocale::LongFormat); }
void FFT::fftCurve() { int n2 = d_n/2; double *amp = (double *)malloc(d_n*sizeof(double)); double *result = (double *)malloc(2*d_n*sizeof(double)); if(!amp || !result){ memoryErrorMessage(); return; } double df = 1.0/(double)(d_n*d_sampling);//frequency sampling double aMax = 0.0;//max amplitude if(!d_inverse){ gsl_fft_real_workspace *work = gsl_fft_real_workspace_alloc(d_n); gsl_fft_real_wavetable *real = gsl_fft_real_wavetable_alloc(d_n); if(!work || !real){ memoryErrorMessage(); return; } gsl_fft_real_transform(d_y, 1, d_n, real, work); gsl_fft_halfcomplex_unpack (d_y, result, 1, d_n); gsl_fft_real_wavetable_free(real); gsl_fft_real_workspace_free(work); } else { gsl_fft_real_unpack (d_y, result, 1, d_n); gsl_fft_complex_wavetable *wavetable = gsl_fft_complex_wavetable_alloc (d_n); gsl_fft_complex_workspace *workspace = gsl_fft_complex_workspace_alloc (d_n); if(!workspace || !wavetable){ memoryErrorMessage(); return; } gsl_fft_complex_inverse (result, 1, d_n, wavetable, workspace); gsl_fft_complex_wavetable_free (wavetable); gsl_fft_complex_workspace_free (workspace); } if (d_shift_order){ for(int i = 0; i < d_n; i++){ d_x[i] = (i - n2)*df; int j = i + d_n; double aux = result[i]; result[i] = result[j]; result[j] = aux; } } else { for(int i = 0; i < d_n; i++) d_x[i] = i*df; } for(int i = 0; i < d_n; i++) { int i2 = 2*i; double real_part = result[i2]; double im_part = result[i2+1]; double a = sqrt(real_part*real_part + im_part*im_part); amp[i]= a; if (a > aMax) aMax = a; } ApplicationWindow *app = (ApplicationWindow *)parent(); QLocale locale = app->locale(); int prec = app->d_decimal_digits; for (int i = 0; i < d_n; i++){ int i2 = 2*i; d_result_table->setText(i, 0, locale.toString(d_x[i], 'g', prec)); d_result_table->setText(i, 1, locale.toString(result[i2], 'g', prec)); d_result_table->setText(i, 2, locale.toString(result[i2 + 1], 'g', prec)); if (d_normalize) d_result_table->setText(i, 3, locale.toString(amp[i]/aMax, 'g', prec)); else d_result_table->setText(i, 3, locale.toString(amp[i], 'g', prec)); d_result_table->setText(i, 4, locale.toString(atan(result[i2 + 1]/result[i2]), 'g', prec)); } free(amp); free(result); }
QString QtPropertyBrowserUtils::dateFormat() { QLocale loc; return loc.dateFormat(QLocale::ShortFormat); }
bool Utils::isChinese() { QLocale locale; return locale.language() == QLocale::Chinese; }
QString DateTimeDelegate::displayText(const QVariant &value, const QLocale &locale) const { if (m_IsDateOnly) return locale.toString(value.toDate(), tkTr(Trans::Constants::DATEFORMAT_FOR_EDITOR)); return locale.toString(value.toDateTime(), tkTr(Trans::Constants::DATETIMEFORMAT_FOR_EDITOR)); }
int main(int argc, char **argv) { //See http://doc.qt.io/qt-5/qopenglwidget.html#opengl-function-calls-headers-and-qopenglfunctions /** Calling QSurfaceFormat::setDefaultFormat() before constructing the QApplication instance is mandatory on some platforms (for example, OS X) when an OpenGL core profile context is requested. This is to ensure that resource sharing between contexts stays functional as all internal contexts are created using the correct version and profile. **/ { QSurfaceFormat format = QSurfaceFormat::defaultFormat(); format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); format.setStencilBufferSize(0); #ifdef CC_GL_WINDOW_USE_QWINDOW format.setStereo(true); #endif #ifdef Q_OS_MAC format.setStereo(false); format.setVersion( 2, 1 ); format.setProfile( QSurfaceFormat::CoreProfile ); #endif #ifdef QT_DEBUG format.setOption(QSurfaceFormat::DebugContext, true); #endif QSurfaceFormat::setDefaultFormat(format); } //The 'AA_ShareOpenGLContexts' attribute must be defined BEFORE the creation of the Q(Gui)Application //DGM: this is mandatory to enable exclusive full screen for ccGLWidget (at least on Windows) QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts); //QT initialiation qccApplication app(argc, argv); //Locale management { //Force 'english' locale so as to get a consistent behavior everywhere QLocale locale = QLocale(QLocale::English); locale.setNumberOptions(QLocale::c().numberOptions()); QLocale::setDefault(locale); #ifdef Q_OS_UNIX //We reset the numeric locale for POSIX functions //See http://qt-project.org/doc/qt-5/qcoreapplication.html#locale-settings setlocale(LC_NUMERIC, "C"); #endif } #ifdef USE_VLD VLDEnable(); #endif QDir workingDir = QCoreApplication::applicationDirPath(); #ifdef Q_OS_MAC // This makes sure that our "working directory" is not within the application bundle if ( workingDir.dirName() == "MacOS" ) { workingDir.cdUp(); workingDir.cdUp(); workingDir.cdUp(); } #endif //store the log message until a valid logging instance is registered ccLog::EnableMessageBackup(true); //restore some global parameters { QSettings settings; settings.beginGroup(ccPS::GlobalShift()); double maxAbsCoord = settings.value(ccPS::MaxAbsCoord(), ccGlobalShiftManager::MaxCoordinateAbsValue()).toDouble(); double maxAbsDiag = settings.value(ccPS::MaxAbsDiag(), ccGlobalShiftManager::MaxBoundgBoxDiagonal()).toDouble(); settings.endGroup(); ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2").arg(maxAbsCoord, 0, 'e', 0).arg(maxAbsDiag, 0, 'e', 0)); ccGlobalShiftManager::SetMaxCoordinateAbsValue(maxAbsCoord); ccGlobalShiftManager::SetMaxBoundgBoxDiagonal(maxAbsDiag); } //Command line mode? bool commandLine = (argc > 1 && argv[1][0] == '-'); //specific commands int lastArgumentIndex = 1; QTranslator translator; if (commandLine) { //translation file selection if (QString(argv[lastArgumentIndex]).toUpper() == "-LANG") { QString langFilename = QString(argv[2]); //Load translation file if (translator.load(langFilename, QCoreApplication::applicationDirPath())) { qApp->installTranslator(&translator); } else { QMessageBox::warning(0, QObject::tr("Translation"), QObject::tr("Failed to load language file '%1'").arg(langFilename)); } commandLine = false; lastArgumentIndex += 2; } } //splash screen QScopedPointer<QSplashScreen> splash(0); QTimer splashTimer; //standard mode if (!commandLine) { if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_1) == 0) { QMessageBox::critical(0, "Error", "This application needs OpenGL 2.1 at least to run!"); return EXIT_FAILURE; } //splash screen QPixmap pixmap(QString::fromUtf8(":/CC/images/imLogoV2Qt.png")); splash.reset(new QSplashScreen(pixmap, Qt::WindowStaysOnTopHint)); splash->show(); QApplication::processEvents(); } //global structures initialization FileIOFilter::InitInternalFilters(); //load all known I/O filters (plugins will come later!) ccNormalVectors::GetUniqueInstance(); //force pre-computed normals array initialization ccColorScalesManager::GetUniqueInstance(); //force pre-computed color tables initialization //load the plugins tPluginInfoList plugins; QStringList dirFilters; QStringList pluginPaths; { QString appPath = QCoreApplication::applicationDirPath(); #if defined(Q_OS_MAC) dirFilters << "*.dylib"; // plugins are in the bundle appPath.remove("MacOS"); pluginPaths += (appPath + "PlugIns/ccPlugins"); #if defined(CC_MAC_DEV_PATHS) // used for development only - this is the path where the plugins are built // this avoids having to install into the application bundle when developing pluginPaths += (appPath + "../../../ccPlugins"); #endif #elif defined(Q_OS_WIN) dirFilters << "*.dll"; //plugins are in bin/plugins pluginPaths << (appPath + "/plugins"); #elif defined(Q_OS_LINUX) dirFilters << "*.so"; // Plugins are relative to the bin directory where the executable is found QDir binDir(appPath); if (binDir.dirName() == "bin") { binDir.cdUp(); pluginPaths << (binDir.absolutePath() + "/lib/cloudcompare/plugins"); } else { // Choose a reasonable default to look in pluginPaths << "/usr/lib/cloudcompare/plugins"; } #else #warning Need to specify the plugin path for this OS. #endif #ifdef Q_OS_MAC // Add any app data paths // Plugins in these directories take precendence over the included ones QStringList appDataPaths = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation); for (const QString &appDataPath : appDataPaths) { pluginPaths << (appDataPath + "/plugins"); } #endif } ccPlugins::LoadPlugins(plugins, pluginPaths, dirFilters); int result = 0; //command line mode if (commandLine) { //command line processing (no GUI) result = ccCommandLineParser::Parse(argc, argv, &plugins); } else { //main window init. MainWindow* mainWindow = MainWindow::TheInstance(); if (!mainWindow) { QMessageBox::critical(0, "Error", "Failed to initialize the main application window?!"); return EXIT_FAILURE; } mainWindow->dispatchPlugins(plugins, pluginPaths); mainWindow->show(); QApplication::processEvents(); //show current Global Shift parameters in Console { ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2") .arg(ccGlobalShiftManager::MaxCoordinateAbsValue(), 0, 'e', 0) .arg(ccGlobalShiftManager::MaxBoundgBoxDiagonal(), 0, 'e', 0)); } if (argc > lastArgumentIndex) { if (splash) { splash->close(); } //any additional argument is assumed to be a filename --> we try to load it/them QStringList filenames; for (int i = lastArgumentIndex; i < argc; ++i) { QString arg(argv[i]); //special command: auto start a plugin if (arg.startsWith(":start-plugin:")) { QString pluginName = arg.mid(14); QString pluginNameUpper = pluginName.toUpper(); //look for this plugin bool found = false; for (const tPluginInfo &plugin : plugins) { if (plugin.object->getName().replace(' ', '_').toUpper() == pluginNameUpper) { found = true; bool success = plugin.object->start(); if (!success) { ccLog::Error(QString("Failed to start the plugin '%1'").arg(plugin.object->getName())); } break; } } if (!found) { ccLog::Error(QString("Couldn't find the plugin '%1'").arg(pluginName.replace('_', ' '))); } } else { filenames << arg; } } mainWindow->addToDB(filenames); } else if (splash) { //count-down to hide the timer (only effective once the application will have actually started!) QObject::connect(&splashTimer, &QTimer::timeout, [&]() { if (splash) splash->close(); QCoreApplication::processEvents(); splash.reset(); }); splashTimer.setInterval(1000); splashTimer.start(); } //change the default path to the application one (do this AFTER processing the command line) QDir::setCurrent(workingDir.absolutePath()); //let's rock! try { result = app.exec(); } catch (...) { QMessageBox::warning(0, "CC crashed!", "Hum, it seems that CC has crashed... Sorry about that :)"); } //release the plugins for (tPluginInfo &plugin : plugins) { plugin.object->stop(); //just in case if (!plugin.qObject->parent()) { delete plugin.object; plugin.object = 0; plugin.qObject = 0; } } } //release global structures MainWindow::DestroyInstance(); FileIOFilter::UnregisterAll(); #ifdef CC_TRACK_ALIVE_SHARED_OBJECTS //for debug purposes unsigned alive = CCShareable::GetAliveCount(); if (alive > 1) { printf("Error: some shared objects (%u) have not been released on program end!",alive); system("PAUSE"); } #endif return result; }
QString DateRenderer::localeFormat() { QLocale locale; return locale.dateFormat(QLocale::ShortFormat); }
GeneralForm::GeneralForm(SettingsWidget *myParent) : GenericForm(QPixmap(":/img/settings/general.png")) { parent = myParent; bodyUI = new Ui::GeneralSettings; bodyUI->setupUi(this); bodyUI->checkUpdates->setVisible(AUTOUPDATE_ENABLED); bodyUI->checkUpdates->setChecked(Settings::getInstance().getCheckUpdates()); bodyUI->cbEnableIPv6->setChecked(Settings::getInstance().getEnableIPv6()); for (int i = 0; i < langs.size(); i++) bodyUI->transComboBox->insertItem(i, langs[i]); bodyUI->transComboBox->setCurrentIndex(locales.indexOf(Settings::getInstance().getTranslation())); bodyUI->cbAutorun->setChecked(Settings::getInstance().getAutorun()); #if defined(__APPLE__) && defined(__MACH__) bodyUI->cbAutorun->setEnabled(false); #endif bool showSystemTray = Settings::getInstance().getShowSystemTray(); bodyUI->showSystemTray->setChecked(showSystemTray); bodyUI->startInTray->setChecked(Settings::getInstance().getAutostartInTray()); bodyUI->startInTray->setEnabled(showSystemTray); bodyUI->closeToTray->setChecked(Settings::getInstance().getCloseToTray()); bodyUI->closeToTray->setEnabled(showSystemTray); bodyUI->minimizeToTray->setChecked(Settings::getInstance().getMinimizeToTray()); bodyUI->minimizeToTray->setEnabled(showSystemTray); bodyUI->lightTrayIcon->setChecked(Settings::getInstance().getLightTrayIcon()); bodyUI->lightTrayIcon->setEnabled(showSystemTray); bodyUI->statusChanges->setChecked(Settings::getInstance().getStatusChangeNotificationEnabled()); bodyUI->useEmoticons->setChecked(Settings::getInstance().getUseEmoticons()); bodyUI->autoacceptFiles->setChecked(Settings::getInstance().getAutoSaveEnabled()); bodyUI->autoSaveFilesDir->setText(Settings::getInstance().getGlobalAutoAcceptDir()); bodyUI->showWindow->setChecked(Settings::getInstance().getShowWindow()); bodyUI->showInFront->setChecked(Settings::getInstance().getShowInFront()); bodyUI->notifySound->setChecked(Settings::getInstance().getNotifySound()); bodyUI->groupAlwaysNotify->setChecked(Settings::getInstance().getGroupAlwaysNotify()); bodyUI->cbFauxOfflineMessaging->setChecked(Settings::getInstance().getFauxOfflineMessaging()); bodyUI->cbCompactLayout->setChecked(Settings::getInstance().getCompactLayout()); bodyUI->cbGroupchatPosition->setChecked(Settings::getInstance().getGroupchatPosition()); for (auto entry : SmileyPack::listSmileyPacks()) bodyUI->smileyPackBrowser->addItem(entry.first, entry.second); bodyUI->smileyPackBrowser->setCurrentIndex(bodyUI->smileyPackBrowser->findData(Settings::getInstance().getSmileyPack())); reloadSmiles(); bodyUI->smileyPackBrowser->setEnabled(bodyUI->useEmoticons->isChecked()); bodyUI->styleBrowser->addItem(tr("None")); bodyUI->styleBrowser->addItems(QStyleFactory::keys()); if (QStyleFactory::keys().contains(Settings::getInstance().getStyle())) bodyUI->styleBrowser->setCurrentText(Settings::getInstance().getStyle()); else bodyUI->styleBrowser->setCurrentText(tr("None")); for (QString color : Style::themeColorNames) bodyUI->themeColorCBox->addItem(color); bodyUI->themeColorCBox->setCurrentIndex(Settings::getInstance().getThemeColor()); bodyUI->emoticonSize->setValue(Settings::getInstance().getEmojiFontPointSize()); QStringList timestamps; for (QString timestamp : timeFormats) timestamps << QString("%1 - %2").arg(timestamp, QTime::currentTime().toString(timestamp)); bodyUI->timestamp->addItems(timestamps); QLocale ql; QStringList datestamps; dateFormats.append(ql.dateFormat()); dateFormats.append(ql.dateFormat(QLocale::LongFormat)); dateFormats.removeDuplicates(); timeFormats.append(ql.timeFormat()); timeFormats.append(ql.timeFormat(QLocale::LongFormat)); timeFormats.removeDuplicates(); for (QString datestamp : dateFormats) datestamps << QString("%1 - %2").arg(datestamp, QDate::currentDate().toString(datestamp)); bodyUI->dateFormats->addItems(datestamps); bodyUI->timestamp->setCurrentText(QString("%1 - %2").arg(Settings::getInstance().getTimestampFormat(), QTime::currentTime().toString(Settings::getInstance().getTimestampFormat()))); bodyUI->dateFormats->setCurrentText(QString("%1 - %2").arg(Settings::getInstance().getDateFormat(), QDate::currentDate().toString(Settings::getInstance().getDateFormat()))); bodyUI->autoAwaySpinBox->setValue(Settings::getInstance().getAutoAwayTime()); bodyUI->cbEnableUDP->setChecked(!Settings::getInstance().getForceTCP()); bodyUI->proxyAddr->setText(Settings::getInstance().getProxyAddr()); int port = Settings::getInstance().getProxyPort(); if (port != -1) bodyUI->proxyPort->setValue(port); bodyUI->proxyType->setCurrentIndex(static_cast<int>(Settings::getInstance().getProxyType())); onUseProxyUpdated(); //general connect(bodyUI->checkUpdates, &QCheckBox::stateChanged, this, &GeneralForm::onCheckUpdateChanged); connect(bodyUI->transComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onTranslationUpdated())); connect(bodyUI->cbAutorun, &QCheckBox::stateChanged, this, &GeneralForm::onAutorunUpdated); connect(bodyUI->showSystemTray, &QCheckBox::stateChanged, this, &GeneralForm::onSetShowSystemTray); connect(bodyUI->startInTray, &QCheckBox::stateChanged, this, &GeneralForm::onSetAutostartInTray); connect(bodyUI->closeToTray, &QCheckBox::stateChanged, this, &GeneralForm::onSetCloseToTray); connect(bodyUI->minimizeToTray, &QCheckBox::stateChanged, this, &GeneralForm::onSetMinimizeToTray); connect(bodyUI->lightTrayIcon, &QCheckBox::stateChanged, this, &GeneralForm::onSetLightTrayIcon); connect(bodyUI->statusChanges, &QCheckBox::stateChanged, this, &GeneralForm::onSetStatusChange); connect(bodyUI->autoAwaySpinBox, SIGNAL(editingFinished()), this, SLOT(onAutoAwayChanged())); connect(bodyUI->showWindow, &QCheckBox::stateChanged, this, &GeneralForm::onShowWindowChanged); connect(bodyUI->showInFront, &QCheckBox::stateChanged, this, &GeneralForm::onSetShowInFront); connect(bodyUI->notifySound, &QCheckBox::stateChanged, this, &GeneralForm::onSetNotifySound); connect(bodyUI->groupAlwaysNotify, &QCheckBox::stateChanged, this, &GeneralForm::onSetGroupAlwaysNotify); connect(bodyUI->autoacceptFiles, &QCheckBox::stateChanged, this, &GeneralForm::onAutoAcceptFileChange); if (bodyUI->autoacceptFiles->isChecked()) connect(bodyUI->autoSaveFilesDir, SIGNAL(clicked()), this, SLOT(onAutoSaveDirChange())); //theme connect(bodyUI->useEmoticons, &QCheckBox::stateChanged, this, &GeneralForm::onUseEmoticonsChange); connect(bodyUI->smileyPackBrowser, SIGNAL(currentIndexChanged(int)), this, SLOT(onSmileyBrowserIndexChanged(int))); connect(bodyUI->styleBrowser, SIGNAL(currentTextChanged(QString)), this, SLOT(onStyleSelected(QString))); connect(bodyUI->themeColorCBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onThemeColorChanged(int))); connect(bodyUI->emoticonSize, SIGNAL(editingFinished()), this, SLOT(onEmoticonSizeChanged())); connect(bodyUI->timestamp, SIGNAL(currentIndexChanged(int)), this, SLOT(onTimestampSelected(int))); connect(bodyUI->dateFormats, SIGNAL(currentIndexChanged(int)), this, SLOT(onDateFormatSelected(int))); //connection connect(bodyUI->cbEnableIPv6, &QCheckBox::stateChanged, this, &GeneralForm::onEnableIPv6Updated); connect(bodyUI->cbEnableUDP, &QCheckBox::stateChanged, this, &GeneralForm::onUDPUpdated); connect(bodyUI->proxyType, SIGNAL(currentIndexChanged(int)), this, SLOT(onUseProxyUpdated())); connect(bodyUI->proxyAddr, &QLineEdit::editingFinished, this, &GeneralForm::onProxyAddrEdited); connect(bodyUI->proxyPort, SIGNAL(valueChanged(int)), this, SLOT(onProxyPortEdited(int))); connect(bodyUI->reconnectButton, &QPushButton::clicked, this, &GeneralForm::onReconnectClicked); connect(bodyUI->cbFauxOfflineMessaging, &QCheckBox::stateChanged, this, &GeneralForm::onFauxOfflineMessaging); connect(bodyUI->cbCompactLayout, &QCheckBox::stateChanged, this, &GeneralForm::onCompactLayout); connect(bodyUI->cbGroupchatPosition, &QCheckBox::stateChanged, this, &GeneralForm::onGroupchatPositionChanged); // prevent stealing mouse whell scroll // scrolling event won't be transmitted to comboboxes or qspinboxes when scrolling // you can scroll through general settings without accidentially chaning theme/skin/icons etc. // @see GeneralForm::eventFilter(QObject *o, QEvent *e) at the bottom of this file for more for (QComboBox* cb : findChildren<QComboBox*>()) { cb->installEventFilter(this); cb->setFocusPolicy(Qt::StrongFocus); } for (QSpinBox* sp : findChildren<QSpinBox*>()) { sp->installEventFilter(this); sp->setFocusPolicy(Qt::WheelFocus); } #ifndef QTOX_PLATFORM_EXT bodyUI->autoAwayLabel->setEnabled(false); // these don't seem to change the appearance of the widgets, bodyUI->autoAwaySpinBox->setEnabled(false); // though they are unusable #endif Translator::registerHandler(std::bind(&GeneralForm::retranslateUi, this), this); }
bool InitSystem(void) { setlocale(LC_ALL, ""); systemData.locale = QLocale::system(); systemData.locale.setNumberOptions(QLocale::OmitGroupSeparator); QLocale::setDefault(systemData.locale); QTextStream out(stdout); systemData.homedir = QDir::toNativeSeparators(QDir::homePath() + QDir::separator()); #ifdef WIN32 /* WINDOWS */ systemData.sharedDir = QDir::toNativeSeparators((QDir::currentPath() + QDir::separator())); #else systemData.sharedDir = QDir::toNativeSeparators(QString(SHARED_DIR) + QDir::separator()); #endif /* WINDOWS */ //logfile #ifdef WIN32 /* WINDOWS */ systemData.logfileName = systemData.homedir + "mandelbulber_log.txt"; #else systemData.logfileName = systemData.homedir + ".mandelbulber_log.txt"; #endif FILE *logfile = fopen(systemData.logfileName.toLocal8Bit().constData(), "w"); fclose(logfile); out << "Mandelbulber " << MANDELBULBER_VERSION_STRING << ", build date: " << QString(__DATE__) << "\n"; out << "Log file name: " << systemData.logfileName << endl; WriteLogString("Mandelbulber version", QString(MANDELBULBER_VERSION_STRING)); WriteLogString("Mandelbulber compilation date", QString(__DATE__) + " " + QString(__TIME__)); //detecting number of CPU cores systemData.numberOfThreads = get_cpu_count(); printf("Detected %d CPUs\n", systemData.numberOfThreads); WriteLogDouble("CPUs detected", systemData.numberOfThreads); #ifdef ONETHREAD //for debugging NR_THREADS = 1; #endif //data directory location #ifdef WIN32 /* WINDOWS */ systemData.dataDirectory = systemData.homedir + "mandelbulber" + QDir::separator(); #else systemData.dataDirectory = QDir::toNativeSeparators(systemData.homedir + ".mandelbulber" + QDir::separator()); #endif out << "Default data directory: " << systemData.dataDirectory << endl; WriteLogString("Default data directory", systemData.dataDirectory); systemData.thumbnailDir = QDir::toNativeSeparators(systemData.dataDirectory + "thumbnails" + QDir::separator()); systemData.autosaveFile = QDir::toNativeSeparators(systemData.dataDirectory + ".autosave.fract"); //*********** temporary set to false ************ systemData.noGui = false; systemData.lastSettingsFile = QDir::toNativeSeparators(systemData.dataDirectory + "settings" + QDir::separator() + QString("settings.fract")); systemData.lastImageFile = QDir::toNativeSeparators(systemData.dataDirectory + "images" + QDir::separator() + QString("image.jpg")); systemData.lastImagePaletteFile = QDir::toNativeSeparators(systemData.sharedDir + "textures" + QDir::separator() + QString("colour palette.jpg")); QLocale systemLocale = QLocale::system(); systemData.decimalPoint = systemLocale.decimalPoint(); WriteLogString("Decimal point", QString(systemData.decimalPoint)); systemData.supportedLanguages.insert("en_EN", "English"); systemData.supportedLanguages.insert("pl_PL", "Polski"); systemData.supportedLanguages.insert("de_DE", "Deutsch"); systemData.supportedLanguages.insert("it_IT", "Italiano"); //get number of columns of console #ifdef WIN32 systemData.terminalWidth = 80; #else handle_winch(-1); #endif return true; }
int main(int argc, char **argv) { manitou_application app(argc,argv); gl_pApplication=&app; #ifndef Q_OS_WIN // The location of the data files depends on the prefix choosen at configure // time except under windows. QString s = QString(MANITOU_DATADIR); #else // under windows, the data directories are expected to be at the same level // than the executable file QString s = QApplication::applicationDirPath(); #endif gl_xpm_path = s + "/xpm"; gl_tr_path = s + "/translations"; gl_help_path = s + "/help"; QTranslator translator(0); QLocale locale = QLocale::system(); // search for a translation file, except for the C locale if (locale.name() != QLocale::c().name()) { if (translator.load(QString("manitou_")+locale.name(), gl_tr_path)) { app.installTranslator(&translator); } } global_debug_level = 5; const char* cnx_string=NULL; QString conf_name; bool explicit_config=false; while(1) { int option_index = 0; static optstruct long_options[] = { {"debug-output", 1, 0, 'l'}, {"config", 1, 0, 'c'}, {"dbcnx", 1, 0, 'd'}, {"help", 1, 0, 'h'}, {0, 0, 0, 0} }; int c = GETOPT_LONG(argc, argv, "d:c:h:", long_options, &option_index); if (c == -1) break; switch (c) { case 0: printf ("option %s", long_options[option_index].name); if (OPTARG) printf (" with arg %s", OPTARG); printf ("\n"); break; case '?': usage(argv[0]); break; case 'h': usage(argv[0]); break; case 'c': conf_name = OPTARG; explicit_config=true; break; case 'l': global_debug_level = OPTARG?atoi(OPTARG):10; break; case 'd': cnx_string = OPTARG; break; } } if (OPTIND < argc && !cnx_string) { /* compatibility with earlier versions: if there are non-named arguments on the command line, they will be interpreted as a connection string */ cnx_string = argv[OPTIND]; } if (conf_name.isEmpty()) { // then configuration is hostname-OSname QString hostname=QHostInfo::localHostName().toLower(); if (hostname.isEmpty()) hostname="unknown"; QString uname; #ifndef Q_OS_WIN struct utsname u; if (::uname(&u)==0 && u.sysname[0]) { uname = QString(u.sysname).toLower(); } #else uname="windows"; #endif conf_name = hostname + "-" + uname; } int connected=0; if (cnx_string==NULL) { // get the connection parameters from a dialog box QString qcs; login_dialog dlg; QSettings settings("Manitou-Mail", "manitou-ui"); dlg.set_login(settings.value("login").toString()); dlg.set_dbname(settings.value("dbname").toString()); dlg.set_host(settings.value("host").toString()); dlg.set_params(settings.value("params").toString()); dlg.set_focus(); do { if (dlg.exec()==1) { qcs = dlg.connect_string(); } else { helper::close(); exit(0); // exit if connection dialog closed with 'Cancel' } QString errstr; if (!(connected=ConnectDb(qcs.toLocal8Bit(), &errstr))) { QMessageBox::critical(NULL, QObject::tr("Fatal database error"), QObject::tr("Error while connecting to the database:\n")+errstr); } else { settings.setValue("login", dlg.login()); settings.setValue("dbname", dlg.dbnames()); // stringlist settings.setValue("host", dlg.host()); settings.setValue("params", dlg.params()); } } while (!connected); } else { QString errstr; if (!ConnectDb(cnx_string, &errstr)) { QMessageBox::critical(NULL, QObject::tr("Fatal database error"), QObject::tr("Error while connecting to the database:\n")+errstr); exit(1); } } if (!explicit_config) { QByteArray qb = conf_name.toLatin1(); printf("Configuration used: %s\n", qb.constData()); fflush(stdout); } global_conf.set_name(conf_name); global_conf.init(); global_conf.apply(); msgs_filter filter; #ifdef WITH_PGSQL filter.m_sql_stmt="0"; #endif /* Instantiate the user in the database if necessary. Ideally we should ask for a fullname if not already known, but there's no GUI support for that yet */ user::create_if_missing(QString::null); users_repository::fetch(); message_port::init(); msg_status_cache::init_db(); msg_list_window* w = new msg_list_window(&filter,0); w->show(); app.connect(&app, SIGNAL(lastWindowClosed()), SLOT(quit())); app.exec(); helper::close(); DisconnectDb(); return 0; }
QwtText ScaleDraw::label(double value) const { switch (d_type) { case Numeric: { QLocale locale = (static_cast<Graph *>(d_plot->parent()))->multiLayer()->locale(); if (d_numeric_format == Superscripts) { QString txt = locale.toString(transformValue(value), 'e', d_prec); QStringList list = txt.split("e", QString::SkipEmptyParts); if (list[0].toDouble() == 0.0) return QString("0"); QString s = list[1]; int l = s.length(); QChar sign = s[0]; s.remove (sign); while (l>1 && s.startsWith ("0", false)) { s.remove ( 0, 1 ); l = s.length(); } if (sign == '-') s.prepend(sign); if (list[0] == "1") return QwtText("10<sup>" + s + "</sup>"); else return QwtText(list[0] + "x10<sup>" + s + "</sup>"); } else return QwtText(locale.toString(transformValue(value), d_fmt, d_prec)); break; } case Day: { int val = static_cast<int>(transformValue(value))%7; if (val < 0) val = 7 - abs(val); else if (val == 0) val = 7; QString day; switch(d_name_format) { case ShortName: day = QDate::shortDayName (val); break; case LongName: day = QDate::longDayName (val); break; case Initial: day = (QDate::shortDayName (val)).left(1); break; } return QwtText(day); break; } case Month: { int val = static_cast<int>(transformValue(value))%12; if (val < 0) val = 12 - abs(val); else if (val == 0) val = 12; QString day; switch(d_name_format) { case ShortName: day = QDate::shortMonthName (val); break; case LongName: day = QDate::longMonthName (val); break; case Initial: day = (QDate::shortMonthName (val)).left(1); break; } return QwtText(day); break; } case Time: return QwtText(d_date_time_origin.time().addMSecs((int)value).toString(d_format_info)); break; case Date: return QwtText(d_date_time_origin.addSecs((int)value).toString(d_format_info)); break; case ColHeader: case Text: { const QwtScaleDiv scDiv = scaleDiv(); if (!scDiv.contains (value)) return QwtText(); QwtValueList ticks = scDiv.ticks (QwtScaleDiv::MajorTick); double break_offset = 0; ScaleEngine *se = static_cast<ScaleEngine *>(d_plot->axisScaleEngine(axis())); /*QwtScaleEngine *qwtsc_engine=d_plot->axisScaleEngine(axis()); ScaleEngine *se =dynamic_cast<ScaleEngine*>(qwtsc_engine); if(se!=NULL) {*/ bool inverted = se->testAttribute(QwtScaleEngine::Inverted); if(se->hasBreak()) { double lb = se->axisBreakLeft(); double rb = se->axisBreakRight(); if(inverted) { if (value <= lb) { int n_ticks = (int)ticks.count() - 1; double val0 = ticks[0]; double val1 = ticks[n_ticks]; for (int i = 1; i < n_ticks; i++) { double aux = ticks[i]; if(aux >= rb && val0 > aux) { val0 = aux; continue; } if(aux <= lb && val1 < aux) val1 = aux; } break_offset = fabs(val1 - val0); } } else { if (value >= rb) { double val0 = ticks[0]; for (int i = 1; i < (int)ticks.count(); i++) { double val = ticks[i]; if(val0 <= lb && val >= rb) { break_offset = fabs(val - val0); break; } val0 = val; } } } } double step = ticks[1] - ticks[0]; int index = static_cast<int>(ticks[0] + step*ticks.indexOf(value) - 1); int offset = abs((int)floor(break_offset/step)); if (offset) offset--; if (step > 0) index += offset; else index -= offset; if (index >= 0 && index < (int)d_text_labels.count()) return QwtText(d_text_labels[index]); else return QwtText(); //} break; } } return QwtText(); }
void WPUtils::replyFinished(QNetworkReply *rep) { QVariantMap _res_bck; model = new GroupDataModel(QStringList() << "sortDate" ); //"date" << "date_created_gmt" << "post_date"); model->setSortedAscending(false); model->setGrouping(ItemGrouping::None); if ( model && !model->isEmpty() ) model->clear(); if ( !res.isEmpty() ) res.clear(); if (!_res_bck.isEmpty() ) _res_bck.clear(); QByteArray ret = rep->readAll(); if ( !ret.isEmpty() ) qDebug() << "reading " << ret; //rep->readAll(); else qDebug() << "ret empty -> error handling /*TODO*/"; QString _current_name = ""; QXmlStreamReader xml(ret); QList<QVariantMap> Entries; int _struct_counter = 0; while(!xml.atEnd() && !xml.hasError()) { QXmlStreamReader::TokenType token = xml.readNext(); if ( token == QXmlStreamReader::StartElement ) { if ( xml.name().toString() == "fault") { res["ERROR"] = "fault"; } else if ( xml.name().toString() == "struct" ) { _struct_counter++; } else if ( xml.name().toString() == "name" ) { token = xml.readNext(); _current_name = xml.text().toString(); } else if ( xml.name().toString() == "value" && !_current_name.isEmpty() ) { token = xml.readNext(); if ( xml.name().toString() == "string" || xml.name().toString() == "boolean" || xml.name().toString() == "dateTime.iso8601" ) { token = xml.readNext(); if ( _current_name == "post_date" || _current_name == "date_created_gmt" ) { QLocale c = QLocale::c(); QDateTime date = c.toDateTime(xml.text().toString(), QLatin1String("yyyyMMddTHH:mm:ss"));//ddd, dd MMM yyyy HH:mm:ss"));// '+0000")); QString outputFromat("dd MMM yyyy - HH:mm:ss"); date.setTimeSpec(Qt::UTC); res["sortDate"] = date; res["date"] = date.toString(outputFromat); /* is this insane?! */ /* QString theDate = xml.text().toString(); //"20130503T14:48:55"; QDateTime date = QDateTime::fromString(theDate, "yyyyMMddTHH:mm:ss"); res["sortDate"] = date; res["date"] = date.toString(Qt::SystemLocaleShortDate); */ } else res[_current_name] = xml.text().toString(); _current_name = ""; } else _current_name = ""; } else if ( xml.name().toString() == "string" ) { /* newpost workaround */ token = xml.readNext(); res["newpostid"] = xml.text().toString(); model->insert(res); _res_bck.unite(res); res.clear(); } else if ( xml.name().toString() == "boolean") { /* deletepost workaround */ token = xml.readNext(); res["delpost"] = xml.text().toString(); model->insert(res); _res_bck.unite(res); res.clear(); } else if ( xml.name().toString() == "int" ) { /* newcomment workaround */ token = xml.readNext(); res["newcommentid"] = xml.text().toString(); model->insert(res); _res_bck.unite(res); res.clear(); } QVariantMap Entry; foreach(const QXmlStreamAttribute &attr, xml.attributes()) { qDebug() << "adding name = " << attr.name().toString() << " value = " << attr.value().toString(); Entry[attr.name().toString()] = attr.value().toString(); } qDebug() << "adding name = " << xml.name().toString() << " and = " << xml.text().toString(); Entry[_current_name] = xml.text().toString(); //xml.text().toString(); Entries.append(Entry); } else if ( token == QXmlStreamReader::EndElement ) { if ( xml.name().toString() == "struct" ) { _struct_counter--; if ( _struct_counter == 0 ) { if ( !res.isEmpty() ) { model->insert(res); _res_bck.unite(res); res.clear(); } else qDebug() << "*+*+*+*+*+*+*+* ouch! res is empty!! =====DO SMTG======"; } } } }
void QwtErrorPlotCurve::loadData() { if (!d_master_curve) return; if (!plot()) return; Table *mt = d_master_curve->table(); if (!mt) return; int xcol = mt->colIndex(d_master_curve->xColumnName()); int ycol = mt->colIndex(d_master_curve->title().text()); int errcol = d_table->colIndex(title().text()); if (xcol<0 || ycol<0 || errcol<0) return; int xColType = mt->columnType(xcol); int yColType = mt->columnType(ycol); d_start_row = d_master_curve->startRow(); d_end_row = d_master_curve->endRow(); int r = abs(d_end_row - d_start_row) + 1; QVector<double> X(r), Y(r), err(r); int data_size = 0; QLocale locale = d_table->locale(); for (int i = d_start_row; i <= d_end_row; i++){ QString xval = mt->text(i, xcol); QString yval = mt->text(i, ycol); QString errval = d_table->text(i, errcol); if (!xval.isEmpty() && !yval.isEmpty() && !errval.isEmpty()){ bool ok = true; if (xColType == Table::Text) X[data_size] = (double)(data_size + 1); else X[data_size] = locale.toDouble(xval, &ok); if (yColType == Table::Text) Y[data_size] = (double)(data_size + 1); else Y[data_size] = locale.toDouble(yval, &ok); if (!ok) continue; err[data_size] = locale.toDouble(errval, &ok); if (ok) data_size++; } } if (!data_size) remove(); X.resize(data_size); Y.resize(data_size); err.resize(data_size); setData(X.data(), Y.data(), data_size); setErrors(err); }
void DateFormatsWidget::localeChanged(QLocale locale) { setLocale(locale); QDateTime now = QDateTime::currentDateTime(); shortDateFormat->setText(locale.toString(now.date(), QLocale::ShortFormat)); shortDateFormat->setToolTip(locale.dateFormat(QLocale::ShortFormat)); longDateFormat->setText(locale.toString(now.date(), QLocale::LongFormat)); longDateFormat->setToolTip(locale.dateFormat(QLocale::LongFormat)); shortTimeFormat->setText(locale.toString(now.time(), QLocale::ShortFormat)); shortTimeFormat->setToolTip(locale.timeFormat(QLocale::ShortFormat)); longTimeFormat->setText(locale.toString(now.time(), QLocale::LongFormat)); longTimeFormat->setToolTip(locale.timeFormat(QLocale::LongFormat)); shortDateTimeFormat->setText(locale.toString(now, QLocale::ShortFormat)); shortDateTimeFormat->setToolTip(locale.dateTimeFormat(QLocale::ShortFormat)); longDateTimeFormat->setText(locale.toString(now, QLocale::LongFormat)); longDateTimeFormat->setToolTip(locale.dateTimeFormat(QLocale::LongFormat)); amText->setText(locale.amText()); pmText->setText(locale.pmText()); firstDayOfWeek->setText(toString(locale.firstDayOfWeek())); int mns = monthNamesShort->currentIndex(); int mnl = monthNamesLong->currentIndex(); int smns = standaloneMonthNamesShort->currentIndex(); int smnl = standaloneMonthNamesLong->currentIndex(); int dnl = dayNamesLong->currentIndex(); int dns = dayNamesShort->currentIndex(); int sdnl = standaloneDayNamesLong->currentIndex(); int sdns = standaloneDayNamesShort->currentIndex(); monthNamesShort->clear(); monthNamesLong->clear(); standaloneMonthNamesShort->clear(); standaloneMonthNamesLong->clear(); dayNamesLong->clear(); dayNamesShort->clear(); standaloneDayNamesLong->clear(); standaloneDayNamesShort->clear(); for (int i = 1; i <= 12; ++i) monthNamesShort->addItem(locale.monthName(i, QLocale::ShortFormat)); monthNamesShort->setCurrentIndex(mns >= 0 ? mns : 0); for (int i = 1; i <= 12; ++i) monthNamesLong->addItem(locale.monthName(i, QLocale::LongFormat)); monthNamesLong->setCurrentIndex(mnl >= 0 ? mnl : 0); for (int i = 1; i <= 12; ++i) standaloneMonthNamesShort->addItem(locale.standaloneMonthName(i, QLocale::ShortFormat)); standaloneMonthNamesShort->setCurrentIndex(smns >= 0 ? smns : 0); for (int i = 1; i <= 12; ++i) standaloneMonthNamesLong->addItem(locale.standaloneMonthName(i, QLocale::LongFormat)); standaloneMonthNamesLong->setCurrentIndex(smnl >= 0 ? smnl : 0); for (int i = 1; i <= 7; ++i) dayNamesLong->addItem(locale.dayName(i, QLocale::LongFormat)); dayNamesLong->setCurrentIndex(dnl >= 0 ? dnl : 0); for (int i = 1; i <= 7; ++i) dayNamesShort->addItem(locale.dayName(i, QLocale::ShortFormat)); dayNamesShort->setCurrentIndex(dns >= 0 ? dns : 0); for (int i = 1; i <= 7; ++i) standaloneDayNamesLong->addItem(locale.standaloneDayName(i, QLocale::LongFormat)); standaloneDayNamesLong->setCurrentIndex(sdnl >= 0 ? sdnl : 0); for (int i = 1; i <= 7; ++i) standaloneDayNamesShort->addItem(locale.standaloneDayName(i, QLocale::ShortFormat)); standaloneDayNamesShort->setCurrentIndex(sdns >= 0 ? sdns : 0); }
About::About(QWidget *parent, QString language) : QDialog(parent) { _language = language; // Setup UI: setupUi(this); #ifdef SMALL_RESOLUTION // https://bugreports.qt.io/browse/QTBUG-16034 // Workaround for window not showing always fullscreen setWindowFlags( Qt::Window ); #endif // Display title/program version: progversion_label->setText(progversion_label->text() + " " + QApplication::applicationVersion()); // Load licence text and changelog: QFile changelog_file; if (language == "de") changelog_file.setFileName(":/changelog_de.txt"); else changelog_file.setFileName(":/changelog_en.txt"); changelog_file.open(QIODevice::ReadOnly | QIODevice::Text); QString changelog_content = static_cast<QString>(changelog_file.readAll()); changelog_textBrowser->setText(changelog_content); changelog_file.close(); // *** Definitions: SSMprotocol2_def_en ssmp_defs; // Display number of supported DTCs: int nrofDTCs_SUB = ssmp_defs.SUBDTCrawDefs().size(); int nrofDTCs_OBD = ssmp_defs.OBDDTCrawDefs().size(); int nrofDTCs_CC = ssmp_defs.CCCCrawDefs().size(); QString dtcstr = QString::number( nrofDTCs_SUB ) + " / " + QString::number( nrofDTCs_OBD ) + " / " + QString::number( nrofDTCs_CC ); nrofsupportedDTCs_label->setText( dtcstr ); // Display number of supported measuring blocks / switches: int nrofMBs = ssmp_defs.MBrawDefs().size(); int nrofSWs = ssmp_defs.SWrawDefs().size(); QString mbswstr = QString::number( nrofMBs ) + " / " + QString::number( nrofSWs ); nrofsupportedMBsSWs_label->setText( mbswstr ); // Display number of supported Adjustment values: int ecu_adjustments = 0; int tcu_adjustments = 0; QStringList adjustmentdefs = ssmp_defs.AdjustmentRawDefs(); for (int k=0; k< adjustmentdefs.size(); k++) { if (adjustmentdefs.at(k).section(';', 1, 1).toInt() == 0) { ecu_adjustments++; } else if (adjustmentdefs.at(k).section(';', 1, 1).toInt() == 1) { tcu_adjustments++; } } QString adjustmentsstr = QString::number( ecu_adjustments ) + " / " + QString::number( tcu_adjustments ); nrofadjustmentvalues_label->setText( adjustmentsstr ); // Display number of supported system tests: int nrofSysTests = ssmp_defs.ActuatorRawDefs().size(); QString systestsstr = QString::number( nrofSysTests ) + " / 1"; nrofActuatortests_label->setText(systestsstr); // Display supported program languages: QString langstr; for (int k=0; k<__supportedLocales.size(); k++) { QLocale locale = __supportedLocales.at(k); QString langname = QLocale::languageToString( locale.language() ); QString langname_tr = QCoreApplication::translate( "Language", langname.toUtf8() ); if (k > 0) langstr.append(", "); langstr.append(langname_tr); } languages_label->setText( langstr ); // Connect buttons: connect( showlicense_pushButton, SIGNAL( released() ), this, SLOT( showLicense() ) ); connect( close_pushButton, SIGNAL( released() ), this, SLOT( close() ) ); }
void CtrlList::read(Xml& xml) { QLocale loc = QLocale::c(); bool ok; for (;;) { Xml::Token token = xml.parse(); const QString& tag = xml.s1(); switch (token) { case Xml::Error: case Xml::End: return; case Xml::Attribut: if (tag == "id") { //_id = xml.s2().toInt(); _id = loc.toInt(xml.s2(), &ok); if (!ok) { printf("CtrlList::read failed reading _id string: %s\n", xml.s2().toLatin1().constData()); initColor(0); //Set the default color if we have an error } else { initColor(_id); } } else if (tag == "cur") { //_curVal = xml.s2().toDouble(); _curVal = loc.toDouble(xml.s2(), &ok); if (!ok) printf("CtrlList::read failed reading _curVal string: %s\n", xml.s2().toLatin1().constData()); } else if(tag == "visible") { _visible = (bool)xml.s2().toInt(); } else if(tag == "color") { ;//xml.skip(tag); } else printf("unknown tag %s\n", tag.toLatin1().constData()); break; case Xml::Text: { // Changed by Tim. Users in some locales reported corrupt reading, // because of the way floating point is represented (2,3456 not 2.3456). /* QByteArray ba = tag.toLatin1(); const char* s = ba;.constData(); int frame; double val; for (;;) { char* endp; while (*s == ' ' || *s == '\n') ++s; if (*s == 0) break; frame = strtol(s, &endp, 10); s = endp; while (*s == ' ' || *s == '\n') ++s; val = strtod(s, &endp); add(frame, val); s = endp; ++s; } */ // Added by Tim. p3.3.6 //printf("CtrlList::read tag:%s\n", tag.toLatin1().constData()); int len = tag.length(); int frame; double val; int i = 0; for (;;) { while (i < len && (tag[i] == ',' || tag[i] == ' ' || tag[i] == '\n')) ++i; if (i == len) break; QString fs; while (i < len && tag[i] != ' ') { fs.append(tag[i]); ++i; } if (i == len) break; // Works OK, but only because if current locale fails it falls back on 'C' locale. // So, let's skip the fallback and force use of 'C' locale. //frame = fs.toInt(&ok); frame = loc.toInt(fs, &ok); if (!ok) { printf("CtrlList::read failed reading frame string: %s\n", fs.toLatin1().constData()); break; } while (i < len && (tag[i] == ' ' || tag[i] == '\n')) ++i; if (i == len) break; QString vs; while (i < len && tag[i] != ' ' && tag[i] != ',') { vs.append(tag[i]); ++i; } // Works OK, but only because if current locale fails it falls back on 'C' locale. // So, let's skip the fallback and force use of 'C' locale. //val = vs.toDouble(&ok); val = loc.toDouble(vs, &ok); if (!ok) { printf("CtrlList::read failed reading value string: %s\n", vs.toLatin1().constData()); break; } // Added by Tim. p3.3.6 //printf("CtrlList::read i:%d len:%d fs:%s frame %d: vs:%s val %f \n", i, len, fs.toLatin1().constData(), frame, vs.toLatin1().constData(), val); add(frame, val); if (i == len) break; } } break; case Xml::TagEnd: if (xml.s1() == "controller") { // Added by Tim. p3.3.6 //printf("CtrlList::read _id:%d _curVal:%f\n", _id, _curVal); return; } default: break; } } }
QVariant LocaleModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || role != Qt::DisplayRole && role != Qt::EditRole && role != Qt::ToolTipRole || index.column() >= g_model_cols || index.row() >= g_locale_list_count + 2) return QVariant(); QVariant data; if (index.column() < g_model_cols - 1) data = m_data_list.at(index.column()); if (index.row() == 0) { if (role == Qt::ToolTipRole) return QVariant(); switch (index.column()) { case 0: return data.toDouble(); case 1: return data.toDate(); case 2: return data.toDate(); case 3: return data.toTime(); case 4: return data.toTime(); case 5: return QVariant(); default: break; } } else { QLocale locale; if (index.row() == 1) { locale = QLocale::system(); } else { LocaleListItem item = g_locale_list[index.row() - 2]; locale = QLocale((QLocale::Language)item.language, (QLocale::Country)item.country); } switch (index.column()) { case 0: if (role == Qt::ToolTipRole) return QVariant(); return locale.toString(data.toDouble()); case 1: if (role == Qt::ToolTipRole) return locale.dateFormat(QLocale::LongFormat); return locale.toString(data.toDate(), QLocale::LongFormat); case 2: if (role == Qt::ToolTipRole) return locale.dateFormat(QLocale::ShortFormat); return locale.toString(data.toDate(), QLocale::ShortFormat); case 3: if (role == Qt::ToolTipRole) return locale.timeFormat(QLocale::LongFormat); return locale.toString(data.toTime(), QLocale::LongFormat); case 4: if (role == Qt::ToolTipRole) return locale.timeFormat(QLocale::ShortFormat); return locale.toString(data.toTime(), QLocale::ShortFormat); case 5: if (role == Qt::ToolTipRole) return QVariant(); return locale.name(); default: break; } } return QVariant(); }
QString get_short_dive_date_string(timestamp_t when) { QDateTime ts; ts.setMSecsSinceEpoch(when * 1000L); return loc.toString(ts.toUTC(), shortDateFormat + " " + timeFormat); }
/// \brief Converts string containing value and (prefix+)unit to double (Counterpart to Helper::valueToString). /// \param text The text containing the value and its unit. /// \param unit The base unit of the value. /// \param ok Pointer to a success-flag, true on success, false on error. /// \return Decoded value. double stringToValue(const QString &text, Unit unit, bool *ok) { // Check if the text is empty int totalSize = text.size(); if(!totalSize){ if(ok) *ok = false; return 0.0; } // Split value and unit apart int valueSize = 0; QLocale locale; bool decimalFound = false; bool exponentFound = false; if(text[valueSize] == locale.negativeSign()) ++valueSize; for(; valueSize < text.size(); ++valueSize) { QChar character = text[valueSize]; if(character.isDigit()) { } else if(character == locale.decimalPoint() && decimalFound == false && exponentFound == false) { decimalFound = true; } else if(character == locale.exponential() && exponentFound == false) { exponentFound = true; if(text[valueSize + 1] == locale.negativeSign()) ++valueSize; } else { break; } } QString valueString = text.left(valueSize); bool valueOk = false; double value = valueString.toDouble(&valueOk); if(!valueOk) { if(ok) *ok = false; return value; } QString unitString = text.right(text.size() - valueSize).trimmed(); if(ok) *ok = true; switch(unit) { case UNIT_VOLTS: { // Voltage string decoding if(unitString.startsWith('\265')) return value * 1e-6; else if(unitString.startsWith('m')) return value * 1e-3; else return value; } case UNIT_DECIBEL: // Power level string decoding return value; case UNIT_SECONDS: // Time string decoding if(unitString.startsWith('p')) return value * 1e-12; else if(unitString.startsWith('n')) return value * 1e-9; else if(unitString.startsWith('\265')) return value * 1e-6; else if(unitString.startsWith("min")) return value * 60; else if(unitString.startsWith('m')) return value * 1e-3; else if(unitString.startsWith('h')) return value * 3600; else return value; case UNIT_HERTZ: // Frequency string decoding if(unitString.startsWith('k')) return value * 1e3; else if(unitString.startsWith('M')) return value * 1e6; else if(unitString.startsWith('G')) return value * 1e9; else return value; case UNIT_SAMPLES: // Sample count string decoding if(unitString.startsWith('k')) return value * 1e3; else if(unitString.startsWith('M')) return value * 1e6; else if(unitString.startsWith('G')) return value * 1e9; else return value; default: if(ok) *ok = false; return value; } }
int QResourceRoot::findNode(const QString &_path, const QLocale &locale) const { QString path = _path; { QString root = mappingRoot(); if(!root.isEmpty()) { if(root == path) { path = QLatin1Char('/'); } else { if(!root.endsWith(QLatin1Char('/'))) root += QLatin1Char('/'); if(path.size() >= root.size() && path.startsWith(root)) path = path.mid(root.length()-1); if(path.isEmpty()) path = QLatin1Char('/'); } } } #ifdef DEBUG_RESOURCE_MATCH qDebug() << "!!!!" << "START" << path << locale.country() << locale.language(); #endif if(path == QLatin1String("/")) return 0; //the root node is always first int child_count = (tree[6] << 24) + (tree[7] << 16) + (tree[8] << 8) + (tree[9] << 0); int child = (tree[10] << 24) + (tree[11] << 16) + (tree[12] << 8) + (tree[13] << 0); //now iterate up the tree int node = -1; QStringSplitter splitter(path); while (child_count && splitter.hasNext()) { QStringRef segment = splitter.next(); #ifdef DEBUG_RESOURCE_MATCH qDebug() << " CHILDREN" << segment; for(int j = 0; j < child_count; ++j) { qDebug() << " " << child+j << " :: " << name(child+j); } #endif const int h = qHash(segment); //do the binary search for the hash int l = 0, r = child_count-1; int sub_node = (l+r+1)/2; while(r != l) { const int sub_node_hash = hash(child+sub_node); if(h == sub_node_hash) break; else if(h < sub_node_hash) r = sub_node - 1; else l = sub_node; sub_node = (l + r + 1) / 2; } sub_node += child; //now do the "harder" compares bool found = false; if(hash(sub_node) == h) { while(sub_node > child && hash(sub_node-1) == h) //backup for collisions --sub_node; for(; sub_node < child+child_count && hash(sub_node) == h; ++sub_node) { //here we go... if(name(sub_node) == segment) { found = true; int offset = findOffset(sub_node); #ifdef DEBUG_RESOURCE_MATCH qDebug() << " TRY" << sub_node << name(sub_node) << offset; #endif offset += 4; //jump past name const short flags = (tree[offset+0] << 8) + (tree[offset+1] << 0); offset += 2; if(!splitter.hasNext()) { if(!(flags & Directory)) { const short country = (tree[offset+0] << 8) + (tree[offset+1] << 0); offset += 2; const short language = (tree[offset+0] << 8) + (tree[offset+1] << 0); offset += 2; #ifdef DEBUG_RESOURCE_MATCH qDebug() << " " << "LOCALE" << country << language; #endif if(country == locale.country() && language == locale.language()) { #ifdef DEBUG_RESOURCE_MATCH qDebug() << "!!!!" << "FINISHED" << __LINE__ << sub_node; #endif return sub_node; } else if((country == QLocale::AnyCountry && language == locale.language()) || (country == QLocale::AnyCountry && language == QLocale::C && node == -1)) { node = sub_node; } continue; } else { #ifdef DEBUG_RESOURCE_MATCH qDebug() << "!!!!" << "FINISHED" << __LINE__ << sub_node; #endif return sub_node; } } if(!(flags & Directory)) return -1; child_count = (tree[offset+0] << 24) + (tree[offset+1] << 16) + (tree[offset+2] << 8) + (tree[offset+3] << 0); offset += 4; child = (tree[offset+0] << 24) + (tree[offset+1] << 16) + (tree[offset+2] << 8) + (tree[offset+3] << 0); break; } } } if(!found) break; } #ifdef DEBUG_RESOURCE_MATCH qDebug() << "!!!!" << "FINISHED" << __LINE__ << node; #endif return node; }
// Apply a simple variant type to a DOM property static bool applySimpleProperty(const QVariant &v, bool translateString, DomProperty *dom_prop) { switch (v.type()) { case QVariant::String: { DomString *str = new DomString(); str->setText(v.toString()); if (!translateString) str->setAttributeNotr(QLatin1String("true")); dom_prop->setElementString(str); } return true; case QVariant::ByteArray: dom_prop->setElementCstring(QString::fromUtf8(v.toByteArray())); return true; case QVariant::Int: dom_prop->setElementNumber(v.toInt()); return true; case QVariant::UInt: dom_prop->setElementUInt(v.toUInt()); return true; case QVariant::LongLong: dom_prop->setElementLongLong(v.toLongLong()); return true; case QVariant::ULongLong: dom_prop->setElementULongLong(v.toULongLong()); return true; case QVariant::Double: dom_prop->setElementDouble(v.toDouble()); return true; case QVariant::Bool: dom_prop->setElementBool(v.toBool() ? QFormBuilderStrings::instance().trueValue : QFormBuilderStrings::instance().falseValue); return true; case QVariant::Char: { DomChar *ch = new DomChar(); const QChar character = v.toChar(); ch->setElementUnicode(character.unicode()); dom_prop->setElementChar(ch); } return true; case QVariant::Point: { DomPoint *pt = new DomPoint(); const QPoint point = v.toPoint(); pt->setElementX(point.x()); pt->setElementY(point.y()); dom_prop->setElementPoint(pt); } return true; case QVariant::PointF: { DomPointF *ptf = new DomPointF(); const QPointF pointf = v.toPointF(); ptf->setElementX(pointf.x()); ptf->setElementY(pointf.y()); dom_prop->setElementPointF(ptf); } return true; case QVariant::Color: { DomColor *clr = new DomColor(); const QColor color = qvariant_cast<QColor>(v); clr->setElementRed(color.red()); clr->setElementGreen(color.green()); clr->setElementBlue(color.blue()); const int alphaChannel = color.alpha(); if (alphaChannel != 255) clr->setAttributeAlpha(alphaChannel); dom_prop->setElementColor(clr); } return true; case QVariant::Size: { DomSize *sz = new DomSize(); const QSize size = v.toSize(); sz->setElementWidth(size.width()); sz->setElementHeight(size.height()); dom_prop->setElementSize(sz); } return true; case QVariant::SizeF: { DomSizeF *szf = new DomSizeF(); const QSizeF sizef = v.toSizeF(); szf->setElementWidth(sizef.width()); szf->setElementHeight(sizef.height()); dom_prop->setElementSizeF(szf); } return true; case QVariant::Rect: { DomRect *rc = new DomRect(); const QRect rect = v.toRect(); rc->setElementX(rect.x()); rc->setElementY(rect.y()); rc->setElementWidth(rect.width()); rc->setElementHeight(rect.height()); dom_prop->setElementRect(rc); } return true; case QVariant::RectF: { DomRectF *rcf = new DomRectF(); const QRectF rectf = v.toRectF(); rcf->setElementX(rectf.x()); rcf->setElementY(rectf.y()); rcf->setElementWidth(rectf.width()); rcf->setElementHeight(rectf.height()); dom_prop->setElementRectF(rcf); } return true; case QVariant::Font: { DomFont *fnt = new DomFont(); const QFont font = qvariant_cast<QFont>(v); const uint mask = font.resolve(); if (mask & QFont::WeightResolved) { fnt->setElementBold(font.bold()); fnt->setElementWeight(font.weight()); } if (mask & QFont::FamilyResolved) fnt->setElementFamily(font.family()); if (mask & QFont::StyleResolved) fnt->setElementItalic(font.italic()); if (mask & QFont::SizeResolved) fnt->setElementPointSize(font.pointSize()); if (mask & QFont::StrikeOutResolved) fnt->setElementStrikeOut(font.strikeOut()); if (mask & QFont::UnderlineResolved) fnt->setElementUnderline(font.underline()); if (mask & QFont::KerningResolved) fnt->setElementKerning(font.kerning()); if (mask & QFont::StyleStrategyResolved) { const QMetaEnum styleStrategy_enum = metaEnum<QAbstractFormBuilderGadget>("styleStrategy"); fnt->setElementStyleStrategy(QLatin1String(styleStrategy_enum.valueToKey(font.styleStrategy()))); } dom_prop->setElementFont(fnt); } return true; #ifndef QT_NO_CURSOR case QVariant::Cursor: { const QMetaEnum cursorShape_enum = metaEnum<QAbstractFormBuilderGadget>("cursorShape"); dom_prop->setElementCursorShape(QLatin1String(cursorShape_enum.valueToKey(qvariant_cast<QCursor>(v).shape()))); } return true; #endif case QVariant::KeySequence: { DomString *s = new DomString(); s->setText(qvariant_cast<QKeySequence>(v).toString(QKeySequence::PortableText)); dom_prop->setElementString(s); } return true; case QVariant::Locale: { DomLocale *dom = new DomLocale(); const QLocale locale = qvariant_cast<QLocale>(v); const QMetaEnum language_enum = metaEnum<QAbstractFormBuilderGadget>("language"); const QMetaEnum country_enum = metaEnum<QAbstractFormBuilderGadget>("country"); dom->setAttributeLanguage(QLatin1String(language_enum.valueToKey(locale.language()))); dom->setAttributeCountry(QLatin1String(country_enum.valueToKey(locale.country()))); dom_prop->setElementLocale(dom); } return true; case QVariant::SizePolicy: { DomSizePolicy *dom = new DomSizePolicy(); const QSizePolicy sizePolicy = qvariant_cast<QSizePolicy>(v); dom->setElementHorStretch(sizePolicy.horizontalStretch()); dom->setElementVerStretch(sizePolicy.verticalStretch()); const QMetaEnum sizeType_enum = metaEnum<QAbstractFormBuilderGadget>("sizeType"); dom->setAttributeHSizeType(QLatin1String(sizeType_enum.valueToKey(sizePolicy.horizontalPolicy()))); dom->setAttributeVSizeType(QLatin1String(sizeType_enum.valueToKey(sizePolicy.verticalPolicy()))); dom_prop->setElementSizePolicy(dom); } return true; case QVariant::Date: { DomDate *dom = new DomDate(); const QDate date = qvariant_cast<QDate>(v); dom->setElementYear(date.year()); dom->setElementMonth(date.month()); dom->setElementDay(date.day()); dom_prop->setElementDate(dom); } return true; case QVariant::Time: { DomTime *dom = new DomTime(); const QTime time = qvariant_cast<QTime>(v); dom->setElementHour(time.hour()); dom->setElementMinute(time.minute()); dom->setElementSecond(time.second()); dom_prop->setElementTime(dom); } return true; case QVariant::DateTime: { DomDateTime *dom = new DomDateTime(); const QDateTime dateTime = qvariant_cast<QDateTime>(v); dom->setElementHour(dateTime.time().hour()); dom->setElementMinute(dateTime.time().minute()); dom->setElementSecond(dateTime.time().second()); dom->setElementYear(dateTime.date().year()); dom->setElementMonth(dateTime.date().month()); dom->setElementDay(dateTime.date().day()); dom_prop->setElementDateTime(dom); } return true; case QVariant::Url: { DomUrl *dom = new DomUrl(); const QUrl url = v.toUrl(); DomString *str = new DomString(); str->setText(url.toString()); dom->setElementString(str); dom_prop->setElementUrl(dom); } return true; case QVariant::StringList: { DomStringList *sl = new DomStringList; sl->setElementString(qvariant_cast<QStringList>(v)); dom_prop->setElementStringList(sl); } return true; default: break; } return false; }