QGroupBox* MainWindow::createAlbumGroupBox()
{
    QGroupBox *box = new QGroupBox(tr("Album"));

    albumView = new QTableView;
    albumView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    albumView->setSortingEnabled(true);
    albumView->setSelectionBehavior(QAbstractItemView::SelectRows);
    albumView->setSelectionMode(QAbstractItemView::SingleSelection);
    albumView->setShowGrid(false);
    albumView->verticalHeader()->hide();
    albumView->setAlternatingRowColors(true);
    albumView->setModel(model);
    adjustHeader();

    QLocale locale = albumView->locale();
    locale.setNumberOptions(QLocale::OmitGroupSeparator);
    albumView->setLocale(locale);

    connect(albumView, SIGNAL(clicked(QModelIndex)),
            this, SLOT(showAlbumDetails(QModelIndex)));
    connect(albumView, SIGNAL(activated(QModelIndex)),
            this, SLOT(showAlbumDetails(QModelIndex)));

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(albumView, 0, 0);
    box->setLayout(layout);

    return box;
}
Beispiel #2
0
void Core::initLocale()
{
    QLocale systemLocale = QLocale();
#ifndef Q_OS_MAC
    setlocale(LC_NUMERIC, NULL);
#else
    setlocale(LC_NUMERIC_MASK, NULL);
#endif
    char *separator = localeconv()->decimal_point;
    if (QString::fromUtf8(separator) != QChar(systemLocale.decimalPoint())) {
        //qDebug()<<"------\n!!! system locale is not similar to Qt's locale... be prepared for bugs!!!\n------";
        // HACK: There is a locale conflict, so set locale to C
        // Make sure to override exported values or it won't work
        qputenv("LANG", "C");
#ifndef Q_OS_MAC
        setlocale(LC_NUMERIC, "C");
#else
        setlocale(LC_NUMERIC_MASK, "C");
#endif
        systemLocale = QLocale::c();
    }

    systemLocale.setNumberOptions(QLocale::OmitGroupSeparator);
    QLocale::setDefault(systemLocale);
}
/*!
    \property QProgressBar::text
    \brief the descriptive text shown with the progress bar

    The text returned is the same as the text displayed in the center
    (or in some styles, to the left) of the progress bar.

    The progress shown in the text may be smaller than the minimum value,
    indicating that the progress bar is in the "reset" state before any
    progress is set.

    In the default implementation, the text either contains a percentage
    value that indicates the progress so far, or it is blank because the
    progress bar is in the reset state.
*/
QString QProgressBar::text() const
{
    Q_D(const QProgressBar);
    if ((d->maximum == 0 && d->minimum == 0) || d->value < d->minimum
            || (d->value == INT_MIN && d->minimum == INT_MIN))
        return QString();

    qint64 totalSteps = qint64(d->maximum) - d->minimum;

    QString result = d->format;
    QLocale locale = d->locale; // Omit group separators for compatibility with previous versions that were non-localized.
    locale.setNumberOptions(locale.numberOptions() | QLocale::OmitGroupSeparator);
    result.replace(QLatin1String("%m"), locale.toString(totalSteps));
    result.replace(QLatin1String("%v"), locale.toString(d->value));

    // If max and min are equal and we get this far, it means that the
    // progress bar has one step and that we are on that step. Return
    // 100% here in order to avoid division by zero further down.
    if (totalSteps == 0) {
        result.replace(QLatin1String("%p"), locale.toString(int(100)));
        return result;
    }

    int progress = (qreal(d->value) - d->minimum) * 100.0 / totalSteps;
    result.replace(QLatin1String("%p"), locale.toString(progress));
    return result;
}
Beispiel #4
0
//---------------------FLOW FUNCTION -----------------------
QGroupBox * Mainwindow::viewadd(QWidget *centralwidget,QString filter)
{
	QGroupBox *box = new QGroupBox(centralwidget);
    QVBoxLayout *layout = new QVBoxLayout;
	RoomView = new QTableView();
    RoomView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    RoomView->setSelectionBehavior(QAbstractItemView::SelectRows);
    RoomView->setSelectionMode(QAbstractItemView::SingleSelection);
    RoomView->hideColumn(4);
    RoomView->hideColumn(5);
    RoomView->setShowGrid(false);
    RoomView->verticalHeader()->hide();
    RoomView->setAlternatingRowColors(true);
    
    if(filter.isEmpty())
    {
    	RoomView->setModel(modelback(centralwidget));
   	}
   	else
   	{
   		RoomView->setModel(searchmodel(filter));
  	}
    
    QLocale locale = RoomView->locale();
    locale.setNumberOptions(QLocale::OmitGroupSeparator);
    RoomView->setLocale(locale);
        
	layout->addWidget(RoomView,0,0);
	box->setLayout(layout);
	box->setGeometry(QRect(20, 55, 251, 261));
	box->show();    
    return box;
}
void MainWindowModel::setLocale (QLocale::Language language,
                                 QLocale::Country country)
{
  QLocale locale (language,
                  country);
  locale.setNumberOptions(HIDE_GROUP_SEPARATOR);

  m_locale = locale;
}
Beispiel #6
0
 otp::token::Encoder oathEncoder(uint length)
 {
     QLocale locale = QLocale::c();
     locale.setNumberOptions(QLocale::OmitGroupSeparator);
     return otp::token::Encoder([length, locale](const QByteArray& token) -> QString
     {
         return oath::encodeOTPToken(token, locale, length);
     });
 }
