Beispiel #1
0
/**
 * Shows a dialog for choosing a file name. Saving the file is up to
 * the caller.
 *
 * @param type Will contain the file type that was chosen by the user.
 *             Can be NULL to be ignored.
 *
 * @return File name with path and extension to determine the file type
 *         or an empty string if the dialog was cancelled.
 */
QString QG_FileDialog::getSaveFileName(QWidget* parent, RS2::FormatType* type) {
    // read default settings:
    RS_SETTINGS->beginGroup("/Paths");
    QString defDir = RS_SETTINGS->readEntry("/Save",
                                              RS_SYSTEM->getHomeDir());
    QString defFilter = RS_SETTINGS->readEntry("/SaveFilter",
                                                 "Drawing Exchange DXF 2000 (*.dxf)");
    //QString defFilter = "Drawing Exchange (*.dxf)";
    RS_SETTINGS->endGroup();

    // prepare file save as dialog:
    QFileDialog* fileDlg = new QFileDialog(parent,"Save as");
    QStringList filters;
    bool done = false;
    bool cancel = false;
    QString fn = "";

    filters.append("Drawing Exchange DXF 2000 (*.dxf)");
#ifdef USE_DXFRW
    filters.append("New Drawing Exchange DXF 2000 (*.DXF)");
#endif
    filters.append("Drawing Exchange DXF R12 (*.dxf)");
    filters.append("LFF Font (*.lff)");
    filters.append("Font (*.cxf)");
    filters.append("JWW (*.jww)");

    fileDlg->setFilters(filters);
    fileDlg->setFileMode(QFileDialog::AnyFile);
    fileDlg->setWindowTitle(QObject::tr("Save Drawing As"));
    fileDlg->setDirectory(defDir);
    fileDlg->setAcceptMode(QFileDialog::AcceptSave);
    fileDlg->selectFilter(defFilter);

    // run dialog:
    do {
        // accepted:
        if (fileDlg->exec()==QDialog::Accepted) {
            QStringList fl = fileDlg->selectedFiles();
            if (!fl.isEmpty())
                fn = fl[0];
            fn = QDir::convertSeparators( QFileInfo(fn).absoluteFilePath() );
            cancel = false;

            // append default extension:
            // TODO, since we are starting to suppor tmore extensions, we need to find a better way to add the default
            if (QFileInfo(fn).fileName().indexOf('.')==-1) {
                if (fileDlg->selectedFilter()=="LFF Font (*.lff)") {
                    fn+=".lff";
                } else if (fileDlg->selectedFilter()=="Font (*.cxf)") {
                        fn+=".cxf";
                } else {
                    fn+=".dxf";
                }
            }

            // set format:
            if (type!=NULL) {
                if (fileDlg->selectedFilter()=="LFF Font (*.lff)") {
                    *type = RS2::FormatLFF;
                } else if (fileDlg->selectedFilter()=="Font (*.cxf)") {
                    *type = RS2::FormatCXF;
                } else if (fileDlg->selectedFilter()=="Drawing Exchange DXF R12 (*.dxf)") {
                    *type = RS2::FormatDXF12;
#ifdef USE_DXFRW
#if QT_VERSION >= 0x040400
                } else if (fileDlg->selectedNameFilter()=="New Drawing Exchange DXF 2000 (*.DXF)") {
                    *type = RS2::FormatDXFRW;
#endif // QT_VERSION
#endif // USE_DXFFRW
                } else if (fileDlg->selectedFilter()=="JWW (*.jww)") {
                    *type = RS2::FormatJWW;
                } else {
                    *type = RS2::FormatDXF;
                }
            }

#if !defined (_WIN32) && !defined (__APPLE__)
            // overwrite warning:
            if(QFileInfo(fn).exists()) {
                int choice =
                        QMessageBox::warning(parent, QObject::tr("Save Drawing As"),
                                             QObject::tr("%1 already exists.\n"
                                                         "Do you want to replace it?")
                                             .arg(fn),
                                             QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel,QMessageBox::Cancel);

                switch (choice) {
                case QMessageBox::Yes:
                    done = true;
                    break;
                default:
                    done = false;
                    break;
                }
            } else {
                done = true;
            }
#else
            done = true;
#endif


        } else {
            done = true;
            cancel = true;
            fn = "";
        }
    } while(!done);

    // store new default settings:
    if (!cancel) {
        RS_SETTINGS->beginGroup("/Paths");
        RS_SETTINGS->writeEntry("/Save", QFileInfo(fn).absolutePath());
        //RS_SETTINGS->writeEntry("/SaveFilter", fileDlg->selectedFilter());
        RS_SETTINGS->endGroup();
    }

    delete fileDlg;

    return fn;
}
Beispiel #2
0
void ContentViewer::addHTMLTab()
{
  if(_entity->hasHTML())
  {
    QWidget *tab=new QWidget(ui->tvFormats);
    tab->setObjectName("HTML");
    tab->setWindowTitle("HTML");

    QVBoxLayout *tabLayout=new QVBoxLayout();

    QTabWidget *innerTabWidget=new QTabWidget(tab);
    QWidget *previewTab=new QWidget(innerTabWidget);
    previewTab->setObjectName("preview");
    previewTab->setWindowTitle("preview");

    QVBoxLayout *previewTabLayout=new QVBoxLayout();


    QTextBrowser *previewTextBorowser=new QTextBrowser(tab);
    previewTextBorowser->setText(_entity->HTMLText(false,-1));
    previewTextBorowser->setReadOnly(true);

    QHBoxLayout *previewTabOptionsLayout=new QHBoxLayout();
    previewTabOptionsLayout->addStretch();

    QLabel *previewCBLabel=new QLabel(previewTab);
    previewCBLabel->setText("background color : ");
    previewTabOptionsLayout->addWidget(previewCBLabel);

    QPushButton *previewBCButton=new QPushButton(previewTab);
    previewBCButton->setText("white");
    previewBCButton->setStyleSheet("background-color : white ;");
    connect(previewBCButton,&QPushButton::clicked,this,[this,previewTextBorowser,previewBCButton](){
      QColorDialog CD(this);
      if(CD.exec())
      {
        QColor color=CD.selectedColor();
        previewTextBorowser->setStyleSheet("background-color :  "+color.name()+";");
        previewBCButton->setText(color.name());
        previewBCButton->setStyleSheet("background-color :  "+color.name()+";");
      }
    });

    previewTabOptionsLayout->addWidget(previewBCButton);
    previewTabLayout->addLayout(previewTabOptionsLayout);

    previewTabLayout->addWidget(previewTextBorowser);
    previewTab->setLayout(previewTabLayout);
    innerTabWidget->addTab(previewTab,"preview");

    QWidget *codeTab=new QWidget(innerTabWidget);
    codeTab->setObjectName("code");
    codeTab->setWindowTitle("code");

    QVBoxLayout *codeTabLayout=new QVBoxLayout();
    QPlainTextEdit *codeTextEdit=new QPlainTextEdit(codeTab);
    codeTextEdit->setPlainText(_entity->HTMLText(false,-1));
    codeTextEdit->setReadOnly(true);
    codeTabLayout->addWidget(codeTextEdit);

    codeTab->setLayout(codeTabLayout);

    innerTabWidget->addTab(codeTab,"code");


    tabLayout->addWidget(innerTabWidget);

    QHBoxLayout *infoLayout=new QHBoxLayout();
    QLabel *infoLabel=new QLabel(tab);
    infoLabel->setText(QString("<b>length :</b> %1").arg(previewTextBorowser->toPlainText().count())
                               +"  "+QString("<b>size :</b> %1 KB").arg((double)_entity->formatSize("text/html")/1024));
    infoLayout->addWidget(infoLabel);

    QPushButton *btnExport=new QPushButton(tab);
    connect(btnExport,&QPushButton::clicked,this,[this](){
      QFileDialog dialog;
      dialog.setAcceptMode(QFileDialog::AcceptSave);
      dialog.setWindowTitle("select a file to save HTML");
      dialog.setWindowIcon(QIcon(Resources::Export16));
      dialog.setFileMode(QFileDialog::AnyFile);
      dialog.setDefaultSuffix("html");
      for(;;)
      {
        if(dialog.exec())
        {
          int length=dialog.selectedFiles().length();
          if(length>0 && length==1)
          {
            QFile file(dialog.selectedFiles().at(0));
            file.open(QIODevice::WriteOnly);
            if(file.isWritable())
            {
              qint64 i= file.write(this->_entity->HTMLText(false,-1).toUtf8());
              if(i<0)
              {
                int messageResult= QMessageBox::critical(this,"cannot write to the file.","cannot write to the selected file.nothing saved. \ntry another file.",QMessageBox::Ok,QMessageBox::Cancel);
                if(messageResult==QMessageBox::Ok)
                  continue;
                else break;
              }
              else break;
            }
            else
            {
              int messageResult= QMessageBox::critical(this,"cannot write to the file.","cannot write selected file. \ntry another file.",QMessageBox::Ok,QMessageBox::Cancel);
              if(messageResult==QMessageBox::Ok)
                continue;
              else break;
            }
          }
        }
        else break;
      }
    });
    btnExport->setIcon(QIcon(Resources::Export16));
    btnExport->setText("export");
    infoLayout->addStretch();
    infoLayout->addWidget(btnExport);
    tabLayout->addLayout(infoLayout);

    tab->setLayout(tabLayout);

    ui->tvFormats->addTab(tab,"HTML");
  }
}
Beispiel #3
0
void ContentViewer::addPlainTextTab()
{
  if(_entity->hasPlainText())
  {

    QWidget *plainTextTab=new QWidget(ui->tvFormats);
    plainTextTab->setObjectName("Plain Text");
    plainTextTab->setWindowTitle("Plain Text");

    QVBoxLayout *plainTextTabLayout=new QVBoxLayout();

    QPlainTextEdit *plainTextEdit=new QPlainTextEdit(plainTextTab);
    plainTextEdit->setPlainText(_entity->plainText(false,-1));
    plainTextEdit->setReadOnly(true);
    plainTextTabLayout->addWidget(plainTextEdit);

    QHBoxLayout *plainTextInfoLayout=new QHBoxLayout();
    QLabel *plainTextInfoLabel=new QLabel(plainTextTab);
    plainTextInfoLabel->setText(QString("<b>length :</b> %1").arg(plainTextEdit->toPlainText().count())
                               +"  "+QString("<b>size :</b> %1 KB").arg((double)_entity->formatSize("text/plain")/1024));
    plainTextInfoLayout->addWidget(plainTextInfoLabel);

    QPushButton *btnExport=new QPushButton(plainTextTab);
    connect(btnExport,&QPushButton::clicked,this,[this,plainTextEdit](){
      QFileDialog dialog;
      dialog.setAcceptMode(QFileDialog::AcceptSave);
      dialog.setWindowTitle("select a file to save text");
      dialog.setWindowIcon(QIcon(Resources::Export16));
      dialog.setFileMode(QFileDialog::AnyFile);
      dialog.setDefaultSuffix("txt");
      for(;;)
      {
        if(dialog.exec())
        {
          int length=dialog.selectedFiles().length();
          if(length>0 && length==1)
          {
            QFile file(dialog.selectedFiles().at(0));
            file.open(QIODevice::WriteOnly);
            if(file.isWritable())
            {
              qint64 i= file.write(plainTextEdit->toPlainText().toUtf8());
              if(i<0)
              {
                int messageResult= QMessageBox::critical(this,"cannot write to the file.","cannot write to the selected file.nothing saved. \ntry another file.",QMessageBox::Ok,QMessageBox::Cancel);
                if(messageResult==QMessageBox::Ok)
                  continue;
                else break;
              }
              else break;
            }
            else
            {
              int messageResult= QMessageBox::critical(this,"cannot write to the file.","cannot write selected file. \ntry another file.",QMessageBox::Ok,QMessageBox::Cancel);
              if(messageResult==QMessageBox::Ok)
                continue;
              else break;
            }
          }
        }
        else break;
      }
    });
    btnExport->setIcon(QIcon(Resources::Export16));
    btnExport->setText("export");
    plainTextInfoLayout->addStretch();
    plainTextInfoLayout->addWidget(btnExport);
    plainTextTabLayout->addLayout(plainTextInfoLayout);

    plainTextTab->setLayout(plainTextTabLayout);

    ui->tvFormats->addTab(plainTextTab,"Plain Text");
  }
}
Beispiel #4
0
void DaoWorker::loadModelIntoAYDesigner(const std::string fileDownloaded)
{
    if(boost::filesystem::exists(fileDownloaded))
    {
        std::string suffix = boost::filesystem::extension(fileDownloaded);
        if(suffix == ".stl" || suffix == ".STL")
        {
            LoggerManager::instance()->logInfo("AY Designer is about to run, loading "+fileDownloaded+".");
            std::string filePathTemp = fileDownloaded;
            std::replace_if(filePathTemp.begin(), filePathTemp.end(), [] (char c) { return (c == '/'); }, '\\\\');

            std::string formatedAyDesignerUrl = MainWindow::GetMainWindow()->getAyDesignerPath();
            if(!boost::filesystem::exists(formatedAyDesignerUrl))
            {
                QFileDialog dialog;
                dialog.setNameFilter(trUtf8("AY Designer (*.exe)"));

                if (dialog.exec())
                {
                    std::string path = QString::fromUtf8(dialog.selectedFiles()[0].toUtf8().constData()).toStdString();
                    MainWindow::GetMainWindow()->updateAyDesignerPathForSetting(path);
                    formatedAyDesignerUrl = MainWindow::GetMainWindow()->getAyDesignerPath();
                }
                else
                {
                    LoggerManager::instance()->logInfo("update AyDesignerPath for setting cancelled.");
                    return;
                }
            }
            QString program = QString::fromStdString(formatedAyDesignerUrl);
            QStringList args;
            args.push_back("-s");
            args.push_back(QString::fromStdString(filePathTemp));

            QProcess::execute(program, args);

            //AYDesigner processes this file, save it to override the original file, "save and save as... in aydesigner"
            //...

            LoggerManager::instance()->logInfo("AY Designer is closed.");
        }
        else if(suffix == ".ply" || suffix == ".PLY")
        {
            LoggerManager::instance()->logInfo("AY Designer is about to run, loading "+fileDownloaded+".");
            std::string filePathTemp = fileDownloaded;
            std::replace_if(filePathTemp.begin(), filePathTemp.end(), [] (char c) { return (c == '/'); }, '\\\\');

            std::string formatedAyDesignerUrl = MainWindow::GetMainWindow()->getAyDesignerPath();
            if(!boost::filesystem::exists(formatedAyDesignerUrl))
            {
                QFileDialog dialog;
                dialog.setNameFilter(trUtf8("AY Designer (*.exe)"));

                if (dialog.exec())
                {
                    std::string path = QString::fromUtf8(dialog.selectedFiles()[0].toUtf8().constData()).toStdString();
                    MainWindow::GetMainWindow()->updateAyDesignerPathForSetting(path);
                    formatedAyDesignerUrl = MainWindow::GetMainWindow()->getAyDesignerPath();
                }
                else
                {
                    LoggerManager::instance()->logInfo("update AyDesignerPath for setting cancelled.");
                    return;
                }
            }
            QString program = QString::fromStdString(formatedAyDesignerUrl);
            QStringList args;
            args.push_back("-p");
            args.push_back(QString::fromStdString(filePathTemp));

            QProcess::execute(program, args);

            //AYDesigner processes this file, save it to override the original file, "save and save as... in aydesigner"
            //...

            LoggerManager::instance()->logInfo("AY Designer is closed.");
        }
        else
            LoggerManager::instance()->logInfo("unsupported cloud file format for AYDesigner.");
    }
}
Beispiel #5
0
//////////////////////////////////////////////////////////////////////////////////
// This function is called when progress needs to be loaded from a text file.
//////////////////////////////////////////////////////////////////////////////////
void MainController::onLoadProgress() {

    if(test) testfile << "MC7  ####################### MainController onLoadProgress #######################\n";

    QString filePath;
    QFileDialog* fileDialog = new QFileDialog(&view, "Load Progress", "", "*.*");
    if(fileDialog->exec()) filePath = fileDialog->selectedFiles().first();
    if(filePath != "")
    {
        if(test) testfile << "MC8  FilePath is not empty\n";
        if(puzzle != NULL){
            if(test) testfile << "MC36 Puzzle is not NULL\n";
            //User started game, do they want to save progress?
            QMessageBox msgBox;
            msgBox.setText("You have unsaved progress.");
            msgBox.setInformativeText("Do you want to save your progress?");
            msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
            msgBox.setDefaultButton(QMessageBox::Save);
            int ret = msgBox.exec();

            if(ret == msgBox.Save){
                if(test) testfile << "MC37 MessageBox save button clicked\n";
                //Save user progress
                onSaveProgress();
            }
            else if(ret == msgBox.Discard){
                if(test) testfile << "MC38 MessageBox discard button clicked\n";
                //Discard user progress
                //Do nothing
            }
            else if(ret == msgBox.Cancel){
                if(test) testfile << "MC39 MessageBox cancel button clicked\n";
                //Don't save or discard progress
                return;
            }

            //User done saving/discarding game, clear board and delete puzzle
            view.clearBoard();
            delete puzzle;
        }

        puzzle = currentProgressSerializer.deserialize(filePath, puzzleSerializer);

        //Display the default and current board
        enableUndoRedo = false;
        displayDefaultBoard();
        displayCurrentBoard();
        enableUndoRedo = true;

        if(puzzle->undo.count() > 0){
            if(test) testfile << "MC9  Puzzle undo count > 0\n";
            view.clearAction->setEnabled(true);
            view.undoAction->setEnabled(true);
        }
        if(puzzle->redo.count() > 0){
            if(test) testfile << "MC10 Puzzle redo count > 0\n";
            view.redoAction->setEnabled(true);
        }

        view.centralWidget()->setEnabled(true);
    } 
    else{
        if(test) testfile << "MC11 Filepath was empty\n";
        //Popup error message...
        //TODO
    }
}
Beispiel #6
0
/* static */
QStringList QIFileDialog::getOpenFileNames (const QString &aStartWith,
                                            const QString &aFilters,
                                            QWidget       *aParent,
                                            const QString &aCaption,
                                            QString       *aSelectedFilter /* = 0 */,
                                            bool           aResolveSymlinks /* = true */,
                                            bool           aSingleFile /* = false */)
{
/* It seems, running QFileDialog in separate thread is NOT needed under windows any more: */
#if defined (VBOX_WS_WIN) && (QT_VERSION < 0x040403)

    /**
     *  QEvent class reimplementation to carry Win32 API native dialog's
     *  result folder information
     */
    class GetOpenFileNameEvent : public OpenNativeDialogEvent
    {
    public:

        enum { TypeId = QEvent::User + 3 };

        GetOpenFileNameEvent (const QString &aResult)
            : OpenNativeDialogEvent (aResult, (QEvent::Type) TypeId) {}
    };

    /**
     *  QThread class reimplementation to open Win32 API native file dialog
     */
    class Thread : public QThread
    {
    public:

        Thread (QWidget *aParent, QObject *aTarget,
                const QString &aStartWith, const QString &aFilters,
                const QString &aCaption) :
                mParent (aParent), mTarget (aTarget),
                mStartWith (aStartWith), mFilters (aFilters),
                mCaption (aCaption) {}

        virtual void run()
        {
            QString result;

            QString workDir;
            QString initSel;
            QFileInfo fi (mStartWith);

            if (fi.isDir())
                workDir = mStartWith;
            else
            {
                workDir = fi.absolutePath();
                initSel = fi.fileName();
            }

            workDir = QDir::toNativeSeparators (workDir);
            if (!workDir.endsWith ("\\"))
                workDir += "\\";

            QString title = mCaption.isNull() ? tr ("Select a file") : mCaption;

            QWidget *topParent = windowManager().realParentWindow(mParent ? mParent : windowManager().mainWindowShown());
            QString winFilters = winFilter (mFilters);
            AssertCompile (sizeof (TCHAR) == sizeof (QChar));
            TCHAR buf [1024];
            if (initSel.length() > 0 && initSel.length() < sizeof (buf))
                memcpy (buf, initSel.isNull() ? 0 : initSel.utf16(),
                        (initSel.length() + 1) * sizeof (TCHAR));
            else
                buf [0] = 0;

            OPENFILENAME ofn;
            memset (&ofn, 0, sizeof (OPENFILENAME));

            ofn.lStructSize = sizeof (OPENFILENAME);
            ofn.hwndOwner = topParent ? topParent->winId() : 0;
            ofn.lpstrFilter = (TCHAR *)(winFilters.isNull() ? 0 : winFilters.utf16());
            ofn.lpstrFile = buf;
            ofn.nMaxFile = sizeof (buf) - 1;
            ofn.lpstrInitialDir = (TCHAR *)(workDir.isNull() ? 0 : workDir.utf16());
            ofn.lpstrTitle = (TCHAR *)(title.isNull() ? 0 : title.utf16());
            ofn.Flags = (OFN_NOCHANGEDIR | OFN_HIDEREADONLY |
                          OFN_EXPLORER | OFN_ENABLEHOOK |
                          OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST);
            ofn.lpfnHook = OFNHookProc;

            if (GetOpenFileName (&ofn))
            {
                result = QString::fromUtf16 ((ushort *) ofn.lpstrFile);
            }

            // qt_win_eatMouseMove();
            MSG msg = {0, 0, 0, 0, 0, 0, 0};
            while (PeekMessage (&msg, 0, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE));
            if (msg.message == WM_MOUSEMOVE)
                PostMessage (msg.hwnd, msg.message, 0, msg.lParam);

            result = result.isEmpty() ? result : QFileInfo (result).absoluteFilePath();

            QApplication::postEvent (mTarget, new GetOpenFileNameEvent (result));
        }

    private:

        QWidget *mParent;
        QObject *mTarget;
        QString mStartWith;
        QString mFilters;
        QString mCaption;
    };

    if (aSelectedFilter)
        *aSelectedFilter = QString::null;

    /* Local event loop to run while waiting for the result from another
     * thread */
    QEventLoop loop;

    QString startWith = QDir::toNativeSeparators (aStartWith);
    LoopObject loopObject ((QEvent::Type) GetOpenFileNameEvent::TypeId, loop);

    if (aParent)
        aParent->setWindowModality (Qt::WindowModal);

    Thread openDirThread (aParent, &loopObject, startWith, aFilters, aCaption);
    openDirThread.start();
    loop.exec();
    openDirThread.wait();

    if (aParent)
        aParent->setWindowModality (Qt::NonModal);

    return QStringList() << loopObject.result();

#elif defined (VBOX_WS_X11) && (QT_VERSION < 0x040400)

    /* Here is workaround for Qt4.3 bug with QFileDialog which crushes when
     * gets initial path as hidden directory if no hidden files are shown.
     * See http://trolltech.com/developer/task-tracker/index_html?method=entry&id=193483
     * for details */
    QFileDialog dlg (aParent);
    dlg.setWindowTitle (aCaption);
    dlg.setDirectory (aStartWith);
    dlg.setFilter (aFilters);
    if (aSingleFile)
        dlg.setFileMode (QFileDialog::ExistingFile);
    else
        dlg.setFileMode (QFileDialog::ExistingFiles);
    if (aSelectedFilter)
        dlg.selectFilter (*aSelectedFilter);
    dlg.setResolveSymlinks (aResolveSymlinks);
    QAction *hidden = dlg.findChild <QAction*> ("qt_show_hidden_action");
    if (hidden)
    {
        hidden->trigger();
        hidden->setVisible (false);
    }
    return dlg.exec() == QDialog::Accepted ? dlg.selectedFiles() : QStringList() << QString::null;

#elif defined (VBOX_WS_MAC) && (QT_VERSION >= 0x040600) && (QT_VERSION < 0x050000)

    /* After 4.5 exec ignores the Qt::Sheet flag.
     * See "New Ways of Using Dialogs" in http://doc.trolltech.com/qq/QtQuarterly30.pdf why.
     * We want the old behavior for file-save dialog. Unfortunately there is a bug in Qt 4.5.x
     * which result in showing the native & the Qt dialog at the same time. */
    QFileDialog dlg(aParent);
    dlg.setWindowTitle(aCaption);

    /* Some predictive algorithm which seems missed in native code. */
    QDir dir(aStartWith);
    while (!dir.isRoot() && !dir.exists())
        dir = QDir(QFileInfo(dir.absolutePath()).absolutePath());
    const QString strDirectory = dir.absolutePath();
    if (!strDirectory.isNull())
        dlg.setDirectory(strDirectory);
    if (strDirectory != aStartWith)
        dlg.selectFile(QFileInfo(aStartWith).absoluteFilePath());

    dlg.setNameFilter(aFilters);
    if (aSingleFile)
        dlg.setFileMode(QFileDialog::ExistingFile);
    else
        dlg.setFileMode(QFileDialog::ExistingFiles);
    if (aSelectedFilter)
        dlg.selectFilter(*aSelectedFilter);
    dlg.setResolveSymlinks(aResolveSymlinks);

    QEventLoop eventLoop;
    QObject::connect(&dlg, SIGNAL(finished(int)),
                     &eventLoop, SLOT(quit()));
    dlg.open();
    eventLoop.exec();

    return dlg.result() == QDialog::Accepted ? dlg.selectedFiles() : QStringList() << QString();

#else

    QFileDialog::Options o;
    if (!aResolveSymlinks)
        o |= QFileDialog::DontResolveSymlinks;
# if defined (VBOX_WS_X11)
    /** @todo see http://bugs.kde.org/show_bug.cgi?id=210904, make it conditional
     *        when this bug is fixed (xtracker 5167)
     *        Apparently not necessary anymore (xtracker 5748)! */
//    if (vboxGlobal().isKWinManaged())
//      o |= QFileDialog::DontUseNativeDialog;
# endif

    if (aSingleFile)
        return QStringList() << QFileDialog::getOpenFileName (aParent, aCaption, aStartWith,
                                                              aFilters, aSelectedFilter, o);
    else
        return QFileDialog::getOpenFileNames (aParent, aCaption, aStartWith,
                                              aFilters, aSelectedFilter, o);
#endif
}
Beispiel #7
0
/**
 *  Reimplementation of QFileDialog::getExistingDirectory() that removes some
 *  oddities and limitations.
 *
 *  On Win32, this function makes sure a native dialog is launched in
 *  another thread to avoid dialog visualization errors occurring due to
 *  multi-threaded COM apartment initialization on the main UI thread while
 *  the appropriate native dialog function expects a single-threaded one.
 *
 *  On all other platforms, this function is equivalent to
 *  QFileDialog::getExistingDirectory().
 */
