Ejemplo n.º 1
0
// Saves the active document in a file.
// [main thread]
void SaveFileCommand::onExecute(Context* context)
{
  const ContextReader reader(context);
  const Document* document(reader.document());

  // If the document is associated to a file in the file-system, we can
  // save it directly without user interaction.
  if (document->isAssociatedToFile()) {
    ContextWriter writer(reader);
    Document* documentWriter = writer.document();

    if (!confirmReadonly(documentWriter->filename()))
      return;

    save_document_in_background(context, documentWriter, true);
    update_screen_for_document(documentWriter);
  }
  // If the document isn't associated to a file, we must to show the
  // save-as dialog to the user to select for first time the file-name
  // for this document.
  else {
    saveAsDialog(reader, "Save File", true);
  }
}
Ejemplo n.º 2
0
void VolumeIOHelper::showFileSaveDialog(const VolumeBase* volume) {
    tgtAssert(volume, "null pointer passed");

    tgtAssert(volumeSerializerPopulator_, "no volumeserializerpopulator");
    tgtAssert(volumeSerializerPopulator_->getVolumeSerializer(), "no volume serializer");

    //
    // 1. Setup and execute file save dialog
    //

    // open path
    std::string savePath;
    QSettings settings;
    settings.beginGroup("VolumeIOHelper");
    if (settings.contains("lastVolumePath"))
        savePath = settings.value("lastVolumePath").toString().toStdString();
    else
        savePath = VoreenApplication::app()->getUserDataPath("volumes");
    // we want absolute path name to prevent problems when the file dialog perform chdir()
    QDir openDir(QString::fromStdString(savePath));

    // create one filter per volume writer and extension
    QStringList filters;
    std::map<std::string, std::pair<VolumeWriter*, std::string> > filterToWriterMap;
    std::vector<VolumeWriter*> volumeWriters =
        volumeSerializerPopulator_->getVolumeSerializer()->getWriters();
    for (size_t i=0; i<volumeWriters.size(); i++) {
        VolumeWriter* curWriter = volumeWriters.at(i);

        // extensions
        std::vector<std::string> extensionVec = curWriter->getSupportedExtensions();
        for (size_t j=0; j<extensionVec.size(); j++) {
            std::string extension = extensionVec.at(j);
            std::string filterStr = curWriter->getFormatDescription() + " (*." + extension + ")";
            if (extension == "vvd")
                filters.insert(0, QString::fromStdString(filterStr)); //< put VVD format at front
            else
                filters << QString::fromStdString(filterStr);
            filterToWriterMap.insert(
                std::pair<std::string, std::pair<VolumeWriter*, std::string> >(filterStr, std::pair<VolumeWriter*, std::string>(curWriter, extension)));
        }

        // filename
        std::vector<std::string> filenamesVec = curWriter->getSupportedFilenames();
        for (size_t j=0; j<filenamesVec.size(); j++) {
            std::string filename = filenamesVec.at(j);
            std::string filterStr = curWriter->getFormatDescription() + " (" + filename + ")";
            filters << QString::fromStdString(filterStr);
            filterToWriterMap.insert(
                std::pair<std::string, std::pair<VolumeWriter*, std::string> >(filterStr, std::pair<VolumeWriter*, std::string>(curWriter, filename)));
        }

    }

    // sidebar URLs
    QList<QUrl> urls;
    urls << QUrl::fromLocalFile(VoreenApplication::app()->getResourcePath("volumes").c_str());
    urls << QUrl::fromLocalFile(VoreenApplication::app()->getUserDataPath().c_str());
    urls << QUrl::fromLocalFile(VoreenApplication::app()->getBasePath("modules").c_str());
    if (QDir(VoreenApplication::app()->getBasePath("custommodules").c_str()).exists())
        urls << QUrl::fromLocalFile(VoreenApplication::app()->getBasePath("custommodules").c_str());
    if (VoreenApplication::app()->getTestDataPath() != "")
        urls << QUrl::fromLocalFile(VoreenApplication::app()->getTestDataPath().c_str());
    urls << QUrl::fromLocalFile(QDesktopServices::storageLocation(QDesktopServices::DesktopLocation));
    urls << QUrl::fromLocalFile(QDesktopServices::storageLocation(QDesktopServices::HomeLocation));

    // create dialog
    QFileDialog saveAsDialog(parent_, tr("Save Volume..."), openDir.absolutePath(), "");
    saveAsDialog.setNameFilters(filters);
    saveAsDialog.setSidebarUrls(urls);
    saveAsDialog.setViewMode(QFileDialog::Detail);
    saveAsDialog.setAcceptMode(QFileDialog::AcceptSave);
    saveAsDialog.setFileMode(QFileDialog::AnyFile);
    saveAsDialog.setConfirmOverwrite(true);

    // execute dialog
    if (saveAsDialog.exec() != QDialog::Accepted)
        return;

    // retrieve selected filename from dialog
    const QStringList& lst = saveAsDialog.selectedFiles();
    if (lst.empty()) {
        LWARNING("no file selected");
        return;
    }
    else if (lst.size() > 1) {
        LWARNING("more than one file selected");
        return;
    }
    std::string filepath = lst.first().toStdString();

    // retrieve the user selected file filter
    QString selectedFilter = saveAsDialog.selectedFilter();

    // store dialog path
    settings.setValue("lastVolumePath", saveAsDialog.directory().absolutePath());
    settings.endGroup();


    //
    // 2. Save file to specified path (depending on selected filter)
    //
    tgtAssert(volumeSerializerPopulator_, "no volumeserializerpopulator");
    if (filterToWriterMap.find(selectedFilter.toStdString()) == filterToWriterMap.end()) {
        LWARNING("unknown filter selected");
        return;
    }
    VolumeWriter* writer = filterToWriterMap.find(selectedFilter.toStdString())->second.first;

    // if file path does not end with extension, add extension to path
    std::string selectedExtension = filterToWriterMap.find(selectedFilter.toStdString())->second.second;
    std::string filename = tgt::FileSystem::fileName(filepath);
    if (filename != selectedExtension && !QString::fromStdString(filename).endsWith(QString::fromStdString("." + selectedExtension)))
        filepath += "." + selectedExtension;

    LDEBUG("saving volume: " << filepath);
    saveVolumeToPath(volume, writer, filepath);
}
Ejemplo n.º 3
0
void SaveFileCopyAsCommand::onExecute(Context* context)
{
  Doc* doc = context->activeDocument();
  std::string outputFilename = m_filename;
  std::string layers = kAllLayers;
  std::string frames = kAllFrames;
  double xscale = 1.0;
  double yscale = 1.0;
  bool applyPixelRatio = false;
  doc::AniDir aniDirValue = convert_string_to_anidir(m_aniDir);
  bool isForTwitter = false;

#if ENABLE_UI
  if (context->isUIAvailable()) {
    ExportFileWindow win(doc);
    bool askOverwrite = true;

    win.SelectOutputFile.connect(
      [this, &win, &askOverwrite, context, doc]() -> std::string {
        std::string result =
          saveAsDialog(
            context, "Export",
            win.outputFilenameValue(), false, false,
            (doc->isAssociatedToFile() ? doc->filename():
                                         std::string()));
        if (!result.empty())
          askOverwrite = false; // Already asked in the file selector dialog

        return result;
      });

  again:;
    if (!win.show())
      return;

    outputFilename = win.outputFilenameValue();

    if (askOverwrite &&
        base::is_file(outputFilename)) {
      int ret = OptionalAlert::show(
        Preferences::instance().exportFile.showOverwriteFilesAlert,
        1, // Yes is the default option when the alert dialog is disabled
        fmt::format(Strings::alerts_overwrite_files_on_export(),
                    outputFilename));
      if (ret != 1)
        goto again;
    }

    // Save the preferences used to export the file, so if we open the
    // window again, we will have the same options.
    win.savePref();

    layers = win.layersValue();
    frames = win.framesValue();
    xscale = yscale = win.resizeValue();
    applyPixelRatio = win.applyPixelRatio();
    aniDirValue = win.aniDirValue();
    isForTwitter = win.isForTwitter();
  }
#endif

  // Pixel ratio
  if (applyPixelRatio) {
    doc::PixelRatio pr = doc->sprite()->pixelRatio();
    xscale *= pr.w;
    yscale *= pr.h;
  }

  // Apply scale
  const undo::UndoState* undoState = nullptr;
  bool undoResize = false;
  if (xscale != 1.0 || yscale != 1.0) {
    Command* resizeCmd = Commands::instance()->byId(CommandId::SpriteSize());
    ASSERT(resizeCmd);
    if (resizeCmd) {
      int width = doc->sprite()->width();
      int height = doc->sprite()->height();
      int newWidth = int(double(width) * xscale);
      int newHeight = int(double(height) * yscale);
      if (newWidth < 1) newWidth = 1;
      if (newHeight < 1) newHeight = 1;
      if (width != newWidth || height != newHeight) {
        doc->setInhibitBackup(true);
        undoState = doc->undoHistory()->currentState();
        undoResize = true;

        Params params;
        params.set("use-ui", "false");
        params.set("width", base::convert_to<std::string>(newWidth).c_str());
        params.set("height", base::convert_to<std::string>(newHeight).c_str());
        params.set("resize-method", "nearest-neighbor"); // TODO add algorithm in the UI?
        context->executeCommand(resizeCmd, params);
      }
    }
  }

  {
    RestoreVisibleLayers layersVisibility;
    if (context->isUIAvailable()) {
      Site site = context->activeSite();

      // Selected layers to export
      calculate_visible_layers(site,
                               layers,
                               layersVisibility);

      // Selected frames to export
      SelectedFrames selFrames;
      FrameTag* frameTag = calculate_selected_frames(
        site, frames, selFrames);
      if (frameTag)
        m_frameTag = frameTag->name();
      m_selFrames = selFrames;
      m_adjustFramesByFrameTag = false;
    }

    base::ScopedValue<std::string> restoreAniDir(
      m_aniDir,
      convert_anidir_to_string(aniDirValue), // New value
      m_aniDir);                             // Restore old value

    // TODO This should be set as options for the specific encoder
    GifEncoderDurationFix fixGif(isForTwitter);
    PngEncoderOneAlphaPixel fixPng(isForTwitter);

    saveDocumentInBackground(
      context, doc, outputFilename, false);
  }

  // Undo resize
  if (undoResize &&
      undoState != doc->undoHistory()->currentState()) {
    moveToUndoState(doc, undoState);
    doc->setInhibitBackup(false);
  }
}
Ejemplo n.º 4
0
void SaveFileAsCommand::onExecute(Context* context)
{
  Doc* document = context->activeDocument();
  saveAsDialog(context, "Save As",
               document->filename(), true);
}
Ejemplo n.º 5
0
void SaveFileAsCommand::onExecute(Context* context)
{
  const ContextReader reader(context);
  saveAsDialog(reader, "Save As", true);
}