QString UnitsSchemaImperialDecimal::schemaTranslate(Base::Quantity quant,double &factor,QString &unitString)
{
    double UnitValue = std::abs(quant.getValue());
    Unit unit = quant.getUnit();
    // for imperial user/programmer mind; UnitValue is in internal system, that means
    // mm/kg/s. And all combined units have to be calculated from there!

    // now do special treatment on all cases seems necessary:
    if(unit == Unit::Length){  // Length handling ============================
        if(UnitValue < 0.00000254){// smaller then 0.001 thou -> inch and scientific notation
            unitString = QString::fromLatin1("in");
            factor = 25.4;
        //}else if(UnitValue < 2.54){ // smaller then 0.1 inch -> Thou (mil)
        //    unitString = QString::fromLatin1("thou");
        //    factor = 0.0254;
        }else{ // bigger then 1000 mi -> scientific notation
            unitString = QString::fromLatin1("in");
            factor = 25.4;
        }
    }else if (unit == Unit::Area){
        // TODO Cascade for the Areas
        // default action for all cases without special treatment:
        unitString = QString::fromLatin1("in^2");
        factor = 645.16;
    }else if (unit == Unit::Volume){
        // TODO Cascade for the Volume
        // default action for all cases without special treatment:
        unitString = QString::fromLatin1("in^3");
        factor = 16387.064;
    }else if (unit == Unit::Mass){
        // TODO Cascade for the wights
        // default action for all cases without special treatment:
        unitString = QString::fromLatin1("lb");
        factor = 0.45359237;
    }else if (unit == Unit::Pressure){
        if(UnitValue < 145.038){// psi is the smallest
            unitString = QString::fromLatin1("psi");
            factor = 0.145038;
        //}else if(UnitValue < 145038){
        //    unitString = QString::fromLatin1("ksi");
        //    factor = 145.038;
        }else{ // bigger then 1000 ksi -> psi + scientific notation
            unitString = QString::fromLatin1("psi");
            factor = 0.145038;
        }
    }else{
        // default action for all cases without special treatment:
        unitString = quant.getUnit().getString();
        factor = 1.0;
    }
    //return QString::fromLatin1("%L1 %2").arg(quant.getValue() / factor).arg(unitString);
    QLocale Lc = QLocale::system();
    Lc.setNumberOptions(Lc.OmitGroupSeparator | Lc.RejectGroupSeparator);
    QString Ln = Lc.toString((quant.getValue() / factor), 'f', Base::UnitsApi::getDecimals());
    return QString::fromUtf8("%1 %2").arg(Ln).arg(unitString);
}
Beispiel #8
0
QString UnitsSchema::toLocale(const Base::Quantity& quant, double factor, const QString& unitString) const
{
    //return QString::fromUtf8("%L1 %2").arg(quant.getValue() / factor).arg(unitString);
    QLocale Lc = QLocale::system();
    const QuantityFormat& format = quant.getFormat();
    if (format.option != QuantityFormat::None) {
        uint opt = static_cast<uint>(format.option);
        Lc.setNumberOptions(static_cast<QLocale::NumberOptions>(opt));
    }

    QString Ln = Lc.toString((quant.getValue() / factor), format.toFormat(), format.precision);
    return QString::fromUtf8("%1 %2").arg(Ln, unitString);
}
Beispiel #9
0
void lengthToWidgets(QLineEdit * input, LengthCombo * combo,
	Length const & len, Length::UNIT /*defaultUnit*/)
{
	if (len.empty()) {
		// no length (UNIT_NONE)
		combo->setCurrentItem(Length::defaultUnit());
		input->setText("");
	} else {
		combo->setCurrentItem(len.unit());
		QLocale loc;
		loc.setNumberOptions(QLocale::OmitGroupSeparator);
		input->setText(loc.toString(Length(len).value()));
	}
}
Beispiel #10
0
void AbstractClipItem::insertKeyframe(QDomElement effect, int pos, double val, bool defaultValue)
{
    if (effect.attribute(QStringLiteral("disable")) == QLatin1String("1")) return;
    QLocale locale;
    locale.setNumberOptions(QLocale::OmitGroupSeparator);
    effect.setAttribute(QStringLiteral("active_keyframe"), pos);
    QDomNodeList params = effect.elementsByTagName(QStringLiteral("parameter"));
    for (int i = 0; i < params.count(); ++i) {
        QDomElement e = params.item(i).toElement();
        if (e.isNull()) continue;
        QString paramName = e.attribute(QStringLiteral("name"));
        if (e.attribute(QStringLiteral("type")) == QLatin1String("animated")) {
            if (!m_keyframeView.activeParam(paramName)) {
                continue;
            }
	    if (defaultValue) {
		m_keyframeView.addDefaultKeyframe(pos, m_keyframeView.type(pos));
	    } else {
		m_keyframeView.addKeyframe(pos, val, m_keyframeView.type(pos));
	    }
            e.setAttribute(QStringLiteral("value"), m_keyframeView.serialize());
        }
        else if (e.attribute(QStringLiteral("type")) == QLatin1String("keyframe")
            || e.attribute(QStringLiteral("type")) == QLatin1String("simplekeyframe")) {
            QString kfr = e.attribute(QStringLiteral("keyframes"));
            const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
            QStringList newkfr;
            bool added = false;
            foreach(const QString &str, keyframes) {
                int kpos = str.section('=', 0, 0).toInt();
                double newval = locale.toDouble(str.section('=', 1, 1));
                if (kpos < pos) {
                    newkfr.append(str);
                } else if (!added) {
                    if (i == m_visibleParam)
                        newkfr.append(QString::number(pos) + '=' + QString::number((int)val));
                    else
                        newkfr.append(QString::number(pos) + '=' + locale.toString(newval));
                    if (kpos > pos) newkfr.append(str);
                    added = true;
                } else newkfr.append(str);
            }
            if (!added) {
                if (i == m_visibleParam)
                    newkfr.append(QString::number(pos) + '=' + QString::number((int)val));
                else
                    newkfr.append(QString::number(pos) + '=' + e.attribute(QStringLiteral("default")));
            }
            e.setAttribute(QStringLiteral("keyframes"), newkfr.join(QStringLiteral(";")));
        }
Beispiel #11
0
QString DateUtils::dateToString(const double date, int precision){
    QLocale locale;
    locale.setNumberOptions(QLocale::OmitGroupSeparator);
    if(precision == -1)
        precision = MainWindow::getInstance()->getAppSettings().mPrecision;
    char fmt = 'f';
    if (date>250000){
        fmt = 'G';
    }
    if (std::fabs(date)<1E-10) {
        return "0";
    }
    else
        return locale.toString(date, fmt, precision);
}
void ProfilesDialog::slotUpdateDisplay(QString currentProfile)
{
    if (askForSave() == false) {
        m_view.profiles_list->blockSignals(true);
        m_view.profiles_list->setCurrentIndex(m_selectedProfileIndex);
        m_view.profiles_list->blockSignals(false);
        return;
    }
    QLocale locale;
    locale.setNumberOptions(QLocale::OmitGroupSeparator);
    m_selectedProfileIndex = m_view.profiles_list->currentIndex();
    if (currentProfile.isEmpty())
        currentProfile = m_view.profiles_list->itemData(m_view.profiles_list->currentIndex()).toString();
    m_isCustomProfile = currentProfile.contains('/');
    m_view.button_create->setEnabled(true);
    m_view.button_delete->setEnabled(m_isCustomProfile);
    m_view.properties->setEnabled(m_isCustomProfile);
    m_view.button_save->setEnabled(m_isCustomProfile);
    QMap< QString, QString > values = ProfilesDialog::getSettingsFromFile(currentProfile);
    m_view.description->setText(values.value("description"));
    m_view.size_w->setValue(values.value("width").toInt());
    m_view.size_h->setValue(values.value("height").toInt());
    m_view.aspect_num->setValue(values.value("sample_aspect_num").toInt());
    m_view.aspect_den->setValue(values.value("sample_aspect_den").toInt());
    m_view.display_num->setValue(values.value("display_aspect_num").toInt());
    m_view.display_den->setValue(values.value("display_aspect_den").toInt());
    m_view.frame_num->setValue(values.value("frame_rate_num").toInt());
    m_view.frame_den->setValue(values.value("frame_rate_den").toInt());
    m_view.progressive->setChecked(values.value("progressive").toInt());
    if (values.value("progressive").toInt()) {
        m_view.fields->setText(locale.toString((double) values.value("frame_rate_num").toInt() / values.value("frame_rate_den").toInt(), 'f', 2));
    } else {
        m_view.fields->setText(locale.toString((double) 2 * values.value("frame_rate_num").toInt() / values.value("frame_rate_den").toInt(), 'f', 2));
    }

    int colorix = m_view.colorspace->findData(values.value("colorspace").toInt());
    if (colorix > -1) m_view.colorspace->setCurrentIndex(colorix);
    m_profileIsModified = false;
}
QLocale ImportASCIIDialog::decimalSeparators()
{
	QLocale locale;
    switch (boxDecimalSeparator->currentIndex()){
        case 0:
            locale = QLocale::system();
        break;
        case 1:
            locale = QLocale::c();
        break;
        case 2:
            locale = QLocale(QLocale::German);
        break;
        case 3:
            locale = QLocale(QLocale::French);
        break;
    }

	if (d_omit_thousands_sep->isChecked())
		locale.setNumberOptions(QLocale::OmitGroupSeparator);

	return locale;
}
Beispiel #14
0
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.setOption(QSurfaceFormat::StereoBuffers, true);
		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

#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
	
	//splash screen
	QSplashScreen* splash = 0;
	QTime splashStartTime;

	//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 case: translation file selection
	int lastArgumentIndex = 1;
	QTranslator translator;
	if (commandLine && QString(argv[1]).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 = 3;
	}

	//command line 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
		splashStartTime.start();
		QPixmap pixmap(QString::fromUtf8(":/CC/images/imLogoV2Qt.png"));
		splash = new QSplashScreen(pixmap, Qt::WindowStaysOnTopHint);
		splash->show();
		QApplication::processEvents();
	}

	//global structures 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

	int result = 0;

	if (commandLine)
	{
		//command line processing (no GUI)
		result = ccCommandLineParser::Parse(argc, argv);
	}
	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->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)
				filenames << QString(argv[i]);

			mainWindow->addToDB(filenames);
		}
		
		if (splash)
		{
			//we want the splash screen to be visible a minimum amount of time (1000 ms.)
			while (splashStartTime.elapsed() < 1000)
			{
				splash->raise();
				QApplication::processEvents(); //to let the system breath!
			}

			splash->close();
			QApplication::processEvents();

			delete splash;
			splash = 0;
		}

		//let's rock!
		try
		{
			result = app.exec();
		}
		catch(...)
		{
			QMessageBox::warning(0, "CC crashed!","Hum, it seems that CC has crashed... Sorry about that :)");
		}
	}

	//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;
}
Beispiel #15
0
int main(int argc, char *argv[])
{
    Q_INIT_RESOURCE(caQtDM);
#ifdef MOBILE
    Q_INIT_RESOURCE(qtcontrols);
#endif
    QApplication app(argc, argv);
    QApplication::setOrganizationName("Paul Scherrer Institut");
    QApplication::setApplicationName("caQtDM");

#ifdef MOBILE_ANDROID
    app.setStyle(QStyleFactory::create("fusion"));
#endif

    // we do not want numbers with a group separators
    QLocale loc = QLocale::system();
    loc.setNumberOptions(QLocale::OmitGroupSeparator);
    loc.setDefault(loc);

    QString fileName = "";
    QString macroString = "";
    QString geometry = "";
    QString macroFile = "";
    QMap<QString, QString> options;
    options.clear();

    searchFile *s = new searchFile("caQtDM_stylesheet.qss");
    QString fileNameFound = s->findFile();
    if(fileNameFound.isNull()) {
        printf("caQtDM -- file <caQtDM_stylesheet.qss> could not be loaded, is 'CAQTDM_DISPLAY_PATH' <%s> defined?\n", qasc(s->displayPath()));
    } else {
        QFile file(fileNameFound);
        file.open(QFile::ReadOnly);
        QString StyleSheet = QLatin1String(file.readAll());
        printf("caQtDM -- file <caQtDM_stylesheet.qss> loaded as the default application stylesheet\n");
        app.setStyleSheet(StyleSheet);
        file.close();
    }

    int	in, numargs;
    bool attach = false;
    bool minimize= false;
    bool nostyles = false;
    bool printscreen = false;
    bool resizing = true;

    for (numargs = argc, in = 1; in < numargs; in++) {
        //qDebug() << argv[in];
        if ( strcmp (argv[in], "-display" ) == 0 ) {
            in++;
            printf("caQtDM -- display <%s>\n", argv[in]);
        } else if ( strcmp (argv[in], "-macro" ) == 0 ) {
            in++;
            printf("caQtDM -- macro <%s>\n", argv[in]);
            macroString = QString(argv[in]);
        } else if ( strcmp (argv[in], "-attach" ) == 0 ) {
            printf("caQtDM -- will attach to another caQtDM if running\n");
            attach = true;
        } else if ( strcmp (argv[in], "-noMsg" ) == 0 ) {
            printf("caQtDM -- will minimize its main windows\n");
            minimize = true;
        } else if( strcmp (argv[in], "-macrodefs" ) == 0) {
            in++;
            printf("caQtDM -- will load macro string from file <%s>\n", argv[in]);
            macroFile = QString(argv[in]);
        } else if ( strcmp (argv[in], "-noStyles" ) == 0 ) {
            printf("caQtDM -- will not replace the default application stylesheet caQtDM_stylesheet.qss\n");
            nostyles = true;
        } else if ( strcmp (argv[in], "-x" ) == 0 ) {

        } else if ( strcmp (argv[in], "-displayFont" ) == 0 ) {
             in++;
        } else if(!strcmp(argv[in],"-help") || !strcmp(argv[in],"-h") || !strcmp(argv[in],"-?")) {
             in++;
                 printf("Usage:\n"
                   "  caQtDM[X options]\n"
                   "  [-help | -h | -?]\n"
                   "  [-x]\n"
                   "  [-attach]\n"
                   "  [-noMsg]\n"
                   "  [-noStyles]      works only when not attaching\n"
                   "  [-macro \"xxx=aaa,yyy=bbb, ...\"]\n"
                   "  [-macrodefs filename] will load macro definitions from file\n"
                   "  [-dg [<width>x<height>][+<xoffset>-<yoffset>]\n"
                   "  [-httpconfig] will display a network configuration screen at startup\n"
                   "  [-print] will print file and exit\n"
                   "  [-noResize] will prevent resizing\n"
                   "  [-cs defaultcontrolsystempluginname]\n"
                   "  [-option \"xxx=aaa,yyy=bbb, ...\"] options for cs plugins\n"
                   "  [file]\n"
                   "  [&]\n"
                   "\n"
                   "  -x -displayFont -display are ignored !\n\n");
                 exit(1);
        } else if((!strcmp(argv[in],"-displayGeometry")) || (!strcmp(argv[in],"-dg"))) {
            // [-dg [xpos[xypos]][+xoffset[+yoffset]]
             in++;
             geometry = QString(argv[in]);
        } else if(!strcmp(argv[in], "-print")) {
             printscreen = true;
             minimize = true;
             resizing = false;
        } else if(!strcmp(argv[in], "-noResize")) {
            resizing = false;
        } else if(!strcmp(argv[in], "-httpconfig")) {
            HTTPCONFIGURATOR = true;
        } else if(!strcmp(argv[in], "-cs")) {
            in++;
            options.insert("defaultPlugin", QString(argv[in]));
        } else if ( strcmp (argv[in], "-option" ) == 0 ) {
            in++;
            printf("caQtDM -- option <%s>\n", argv[in]);
            createMap(options, QString(argv[in]));
        } else if (strncmp (argv[in], "-" , 1) == 0) {
            /* unknown application argument */
            printf("caQtDM -- Argument %d = [%s] is unknown!, possible -attach -macro -noMsg -noStyles -dg -x -print -httpconfig -noResize\n",in,argv[in]);
        } else {
            printf("caQtDM -- file = <%s>\n", argv[in]);
            fileName = QString(argv[in]);
            break;
        }
    }

    // must be always true for mobile plattforms
#ifdef MOBILE
     HTTPCONFIGURATOR = true;
#endif

    if(!nostyles) {
        s = new searchFile("stylesheet.qss");
        fileNameFound = s->findFile();
        if(fileNameFound.isNull()) {
            printf("caQtDM -- file <stylesheet.qss> could not be loaded, is 'CAQTDM_DISPLAY_PATH' <%s> defined?\n", qasc(s->displayPath()));
        } else {
            QFile file(fileNameFound);
            file.open(QFile::ReadOnly);
            QString StyleSheet = QLatin1String(file.readAll());
            printf("caQtDM -- file <stylesheet.qss> replaced the default stylesheet\n");
            app.setStyleSheet(StyleSheet);
            file.close();
        }
    }

    // load macro definitions from file (located in this directory or in the caQTDM_DISPLAY_PATH)
    if(macroFile.length() > 0) {
        s = new searchFile(macroFile);
        fileNameFound = s->findFile();
        if(fileNameFound.isNull()) {
            printf("caQtDM -- file <stylesheet.qss> could not be loaded, is 'CAQTDM_DISPLAY_PATH' <%s> defined?\n", qasc(s->displayPath()));
        } else {
            QFile file(fileNameFound);
            file.open(QFile::ReadOnly);
            macroString = QLatin1String(file.readAll());
            file.close();
        }
    }

#ifdef IO_OPTIMIZED_FOR_TABWIDGETS
    printf("caQtDM -- viewer will disable monitors for hidden pages of QTabWidgets, in case of problems\n");
    printf("          you may disable this by not defining IO_OPTIMIZED_FOR_TABWIDGETS in qtdefs.pri\n");
#else
    printf("caQtDM -- viewer will not disable monitors for hidden pages of QTabWidgets\n");
    printf("          you may enable this by defining IO_OPTIMIZED_FOR_TABWIDGETS in qtdefs.pri\n");
#endif

#ifndef CONFIGURATOR
    QString displayPath = (QString)  qgetenv("CAQTDM_URL_DISPLAY_PATH");
    if(displayPath.length() > 0) {
         printf("caQtDM -- files will be downloaded from <%s> when not locally found\n", qasc(displayPath));
    } else {
        printf("caQtDM -- files will not be downloaded from an url when not locally found, while CAQTDM_URL_DISPLAY_PATH is not defined\n");
    }
#endif

    FileOpenWindow window (0, fileName, macroString, attach, minimize, geometry, printscreen, resizing, options);
    window.setWindowIcon (QIcon(":/caQtDM.ico"));
    window.show();
    window.move(0,0);

    if (signal(SIGINT, unixSignalHandler) == SIG_ERR) {
        qFatal("ERR - %s(%d): An error occurred while setting a signal handler.\n", __FILE__,__LINE__);
    }
    if (signal(SIGTERM, unixSignalHandler) == SIG_ERR) {
        qFatal("ERR - %s(%d): An error occurred while setting a signal handler.\n", __FILE__,__LINE__);
    }

    QObject::connect(&app, SIGNAL(aboutToQuit()), &window, SLOT(doSomething()));

    return app.exec();
}
Beispiel #16
0
void SearchResultWidget::showSearchResult(int start)
{
    if (resultList.isEmpty()) {
        return;
    }
    if (start < 0) {
        start = 0;
    }
    int end = 0;
    if (SearchResultWidget::maxItemPerPage == 0 || SearchResultWidget::nonPagedSearch) {
        SearchResultWidget::nonPagedSearch = true;
        moreThanOnePage = false;
    }
    else {
        end = start + SearchResultWidget::maxItemPerPage - 1;

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

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

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

    navButtonsNeeded = moreThanOnePage;

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

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

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

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

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

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

    QColor color = fisrtColor;

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

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

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

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

        //poem._HighlightText = phrase;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        ++it;
        ++i;
    }

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

    searchTable->setUpdatesEnabled(true);

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

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

    QApplication::restoreOverrideCursor();
}
Beispiel #17
0
QString Value::toString() const
{
    if (! isValid()) {
        return QLatin1String("nan");
    }

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

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

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

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

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

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

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

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

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

    return number + suffix;
}
Beispiel #18
0
void doubleToWidget(QLineEdit * input, double const & value, char f, int prec)
{
	QLocale loc;
	loc.setNumberOptions(QLocale::OmitGroupSeparator);
	input->setText(loc.toString(value, f, prec));
}
QString UnitsSchemaImperialBuilding::schemaTranslate(Base::Quantity quant,double &factor,QString &unitString)
{
    // this schema expresses distances in feet + inches + fractions
    // ex: 3'- 4 1/4"
    Unit unit = quant.getUnit();
    if(unit == Unit::Length){
        unitString = QString::fromLatin1("in");
        factor = 25.4;
        double inchValue = std::abs(quant.getValue())/25.4;
        int feet = inchValue/12;
        double inchPart = inchValue - (double)feet*12;
        int inches = (int)inchPart;
        double fraction = inchPart - (int)inchPart;
        if (fraction > 0.9375) {
            inches++;
            fraction = 0.0;
        }
        // if the quantity is too small it is rounded to zero
        if (std::abs(quant.getValue()) <= 1.5875)
            return QString::fromLatin1("0");
        // build representation
        std::stringstream output;
        if (quant.getValue() < 0)
            output << "-";
        // feet
        if (feet > 0) {
            output << feet << "'";
            if ( (inches > 0) || (fraction > 0.0625) )
                output << " ";
        }
        // inches
        if (inches > 0) {
            output << inches;
            if (fraction > 0.0625)
                output << "+";
            else
                output << "\"";
        }
        // fraction
        if (fraction <= 0.0625) {}
        else if (fraction > 0.8125)
            output << "7/8\"";
        else if (fraction > 0.6875)
            output << "3/4\"";
        else if (fraction > 0.5625)
            output << "5/8\"";
        else if (fraction > 0.4375)
            output << "1/2\"";
        else if (fraction > 0.3125)
            output << "3/8\"";
        else if (fraction > 0.1875)
            output << "1/4\"";
        else
            output << "1/8\"";
        return QString::fromLatin1(output.str().c_str());
    }else if (unit == Unit::Area){
        unitString = QString::fromLatin1("sqft");
        factor = 92903.04;
    }else if (unit == Unit::Volume){
        unitString = QString::fromLatin1("cuft");
        factor = 28316846.592;
    }else{
        unitString = quant.getUnit().getString();
        factor = 1.0;
    }
    QLocale Lc = QLocale::system();
    Lc.setNumberOptions(Lc.OmitGroupSeparator | Lc.RejectGroupSeparator);
    QString Ln = Lc.toString((quant.getValue() / factor), 'f', Base::UnitsApi::getDecimals());
    return QString::fromUtf8("%1 %2").arg(Ln).arg(unitString);
}
Beispiel #20
0
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
	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;
}
Beispiel #21
0
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.setOption(QSurfaceFormat::StereoBuffers, true);
		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

#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

	//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
	QSplashScreen* splash = 0;
	QTime splashStartTime;

	//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
		splashStartTime.start();
		QPixmap pixmap(QString::fromUtf8(":/CC/images/imLogoV2Qt.png"));
		splash = 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);
	}
	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);
		}
		
		if (splash)
		{
			//we want the splash screen to be visible a minimum amount of time (1000 ms.)
			while (splashStartTime.elapsed() < 1000)
			{
				splash->raise();
				QApplication::processEvents(); //to let the system breath!
			}

			splash->close();
			QApplication::processEvents();

			delete splash;
			splash = 0;
		}

		//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;
}
Beispiel #22
0
const QString Timecode::getTimecodeSeconds(const GenTime & time) const
{
    QLocale locale;
    locale.setNumberOptions(QLocale::OmitGroupSeparator);
    return locale.toString(time.seconds());
}