void TaskSketcherSolverAdvanced::updateDefaultMethodParameters(void)
{
    ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/SolverAdvanced");

    switch(ui->comboBoxDefaultSolver->currentIndex())
    {
    case 0: // BFGS
        ui->labelSolverParam1->setText(QString::fromLatin1(""));
        ui->labelSolverParam2->setText(QString::fromLatin1(""));
        ui->labelSolverParam3->setText(QString::fromLatin1(""));
        ui->lineEditSolverParam1->clear();
        ui->lineEditSolverParam2->clear();
        ui->lineEditSolverParam3->clear();
        ui->lineEditSolverParam1->setDisabled(true);
        ui->lineEditSolverParam2->setDisabled(true);
        ui->lineEditSolverParam3->setDisabled(true);
        break;
    case 1: // LM
    {
        ui->labelSolverParam1->setText(QString::fromLatin1("Eps"));
        ui->labelSolverParam2->setText(QString::fromLatin1("Eps1"));
        ui->labelSolverParam3->setText(QString::fromLatin1("Tau"));
        ui->lineEditSolverParam1->setEnabled(true);
        ui->lineEditSolverParam2->setEnabled(true);
        ui->lineEditSolverParam3->setEnabled(true);
        double eps = ::atof(hGrp->GetASCII("LM_eps",QString::number(LM_EPS).toUtf8()).c_str());
        double eps1 = ::atof(hGrp->GetASCII("LM_eps1",QString::number(LM_EPS1).toUtf8()).c_str());
        double tau = ::atof(hGrp->GetASCII("LM_tau",QString::number(LM_TAU).toUtf8()).c_str());
        ui->lineEditSolverParam1->setText(QString::number(eps).remove(QString::fromLatin1("+").replace(QString::fromLatin1("e0"),QString::fromLatin1("E")).toUpper()));
        ui->lineEditSolverParam2->setText(QString::number(eps1).remove(QString::fromLatin1("+").replace(QString::fromLatin1("e0"),QString::fromLatin1("E")).toUpper()));
        ui->lineEditSolverParam3->setText(QString::number(tau).remove(QString::fromLatin1("+").replace(QString::fromLatin1("e0"),QString::fromLatin1("E")).toUpper()));
        sketchView->getSketchObject()->getSolvedSketch().setLM_eps(eps);
        sketchView->getSketchObject()->getSolvedSketch().setLM_eps1(eps1);
        sketchView->getSketchObject()->getSolvedSketch().setLM_tau(tau);
        break;
    }
    case 2: // DogLeg
    {
        ui->labelSolverParam1->setText(QString::fromLatin1("Tolg"));
        ui->labelSolverParam2->setText(QString::fromLatin1("Tolx"));
        ui->labelSolverParam3->setText(QString::fromLatin1("Tolf"));
        ui->lineEditSolverParam1->setEnabled(true);
        ui->lineEditSolverParam2->setEnabled(true);
        ui->lineEditSolverParam3->setEnabled(true);
        double tolg = ::atof(hGrp->GetASCII("DL_tolg",QString::number(DL_TOLG).toUtf8()).c_str());
        double tolx = ::atof(hGrp->GetASCII("DL_tolx",QString::number(DL_TOLX).toUtf8()).c_str());
        double tolf = ::atof(hGrp->GetASCII("DL_tolf",QString::number(DL_TOLF).toUtf8()).c_str());
        ui->lineEditSolverParam1->setText(QString::number(tolg).remove(QString::fromLatin1("+").replace(QString::fromLatin1("e0"),QString::fromLatin1("E")).toUpper()));
        ui->lineEditSolverParam2->setText(QString::number(tolx).remove(QString::fromLatin1("+").replace(QString::fromLatin1("e0"),QString::fromLatin1("E")).toUpper()));
        ui->lineEditSolverParam3->setText(QString::number(tolf).remove(QString::fromLatin1("+").replace(QString::fromLatin1("e0"),QString::fromLatin1("E")).toUpper()));
        sketchView->getSketchObject()->getSolvedSketch().setDL_tolg(tolg);
        sketchView->getSketchObject()->getSolvedSketch().setDL_tolf(tolf);
        sketchView->getSketchObject()->getSolvedSketch().setDL_tolx(tolx);
        break;
    }
    }
}
void StdCmdFreeCADFAQ::activated(int iMsg)
{
    ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Websites");
    std::string url = hURLGrp->GetASCII("FAQ", "http://www.freecadweb.org/wiki/index.php?title=FAQ");
    hURLGrp->SetASCII("FAQ", url.c_str());
    OpenURLInBrowser(url.c_str());
}
void DlgGeneralImp::saveSettings()
{
    int index = AutoloadModuleCombo->currentIndex();
    QVariant data = AutoloadModuleCombo->itemData(index);
    QString startWbName = data.toString();
    App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")->
                          SetASCII("AutoloadModule", startWbName.toAscii());
    
    AutoloadTabCombo->onSave();
    RecentFiles->onSave();
    SplashScreen->onSave();

    // set new user defined style
    (void)QApplication::setStyle(WindowStyle->currentText());

    setRecentFileSize();
    ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("General");
    QString lang = QLocale::languageToString(QLocale::system().language());
    QByteArray language = hGrp->GetASCII("Language", (const char*)lang.toAscii()).c_str();
    QByteArray current = Languages->itemData(Languages->currentIndex()).toByteArray();
    if (current != language)
    {
        hGrp->SetASCII("Language", current.constData());
        Translator::instance()->activateLanguage(current.constData());
    }

    QVariant size = this->toolbarIconSize->itemData(this->toolbarIconSize->currentIndex());
    int pixel = size.toInt();
    hGrp->SetInt("ToolbarIconSize", pixel);
    getMainWindow()->setIconSize(QSize(pixel,pixel));
}
예제 #4
0
void DlgSettings3DViewImp::loadSettings()
{
    checkBoxZoomAtCursor->onRestore();
    checkBoxInvertZoom->onRestore();
    spinBoxZoomStep->onRestore();
    checkBoxAntiAliasing->onRestore();
    CheckBox_CornerCoordSystem->onRestore();
    CheckBox_ShowFPS->onRestore();
    CheckBox_UseAutoRotation->onRestore();
    FloatSpinBox_EyeDistance->onRestore();
    checkBoxBacklight->onRestore();
    backlightColor->onRestore();
    sliderIntensity->onRestore();
    radioPerspective->onRestore();
    radioOrthographic->onRestore();

    ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath
                                ("User parameter:BaseApp/Preferences/View");
    std::string model = hGrp->GetASCII("NavigationStyle",CADNavigationStyle::getClassTypeId().getName());
    int index = comboNavigationStyle->findData(QByteArray(model.c_str()));
    if (index > -1) comboNavigationStyle->setCurrentIndex(index);

    index = comboOrbitStyle->currentIndex();
    index = hGrp->GetInt("OrbitStyle", index);
    index = Base::clamp(index, 0, comboOrbitStyle->count()-1);
    comboOrbitStyle->setCurrentIndex(index);
}
void DlgGeneralImp::loadSettings()
{
    std::string start = App::Application::Config()["StartWorkbench"];
    start = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")->
                                  GetASCII("AutoloadModule", start.c_str());
    QString startWbName = QLatin1String(start.c_str());
    AutoloadModuleCombo->setCurrentIndex(AutoloadModuleCombo->findData(startWbName));

    AutoloadTabCombo->onRestore();
    RecentFiles->onRestore();
    SplashScreen->onRestore();

    // fill up styles
    //
    QStringList styles = QStyleFactory::keys();
    WindowStyle->addItems(styles);
    QString style = QApplication::style()->objectName().toLower();
    int i=0;
    for (QStringList::ConstIterator it = styles.begin(); it != styles.end(); ++it, i++) {
        if (style == (*it).toLower()) {
            WindowStyle->setCurrentIndex( i );
            break;
        }
    }

    // search for the language files
    ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("General");
    QString lang = QLocale::languageToString(QLocale::system().language());
    QByteArray language = hGrp->GetASCII("Language", (const char*)lang.toAscii()).c_str();
    int index = 1;
    Languages->addItem(QString::fromAscii("English"), QByteArray("English"));
    TStringMap list = Translator::instance()->supportedLocales();
    for (TStringMap::iterator it = list.begin(); it != list.end(); ++it, index++) {
        QLocale locale(QString::fromAscii(it->second.c_str()));
        QByteArray lang = it->first.c_str();
        QString langname = QString::fromAscii(lang.constData());
#if QT_VERSION >= 0x040800
        QString native = locale.nativeLanguageName();
        if (!native.isEmpty()) {
            if (native[0].isLetter())
                native[0] = native[0].toUpper();
            langname = native;
        }
#endif
        Languages->addItem(langname, lang);
        if (language == lang) {
            Languages->setCurrentIndex(index);
        }
    }

    int size = QApplication::style()->pixelMetric(QStyle::PM_ToolBarIconSize);
    int current = getMainWindow()->iconSize().width();
    this->toolbarIconSize->addItem(tr("Default (%1 x %1)").arg(size), QVariant((int)size));
    this->toolbarIconSize->addItem(tr("Small (%1 x %1)").arg(16), QVariant((int)16));
    this->toolbarIconSize->addItem(tr("Large (%1 x %1)").arg(32), QVariant((int)32));
    this->toolbarIconSize->addItem(tr("Extra large (%1 x %1)").arg(48), QVariant((int)48));
    index = this->toolbarIconSize->findData(QVariant(current));
    if (index > -1) this->toolbarIconSize->setCurrentIndex(index);
}
예제 #6
0
void StdCmdFreeCADFAQ::activated(int iMsg)
{
    std::string defaulturl = QCoreApplication::translate(this->className(),"http://www.freecadweb.org/wiki/index.php?title=FAQ").toStdString();
    ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Websites");
    std::string url = hURLGrp->GetASCII("FAQ", defaulturl.c_str());
    hURLGrp->SetASCII("FAQ", url.c_str());
    OpenURLInBrowser(url.c_str());
}
예제 #7
0
SheetModel::SheetModel(Sheet *_sheet, QObject *parent)
    : QAbstractTableModel(parent)
    , sheet(_sheet)
{
    cellUpdatedConnection = sheet->cellUpdated.connect(bind(&SheetModel::cellUpdated, this, _1));

    ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Spreadsheet");
    aliasBgColor = QColor(Base::Tools::fromStdString(hGrp->GetASCII("AliasedCellBackgroundColor", "#feff9e")));
}
예제 #8
0
void StdCmdFreeCADForum::activated(int iMsg)
{
    Q_UNUSED(iMsg); 
    std::string defaulturl = QCoreApplication::translate(this->className(),"http://forum.freecadweb.org").toStdString();
    ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Websites");
    std::string url = hURLGrp->GetASCII("UserForum", defaulturl.c_str());
    hURLGrp->SetASCII("UserForum", url.c_str());
    OpenURLInBrowser(url.c_str());
}
예제 #9
0
QStringList DlgWorkbenchesImp::load_disabled_workbenches()
{
    QString disabled_wbs;
    QStringList disabled_wbs_list;
    ParameterGrp::handle hGrp;

    hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Workbenches");
    disabled_wbs = QString::fromStdString(hGrp->GetASCII("Disabled", ""));
    disabled_wbs_list = disabled_wbs.split(QLatin1String(","), QString::SkipEmptyParts);

    return disabled_wbs_list;
}
void DlgSettings3DViewImp::loadSettings()
{
    checkBoxZoomAtCursor->onRestore();
    checkBoxInvertZoom->onRestore();
    spinBoxZoomStep->onRestore();
    checkBoxDragAtCursor->onRestore();
    CheckBox_CornerCoordSystem->onRestore();
    CheckBox_ShowFPS->onRestore();
    CheckBox_useVBO->onRestore();
    CheckBox_NaviCube->onRestore();
    CheckBox_UseAutoRotation->onRestore();
    FloatSpinBox_EyeDistance->onRestore();
    checkBoxBacklight->onRestore();
    backlightColor->onRestore();
    sliderIntensity->onRestore();
    radioPerspective->onRestore();
    radioOrthographic->onRestore();

    ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath
        ("User parameter:BaseApp/Preferences/View");
    std::string model = hGrp->GetASCII("NavigationStyle",CADNavigationStyle::getClassTypeId().getName());
    int index = comboNavigationStyle->findData(QByteArray(model.c_str()));
    if (index > -1) comboNavigationStyle->setCurrentIndex(index);

    index = hGrp->GetInt("OrbitStyle", int(NavigationStyle::Trackball));
    index = Base::clamp(index, 0, comboOrbitStyle->count()-1);
    comboOrbitStyle->setCurrentIndex(index);
    
    index = hGrp->GetInt("AntiAliasing", int(Gui::View3DInventorViewer::None));
    index = Base::clamp(index, 0, comboAliasing->count()-1);
    comboAliasing->setCurrentIndex(index);
    // connect after setting current item of the combo box
    connect(comboAliasing, SIGNAL(currentIndexChanged(int)),
            this, SLOT(onAliasingChanged(int)));

    index = hGrp->GetInt("CornerNaviCube", 1);
    naviCubeCorner->setCurrentIndex(index);

    int const current = hGrp->GetInt("MarkerSize", 9L);
    this->boxMarkerSize->addItem(tr("5px"), QVariant(5));
    this->boxMarkerSize->addItem(tr("7px"), QVariant(7));
    this->boxMarkerSize->addItem(tr("9px"), QVariant(9));
    this->boxMarkerSize->addItem(tr("11px"), QVariant(11));
    this->boxMarkerSize->addItem(tr("13px"), QVariant(13));
    this->boxMarkerSize->addItem(tr("15px"), QVariant(15));
    index = this->boxMarkerSize->findData(QVariant(current));
    if (index < 0) index = 2;
    this->boxMarkerSize->setCurrentIndex(index);
}
예제 #11
0
void DlgParameterImp::showEvent(QShowEvent* )
{
    ParameterGrp::handle hGrp = App::GetApplication().GetUserParameter()
        .GetGroup("BaseApp")->GetGroup("Preferences");
    hGrp = hGrp->GetGroup("ParameterEditor");
    std::string buf = hGrp->GetASCII("Geometry", "");
    if (!buf.empty()) {
        int x1, y1, x2, y2;
        char sep;
        std::stringstream str(buf);
        str >> sep >> x1
            >> sep >> y1
            >> sep >> x2
            >> sep >> y2;
        QRect rect;
        rect.setCoords(x1, y1, x2, y2);
        this->setGeometry(rect);
    }
예제 #12
0
QStringList DlgWorkbenchesImp::load_enabled_workbenches()
{
    QString enabled_wbs;
    QStringList enabled_wbs_list;
    ParameterGrp::handle hGrp;

    hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Workbenches");
    enabled_wbs = QString::fromStdString(hGrp->GetASCII("Enabled", all_workbenches.toStdString().c_str()).c_str());
    enabled_wbs_list = enabled_wbs.split(QLatin1String(","), QString::SkipEmptyParts);

    if (enabled_wbs_list.at(0) == all_workbenches) {
        enabled_wbs_list.removeFirst();
        QStringList workbenches = Application::Instance->workbenches();
        for (QStringList::Iterator it = workbenches.begin(); it != workbenches.end(); ++it) {
            enabled_wbs_list.append(*it);
        }
        enabled_wbs_list.sort();
    }
    return enabled_wbs_list;
}
예제 #13
0
void StdCmdOnlineHelpWebsite::activated(int iMsg)
{
    ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/OnlineHelp");
    std::string url = hURLGrp->GetASCII("DownloadURL", "http://www.freecadweb.org/wiki/index.php?title=Online_Help_Toc");
    OpenURLInBrowser(url.c_str());
}
예제 #14
0
void StdCmdExportGraphviz::activated(int iMsg)
{
    App::Document* doc = App::GetApplication().getActiveDocument();
    std::stringstream str;
    doc->exportGraphviz(str);

    ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Paths");
    QProcess proc;
    QStringList args;
    args << QLatin1String("-Tpng");
#ifdef FC_OS_LINUX
    QString path = QString::fromUtf8(hGrp->GetASCII("Graphviz", "/usr/bin").c_str());
#else
    QString path = QString::fromUtf8(hGrp->GetASCII("Graphviz").c_str());
#endif
    bool pathChanged = false;
#ifdef FC_OS_WIN32
    QString exe = QString::fromAscii("\"%1/dot\"").arg(path);
#else
    QString exe = QString::fromAscii("%1/dot").arg(path);
#endif
    proc.setEnvironment(QProcess::systemEnvironment());
    do {
        proc.start(exe, args);
        if (!proc.waitForStarted()) {
            int ret = QMessageBox::warning(getMainWindow(),
                                           qApp->translate("Std_ExportGraphviz","Graphviz not found"),
                                           qApp->translate("Std_ExportGraphviz","Graphviz couldn't be found on your system.\n"
                                                   "Do you want to specify its installation path if it's already installed?"),
                                           QMessageBox::Yes, QMessageBox::No);
            if (ret == QMessageBox::No)
                return;
            path = QFileDialog::getExistingDirectory(Gui::getMainWindow(),
                    qApp->translate("Std_ExportGraphviz","Graphviz installation path"));
            if (path.isEmpty())
                return;
            pathChanged = true;
#ifdef FC_OS_WIN32
            exe = QString::fromAscii("\"%1/dot\"").arg(path);
#else
            exe = QString::fromAscii("%1/dot").arg(path);
#endif
        }
        else {
            if (pathChanged)
                hGrp->SetASCII("Graphviz", (const char*)path.toUtf8());
            break;
        }
    }
    while(true);

    proc.write(str.str().c_str(), str.str().size());
    proc.closeWriteChannel();
    if (!proc.waitForFinished())
        return;

    QPixmap px;
    if (px.loadFromData(proc.readAll(), "PNG")) {
        Gui::ImageView* view = new Gui::ImageView(px);
        view->setWindowTitle(qApp->translate("Std_ExportGraphviz","Dependency graph"));
        getMainWindow()->addWindow(view);
    }
    else {
        QMessageBox::warning(getMainWindow(),
                             qApp->translate("Std_ExportGraphviz","Graphviz failed"),
                             qApp->translate("Std_ExportGraphviz","Graphviz failed to create an image file"));
    }
}
void StdCmdDownloadOnlineHelp::activated(int iMsg)
{
    if (!wget->isDownloading()) {
        ParameterGrp::handle hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp");
        hGrp = hGrp->GetGroup("Preferences")->GetGroup("OnlineHelp");
        std::string url = hGrp->GetASCII("DownloadURL", "www.freecadweb.org/wiki/");
        std::string prx = hGrp->GetASCII("ProxyText", "");
        bool bUseProxy  = hGrp->GetBool ("UseProxy", false);
        bool bAuthor    = hGrp->GetBool ("Authorize", false);

        if (bUseProxy) {
            QString username = QString::null;
            QString password = QString::null;

            if (bAuthor) {
                QDialog dlg(getMainWindow());
                dlg.setModal(true);
                Ui_DlgAuthorization ui;
                ui.setupUi(&dlg);

                if (dlg.exec() == QDialog::Accepted) {
                    username = ui.username->text();
                    password = ui.password->text();
                }
            }

            wget->setProxy(QString::fromAscii(prx.c_str()), username, password);
        }

        int loop=3;
        bool canStart = false;

        // set output directory
        QString path = QString::fromUtf8(App::GetApplication().GetHomePath());
        path += QString::fromAscii("/doc/");
        ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/OnlineHelp");
        path = QString::fromUtf8(hURLGrp->GetASCII( "DownloadLocation", path.toAscii() ).c_str());

        while (loop > 0) {
            loop--;
            QFileInfo fi( path);
            if (!fi.exists()) {
                if (QMessageBox::critical(getMainWindow(), tr("Non-existing directory"), 
                     tr("The directory '%1' does not exist.\n\n"
                        "Do you want to specify an existing directory?").arg(fi.filePath()), 
                     QMessageBox::Yes|QMessageBox::Default, QMessageBox::No|QMessageBox::Escape) != 
                     QMessageBox::Yes)
                {
                    // exit the command
                    return;
                }
                else 
                {
                    path = FileDialog::getExistingDirectory();
                    if ( path.isEmpty() )
                        return;
                }
            }

            if (!fi.permission( QFile::WriteUser)) {
                if (QMessageBox::critical(getMainWindow(), tr("Missing permission"), 
                     tr("You don't have write permission to '%1'\n\n"
                        "Do you want to specify another directory?").arg(fi.filePath()), 
                     QMessageBox::Yes|QMessageBox::Default, QMessageBox::No|QMessageBox::Escape) != 
                     QMessageBox::Yes)
                {
                    // exit the command
                    return;
                }
                else {
                    path = FileDialog::getExistingDirectory();
                    if ( path.isEmpty() )
                        return;
                }
            }
            else {
                wget->setOutputDirectory( path );
                canStart = true;
                break;
            }
        }

        if (canStart) {
            bool ok = wget->startDownload(QString::fromAscii(url.c_str()));
            if ( ok == false )
                Base::Console().Error("The tool 'wget' couldn't be found. Please check your installation.");
            else if ( wget->isDownloading() && _pcAction )
                _pcAction->setText(tr("Stop downloading"));
        }
    }
    else // kill the process now
    {
        wget->abort();
    }
}
예제 #16
0
int main( int argc, char ** argv )
{
#if defined (FC_OS_LINUX) || defined(FC_OS_BSD)
    // Make sure to setup the Qt locale system before setting LANG and LC_ALL to C.
    // which is needed to use the system locale settings.
    (void)QLocale::system();
#if QT_VERSION < 0x050000
    // http://www.freecadweb.org/tracker/view.php?id=399
    // Because of setting LANG=C the Qt automagic to use the correct encoding
    // for file names is broken. This is a workaround to force the use of UTF-8 encoding
    QFile::setEncodingFunction(myEncoderFunc);
    QFile::setDecodingFunction(myDecoderFunc);
#endif
    // See https://forum.freecadweb.org/viewtopic.php?f=18&t=20600
    // See Gui::Application::runApplication()
    putenv("LC_NUMERIC=C");
    putenv("PYTHONPATH=");
#elif defined(FC_OS_MACOSX)
    (void)QLocale::system();
    putenv("PYTHONPATH=");
#else
    _putenv("PYTHONPATH=");
    // https://forum.freecadweb.org/viewtopic.php?f=4&t=18288
    // https://forum.freecadweb.org/viewtopic.php?f=3&t=20515
    const char* fc_py_home = getenv("FC_PYTHONHOME");
    if (fc_py_home)
        _putenv_s("PYTHONHOME", fc_py_home);
    else
        _putenv("PYTHONHOME=");
#endif

#if defined (FC_OS_WIN32)
    int argc_ = argc;
    QVector<QByteArray> data;
    QVector<char *> argv_;

    // get the command line arguments as unicode string
    {
        QCoreApplication app(argc, argv);
        QStringList args = app.arguments();
        for (QStringList::iterator it = args.begin(); it != args.end(); ++it) {
            data.push_back(it->toUtf8());
            argv_.push_back(data.back().data());
        }
        argv_.push_back(0); // 0-terminated string
    }
#endif

#if PY_MAJOR_VERSION >= 3
#if defined(_MSC_VER) && _MSC_VER <= 1800
    // See InterpreterSingleton::init
    Redirection out(stdout), err(stderr), inp(stdin);
#endif
#endif // PY_MAJOR_VERSION

    // Name and Version of the Application
    App::Application::Config()["ExeName"] = "FreeCAD";
    App::Application::Config()["ExeVendor"] = "FreeCAD";
    App::Application::Config()["AppDataSkipVendor"] = "true";
    App::Application::Config()["MaintainerUrl"] = "http://www.freecadweb.org/wiki/Main_Page";

    // set the banner (for logging and console)
    App::Application::Config()["CopyrightInfo"] = sBanner;
    App::Application::Config()["AppIcon"] = "freecad";
    App::Application::Config()["SplashScreen"] = "freecadsplash";
    App::Application::Config()["StartWorkbench"] = "StartWorkbench";
    //App::Application::Config()["HiddenDockWindow"] = "Property editor";
    App::Application::Config()["SplashAlignment" ] = "Bottom|Left";
    App::Application::Config()["SplashTextColor" ] = "#ffffff"; // white
    App::Application::Config()["SplashInfoColor" ] = "#c8c8c8"; // light grey

    try {
        // Init phase ===========================================================
        // sets the default run mode for FC, starts with gui if not overridden in InitConfig...
        App::Application::Config()["RunMode"] = "Gui";
        App::Application::Config()["Console"] = "0";

        // Inits the Application 
#if defined (FC_OS_WIN32)
        App::Application::init(argc_, argv_.data());
#else
        App::Application::init(argc, argv);
#endif
#if defined(_MSC_VER)
        // create a dump file when the application crashes
        std::string dmpfile = App::Application::getUserAppDataDir();
        dmpfile += "crash.dmp";
        InitMiniDumpWriter(dmpfile);
#endif
        std::map<std::string, std::string>::iterator it = App::Application::Config().find("NavigationStyle");
        if (it != App::Application::Config().end()) {
            ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View");
            // if not already defined do it now (for the very first start)
            std::string style = hGrp->GetASCII("NavigationStyle", it->second.c_str());
            hGrp->SetASCII("NavigationStyle", style.c_str());
        }

        Gui::Application::initApplication();

        // Only if 'RunMode' is set to 'Gui' do the replacement
        if (App::Application::Config()["RunMode"] == "Gui")
            Base::Interpreter().replaceStdOutput();
    }
    catch (const Base::UnknownProgramOption& e) {
        QApplication app(argc,argv);
        QString appName = QString::fromLatin1(App::Application::Config()["ExeName"].c_str());
        QString msg = QString::fromLatin1(e.what());
        QString s = QLatin1String("<pre>") + msg + QLatin1String("</pre>");
        QMessageBox::critical(0, appName, s);
        exit(1);
    }
    catch (const Base::ProgramInformation& e) {
        QApplication app(argc,argv);
        QString appName = QString::fromLatin1(App::Application::Config()["ExeName"].c_str());
        QString msg = QString::fromUtf8(e.what());
        QString s = QLatin1String("<pre>") + msg + QLatin1String("</pre>");

        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Information);
        msgBox.setWindowTitle(appName);
        msgBox.setDetailedText(msg);
        msgBox.setText(s);
        msgBox.exec();
        exit(0);
    }
    catch (const Base::Exception& e) {
        // Popup an own dialog box instead of that one of Windows
        QApplication app(argc,argv);
        QString appName = QString::fromLatin1(App::Application::Config()["ExeName"].c_str());
        QString msg;
        msg = QObject::tr("While initializing %1 the following exception occurred: '%2'\n\n"
                          "Python is searching for its files in the following directories:\n%3\n\n"
                          "Python version information:\n%4\n")
                          .arg(appName).arg(QString::fromUtf8(e.what()))
#if PY_MAJOR_VERSION >= 3
#if PY_MINOR_VERSION >= 5
                          .arg(QString::fromUtf8(Py_EncodeLocale(Py_GetPath(),NULL))).arg(QString::fromLatin1(Py_GetVersion()));
#else
                          .arg(QString::fromUtf8(_Py_wchar2char(Py_GetPath(),NULL))).arg(QString::fromLatin1(Py_GetVersion()));
#endif
#else
                          .arg(QString::fromUtf8(Py_GetPath())).arg(QString::fromLatin1(Py_GetVersion()));
예제 #17
0
int main( int argc, char ** argv )
{
#if defined (FC_OS_LINUX) || defined(FC_OS_BSD)
    // Make sure to setup the Qt locale system before setting LANG and LC_ALL to C.
    // which is needed to use the system locale settings.
    (void)QLocale::system();
    // http://www.freecadweb.org/tracker/view.php?id=399
    // Because of setting LANG=C the Qt automagic to use the correct encoding
    // for file names is broken. This is a workaround to force the use of UTF-8 encoding
    QFile::setEncodingFunction(myEncoderFunc);
    QFile::setDecodingFunction(myDecoderFunc);
    // Make sure that we use '.' as decimal point. See also
    // http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=559846
    putenv("LC_NUMERIC=C");
    putenv("PYTHONPATH=");
#elif defined(FC_OS_MACOSX)
    (void)QLocale::system();
    putenv("LC_NUMERIC=C");
    putenv("PYTHONPATH=");
#else
    setlocale(LC_NUMERIC, "C");
    _putenv("PYTHONPATH=");
#endif

#if defined (FC_OS_WIN32)
    int argc_ = argc;
    QVector<QByteArray> data;
    QVector<char *> argv_;

    // get the command line arguments as unicode string
    {
        QCoreApplication app(argc, argv);
        QStringList args = app.arguments();
        for (QStringList::iterator it = args.begin(); it != args.end(); ++it) {
            data.push_back(it->toUtf8());
            argv_.push_back(data.back().data());
        }
        argv_.push_back(0); // 0-terminated string
    }
#endif

    // Name and Version of the Application
    App::Application::Config()["ExeName"] = "FreeCAD";
    App::Application::Config()["ExeVendor"] = "FreeCAD";
    App::Application::Config()["AppDataSkipVendor"] = "true";
    App::Application::Config()["MaintainerUrl"] = "http://www.freecadweb.org/wiki/index.php?title=Main_Page";

    // set the banner (for logging and console)
    App::Application::Config()["CopyrightInfo"] = sBanner;
    App::Application::Config()["AppIcon"] = "freecad";
    App::Application::Config()["SplashScreen"] = "freecadsplash";
    App::Application::Config()["StartWorkbench"] = "StartWorkbench";
    //App::Application::Config()["HiddenDockWindow"] = "Property editor";
    App::Application::Config()["SplashAlignment" ] = "Bottom|Left";
    App::Application::Config()["SplashTextColor" ] = "#ffffff"; // white
    App::Application::Config()["SplashInfoColor" ] = "#c8c8c8"; // light grey

    try {
        // Init phase ===========================================================
        // sets the default run mode for FC, starts with gui if not overridden in InitConfig...
        App::Application::Config()["RunMode"] = "Gui";

        // Inits the Application 
#if defined (FC_OS_WIN32)
        App::Application::init(argc_, argv_.data());
#else
        App::Application::init(argc, argv);
#endif
#if defined(_MSC_VER)
        // create a dump file when the application crashes
        std::string dmpfile = App::Application::getUserAppDataDir();
        dmpfile += "crash.dmp";
        InitMiniDumpWriter(dmpfile);
#endif
        std::map<std::string, std::string>::iterator it = App::Application::Config().find("NavigationStyle");
        if (it != App::Application::Config().end()) {
            ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View");
            // if not already defined do it now (for the very first start)
            std::string style = hGrp->GetASCII("NavigationStyle", it->second.c_str());
            hGrp->SetASCII("NavigationStyle", style.c_str());
        }

        Gui::Application::initApplication();

        // Only if 'RunMode' is set to 'Gui' do the replacement
        if (App::Application::Config()["RunMode"] == "Gui")
            Base::Interpreter().replaceStdOutput();
    }
    catch (const Base::UnknownProgramOption& e) {
        QApplication app(argc,argv);
        QString appName = QString::fromAscii(App::Application::Config()["ExeName"].c_str());
        QString msg = QString::fromAscii(e.what());
        QString s = QLatin1String("<pre>") + msg + QLatin1String("</pre>");
        QMessageBox::critical(0, appName, s);
        exit(1);
    }
    catch (const Base::ProgramInformation& e) {
        QApplication app(argc,argv);
        QString appName = QString::fromAscii(App::Application::Config()["ExeName"].c_str());
        QString msg = QString::fromAscii(e.what());
        QString s = QLatin1String("<pre>") + msg + QLatin1String("</pre>");
        QMessageBox::information(0, appName, s);
        exit(0);
    }
    catch (const Base::Exception& e) {
        // Popup an own dialog box instead of that one of Windows
        QApplication app(argc,argv);
        QString appName = QString::fromAscii(App::Application::Config()["ExeName"].c_str());
        QString msg;
        msg = QObject::tr("While initializing %1 the  following exception occurred: '%2'\n\n"
                          "Python is searching for its files in the following directories:\n%3\n\n"
                          "Python version information:\n%4\n")
                          .arg(appName).arg(QString::fromUtf8(e.what()))
                          .arg(QString::fromUtf8(Py_GetPath())).arg(QString::fromAscii(Py_GetVersion()));
        const char* pythonhome = getenv("PYTHONHOME");
        if (pythonhome) {
            msg += QObject::tr("\nThe environment variable PYTHONHOME is set to '%1'.")
                .arg(QString::fromUtf8(pythonhome));
            msg += QObject::tr("\nSetting this environment variable might cause Python to fail. "
                "Please contact your administrator to unset it on your system.\n\n");
        } else {
            msg += QObject::tr("\nPlease contact the application's support team for more information.\n\n");
        }

        QMessageBox::critical(0, QObject::tr("Initialization of %1 failed").arg(appName), msg);
        exit(100);
    }
    catch (...) {
        // Popup an own dialog box instead of that one of Windows
        QApplication app(argc,argv);
        QString appName = QString::fromAscii(App::Application::Config()["ExeName"].c_str());
        QString msg = QObject::tr("Unknown runtime error occurred while initializing %1.\n\n"
                                  "Please contact the application's support team for more information.\n\n").arg(appName);
        QMessageBox::critical(0, QObject::tr("Initialization of %1 failed").arg(appName), msg);
        exit(101);
    }

    // Run phase ===========================================================
    Base::RedirectStdOutput stdcout;
    Base::RedirectStdLog    stdclog;
    Base::RedirectStdError  stdcerr;
    std::streambuf* oldcout = std::cout.rdbuf(&stdcout);
    std::streambuf* oldclog = std::clog.rdbuf(&stdclog);
    std::streambuf* oldcerr = std::cerr.rdbuf(&stdcerr);

    try {
        if (App::Application::Config()["RunMode"] == "Gui")
            Gui::Application::runApplication();
        else
            App::Application::runApplication();
    }
    catch (const Base::SystemExitException&) {
        exit(0);
    }
    catch (const Base::Exception& e) {
        Base::Console().Error("%s\n", e.what());
    }
    catch (...) {
        Base::Console().Error("Application unexpectedly terminated\n");
    }

    std::cout.rdbuf(oldcout);
    std::clog.rdbuf(oldclog);
    std::cerr.rdbuf(oldcerr);

    // Destruction phase ===========================================================
    Base::Console().Log("%s terminating...\n",App::Application::Config()["ExeName"].c_str());

    // cleans up 
    App::Application::destruct();

    Base::Console().Log("%s completely terminated\n",App::Application::Config()["ExeName"].c_str());

    return 0;
}
예제 #18
0
void CmdRaytracingRender::activated(int iMsg)
{
    // determining render type
    Base::Type renderType;
    unsigned int n1 = getSelection().countObjectsOfType(Raytracing::RayProject::getClassTypeId());
    if (n1 != 1) {
        unsigned int n2 = getSelection().countObjectsOfType(Raytracing::LuxProject::getClassTypeId());
        if (n2 != 1) {
            QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"),
                QObject::tr("Select one Raytracing project object."));
            return;
        } else {
            renderType = Raytracing::LuxProject::getClassTypeId();
        }
    } else {
        renderType = Raytracing::RayProject::getClassTypeId();
    }
    
    // checking if renderer is present
    ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Raytracing");
    std::string renderer;
    if (renderType == Raytracing::RayProject::getClassTypeId()) {
        renderer = hGrp->GetASCII("PovrayExecutable", "");
        if (renderer == "") {
            QMessageBox::warning(Gui::getMainWindow(), QObject::tr("POV-Ray not found"),
                QObject::tr("Please set the path to the POV-Ray executable in the preferences."));
            return;
        } else {
            QFileInfo fi(QString::fromUtf8(renderer.c_str()));
            if (!fi.exists() || !fi.isFile()) {
                QMessageBox::warning(Gui::getMainWindow(), QObject::tr("POV-Ray not found"),
                    QObject::tr("Please correct the path to the POV-Ray executable in the preferences."));
                return;
            }
        }
    } else {
        renderer = hGrp->GetASCII("LuxrenderExecutable", "");
        if (renderer == "") {
            QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Luxrender not found"),
                QObject::tr("Please set the path to the luxrender or luxconsole executable in the preferences."));
            return;
        } else {
            QFileInfo fi(QString::fromUtf8(renderer.c_str()));
            if (!fi.exists() || !fi.isFile()) {
                QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Luxrender not found"),
                    QObject::tr("Please correct the path to the luxrender or luxconsole executable in the preferences."));
                return;
            }
        }
    }
    
    std::vector<Gui::SelectionObject> Sel = getSelection().getSelectionEx(0, renderType);
    
    if (renderType == Raytracing::RayProject::getClassTypeId()) {
        Raytracing::RayProject* proj = static_cast<Raytracing::RayProject*>(Sel[0].getObject());
        QFileInfo fi(QString::fromUtf8(proj->PageResult.getValue()));
        if (!fi.exists() || !fi.isFile()) {
            QMessageBox::warning(Gui::getMainWindow(), QObject::tr("POV-Ray file missing"),
                QObject::tr("The POV-Ray project file doesn't exist."));
            return;
        }

        QStringList filter;
#ifdef FC_OS_WIN32
        filter << QObject::tr("Rendered image (*.bmp *.png)");
#else
        filter << QObject::tr("Rendered image (*.png)");
#endif
        filter << QObject::tr("All Files (*.*)");
        QString fn = Gui::FileDialog::getSaveFileName(Gui::getMainWindow(), QObject::tr("Rendered image"), QString(), filter.join(QLatin1String(";;")));
        if (!fn.isEmpty()) {
            fn = QDir::toNativeSeparators(fn);
#ifdef FC_OS_WIN32
            fn.replace(QLatin1String("\\"), QLatin1String("\\\\"));
#endif
            std::string fname = (const char*)fn.toUtf8();
            openCommand("Render project");
            int width = hGrp->GetInt("OutputWidth", 800);
            std::stringstream w;
            w << width;
            int height = hGrp->GetInt("OutputHeight", 600);
            std::stringstream h;
            h << height;
            std::string par = hGrp->GetASCII("OutputParameters", "+P +A");
            doCommand(Doc,"PageFile = open(App.activeDocument().%s.PageResult,'r')",Sel[0].getFeatName());
            doCommand(Doc,"import subprocess,tempfile");
            doCommand(Doc,"TempFile = tempfile.mkstemp(suffix='.pov')[1]");
            doCommand(Doc,"f = open(TempFile,'wb')");
            doCommand(Doc,"f.write(PageFile.read())");
            doCommand(Doc,"f.close()");
#ifdef FC_OS_WIN32
            // http://povray.org/documentation/view/3.6.1/603/
            doCommand(Doc,"subprocess.call('\"%s\" %s +W%s +H%s +O\"%s\" /EXIT /RENDER '+TempFile)",renderer.c_str(),par.c_str(),w.str().c_str(),h.str().c_str(),fname.c_str());
#else
            doCommand(Doc,"subprocess.call('\"%s\" %s +W%s +H%s +O\"%s\" '+TempFile,shell=True)",renderer.c_str(),par.c_str(),w.str().c_str(),h.str().c_str(),fname.c_str());
#endif
            doCommand(Gui,"import ImageGui");
            doCommand(Gui,"ImageGui.open('%s')",fname.c_str());
            doCommand(Doc,"del TempFile,PageFile");
            commitCommand();
        }
    } else {
        Raytracing::LuxProject* proj = static_cast<Raytracing::LuxProject*>(Sel[0].getObject());
        QFileInfo fi(QString::fromUtf8(proj->PageResult.getValue()));
        if (!fi.exists() || !fi.isFile()) {
            QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Lux project file missing"),
                QObject::tr("The Lux project file doesn't exist."));
            return;
        }

        openCommand("Render project");
        doCommand(Doc,"PageFile = open(App.activeDocument().%s.PageResult,'r')",Sel[0].getFeatName());
        doCommand(Doc,"import subprocess,tempfile");
        doCommand(Doc,"TempFile = tempfile.mkstemp(suffix='.lxs')[1]");
        doCommand(Doc,"f = open(TempFile,'wb')");
        doCommand(Doc,"f.write(PageFile.read())");
        doCommand(Doc,"f.close()");
        doCommand(Doc,"subprocess.Popen([\"%s\",TempFile])",renderer.c_str());
        doCommand(Doc,"del TempFile,PageFile");            
        commitCommand();
    }
}