Esempio n. 1
0
int main(int argc, char **argv)
{
    int p = 0;

    toConfigurationNew::setQSettingsEnv();

    QApplication app(argc, argv);

    qRegisterMetaType<toQColumnDescriptionList>("toQColumnDescriptionList&");
    qRegisterMetaType<ValuesList>("ValuesList&");
    qRegisterMetaType<toConnection::exception>("toConnection::exception");

    try
    {
        toSplash splash(NULL);
        splash.show();

        QList<QString> plugins;

        // List of all connection provider finders
        std::vector<std::string> finders = ConnectionProviderFinderFactory::Instance().keys();
        // Resulting list of all the providers found
        toProvidersList &allProviders = toProvidersListSing::Instance();

        QProgressBar *progress = splash.progress();
        QLabel *label = splash.label();
        progress->setRange(1, plugins.size() + finders.size()*2);
        qApp->processEvents();
        Q_FOREACH(QString path, plugins)
        {
            label->setText(qApp->translate("main", "Loading plugin %1").arg(path));
            qApp->processEvents();
            bool success = false;
            try
            {
                QLibrary library(path);
                success = library.load();
            }
            TOCATCH;

            if (success)
            {
                label->setText(qApp->translate("main", "Loaded plugin %1").arg(path));
                TLOG(5, toDecoratorNC, __HERE__) << "Loaded plugin " << path << std::endl;
            }
            else
            {
                label->setText(qApp->translate("main", "Failed loading plugin %1").arg(path));
                TLOG(5, toDecoratorNC, __HERE__) << "Failed loading plugin " << path << std::endl;
            }
            progress->setValue(progress->value()+1);
            qApp->processEvents();
        }

        // Loop over all finders and call their "find" method, each of them can return several locations
        for (std::vector<std::string>::const_iterator i = finders.begin(); i != finders.end(); ++i)
        {
            QString finderName(i->c_str());
            label->setText(qApp->translate("main", "Looking for %1").arg(finderName));
            qApp->processEvents();
            TLOG(5, toDecoratorNC, __HERE__) << "Looking for client: " << *i << std::endl;
            try
            {
                std::auto_ptr<toConnectionProviderFinder> finder = ConnectionProviderFinderFactory::Instance().create(*i, 0);
                QList<toConnectionProviderFinder::ConnectionProvirerParams> l = finder->find();
                allProviders.append(l);
                finderName = finder->name();
            }
            TOCATCH;
            progress->setValue(progress->value()+1);
            qApp->processEvents();
        }

        // Loop over all providers found and try to load desired Oracle client
        // 1st try to load requested Oracle client(if set) then load thick(TNS) Oracle client
        QDir oHome = toConfigurationNewSingle::Instance().option(ToConfiguration::Global::OracleHomeDirectory).toString();
        Q_FOREACH(toConnectionProviderFinder::ConnectionProvirerParams const& params, allProviders)
        {
            QString providerName = params.value("PROVIDER").toString();
            if ( params.value("PROVIDER").toString() != ORACLE_PROVIDER)
                continue;
            QDir pHome(params.value("ORACLE_HOME").toString());
            if (oHome != pHome)
                continue;
            try
            {
                label->setText(qApp->translate("main", "Loading provider %1").arg(providerName));
                qApp->processEvents();
                TLOG(5, toDecoratorNC, __HERE__) << "Loading: " << params.value("PATH").toString() << std::endl;
                toConnectionProviderRegistrySing::Instance().load(params);
                progress->setValue(progress->value()+1);
                qApp->processEvents();
                break;
            }
            TOCATCH;
        }
Esempio n. 2
0
void FtpSessionDialog::updateProgress(int id, qint64 done, qint64 total)
{
	QProgressBar *progress = progressBars->value(id);
	progress->setMaximum(total);
	progress->setValue(done);
}
Esempio n. 3
0
MainWindow::MainWindow()
	: mUi(new Ui::MainWindowUi())
	, mListenerManager(NULL)
	, mPropertyModel(NULL)
{
	QSettings settings("SPbSU", "QReal");
	//bool showSplash = settings.value("Splashscreen", true).toBool();
	bool showSplash = false;
	QSplashScreen* splash =
			new QSplashScreen(QPixmap(":/icons/kroki3.PNG"), Qt::SplashScreen | Qt::WindowStaysOnTopHint);

	QProgressBar *progress = new QProgressBar((QWidget*) splash);
	progress->move(20,270);
	progress->setFixedWidth(600);
	progress->setFixedHeight(15);
	progress->setRange(0, 100);

	// Step 1: splash screen loaded, progress bar initialized.
	progress->setValue(5);
	if (showSplash)
	{
		splash->show();
		QApplication::processEvents();
	}
	mUi->setupUi(this);

#if defined(Q_WS_WIN)
	mUi->menuSvn->setEnabled(false);  // Doesn't work under Windows anyway.
#endif

	mUi->tabs->setTabsClosable(true);
	mUi->tabs->setMovable(true);

	if (!showSplash)
		mUi->actionShowSplash->setChecked(false);

	mUi->minimapView->setRenderHint(QPainter::Antialiasing, true);

	// Step 2: Ui is ready, splash screen shown.
	progress->setValue(20);
	mUi->actionShow_grid->setChecked(settings.value("ShowGrid", true).toBool());
	mUi->actionShow_alignment->setChecked(settings.value("ShowAlignment", true).toBool());
	mUi->actionSwitch_on_grid->setChecked(settings.value("ActivateGrid", false).toBool());
	mUi->actionSwitch_on_alignment->setChecked(settings.value("ActivateAlignment", true).toBool());

	connect(mUi->actionQuit, SIGNAL(triggered()), this, SLOT(close()));

	connect(mUi->actionShowSplash, SIGNAL(toggled(bool)), this, SLOT (toggleShowSplash(bool)));

	connect(mUi->actionOpen, SIGNAL(triggered()), this, SLOT(open()));
	connect(mUi->actionSave, SIGNAL(triggered()), this, SLOT(saveAll()));
	connect(mUi->actionSave_as, SIGNAL(triggered()), this, SLOT(saveAs()));
	connect(mUi->actionPrint, SIGNAL(triggered()), this, SLOT(print()));
	connect(mUi->actionMakeSvg, SIGNAL(triggered()), this, SLOT(makeSvg()));

	connect(mUi->actionDeleteFromDiagram, SIGNAL(triggered()), this, SLOT(deleteFromDiagram()));

	connect(mUi->tabs, SIGNAL(currentChanged(int)), this, SLOT(changeMiniMapSource(int)));
	connect(mUi->tabs, SIGNAL(tabCloseRequested(int)), this, SLOT(closeTab(int)));

	connect(mUi->actionCheckout, SIGNAL(triggered()), this, SLOT(doCheckout()));
	connect(mUi->actionCommit, SIGNAL(triggered()), this, SLOT(doCommit()));
	connect(mUi->actionExport_to_XMI, SIGNAL(triggered()), this, SLOT(exportToXmi()));
	connect(mUi->actionGenerate_to_Java, SIGNAL(triggered()), this, SLOT(generateToJava()));
	connect(mUi->actionGenerate_to_Hascol, SIGNAL(triggered()), this, SLOT(generateToHascol()));
	connect(mUi->actionShape_Edit, SIGNAL(triggered()), this, SLOT(openShapeEditor()));
	connect(mUi->actionGenerate_Editor, SIGNAL(triggered()), this, SLOT(generateEditor()));
	connect(mUi->actionGenerate_Editor_qrmc, SIGNAL(triggered()), this, SLOT(generateEditorWithQRMC()));
	connect(mUi->actionParse_Editor_xml, SIGNAL(triggered()), this, SLOT(parseEditorXml()));
	connect(mUi->actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferencesDialog()));

	connect(mUi->actionParse_Hascol_sources, SIGNAL(triggered()), this, SLOT(parseHascol()));
	connect(mUi->actionParse_Java_Libraries, SIGNAL(triggered()), this, SLOT(parseJavaLibraries()));

	connect(mUi->actionPlugins, SIGNAL(triggered()), this, SLOT(settingsPlugins()));
	connect(mUi->actionShow_grid, SIGNAL(toggled(bool)), this, SLOT(showGrid(bool)));
	connect(mUi->actionShow_alignment, SIGNAL(toggled(bool)), this, SLOT(showAlignment(bool)));
	connect(mUi->actionSwitch_on_grid, SIGNAL(toggled(bool)), this, SLOT(switchGrid(bool)));
	connect(mUi->actionSwitch_on_alignment, SIGNAL(toggled(bool)), this, SLOT(switchAlignment(bool)));

	connect(mUi->actionHelp, SIGNAL(triggered()), this, SLOT(showHelp()));
	connect(mUi->actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
	connect(mUi->actionAboutQt, SIGNAL(triggered()), qApp, SLOT(aboutQt()));

	connect(mUi->actionShow, SIGNAL(triggered()), this, SLOT(showGestures()));

	connect(mUi->minimapZoomSlider, SIGNAL(valueChanged(int)), this, SLOT(adjustMinimapZoom(int)));

	connect(mUi->actionDebug, SIGNAL(triggered()), this, SLOT(debug()));
	connect(mUi->actionDebug_Single_step, SIGNAL(triggered()), this, SLOT(debugSingleStep()));

	connect(mUi->actionClear, SIGNAL(triggered()), this, SLOT(exterminate()));
	connect(mUi->save_metamodel, SIGNAL(triggered()), this, SLOT(saveMetaModel()));

	adjustMinimapZoom(mUi->minimapZoomSlider->value());
	initGridProperties();

	// Step 3: Ui connects are done.
	progress->setValue(40);

	QString workingDir = settings.value("workingDir", ".").toString();

	mRootIndex = QModelIndex();
	mModels = new models::Models(workingDir, mEditorManager);

	mPropertyModel = new PropertyEditorModel(mEditorManager, mModels->logicalModelAssistApi());

	mUi->paletteDock->setWidget(mUi->paletteToolbox);
	mUi->errorDock->setWidget(mUi->errorListWidget);
	mUi->errorListWidget->init(this);
	mUi->errorDock->setVisible(false);
	mUi->propertyEditor->setModel(mPropertyModel);
	mUi->propertyEditor->verticalHeader()->hide();
	mUi->propertyEditor->horizontalHeader()->setResizeMode(0, QHeaderView::ResizeToContents);
	mUi->propertyEditor->horizontalHeader()->setResizeMode(1, QHeaderView::Stretch);
	mUi->propertyEditor->setItemDelegate(&mDelegate);

	connect(mUi->graphicalModelExplorer, SIGNAL(clicked(QModelIndex const &)), this, SLOT(graphicalModelExplorerClicked(QModelIndex)));
	connect(mUi->logicalModelExplorer, SIGNAL(clicked(QModelIndex const &)), this, SLOT(logicalModelExplorerClicked(QModelIndex)));

	mUi->graphicalModelExplorer->addAction(mUi->actionDeleteFromDiagram);
	mUi->logicalModelExplorer->addAction(mUi->actionDeleteFromDiagram);

	// Step 4: Property editor and model explorers are initialized.
	progress->setValue(60);
	loadPlugins();
	showMaximized();

	// Step 5: Plugins are loaded.
	progress->setValue(70);

	settings.beginGroup("MainWindow");
	if (!settings.value("maximized", true).toBool()) {
		showNormal();
		resize(settings.value("size", QSize(1024, 800)).toSize());
		move(settings.value("pos", QPoint(0, 0)).toPoint());
	}
	settings.endGroup();

	// Step 6: Save loaded, models initialized.
	progress->setValue(80);

	mListenerManager = new ListenerManager(mEditorManager.listeners()
										   , mModels->logicalModelAssistApi(), mModels->graphicalModelAssistApi());

	TypeList missingPlugins = mEditorManager.checkNeededPlugins(mModels->logicalRepoApi(), mModels->graphicalRepoApi());
	if (!missingPlugins.isEmpty()) {
		QString text = "These plugins are not present, but needed to load the save:\n";
		foreach (NewType const type, missingPlugins) {
			text += type.editor() + "\n";
			QMessageBox::warning(this, tr("Some plugins are missing"), text);
			close();
			return;
		}
Esempio n. 4
0
void BrowserView::onLoadProgress(int step)
{
    QProgressBar* bar = Gui::Sequencer::instance()->getProgressBar();
    bar->setValue(step);
}
Esempio n. 5
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->textBrowser->setFont(QFont("Monospace",11));
    ui->textBrowser->setLineWrapMode(QTextEdit::NoWrap);

    updater->moveToThread(pthread);
    fileTotal->moveToThread(fthread);

    //User selects directory, or action
    connect(this,SIGNAL(userSelect(QString)),updater,SLOT(action(QString)));
    connect(this,SIGNAL(selectDir(QString)),updater,SLOT(selectDir(QString)));
    connect(this,SIGNAL(selectDir(QString)),fileTotal,SLOT(selectDir(QString)));

    //Returning from Worker Thread
    connect(updater,SIGNAL(Finished(QString)),this,SLOT(action(QString)));

    //Clean up threads
    connect(updater,SIGNAL(close()),pthread,SLOT(quit()));
    connect(pthread, SIGNAL(finished()), updater, SLOT(deleteLater()));
    connect(fileTotal,SIGNAL(close()),fthread,SLOT(quit()));
    connect(fthread,SIGNAL(finished()),fileTotal,SLOT(deleteLater()));

    //Start Thread(s)
    pthread->start();
    fthread->start();

    //Get number of files in directory for progress bar
    //connect(this,SIGNAL(getfileTotal()),updater,SLOT(getfileTotal()));
    connect(this,SIGNAL(getfileTotal(QString)),fileTotal,SLOT(getfileTotal(QString)));        //request from main thread
    connect(fileTotal,SIGNAL(finished(int)),updater,SLOT(getfileTotal(int)));   //transfer total from getfiletotal object to worker object
    connect(updater,SIGNAL(getfileTotal(QString)),fileTotal,SLOT(getfileTotal(QString)));     //request from updater
    connect(updater,SIGNAL(displayFileTotal(int)),this,SLOT(displayFileTotal(int)));

    connect(fileTotal,SIGNAL(finished(int)),this,SLOT(enableButton()));

    //Create ProgressBar
    QProgressBar *bar = new QProgressBar(ui->statusBar);
    ui->statusBar->addWidget(bar);
    bar->setRange(0,100);
    bar->setValue(0);
    bar->hide();
    connect(updater,SIGNAL(percentChanged(int)),bar,SLOT(setValue(int)));
    connect(updater,SIGNAL(percentChanged(int)),bar,SLOT(show()));
    connect(this,SIGNAL(hidebar()),bar,SLOT(hide()));

    //fileTotal->getfileTotal();
    emit getfileTotal(dirSelect);
    ui->pushButton->setEnabled(false);



    //TABLE FUNZ
    QShortcut *shortcut = new QShortcut(QKeySequence("Ctrl+C"), this);
    connect(shortcut,SIGNAL(activated()),this,SLOT(on_actionCopy_triggered()));
//    ui->tableWidget->setColumnCount(3);
//    ui->tableWidget->setRowCount(100);

//    ui->tableWidget->setHorizontalHeaderLabels(QStringList() << "File" << "Hash" << "Check");
//    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
//    ui->tableWidget->horizontalHeader()->setSectionResizeMode(1,QHeaderView::Stretch);
}
Esempio n. 6
0
QWidget* WidgetStyle::createWidget(const QString& name)
{
    if(name == "CheckBox")
    {
        QCheckBox* box = new QCheckBox("CheckBox");
        box->setObjectName("CheckBox");
        return setLayoutWidget({ box }, { 100, 30 });
    }
    else if(name == "ComboBox")
    {
        QComboBox* box = new QComboBox;
        box->addItem("Item1");
        box->addItem("Item3");
        box->addItem("Item3");
        box->setObjectName("ComboBox");
        return setLayoutWidget({ box }, { 70, 30 });
    }
    else if(name == "DateEdit")
    {
        QDateEdit* date = new QDateEdit;
        date->setObjectName("DateEdit");
        return setLayoutWidget({ date }, { 110, 40 });
    }
    else if(name == "DateTimeEdit")
    {
        QDateTimeEdit* date = new QDateTimeEdit;
        date->setObjectName("DateTimeEdit");
        return setLayoutWidget({ date }, { 160, 30 });
    }
    else if(name == "Dialog")
    {
        QDialog* dialog = new QDialog;
        dialog->setObjectName("Dialog");
        return setLayoutWidget({ dialog }, { 160, 110 });
    }
    else if(name == "DockWidget") //?
    {
        QDockWidget* widget = new QDockWidget;
        widget->setObjectName("DockWidget");
        widget->resize(61, 22);
        return widget;
    }
    else if(name == "DoubleSpinBox")
    {
        QDoubleSpinBox* box = new QDoubleSpinBox;
        box->setObjectName("DoubleSpinBox");
        return setLayoutWidget({ box }, { 90, 40 });
    }
    else if(name == "Frame") //??
    {
        QFrame* frame = new QFrame;
        frame->setObjectName("Frame");
        frame->resize(150, 100);
        return frame;
    }
    else if(name == "GroupBox")
    {
        QGroupBox* box = new QGroupBox("GroupBox");
        box->setObjectName("GroupBox");
        return setLayoutWidget({ box }, { 160, 110 });
    }
    else if(name == "Label")
    {
        QLabel* label = new QLabel("Label");
        label->setObjectName("Label");
        return setLayoutWidget({ label }, { 40, 20});
    }
    else if(name == "LineEdit")
    {
        QLineEdit* line = new QLineEdit;
        line->setObjectName("LineEdit");
        return setLayoutWidget({ line }, { 30, 30 });
    }
    else if(name == "ListView") //??
    {
        QListView* view = new QListView;
        view->setObjectName("ListView");
        view->resize(71, 71);
        return view;
    }
    else if(name == "ListWidget")
    {
        QListWidget* list = new QListWidget;
        list->setObjectName("ListWidget");
        for(int i = 0; i < 20; i++)
            list->addItem(QString("Item %1").arg(i));
        return setLayoutWidget({ list }, { 80, 80 });
    }
    else if(name == "MainWindow")
    {
        QMainWindow* window = new QMainWindow;
        window->setObjectName("MainWindow");
        return setLayoutWidget({ window }, { 160, 110 });
    }
    else if(name == "Menu")
    {
        QMenu* parentMenu = new QMenu;
        parentMenu->setObjectName("Menu");
        parentMenu->addMenu("Menu1");
        QMenu* menu1 = parentMenu->addMenu("Menu2");
        menu1->addMenu("Menu1");
        menu1->addMenu("Menu2");
        parentMenu->addSeparator();
        parentMenu->addMenu("Menu3");
        return setLayoutWidget({ parentMenu }, { 160, 110 });
    }
    else if(name == "MenuBar")
    {
        QMenuBar* bar = new QMenuBar;
        bar->setObjectName("QMenuBar");
        QMenu* menu1 = bar->addMenu("MenuBar1");
        menu1->addMenu("Menu1");
        menu1->addSeparator();
        menu1->addMenu("Menu2");
        QMenu* menu2 = bar->addMenu("MenuBar2");
        menu2->addMenu("Menu1");
        menu2->addSeparator();
        menu2->addMenu("Menu2");
        QMenu* menu3 = bar->addMenu("MenuBar3");
        menu3->addMenu("Menu1");
        menu3->addSeparator();
        menu3->addMenu("Menu2");
        return setLayoutWidget({ bar }, { 280, 60 });
    }
    else if(name == "ProgressBar")
    {
        QProgressBar* bar = new QProgressBar;
        bar->setObjectName("ProgressBar");
        bar->setRange(0, 100);
        bar->setValue(0);

        QTimer* timer = new QTimer(bar);
        this->connect(timer, &QTimer::timeout, this, [bar]()
        {
            if(bar->value() == 100)
                bar->setValue(0);
            else
                bar->setValue(bar->value() + 1);
        });
        timer->start(100);
        return setLayoutWidget({ bar }, { 110, 30 });
    }
    else if(name == "PushButton")
    {
        QPushButton* button = new QPushButton("PushButton");
        button->setObjectName("PushButton");
        return setLayoutWidget({ button }, { 125, 30 });
    }
    else if(name == "RadioButton")
    {
        QRadioButton* button = new QRadioButton("RadioButton");
        button->setObjectName("RadioButton");
        return setLayoutWidget({ button }, { 125, 30 });
    }
    else if(name == "ScrollBar")
    {
        QScrollBar* barH = new QScrollBar(Qt::Horizontal);
        QScrollBar* barV = new QScrollBar(Qt::Vertical);
        barH->setObjectName("ScrollBarH");
        barV->setObjectName("ScrollBarV");
        return setLayoutWidget({ barH, barV }, { 200, 100 });
    }
    else if(name == "Slider")
    {
        QSlider* sliderH = new QSlider(Qt::Horizontal);
        QSlider* sliderV = new QSlider(Qt::Vertical);
        sliderH->setObjectName("SliderH");
        sliderV->setObjectName("SliderV");
        return setLayoutWidget({ sliderH, sliderV }, { 200, 100 });
    }
    else if(name == "SpinBox")
    {
        QSpinBox* spinBox = new QSpinBox;
        spinBox->setObjectName("SpinBox");
        return setLayoutWidget({ spinBox }, { 60, 35 });
    }
    else if(name == "Splitter")
    {
        QSplitter* splitterV = new QSplitter(Qt::Vertical);
        QSplitter* splitterH = new QSplitter(Qt::Horizontal);
        splitterV->setObjectName("SplitterV");
        splitterH->setObjectName("SplitterH");
        splitterV->addWidget(new QPushButton("PushButton1"));
        splitterV->addWidget(new QPushButton("PushButton2"));
        splitterH->addWidget(splitterV);
        splitterH->addWidget(new QPushButton("PushButton3"));
        return setLayoutWidget({ splitterH }, { 250, 110 });
    }
    else if(name == "TabWidget")
    {
        QTabWidget* tab = new QTabWidget;
        tab->addTab(new QWidget, "Widget1");
        tab->addTab(new QWidget, "Widget2");
        tab->addTab(new QWidget, "Widget3");
        tab->setObjectName("TabWidget");
        return setLayoutWidget({ tab }, { 210, 110 });
    }
    else if(name == "TableView") //?
    {
        QTableView* view = new QTableView;
        view->setObjectName("TableView");
        view->resize(200, 100);
        return view;
    }
    else if(name == "TableWidget")
    {
        const int n = 100;
        QStringList list = { "one", "two", "three" };
        QTableWidget* table = new QTableWidget(n, n);
        table->setObjectName("TableWidget");
        table->setHorizontalHeaderLabels(list);
        table->setVerticalHeaderLabels(list);
        for(int i = 0; i < n; i++)
            for(int j = 0; j < n; j++)
                table->setItem(i, j, new QTableWidgetItem(QString("%1, %2").arg(i).arg(j)));
        return setLayoutWidget({ table }, { 210, 110 });
    }
    else if(name == "TextEdit")
    {
        QTextEdit* text = new QTextEdit;
        text->setObjectName("TextEdit");
        return setLayoutWidget({ text }, { 80, 80 });
    }
    else if(name == "TimeEdit")
    {
        QTimeEdit* time = new QTimeEdit;
        time->setObjectName("TimeEdit");
        return setLayoutWidget({ time }, { 80, 80 });
    }
    else if(name == "ToolButton")
    {
        QToolButton* button = new QToolButton;
        button->setText("ToolButton");
        button->setObjectName("ToolButton");
        return setLayoutWidget({ button }, { 95, 25 });
    }
    else if(name == "ToolBox")
    {
        QToolBox* box = new QToolBox;
        box->addItem(new QWidget, "Widget1");
        box->addItem(new QWidget, "Widget2");
        box->addItem(new QWidget, "Widget3");
        box->setObjectName("ToolBox");
        return setLayoutWidget({ box }, { 110, 180 });
    }
    else if(name == "TreeView") //?
    {
        QTreeView* tree = new QTreeView;
        tree->setObjectName("TreeView");
        tree->resize(200, 100);
        return tree;
    }
    else if(name == "TreeWidget")
    {
        QTreeWidget* tree = new QTreeWidget;
        tree->setObjectName("TreeWidget");
        tree->setHeaderLabels({ "Folders", "Used Space" });
        QTreeWidgetItem* item = new QTreeWidgetItem(tree);
        item->setText(0, "Local Disk");
        for(int i = 1; i < 20; i++)
        {
            QTreeWidgetItem* dir = new QTreeWidgetItem(item);
            dir->setText(0, "Directory" + QString::number(i));
            dir->setText(1, QString::number(i) + "MB");
        }
        tree->setItemExpanded(item, true);
        return setLayoutWidget({ tree }, { 210, 110 });
    }
    else if(name == "Widget")
    {
        QWidget* widget = new QWidget;
        widget->setObjectName("Widget");
        return setLayoutWidget({ widget }, { 210, 110 });
    }
    return nullptr;
}
Esempio n. 7
0
void MainWindow::fillMainWindow()
{
    ui->listUV->clear();
    ui->m_tree->clear();

    for(int rows = 0; rows != ui->m_gridcursus->rowCount();rows++){
        ui->m_gridcursus->removeItem(ui->m_gridcursus->itemAtPosition(rows,0));
        ui->m_gridcursus->removeItem(ui->m_gridcursus->itemAtPosition(rows,1));
        ui->m_gridcursus->removeItem(ui->m_gridcursus->itemAtPosition(rows,2));
    }

    /* ONGLET DOSSIER */

    ui->m_tree->setColumnCount(5);
    QTreeWidgetItem* headerItem = new QTreeWidgetItem();
    headerItem->setText(0,QString("Nom"));
    headerItem->setText(1,QString("Titre"));
    headerItem->setText(2,QString("Crédits"));
    headerItem->setText(3,QString("Catégories"));
    headerItem->setText(4,QString("Résultat"));
    ui->m_tree->setHeaderItem(headerItem);
    ui->m_tree->header()->resizeSection(0, 150);
    ui->m_tree->header()->resizeSection(1, 300);
    ui->m_tree->header()->resizeSection(2, 70);
    ui->m_tree->header()->resizeSection(3, 70);
    ui->m_tree->header()->resizeSection(4, 40);
    ui->m_tree->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->m_tree->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->m_tree->setSelectionMode(QAbstractItemView::SingleSelection);



    QList <Dossier *> myDossiers = fac->getDossierDAO()->findAllByEtudiant(currentEtudiant->ID());

    QMap<QString, Cursus*> cursusToCompute;

    for (QList<Dossier *>::const_iterator d = myDossiers.begin(); d != myDossiers.end(); ++d) {

        QTreeWidgetItem *folderWidget = new QTreeWidgetItem(ui->m_tree,QStringList( (*d)->getTitre() ));

        QList<Semestre *> mySemestres = fac->getInscriptionDAO()->findSemestresByDossier( (*d)->ID() );
        for(QList<Semestre *>::const_iterator s = mySemestres.begin(); s != mySemestres.end(); ++s){

            QStringList columns;
            columns << (*s)->getTitre()
                    << (*s)->getComputedCode()
                    << QString::number( fac->getSemestreDAO()->calculEcts( (*s)->ID() ) );
            if((*s)->getCursus()){
                columns << (*s)->getCursus()->getFull();
            }
            if((*d)->isCurrent()){
                cursusToCompute.insert( (*s)->getCursus()->getCode(), (*s)->getCursus() );
            }


            QTreeWidgetItem *semWidget = new QTreeWidgetItem(folderWidget, columns );

            QList<UV *> myUVs = fac->getInscriptionDAO()->findUvsBySemestre( (*s)->ID() );
            qDebug()<<myUVs;
            for(QList<UV *>::const_iterator u = myUVs.begin(); u != myUVs.end(); ++u){

                QStringList columns;
                columns << (*u)->getCode()
                        << (*u)->getTitre()
                        << (*u)->getCreditsString()
                        << (*u)->getCursusString()
                        << fac->getInscriptionDAO()->getResultat((*d)->ID(),(*s)->ID(),(*u)->ID());

                QTreeWidgetItem *uvWidget = new QTreeWidgetItem(semWidget, columns);

            }
        }

    }

    /* ONGLET CURSUS */

    int row = 0;


    for(QMap<QString, Cursus*>::const_iterator i = cursusToCompute.begin(); i != cursusToCompute.end(); ++i){
        QProgressBar* pb = new QProgressBar();
        QLabel *lab = new QLabel(i.value()->getCode());
        pb->setMaximum(i.value()->getEcts());

        ui->m_gridcursus->addWidget(lab,row,0);
        ui->m_gridcursus->addWidget(pb,row,1,1,2);

        row++;
        int somme =0;

        QMap<QString, int> detail = fac->getCursusDAO()->computePercent(i.value()->ID());
        for(QMap<QString, int>::const_iterator j = detail.begin(); j != detail.end(); ++j){
            QProgressBar* pb = new QProgressBar();
            int max =  i.value()->getCredits().find(j.key()).value();
            int val = j.value();
            somme += val;
            pb->setMaximum( max );
            pb->setValue(val);
            ui->m_gridcursus->addWidget(new QLabel(j.key() + "("+QString::number( val )+"/"+QString::number( max )+")"),row,1 );
            ui->m_gridcursus->addWidget(pb,row,2);
            row++;
        }
        pb->setValue(somme);
        lab->setText( i.value()->getCode() + "("+QString::number( somme )+"/"+QString::number( i.value()->getEcts() )+")" );

    }

}
Esempio n. 8
0
Spectrum::Spectrum(QMap<QString, unsigned int> answerCount, QWidget *parent) :
    QWidget(parent)
{
    QVBoxLayout *mainLayout = new QVBoxLayout;
    setLayout(mainLayout);

    QLabel *title = new QLabel(tr("Spectre"));
    title->setAlignment(Qt::AlignCenter);
    mainLayout->addWidget(title);

    QHBoxLayout *extraversionIntroversionLayout = new QHBoxLayout;
    mainLayout->addLayout(extraversionIntroversionLayout);

    QLabel *extraversion = new QLabel(tr("Extraversion"));
    extraversion->setMinimumWidth(100);
    extraversion->setAlignment(Qt::AlignRight);
    extraversionIntroversionLayout->addWidget(extraversion);
    QProgressBar *extraversionProgressBar = new QProgressBar;
    extraversionProgressBar->setInvertedAppearance(true);
    extraversionProgressBar->setMaximum(10);
    extraversionIntroversionLayout->addWidget(extraversionProgressBar);
    QProgressBar *introversionProgressBar = new QProgressBar;
    introversionProgressBar->setMaximum(10);
    extraversionIntroversionLayout->addWidget(introversionProgressBar);
    QLabel *introversion = new QLabel(tr("Introversion"));
    introversion->setMinimumWidth(100);
    extraversionIntroversionLayout->addWidget(introversion);

    QHBoxLayout *sensingIntuitionLayout = new QHBoxLayout;
    mainLayout->addLayout(sensingIntuitionLayout);

    QLabel *sensing = new QLabel(tr("Sensation"));
    sensing->setMinimumWidth(100);
    sensing->setAlignment(Qt::AlignRight);
    sensingIntuitionLayout->addWidget(sensing);
    QProgressBar *sensingProgressBar = new QProgressBar;
    sensingProgressBar->setInvertedAppearance(true);
    sensingProgressBar->setMaximum(20);
    sensingIntuitionLayout->addWidget(sensingProgressBar);
    QProgressBar *intuitionProgressBar = new QProgressBar;
    intuitionProgressBar->setMaximum(20);
    sensingIntuitionLayout->addWidget(intuitionProgressBar);
    QLabel *intuition = new QLabel(tr("Intuition"));
    intuition->setMinimumWidth(100);
    sensingIntuitionLayout->addWidget(intuition);

    QHBoxLayout *thinkingFeelingLayout = new QHBoxLayout;
    mainLayout->addLayout(thinkingFeelingLayout);

    QLabel *thinking = new QLabel(tr("Pensée"));
    thinking->setAlignment(Qt::AlignRight);
    thinking->setMinimumWidth(100);
    thinkingFeelingLayout->addWidget(thinking);
    QProgressBar *thinkingProgressBar = new QProgressBar;
    thinkingProgressBar->setInvertedAppearance(true);
    thinkingProgressBar->setMaximum(20);
    thinkingFeelingLayout->addWidget(thinkingProgressBar);
    QProgressBar *feelingProgressBar = new QProgressBar;
    feelingProgressBar->setMaximum(20);
    thinkingFeelingLayout->addWidget(feelingProgressBar);
    QLabel *feeling = new QLabel(tr("Sentiment"));
    feeling->setMinimumWidth(100);
    thinkingFeelingLayout->addWidget(feeling);

    QHBoxLayout *judgingPerceptionLayout = new QHBoxLayout;
    mainLayout->addLayout(judgingPerceptionLayout);

    QLabel *judging = new QLabel(tr("Jugement"));
    judging->setAlignment(Qt::AlignRight);
    judging->setMinimumWidth(100);
    judgingPerceptionLayout->addWidget(judging);
    QProgressBar *judgingProgressBar = new QProgressBar;
    judgingProgressBar->setInvertedAppearance(true);
    judgingProgressBar->setMaximum(20);
    judgingPerceptionLayout->addWidget(judgingProgressBar);
    QProgressBar *perceptionProgressBar = new QProgressBar;
    perceptionProgressBar->setMaximum(20);
    judgingPerceptionLayout->addWidget(perceptionProgressBar);
    QLabel *perception = new QLabel(tr("Perception"));
    perception->setMinimumWidth(100);
    judgingPerceptionLayout->addWidget(perception);

    QLabel *result = new QLabel(tr("Resultat"));
    result->setAlignment(Qt::AlignCenter);
    mainLayout->addWidget(result);

    QHBoxLayout *resultLayout = new QHBoxLayout;
    mainLayout->addLayout(resultLayout);

    //search result, if there is equal result, we have to
    //set several button.

    QList<QString> firstLetters;
    if (answerCount["extraversion"] < answerCount["introversion"]) {
        firstLetters.append("I");
    } else if (answerCount["extraversion"] > answerCount["introversion"]) {
        firstLetters.append("E");
    } else {
        firstLetters.append("I");
        firstLetters.append("E");
    }

    QList<QString> secondLetters;
    if (answerCount["sensing"] < answerCount["intuition"]) {
        secondLetters.append("N");
    } else if (answerCount["sensing"] > answerCount["intuition"]) {
        secondLetters.append("S");
    } else {
        secondLetters.append("N");
        secondLetters.append("S");
    }

    QList<QString> thirdLetters;
    if (answerCount["thinking"] < answerCount["feeling"]) {
        thirdLetters.append("F");
    } else if (answerCount["thinking"] > answerCount["feeling"]) {
        thirdLetters.append("T");
    } else {
        thirdLetters.append("F");
        thirdLetters.append("T");
    }

    QList<QString> fourthLetters;
    if (answerCount["judging"] < answerCount["perception"]) {
        fourthLetters.append("P");
    } else if (answerCount["judging"] > answerCount["perception"]) {
        fourthLetters.append("J");
    } else {
        fourthLetters.append("P");
        fourthLetters.append("J");
    }

    signalMapper = new QSignalMapper(this);

    //release the cartesian product of letters, and create a button
    //for each case
    for (int i = 0; i < firstLetters.size(); i++) {
        for (int j = 0; j < secondLetters.size(); j++) {
            for (int k = 0; k < thirdLetters.size(); k++) {
                for (int l = 0; l < fourthLetters.size(); l++) {
                    QString type = firstLetters[i] + secondLetters[j] + thirdLetters[k] + fourthLetters[l];
                    QPushButton *resultButton = new QPushButton(type);
                    resultLayout->addWidget(resultButton);
                    connect(resultButton, SIGNAL(clicked()), signalMapper, SLOT(map()));
                    signalMapper->setMapping(resultButton, type);
                }
            }
        }
    }
    connect(signalMapper, SIGNAL(mapped(QString)), this, SLOT(openTypeDescription(QString)));

    extraversionProgressBar->setValue(answerCount["extraversion"]);
    introversionProgressBar->setValue(answerCount["introversion"]);
    sensingProgressBar->setValue(answerCount["sensing"]);
    intuitionProgressBar->setValue(answerCount["intuition"]);
    thinkingProgressBar->setValue(answerCount["thinking"]);
    feelingProgressBar->setValue(answerCount["feeling"]);
    judgingProgressBar->setValue(answerCount["judging"]);
    perceptionProgressBar->setValue(answerCount["perception"]);

    QPushButton *openTypeDescriptionsButton = new QPushButton(tr("Tableau des types"));
    mainLayout->addWidget(openTypeDescriptionsButton);
    connect(openTypeDescriptionsButton, SIGNAL(clicked()), this, SLOT(openTypeDescriptions()));
}
Esempio n. 9
0
void HistoryProgressBar::setProgress(unsigned n)
{
    m_bar->setValue(n);
}
Esempio n. 10
0
void Archive::save(Basket *basket, bool withSubBaskets, const QString &destination)
{
	QDir dir;
	KProgressDialog dialog(0, i18n("Save as Basket Archive"), i18n("Saving as basket archive. Please wait..."), /*Not modal, for password dialogs!*/false);
	dialog.showCancelButton(false);
	dialog.setAutoClose(true);
	dialog.show();
	QProgressBar *progress = dialog.progressBar();
    
    progress->setRange(0,/*Preparation:*/1 + /*Finishing:*/1 + /*Basket:*/1 + /*SubBaskets:*/(withSubBaskets ? Global::bnpView->basketCount(Global::bnpView->listViewItemForBasket(basket)) : 0));
	progress->setValue(0);

	// Create the temporary folder:
	QString tempFolder = Global::savesFolder() + "temp-archive/";
	dir.mkdir(tempFolder);

	// Create the temporary archive file:
	QString tempDestination = tempFolder + "temp-archive.tar.gz";
	KTar tar(tempDestination, "application/x-gzip");
	tar.open(QIODevice::WriteOnly);
	tar.writeDir("baskets", "", "");

    progress->setValue(progress->value()+1);        // Preparation finished
    
	kDebug() << "Preparation finished out of " << progress->maximum();

	// Copy the baskets data into the archive:
	QStringList backgrounds;
	Archive::saveBasketToArchive(basket, withSubBaskets, &tar, backgrounds, tempFolder, progress);

	// Create a Small baskets.xml Document:
	QDomDocument document("basketTree");
	QDomElement root = document.createElement("basketTree");
	document.appendChild(root);
	Global::bnpView->saveSubHierarchy(Global::bnpView->listViewItemForBasket(basket), document, root, withSubBaskets);
	Basket::safelySaveToFile(tempFolder + "baskets.xml", "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + document.toString());
	tar.addLocalFile(tempFolder + "baskets.xml", "baskets/baskets.xml");
	dir.remove(tempFolder + "baskets.xml");

	// Save a Small tags.xml Document:
	QList<Tag*> tags;
	listUsedTags(basket, withSubBaskets, tags);
	Tag::saveTagsTo(tags, tempFolder + "tags.xml");
	tar.addLocalFile(tempFolder + "tags.xml", "tags.xml");
	dir.remove(tempFolder + "tags.xml");

	// Save Tag Emblems (in case they are loaded on a computer that do not have those icons):
	QString tempIconFile = tempFolder + "icon.png";
	for (Tag::List::iterator it = tags.begin(); it != tags.end(); ++it) {
		State::List states = (*it)->states();
		for (State::List::iterator it2 = states.begin(); it2 != states.end(); ++it2) {
			State *state = (*it2);
			QPixmap icon = KIconLoader::global()->loadIcon(
                state->emblem(), KIconLoader::Small, 16, KIconLoader::DefaultState,
                QStringList(), 0L, true
                );
			if (!icon.isNull()) {
				icon.save(tempIconFile, "PNG");
				QString iconFileName = state->emblem().replace('/', '_');
				tar.addLocalFile(tempIconFile, "tag-emblems/" + iconFileName);
			}
		}
	}
	dir.remove(tempIconFile);

	// Finish Tar.Gz Exportation:
	tar.close();

	// Computing the File Preview:
	Basket *previewBasket = basket; // FIXME: Use the first non-empty basket!
	QPixmap previewPixmap(previewBasket->visibleWidth(), previewBasket->visibleHeight());
	QPainter painter(&previewPixmap);
	// Save old state, and make the look clean ("smile, you are filmed!"):
	NoteSelection *selection = previewBasket->selectedNotes();
	previewBasket->unselectAll();
	Note *focusedNote = previewBasket->focusedNote();
	previewBasket->setFocusedNote(0);
	previewBasket->doHoverEffects(0, Note::None);
	// Take the screenshot:
	previewBasket->drawContents(&painter, 0, 0, previewPixmap.width(), previewPixmap.height());
	// Go back to the old look:
	previewBasket->selectSelection(selection);
	previewBasket->setFocusedNote(focusedNote);
	previewBasket->doHoverEffects();
	// End and save our splandid painting:
	painter.end();
	QImage previewImage = previewPixmap.toImage();
	const int PREVIEW_SIZE = 256;
	previewImage = previewImage.scaled(PREVIEW_SIZE, PREVIEW_SIZE, Qt::KeepAspectRatio);
	previewImage.save(tempFolder + "preview.png", "PNG");

	// Finaly Save to the Real Destination file:
	QFile file(destination);
	if (file.open(QIODevice::WriteOnly)) {
		ulong previewSize = QFile(tempFolder + "preview.png").size();
		ulong archiveSize = QFile(tempDestination).size();
		QTextStream stream(&file);
		stream.setCodec("ISO-8859-1");
		stream << "BasKetNP:archive\n"
		       << "version:0.6.1\n"
//		       << "read-compatible:0.6.1\n"
//		       << "write-compatible:0.6.1\n"
		       << "preview*:" << previewSize << "\n";

		stream.flush();
		// Copy the Preview File:
		const unsigned long BUFFER_SIZE = 1024;
		char *buffer = new char[BUFFER_SIZE];
		long sizeRead;
		QFile previewFile(tempFolder + "preview.png");
		if (previewFile.open(QIODevice::ReadOnly)) {
			while ((sizeRead = previewFile.read(buffer, BUFFER_SIZE)) > 0)
				file.write(buffer, sizeRead);
		}
		stream << "archive*:" << archiveSize << "\n";
		stream.flush();

		// Copy the Archive File:
		QFile archiveFile(tempDestination);
		if (archiveFile.open(QIODevice::ReadOnly)) {
			while ((sizeRead = archiveFile.read(buffer, BUFFER_SIZE)) > 0)
				file.write(buffer, sizeRead);
		}
		// Clean Up:
		delete buffer;
		buffer = 0;
		file.close();
	}

    progress->setValue(progress->value()+1); // Finishing finished
	kDebug() << "Finishing finished";

	// Clean Up Everything:
	dir.remove(tempFolder + "preview.png");
	dir.remove(tempDestination);
	dir.rmdir(tempFolder);
}
/*!
 * \brief main
 * Ejercicio 2 Guia de Trabajos Practicos 1
 * \param argc
 * \param argv
 * \return
 */
int main(int argc, char *argv[])
{
    QApplication a( argc, argv );
    QMainWindow main;
    a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) );
    main.showMaximized();
    QMdiArea *mdiArea = new QMdiArea;
    mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    main.setCentralWidget(mdiArea);

    //Inicializo con una semilla aleatoria para la generacion de Aleatorios
    qsrand( QTime::currentTime().msec() );

    // Cargo los parametros del ejercicio
    QSettings parametros( "parametros.cfg", QSettings::IniFormat );

    // Archivo de entrada
    QString archivo = QCoreApplication::applicationDirPath().append( QDir::separator() ).append( parametros.value( "archivo_entrada" ).toString() );

    // Cargo los datos de los archivos que corresponda
    matriz entradas( parametros.value( "cantidad_entradas" ).toInt() );
    QVector<int> salidas;

    qDebug() << endl << "--------------- /Datos del entrenamiento/ -----------------" << endl;
    qWarning() << "Archivo de lectura de datos originales: "<< archivo;
    if( ! leer_archivo_entrenamiento( archivo,
                                      &entradas,
                                      &salidas,
                                      parametros.value( "cantidad_entradas" ).toInt() )  ) {
        qDebug() << "No se pudo encontrar el archivo de entrenamiento! cancelando!";
        abort();
    }

    // particionamos los datos
    Particionador particiones;
    particiones.setearCantidadDatos( entradas.size() );
    particiones.setearCantidadDeParticiones( parametros.value( "cantidad_particiones" ).toInt() );
    particiones.setearPorcentajeEntrenamiento( parametros.value( "porcentaje_entrenamiento" ).toDouble() );
    particiones.setearPorcentajeValidacion( parametros.value("porcentaje_validacion").toDouble() );
    particiones.setearK(parametros.value("k").toInt());
    particiones.particionarDatos();

    // Inicializo la red neuronal
    QVector<int> neuronas_por_capas;
    // Primer parametro es la cantidad de clases
    neuronas_por_capas << parametros.value( "cant_clases" ).toInt();
    neuronas_por_capas << stringAQVector( parametros.value( "codificacion_salida" ).toString() ).size();

    // Inicilizo la red radial

    RedNeuronalRadial red( neuronas_por_capas.at(0),
                           neuronas_por_capas.at(1),
                           parametros.value("cantidad_entradas").toInt(),
                           parametros.value( "cant_clases" ).toInt()  );

    red.setearTasaAprendizaje( parametros.value( "tasa_aprendizaje" ).toDouble() );
    qDebug() << "Tasa de aprendizaje: " << parametros.value( "tasa_aprendizaje" ).toDouble();

    red.setearCodificacion( stringAQVector( parametros.value( "codificacion_salida" ).toString() ) );
    qDebug() << "Codificacion salida: " << red.mostrarCodificacionSalida();

    int max_epocas = parametros.value( "epocas_maximas", 20 ).toInt();
    qDebug() << "Epocas: " << max_epocas;

    double tolerancia_error = parametros.value( "tolerancia_error" ).toDouble();
    qDebug() << "Error de corte: " << ( tolerancia_error ) << "%";

    qDebug() << endl << "---------------- /Comienza el entrenamiento/ ----------------";

    int epoca = 0; /* Contador de epocas */
    double porcentaje_error = 100.0; /* Mucho sino sale */
    int cantidad_particiones_exitosas = 0;

    GraficadorMdi *graf1 = new GraficadorMdi( mdiArea );
    graf1->setearTitulo( QString::fromUtf8( "Porcentaje de error según particion ( entrenamiento )" ) );
    graf1->setearTituloEjeX( QString::fromUtf8( "Epoca" ) );
    graf1->setearTituloEjeY( QString::fromUtf8( "Porcentaje error" ) );
    mdiArea->addSubWindow( graf1 );
    mdiArea->tileSubWindows();

    if( stringAQVector( parametros.value( "codificacion_salida" ).toString() ).size() <= 2 ) {
        GraficadorMdi *graf2 = new GraficadorMdi( mdiArea );
        mdiArea->addSubWindow( graf2 );
        graf2->showMaximized();
        graf2->setearTitulo( "Datos originales" );
        graf2->setearEjesEnGrafico();
        graf2->setearTituloEjeX( " X " );
        graf2->setearTituloEjeY( " y " );
        graf2->agregarPuntosClasificados( entradas, salidas, 0.5 );
        mdiArea->tileSubWindows();
    } else {

        matriz entradas1, entradas2;
        vector salidas1, salidas2;
        for( int i=0; i < entradas.size(); i++ ) {
            vector temp;
            temp.append( entradas.at(i).at(0) );
            temp.append( entradas.at(i).at(1) );
            entradas1.append( temp );
            vector temp2;
            temp2.append( entradas.at(i).at(2) );
            temp2.append( entradas.at(i).at(3) );
            entradas2.append( temp2 );
            salidas1.append( salidas.at( i ) );
            salidas2.append( salidas.at( i ) );
        }

        GraficadorMdi *graf2 = new GraficadorMdi( mdiArea );
        mdiArea->addSubWindow( graf2 );
        graf2->showMaximized();
        graf2->setearTitulo( "Datos originales" );
        //graf2->setearEjesEnGrafico();
        graf2->setearTituloEjeX( "Longitud" );
        graf2->setearTituloEjeY( "Ancho" );
        graf2->agregarPuntosClasificados( entradas1, salidas1, stringAQVector( parametros.value( "codificacion_salida" ).toString() ) );

        GraficadorMdi *graf3 = new GraficadorMdi( mdiArea );
        mdiArea->addSubWindow( graf3 );
        graf3->showMaximized();
        graf3->setearTitulo( "Datos originales" );
        graf3->setearTituloEjeX( "Petalos" );
        graf3->setearTituloEjeY( "Sepalos" );
        graf3->agregarPuntosClasificados( entradas2, salidas2, stringAQVector( parametros.value( "codificacion_salida" ).toString() ) );
        mdiArea->tileSubWindows();

    }

    QDockWidget *dockBarra1 = new QDockWidget( "Progreso de Particiones" );
    main.addDockWidget( Qt::BottomDockWidgetArea, dockBarra1 );
    QProgressBar *PBParticiones = new QProgressBar( dockBarra1 );
    dockBarra1->setWidget( PBParticiones );

    QDockWidget *dockBarra2 = new QDockWidget( "Progreso de Epocas" );
    main.addDockWidget( Qt::BottomDockWidgetArea, dockBarra2 );
    QProgressBar *PBEpocas = new QProgressBar( dockBarra2 );
    dockBarra2->setWidget( PBEpocas );

    QVector<double> errores_particiones;

    PBParticiones->setRange( 0, particiones.cantidadDeParticiones() );
    PBParticiones->setValue( 0 );
    PBParticiones->setFormat( "Particion %v de %m - %p%" );

    PBEpocas->setRange( 0, max_epocas );
    PBEpocas->setFormat( "Epoca %v de %m - %p%" );

    // Mido el tiempo
    QElapsedTimer medidor_tiempo;
    medidor_tiempo.start();

    // Busco los centroides
    red.setearDatosOriginales( entradas, &salidas );
    red.buscarCentroides();

    // Grafico la agrupacion que hizo
    GraficadorMdi *graf = new GraficadorMdi( mdiArea );
    mdiArea->addSubWindow( graf );
    graf->setearTitulo( QString( "Agrupamientos según RB" ) );
    graf->setearEjesEnGrafico();
    graf->setearTituloEjeX( " X " );
    graf->setearTituloEjeY( " Y " );
    red.graficarClusters( graf );
    mdiArea->tileSubWindows();

    //return a.exec();

    for( int p=0; p<particiones.cantidadDeParticiones(); p++ ) {

        Particionador::particion part_local = particiones.getParticion( p );

        qDebug() << endl << "Utilizando Particion: " << p ;

        //pongo nuevamente en los valores iniciales las variables de corte para que entre en todas las particiones
        epoca = 0;
        porcentaje_error = 100.0;
        red.inicializarPesos();

        QVector<double> errores_epocas;

        //std::cout << "Epoca: " << std::endl;
        PBEpocas->setValue( 0 );

        while ( epoca < max_epocas
                && porcentaje_error > tolerancia_error )
        {
            // Inicio la etapa de entrenamiento
            for(int i = 0; i < part_local.entrenamiento.size(); i++ )
            {
                vector prueba = entradas.at( part_local.entrenamiento.at(i) );
                int salida = salidas.at( part_local.entrenamiento.at( i ) );
                red.entrenarCapaNeuronalComun( prueba, salida );
            }

            // Verifico el error
            int errores = 0;
            int correcto = 0;

            for( int i = 0; i < part_local.validacion.size(); i++ ) {
                int pos = part_local.validacion.at( i );
                vector entrada_a_evaluar = entradas.at( pos );
                int salida_red = red.probarPatron( entrada_a_evaluar ) ;
                //double salida_mapeada = red.mapeadorSalidas( salida_red );
                double salida_deseada = salidas.at( pos );
                if( salida_red != salida_deseada  ) {
                    errores++;
                } else {
                    correcto++;
                }
            }
            porcentaje_error = ( (double) errores * 100 ) / (double) part_local.validacion.size();
            errores_epocas.push_back( porcentaje_error );

            // Aumento el contador de epocas
            epoca++;
            PBEpocas->setValue( epoca );

            QApplication::processEvents();

        }

        graf1->agregarCurva( errores_epocas, QString( "Particion %1" ).arg( p ) );

        qDebug() << " Epoca de finalizacion: " << epoca+1 << " - Error de salida de entrenamiento: " << porcentaje_error << "%";

        // Genero las estadisticas con los datos de prueba
        porcentaje_error = 0.0;
        int errores = 0;
        int correcto = 0;
        for( int i = 0; i < part_local.prueba.size(); i++ ) {
            if( red.probarPatron( entradas.at( part_local.prueba.at( i ) ) )  != salidas.at( part_local.prueba.at( i ) ) ) {
                errores++;
            } else {
                correcto++;
            }
        }
        porcentaje_error = ( (double) errores * 100 ) / (double) part_local.prueba.size();
        errores_particiones.push_back( porcentaje_error );

        //Aumento el contador de las no exitosas
        if (epoca < max_epocas)
        {
            cantidad_particiones_exitosas++;
        }

        //qDebug() << errores_epocas;
        qDebug() <<"Terminada particion " << p << "- Error de prueba: " << errores_particiones.at( p ) << "%";

        //Calculo el error promedio y la desviacion estandar para la particion
        //        double error_promedio = 0.0;
        //        double desviacion_estandar = 0.0;
        //        double error_aux = 0.0;


        //        for (int i = 0 ; i < errores_epocas.size() ; i++ ) { error_promedio += errores_epocas.at(i);}
        //        error_promedio /= errores_epocas.size();

        //        qDebug() <<"Error Promedio: " << error_promedio << "%";

        //        for (int i = 0 ; i < errores_epocas.size() ; i++ ) { error_aux += exp(errores_epocas.at(i) - error_promedio);}
        //        desviacion_estandar = sqrt( (1.0 / (errores_epocas.size() - 1.0) ) * error_aux );

        //        qDebug() <<"Desviacion Estandar: " << desviacion_estandar << "%";

        errores_epocas.clear();
        PBParticiones->setValue( PBParticiones->value() + 1 );

        QVector<int> nueva_salida;
        matriz nueva_entrada;
        for( int i=0; i<part_local.prueba.size(); i++ ) {
            nueva_salida.append( red.probarPatron( entradas.at( part_local.prueba.at( i ) ) )  );
            nueva_entrada.append( entradas.at( part_local.prueba.at( i ) ) );
        }

        /*if( particiones.cantidadDeParticiones() <= 5 ) {
            GraficadorMdi *graf = new GraficadorMdi( mdiArea );
            mdiArea->addSubWindow( graf );
            graf->show();
            graf->setearTitulo( QString( "Datos de prueba evaluados con red neuronal - Particion %1" ).arg( p+1 ) );
            graf->setearEjesEnGrafico();
            graf->setearTituloEjeX( " X " );
            graf->setearTituloEjeY( " y " );
            graf->agregarPuntosClasificados( nueva_entrada, nueva_salida, stringAQVector( parametros.value( "codificacion_salida" ).toString() ) );
            mdiArea->tileSubWindows();
        }*/

        QApplication::processEvents();
    }
    qint64 milisegundos = medidor_tiempo.elapsed();

    //std::cout << std::endl;

    // Calculo el promedio de todos los errores
    double sumatoria = 0.0;
    for( int i=0; i<errores_particiones.size(); i++ ) {
        sumatoria+=errores_particiones.at(i);
    }
    qDebug() << endl << "--------------- /Resumen/ -----------------";
    qDebug() << endl << "Error total: " << sumatoria/errores_particiones.size() << "%";
    qDebug() << endl << "Cantidad de Particiones que convergen: " << cantidad_particiones_exitosas ;
    qDebug() << endl << "Cantidad de Particiones sin converger: " << (particiones.cantidadDeParticiones() - cantidad_particiones_exitosas) ;

    //Calculo el error promedio y la desviacion estandar para todo
    double error_promedio = sumatoria/errores_particiones.size();
    double desviacion_estandar = 0.0;
    double error_aux = 0.0;

    for (int i = 0 ; i < errores_particiones.size() ; i++ ) { error_aux += exp(errores_particiones.at(i) - error_promedio);}
    desviacion_estandar = sqrt( (1.0 / (errores_particiones.size() - 1.0) ) * error_aux );

    qDebug() <<"Desviacion Estandar: " << desviacion_estandar << "%";

    qDebug() << "Tiempo medido: " << milisegundos << " ms";

    if( particiones.cantidadDeParticiones() != 1 ) {
        GraficadorMdi *graf3 = new GraficadorMdi( mdiArea );
        mdiArea->addSubWindow( graf3 );
        graf3->showMaximized();
        graf3->setearTitulo( "Errores por particion( datos de prueba )" );
        graf3->setearTituloEjeX( "Particion" );
        graf3->setearTituloEjeY( "Error" );
        graf3->agregarCurva( errores_particiones, "Errores" );
        mdiArea->tileSubWindows();
    }

    QVector<int> nueva_salida;
    for( int i=0; i<entradas.size(); i++ ) {
        nueva_salida.append( red.probarPatron( entradas.at(i) ) );
    }

    matriz entradas1, entradas2;
    vector salidas1, salidas2;
    for( int i=0; i < entradas.size(); i++ ) {
        vector temp;
        temp.append( entradas.at(i).at(0) );
        temp.append( entradas.at(i).at(1) );
        entradas1.append( temp );
        if( entradas.at(i).size() > 2 ) {
            vector temp2;
            temp2.append( entradas.at(i).at(2) );
            temp2.append( entradas.at(i).at(3) );
            entradas2.append( temp2 );
        }
        salidas1.append( nueva_salida.at( i ) );
        salidas2.append( nueva_salida.at( i ) );
    }

    if( stringAQVector( parametros.value( "codificacion_salida" ).toString() ).size() == 2 ) {
        GraficadorMdi *graf4 = new GraficadorMdi( mdiArea );
        mdiArea->addSubWindow( graf4 );
        graf4->showMaximized();
        graf4->setearTitulo( "Datos evaluados con red neuronal" );
        graf4->setearEjesEnGrafico();
        graf4->setearTituloEjeX( " X " );
        graf4->setearTituloEjeY( " y " );
        graf4->agregarPuntosClasificados( entradas, nueva_salida, stringAQVector( parametros.value( "codificacion_salida" ).toString() ) );
        //graf4->agregarPuntosClasificados( entradas, nueva_salida );
    } else if( stringAQVector( parametros.value("codificacion_salida").toString() ).size() == 1 ) {
        GraficadorMdi *graf4 = new GraficadorMdi( mdiArea );
        mdiArea->addSubWindow( graf4 );
        graf4->showMaximized();
        graf4->setearTitulo( "Datos evaluados con red neuronal" );
        graf4->setearEjesEnGrafico();
        graf4->setearTituloEjeX( " X " );
        graf4->setearTituloEjeY( " y " );
        //graf4->agregarPuntosClasificados( entradas, nueva_salida, stringAQVector( parametros.value( "codificacion_salida" ).toString() ) );
        graf4->agregarPuntosClasificados( entradas, nueva_salida );
    } else {
        GraficadorMdi *graf4 = new GraficadorMdi( mdiArea );
        mdiArea->addSubWindow( graf4 );
        graf4->showMaximized();
        graf4->setearTitulo( "Datos evaluados con red neuronal" );
        graf4->setearTituloEjeX( "Largo" );
        graf4->setearTituloEjeY( "Ancho" );
        graf4->agregarPuntosClasificados( entradas1, salidas1, stringAQVector( parametros.value( "codificacion_salida" ).toString() ) );

        GraficadorMdi *graf5 = new GraficadorMdi( mdiArea );
        mdiArea->addSubWindow( graf5 );
        graf5->showMaximized();
        graf5->setearTitulo( "Datos evaluados con red neuronal" );
        graf5->setearTituloEjeX( "Petalos" );
        graf5->setearTituloEjeY( "Sepalos" );
        graf5->agregarPuntosClasificados( entradas2, salidas2, stringAQVector( parametros.value( "codificacion_salida" ).toString() ) );
    }
    mdiArea->tileSubWindows();

    return a.exec();

}
void ProgressListDelegate::updateItemWidgets(const QList<QWidget*> widgets,
        const QStyleOptionViewItem &option,
        const QPersistentModelIndex &index) const
{
    if (!index.isValid()) {
        return;
    }

    QPushButton *pauseResumeButton = static_cast<QPushButton*>(widgets[0]);

    QPushButton *cancelButton = static_cast<QPushButton*>(widgets[1]);
    cancelButton->setToolTip(i18n("Cancel"));

    QProgressBar *progressBar = static_cast<QProgressBar*>(widgets[2]);
    QPushButton *clearButton = static_cast<QPushButton*>(widgets[3]);

    int percent = d->getPercent(index);

    cancelButton->setVisible(percent < 100);
    pauseResumeButton->setVisible(percent < 100);
    clearButton->setVisible(percent > 99);

    KJob::Capabilities capabilities = (KJob::Capabilities) index.model()->data(index, JobView::Capabilities).toInt();
    cancelButton->setEnabled(capabilities & KJob::Killable);
    pauseResumeButton->setEnabled(capabilities & KJob::Suspendable);


    JobView::JobState state = (JobView::JobState) index.model()->data(index, JobView::State).toInt();
    switch (state) {
    case JobView::Running:
        pauseResumeButton->setToolTip(i18n("Pause"));
        pauseResumeButton->setIcon(QIcon::fromTheme(QStringLiteral("media-playback-pause")));
        break;
    case JobView::Suspended:
        pauseResumeButton->setToolTip(i18n("Resume"));
        pauseResumeButton->setIcon(QIcon::fromTheme(QStringLiteral("media-playback-start")));
        break;
    default:
        Q_ASSERT(0);
        break;
    }

    QSize progressBarButtonSizeHint;



    if (percent < 100) {
        QSize cancelButtonSizeHint = cancelButton->sizeHint();

        cancelButton->move(option.rect.width() - d->separatorPixels - cancelButtonSizeHint.width(),
                           option.rect.height() - d->separatorPixels - cancelButtonSizeHint.height());

        QSize pauseResumeButtonSizeHint = pauseResumeButton->sizeHint();


        pauseResumeButton->move(option.rect.width() - d->separatorPixels * 2 - pauseResumeButtonSizeHint.width() - cancelButtonSizeHint.width(),
                                option.rect.height() - d->separatorPixels - pauseResumeButtonSizeHint.height());

        progressBarButtonSizeHint = pauseResumeButtonSizeHint;
    } else {
        progressBarButtonSizeHint = clearButton->sizeHint();
        clearButton->resize(progressBarButtonSizeHint);

        clearButton->move(option.rect.width() - d->separatorPixels - progressBarButtonSizeHint.width(),
                          option.rect.height() - d->separatorPixels - progressBarButtonSizeHint.height());
    }
    progressBar->setValue(percent);

    QFontMetrics fm(QApplication::font());
    QSize progressBarSizeHint = progressBar->sizeHint();

    progressBar->resize(QSize(option.rect.width() - d->getCurrentLeftMargin(fm.height()) - d->rightMargin, progressBarSizeHint.height()));

    progressBar->move(d->getCurrentLeftMargin(fm.height()),
                      option.rect.height() - d->separatorPixels * 2 - progressBarButtonSizeHint.height() - progressBarSizeHint.height());
}
Esempio n. 13
0
void USNavigation::UpdateMeters()
{
  // Get NeedlePosition
  mitk::NavigationData::Pointer needle = this->m_Tracker->GetOutput(0);
  if (! needle->IsDataValid()) return;
  mitk::Point3D needlePosition = needle->GetPosition();
  // Update each meter
  for (int i = 0; i < m_Zones.size(); i++)
  {
    mitk::Point3D zoneOrigin = m_Zones.at(i)->GetData()->GetGeometry()->GetOrigin();
    // calculate absolute distance
    mitk::ScalarType distance = sqrt( pow(zoneOrigin[0] - needlePosition[0], 2) + pow(zoneOrigin[1] - needlePosition[1], 2) + pow(zoneOrigin[2] - needlePosition[2], 2) );
    // Subtract zone size
    float zoneSize;
    m_Zones.at(i)->GetFloatProperty("zone.size", zoneSize);
    distance = distance - zoneSize;

    // Prepare new Style
    float zoneColor[3];
    m_Zones.at(i)->GetColor(zoneColor);
    QString zoneColorString = QString("#%1%2%3").arg(static_cast<unsigned int>(zoneColor[0]*255), 2, 16, QChar('0'))
      .arg(static_cast<unsigned int>(zoneColor[1]*255), 2, 16, QChar('0')).arg(static_cast<unsigned int>(zoneColor[2]*255), 2, 16, QChar('0'));
    QString style = m_RangeMeterStyle;
    QString text =  m_Zones.at(i)->GetName().c_str();
    int value = 0;
    // There Are now four possible Outcomes
    // 1) Needle is inside zone (bad news)
    if (distance < 0)
    {
      style = style.replace("#StartColor#", "red");
      style = style.replace("#StopColor#", "red");
      text  = text + ": VIOLATED";
      value = 100;
    } // 2) Needle is close to Zone
    else if (distance < WARNRANGE)
    {
      style = style.replace("#StartColor#", zoneColorString);
      style = style.replace("#StopColor#", "red");
      text  = text + ": " + QString::number(distance) + " mm";
      value = 100 -  100 * ((float) distance / (float )MAXRANGE);
    } // 3) Needle is away from zone
    else if (distance < MAXRANGE)
    {
      style = style.replace("#StartColor#", zoneColorString);
      style = style.replace("#StopColor#", zoneColorString);
      text  = text + ": " + QString::number(distance) + " mm";
      value = 100 -  100 * ((float) distance / (float )MAXRANGE);
    } // 4) Needle is far away from zone
    else
    {
      style = style.replace("#StartColor#", zoneColorString);
      style = style.replace("#StopColor#", zoneColorString);
      text  = text + ": " + QString::number(distance) + " mm";
      value = 0;
    }

    QProgressBar * meter = this->m_RangeMeters.at(i);
    meter->setStyleSheet(style);
    meter->setFormat(text);
    meter->setValue(value);
  }
}
Esempio n. 14
0
void ProfileWizard::createProfile(int result)
{
  if (_profile_edit->isComplete() )
  {
    bts::profile_config conf;
    conf.firstname  = _profile_edit->ui.first_name->text().toUtf8().constData();
    conf.firstname  = fc::trim( conf.firstname );
    conf.middlename = _profile_edit->ui.middle_name->text().toUtf8().constData();
    conf.middlename = fc::trim( conf.middlename );
    conf.lastname   = _profile_edit->ui.last_name->text().toUtf8().constData();
    conf.lastname   = fc::trim( conf.lastname );
    conf.brainkey   = _profile_edit->ui.brainkey->text().toUtf8().constData();
    conf.brainkey   = fc::trim( conf.brainkey );

    std::string                      password = _profile_edit->ui.local_password1->text().toUtf8().constData();

    std::string profile_name         = conf.firstname + " " + conf.lastname;
    auto                             app = bts::application::instance();
    fc::thread* main_thread = &fc::thread::current();
    QProgressBar* progress = new QProgressBar();
    progress->setWindowTitle( "Creating Profile" );
    progress->setMaximum(1000);
    progress->resize( 640, 20 );
    progress->show();
    int x=(qApp->desktop()->width() - progress->width())/2;
    int y=(qApp->desktop()->height() - progress->height())/2;
    progress->move(x,y);
    auto                             profile = app->create_profile(profile_name, conf, password, 
                                               [=]( double p )
                                               {
                                                  main_thread->async( [=](){ 
                                                                      progress->setValue( 1000*p );
                                                                      qApp->sendPostedEvents();
                                                                      qApp->processEvents();
                                                                      if( p >= 1.0 ) progress->deleteLater();
                                                                      } ).wait();
                                               }
                                               );
    assert(profile != nullptr);

    //store myself as contact
  /*
    std::string dac_id_string = _nym_page->_profile_nym_ui.keyhotee_id->text().toStdString();
    bts::addressbook::wallet_contact myself;
    myself.wallet_index = 0;
    myself.first_name = conf.firstname;
    myself.last_name = conf.lastname;
    myself.set_dac_id(dac_id_string);
    auto priv_key = profile->get_keychain().get_identity_key(myself.dac_id_string);
    myself.public_key = priv_key.get_public_key();
    profile->get_addressbook()->store_contact(myself);

    //store myself as identity
    bts::addressbook::wallet_identity new_identity;
    static_cast<bts::addressbook::contact&>(new_identity) = myself;
    profile->store_identity(new_identity);

    bts::application::instance()->add_receive_key(priv_key);
    */

    _mainApp.displayMainWindow();
  }
}
Esempio n. 15
0
void PinDialog::init( PinFlags flags, const QString &title, TokenData::TokenFlags token )
{
	setMinimumWidth( 350 );
	setWindowModality( Qt::ApplicationModal );

	QLabel *label = new QLabel( this );
	QVBoxLayout *l = new QVBoxLayout( this );
	l->addWidget( label );

	QString _title = title;
	QString text;

	if( token & TokenData::PinFinalTry )
		text += "<font color='red'><b>" + tr("PIN will be locked next failed attempt") + "</b></font><br />";
	else if( token & TokenData::PinCountLow )
		text += "<font color='red'><b>" + tr("PIN has been entered incorrectly one time") + "</b></font><br />";

	text += QString( "<b>%1</b><br />" ).arg( title );
	if( flags & Pin2Type )
	{
		_title = tr("Signing") + " - " + title;
		QString t = flags & PinpadFlag ?
			tr("For using sign certificate enter PIN2 at the reader") :
			tr("For using sign certificate enter PIN2");
		text += tr("Selected action requires sign certificate.") + "<br />" + t;
		regexp.setPattern( "\\d{5,12}" );
	}
	else
	{
		_title = tr("Authentication") + " - " + title;
		QString t = flags & PinpadFlag ?
			tr("For using authentication certificate enter PIN1 at the reader") :
			tr("For using authentication certificate enter PIN1");
		text += tr("Selected action requires authentication certificate.") + "<br />" + t;
		regexp.setPattern( "\\d{4,12}" );
	}
	setWindowTitle( _title );
	label->setText( text );
	Common::setAccessibleName( label );

	if( flags & PinpadFlag )
	{
		setWindowFlags( (windowFlags() | Qt::CustomizeWindowHint) & ~Qt::WindowCloseButtonHint );
		QProgressBar *progress = new QProgressBar( this );
		progress->setRange( 0, 30 );
		progress->setValue( progress->maximum() );
		progress->setTextVisible( false );
		l->addWidget( progress );
		QTimeLine *statusTimer = new QTimeLine( progress->maximum() * 1000, this );
		statusTimer->setCurveShape( QTimeLine::LinearCurve );
		statusTimer->setFrameRange( progress->maximum(), progress->minimum() );
		connect( statusTimer, SIGNAL(frameChanged(int)), progress, SLOT(setValue(int)) );
		connect( this, SIGNAL(startTimer()), statusTimer, SLOT(start()) );
	}
	else if( !(flags & PinpadNoProgressFlag) )
	{
		m_text = new QLineEdit( this );
		m_text->setEchoMode( QLineEdit::Password );
		m_text->setFocus();
		m_text->setValidator( new QRegExpValidator( regexp, m_text ) );
		connect( m_text, SIGNAL(textEdited(QString)), SLOT(textEdited(QString)) );
		l->addWidget( m_text );
		label->setBuddy( m_text );

		QDialogButtonBox *buttons = new QDialogButtonBox(
			QDialogButtonBox::Ok|QDialogButtonBox::Cancel, Qt::Horizontal, this );
		ok = buttons->button( QDialogButtonBox::Ok );
		ok->setAutoDefault( true );
		connect( buttons, SIGNAL(accepted()), SLOT(accept()) );
		connect( buttons, SIGNAL(rejected()), SLOT(reject()) );
		l->addWidget( buttons );

		textEdited( QString() );
	}
}
Esempio n. 16
0
void BackupDialog::restore()
{
    // Get last backup folder:
    KConfig *config = KGlobal::config().data();
    KConfigGroup configGroup(config, "Backups");
    QString folder = configGroup.readEntry("lastFolder", QDir::homePath()) + "/";

    // Ask a file name to the user:
    QString filter = "*.tar.gz|" + i18n("Tar Archives Compressed by Gzip") + "\n*|" + i18n("All Files");
    QString path = KFileDialog::getOpenFileName(folder, filter, this, i18n("Open Basket Archive"));
    if (path.isEmpty()) // User has canceled
        return;

    // Before replacing the basket data folder with the backup content, we safely backup the current baskets to the home folder.
    // So if the backup is corrupted or something goes wrong while restoring (power cut...) the user will be able to restore the old working data:
    QString safetyPath = Backup::newSafetyFolder();
    FormatImporter copier;
    copier.moveFolder(Global::savesFolder(), safetyPath);

    // Add the README file for user to cancel a bad restoration:
    QString readmePath = safetyPath + i18n("README.txt");
    QFile file(readmePath);
    if (file.open(QIODevice::WriteOnly)) {
        QTextStream stream(&file);
        stream << i18n("This is a safety copy of your baskets like they were before you started to restore the backup %1.", KUrl(path).fileName()) + "\n\n"
        << i18n("If the restoration was a success and you restored what you wanted to restore, you can remove this folder.") + "\n\n"
        << i18n("If something went wrong during the restoration process, you can re-use this folder to store your baskets and nothing will be lost.") + "\n\n"
        << i18n("Choose \"Basket\" -> \"Backup & Restore...\" -> \"Use Another Existing Folder...\" and select that folder.") + "\n";
        file.close();
    }

    QString message =
        "<p><nobr>" + i18n("Restoring <b>%1</b>. Please wait...", KUrl(path).fileName()) + "</nobr></p><p>" +
        i18n("If something goes wrong during the restoration process, read the file <b>%1</b>.", readmePath);

    KProgressDialog *dialog = new KProgressDialog(0, i18n("Restore Baskets"), message);
    dialog->setModal(/*modal=*/true);
    dialog->setAllowCancel(false);
    dialog->setAutoClose(true);
    dialog->show();
    QProgressBar *progress = dialog->progressBar();
    progress->setRange(0, 0/*Busy/Undefined*/);
    progress->setValue(0);
    progress->setTextVisible(false);

    // Uncompress:
    RestoreThread thread(path, Global::savesFolder());
    thread.start();
    while (thread.isRunning()) {
        progress->setValue(progress->value() + 1); // Or else, the animation is not played!
        kapp->processEvents();
        usleep(300); // Not too long because if the restore process is finished, we wait for nothing
    }

    dialog->hide(); // The restore is finished, do not continue to show it while telling the user the application is going to be restarted
    delete dialog; // If we only hidden it, it reappeared just after having restored a small backup... Very strange.
    dialog = 0;    // This was annoying since it is modal and the "BasKet Note Pads is going to be restarted" message was not reachable.
    //kapp->processEvents();

    // Check for errors:
    if (!thread.success()) {
        // Restore the old baskets:
        QDir dir;
        dir.remove(readmePath);
        copier.moveFolder(safetyPath, Global::savesFolder());
        // Tell the user:
        KMessageBox::error(0, i18n("This archive is either not a backup of baskets or is corrupted. It cannot be imported. Your old baskets have been preserved instead."), i18n("Restore Error"));
        return;
    }

    // Note: The safety backup is not removed now because the code can has been wrong, somehow, or the user perhapse restored an older backup by error...
    //       The restore process will not be called very often (it is possible it will only be called once or twice arround the world during the next years).
    //       So it is rare enough to force the user to remove the safety folder, but keep him in control and let him safely recover from restoration errors.

    Backup::setFolderAndRestart(Global::savesFolder()/*No change*/, i18n("Your backup has been successfuly restored to <b>%1</b>. %2 is going to be restarted to take this change into account."));
}
void MetaEditorSupportPlugin::generateEditorWithQrmc()
{
	qrmc::MetaCompiler metaCompiler(qApp->applicationDirPath() + "/../qrmc", mLogicalRepoApi);

	IdList const metamodels = mLogicalRepoApi->children(Id::rootId());

	QProgressBar *progress = new QProgressBar(mMainWindowInterface->windowWidget());
	progress->show();
	int const progressBarWidth = 240;
	int const progressBarHeight = 20;

	QApplication::processEvents();
	QRect const screenRect = qApp->desktop()->availableGeometry();
	progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
	progress->setFixedWidth(progressBarWidth);
	progress->setFixedHeight(progressBarHeight);
	progress->setRange(0, 100);

	int forEditor = 60 / metamodels.size();

	foreach (Id const &key, metamodels) {
		QString const objectType = key.element();
		if (objectType == "MetamodelDiagram" && mLogicalRepoApi->isLogicalElement(key)) {
			QString nameOfTheDirectory = mLogicalRepoApi->stringProperty(key, "name of the directory");
			QString nameOfMetamodel = mLogicalRepoApi->stringProperty(key, "name");
			QString nameOfPlugin = nameOfTheDirectory.split("/").last();

			if (QMessageBox::question(mMainWindowInterface->windowWidget()
					, tr("loading..")
					, QString(tr("Do you want to compile and load editor %1?")).arg(nameOfPlugin)
					, QMessageBox::Yes, QMessageBox::No)
					== QMessageBox::No)
			{
				continue;
			}

			progress->setValue(5);

			if (!metaCompiler.compile(nameOfMetamodel)) { // generating source code for all metamodels
				QMessageBox::warning(mMainWindowInterface->windowWidget()
						, tr("error")
						, tr("Cannot generate source code for editor ") + nameOfPlugin);
				continue;
			}
			progress->setValue(20);

			QProcess builder;
			builder.setWorkingDirectory("../qrmc/plugins");
			builder.start(SettingsManager::value("pathToQmake").toString());
			qDebug()  << "qmake";
			if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
				progress->setValue(40);

				builder.start(SettingsManager::value("pathToMake").toString());

				bool finished = builder.waitForFinished(100000);
				qDebug()  << "make";
				if (finished && (builder.exitCode() == 0)) {
					qDebug()  << "make ok";

					progress->setValue(progress->value() + forEditor / 2);

					QString normalizedName = nameOfPlugin.at(0).toUpper() + nameOfPlugin.mid(1);
					if (!nameOfPlugin.isEmpty()) {
						if (!mMainWindowInterface->unloadPlugin(normalizedName)) {
							QMessageBox::warning(mMainWindowInterface->windowWidget()
									, tr("error")
									, tr("cannot unload plugin ") + normalizedName);
							progress->close();
							delete progress;
							continue;
						}
					}

					QString const generatedPluginFileName = SettingsManager::value("prefix").toString()
							+ nameOfPlugin
							+ "."
							+ SettingsManager::value("pluginExtension").toString()
							;

					if (mMainWindowInterface->loadPlugin(generatedPluginFileName, normalizedName)) {
						progress->setValue(progress->value() + forEditor / 2);
					}
				}
				progress->setValue(100);
			}
		}
	}