QString QIFileDialog::getExistingDirectory (const QString &aDir,
                                            QWidget *aParent,
                                            const QString &aCaption,
                                            bool aDirOnly,
                                            bool aResolveSymlinks)
{
#if defined(VBOX_WS_WIN) && (QT_VERSION < 0x050000)

    /**
     *  QEvent class reimplementation to carry Win32 API
     *  native dialog's result folder information
     */
    class GetExistDirectoryEvent : public OpenNativeDialogEvent
    {
    public:

        enum { TypeId = QEvent::User + 1 };

        GetExistDirectoryEvent (const QString &aResult)
            : OpenNativeDialogEvent (aResult, (QEvent::Type) TypeId) {}
    };

    /**
     *  QThread class reimplementation to open Win32 API
     *  native folder's dialog
     */
    class Thread : public QThread
    {
    public:

        Thread (QWidget *aParent, QObject *aTarget,
                const QString &aDir, const QString &aCaption)
            : mParent (aParent), mTarget (aTarget), mDir (aDir), mCaption (aCaption) {}

        virtual void run()
        {
            QString result;

            QWidget *topParent = windowManager().realParentWindow(mParent ? mParent : windowManager().mainWindowShown());
            QString title = mCaption.isNull() ? tr ("Select a directory") : mCaption;

            TCHAR path [MAX_PATH];
            path [0] = 0;
            TCHAR initPath [MAX_PATH];
            initPath [0] = 0;

            BROWSEINFO bi;
            bi.hwndOwner = topParent ? topParent->winId() : 0;
            bi.pidlRoot = 0;
            bi.lpszTitle = (TCHAR*)(title.isNull() ? 0 : title.utf16());
            bi.pszDisplayName = initPath;
            bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT | BIF_NEWDIALOGSTYLE;
            bi.lpfn = winGetExistDirCallbackProc;
            bi.lParam = uintptr_t(&mDir);

            LPITEMIDLIST itemIdList = SHBrowseForFolder (&bi);
            if (itemIdList)
            {
                SHGetPathFromIDList (itemIdList, path);
                IMalloc *pMalloc;
                if (SHGetMalloc (&pMalloc) != NOERROR)
                    result = QString::null;
                else
                {
                    pMalloc->Free (itemIdList);
                    pMalloc->Release();
                    result = QString::fromUtf16 ((ushort*)path);
                }
            }
            else
                result = QString::null;
            QApplication::postEvent (mTarget, new GetExistDirectoryEvent (result));
        }

    private:

        QWidget *mParent;
        QObject *mTarget;
        QString mDir;
        QString mCaption;
    };

    /* Local event loop to run while waiting for the result from another
     * thread */
    QEventLoop loop;

    QString dir = QDir::toNativeSeparators (aDir);
    LoopObject loopObject ((QEvent::Type) GetExistDirectoryEvent::TypeId, loop);

    Thread openDirThread (aParent, &loopObject, dir, aCaption);
    openDirThread.start();
    loop.exec();
    openDirThread.wait();

    return loopObject.result();

#elif defined (VBOX_WS_X11) && (QT_VERSION < 0x040400)

    /* Here is workaround for Qt4.3 bug with QFileDialog which crushes when
     * gets initial path as hidden directory if no hidden files are shown.
     * See http://trolltech.com/developer/task-tracker/index_html?method=entry&id=193483
     * for details */
    QFileDialog dlg (aParent);
    dlg.setWindowTitle (aCaption);
    dlg.setDirectory (aDir);
    dlg.setResolveSymlinks (aResolveSymlinks);
    dlg.setFileMode (aDirOnly ? QFileDialog::DirectoryOnly : QFileDialog::Directory);
    QAction *hidden = dlg.findChild <QAction*> ("qt_show_hidden_action");
    if (hidden)
    {
        hidden->trigger();
        hidden->setVisible (false);
    }
    return dlg.exec() ? dlg.selectedFiles() [0] : QString::null;
#elif defined (VBOX_WS_MAC) && (QT_VERSION >= 0x040600)

    /* After 4.5 exec ignores the Qt::Sheet flag.
     * See "New Ways of Using Dialogs" in http://doc.trolltech.com/qq/QtQuarterly30.pdf why.
     * We want the old behavior for file-save dialog. Unfortunately there is a bug in Qt 4.5.x
     * which result in showing the native & the Qt dialog at the same time. */
    QFileDialog dlg(aParent);
    dlg.setWindowTitle(aCaption);
    dlg.setDirectory(aDir);
    dlg.setResolveSymlinks(aResolveSymlinks);
    dlg.setFileMode(aDirOnly ? QFileDialog::DirectoryOnly : QFileDialog::Directory);

    QEventLoop eventLoop;
    QObject::connect(&dlg, SIGNAL(finished(int)),
                     &eventLoop, SLOT(quit()));
    dlg.open();
    eventLoop.exec();

    return dlg.result() == QDialog::Accepted ? dlg.selectedFiles().value(0, QString()) : QString();

#else

    QFileDialog::Options o;
# if defined (VBOX_WS_X11)
    /** @todo see http://bugs.kde.org/show_bug.cgi?id=210904, make it conditional
     *        when this bug is fixed (xtracker 5167).
     *        Apparently not necessary anymore (xtracker 5748)! */
//    if (vboxGlobal().isKWinManaged())
//      o |= QFileDialog::DontUseNativeDialog;
# endif
    if (aDirOnly)
        o |= QFileDialog::ShowDirsOnly;
    if (!aResolveSymlinks)
        o |= QFileDialog::DontResolveSymlinks;
    return QFileDialog::getExistingDirectory (aParent, aCaption, aDir, o);

#endif
}
Beispiel #8
0
void NWebView::downloadRequested(QNetworkRequest req) {
    QString urlString = req.url().toString();
    if (urlString == "")  {
        downloadImageAction()->trigger();
        return;
    }
    if (urlString.startsWith("nnres:")) {
        int pos = urlString.indexOf(global.attachmentNameDelimeter);
        QString extension = "";
        if (pos > 0) {
            extension = urlString.mid(pos+global.attachmentNameDelimeter.length());
            urlString = urlString.mid(0,pos);
        }
        urlString = urlString.mid(6);

        qint32 lid = urlString.toInt();
        ResourceTable resTable(global.db);
        Resource r;
        resTable.get(r, lid, false);
        QString filename;
        ResourceAttributes attributes;
        if (r.attributes.isSet())
            attributes = r.attributes;
        if (attributes.fileName.isSet())
            filename = attributes.fileName;
        else
            filename = urlString + QString(".") + extension;

        QFileDialog fd;
        fd.setFileMode(QFileDialog::AnyFile);
        fd.setWindowTitle(tr("Save File"));
        fd.setAcceptMode(QFileDialog::AcceptSave);
        fd.selectFile(filename);
        fd.setConfirmOverwrite(true);
        if (fd.exec()) {
            if (fd.selectedFiles().size() == 0)
                return;
            filename = fd.selectedFiles()[0];
            QFile newFile(filename);
            newFile.open(QIODevice::WriteOnly);
            Data d;
            if (r.data.isSet())
                d = r.data;
            QByteArray body;
            if (d.body.isSet())
                body = d.body;
            int size = 0;
            if (d.size.isSet())
                size = d.size;
            newFile.write(body, size);
            newFile.close();
            return;
        }
    }
    if (urlString.startsWith("file:////")) {
        if (!req.url().isValid())
            return;
        urlString = urlString.mid(8);
        QFileDialog fd;
        fd.setFileMode(QFileDialog::AnyFile);
        fd.setWindowTitle(tr("Save File"));
        fd.setAcceptMode(QFileDialog::AcceptSave);
        QString oldname = urlString;
        fd.selectFile(urlString.replace(global.fileManager.getDbaDirPath(), ""));
        fd.setConfirmOverwrite(true);
        if (fd.exec()) {
            if (fd.selectedFiles().size() == 0)
                return;
            QString newname = fd.selectedFiles()[0];
            QFile::remove(urlString);
            QFile::copy(oldname, newname);
            return;
        }

    }
}