<commit_before>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.

// Copyright (c) 2016 cDc <cdc.seacave@gmail.com>, Pierre MOULON

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/cameras/Camera_Pinhole.hpp"
#include "openMVG/cameras/Camera_undistort_image.hpp"
#include "openMVG/image/image_io.hpp"
#include "openMVG/sfm/sfm_data.hpp"
#include "openMVG/sfm/sfm_data_io.hpp"

#define _USE_EIGEN
#include "InterfaceMVS.h"

#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include "third_party/progress/progress.hpp"

using namespace openMVG;
using namespace openMVG::cameras;
using namespace openMVG::geometry;
using namespace openMVG::image;
using namespace openMVG::sfm;

#include <cstdlib>
#include <string>

bool exportToOpenMVS(
  const SfM_Data & sfm_data,
  const std::string & sOutFile,
  const std::string & sOutDir
  )
{
  // Create undistorted images directory structure
  if (!stlplus::is_folder(sOutDir))
  {
    stlplus::folder_create(sOutDir);
    if (!stlplus::is_folder(sOutDir))
    {
      std::cerr << "Cannot access to one of the desired output directory" << std::endl;
      return false;
    }
  }

  // Export data :
  MVS::Interface scene;
  size_t nPoses(0);
  const uint32_t nViews((uint32_t)sfm_data.GetViews().size());

  C_Progress_display my_progress_bar(nViews);

  // OpenMVG can have not contiguous index, use a map to create the required OpenMVS contiguous ID index
  std::map<openMVG::IndexT, uint32_t> map_intrinsic, map_view;

  // define a platform with all the intrinsic group
  for (const auto& intrinsic: sfm_data.GetIntrinsics())
  {
    if (isPinhole(intrinsic.second->getType()))
    {
      const Pinhole_Intrinsic * cam = dynamic_cast<const Pinhole_Intrinsic*>(intrinsic.second.get());
      if (map_intrinsic.count(intrinsic.first) == 0)
        map_intrinsic.insert(std::make_pair(intrinsic.first, scene.platforms.size()));
      MVS::Interface::Platform platform;
      // add the camera
      MVS::Interface::Platform::Camera camera;
      camera.K = cam->K();
      // sub-pose
      camera.R = Mat3::Identity();
      camera.C = Vec3::Zero();
      platform.cameras.push_back(camera);
      scene.platforms.push_back(platform);
    }
  }

  // define images & poses
  scene.images.reserve(nViews);
  for (const auto& view : sfm_data.GetViews())
  {
    map_view[view.first] = scene.images.size();
    MVS::Interface::Image image;
    const std::string srcImage = stlplus::create_filespec(sfm_data.s_root_path, view.second->s_Img_path);
    image.name = stlplus::create_filespec(sOutDir, view.second->s_Img_path);
    image.platformID = map_intrinsic.at(view.second->id_intrinsic);
    MVS::Interface::Platform& platform = scene.platforms[image.platformID];
    image.cameraID = 0;
    if (sfm_data.IsPoseAndIntrinsicDefined(view.second.get()) && stlplus::is_file(srcImage))
    {
      MVS::Interface::Platform::Pose pose;
      image.poseID = platform.poses.size();
      const openMVG::geometry::Pose3 poseMVG(sfm_data.GetPoseOrDie(view.second.get()));
      pose.R = poseMVG.rotation();
      pose.C = poseMVG.center();
      // export undistorted images
      const openMVG::cameras::IntrinsicBase * cam = sfm_data.GetIntrinsics().at(view.second->id_intrinsic).get();
      if (cam->have_disto())
      {
        // undistort image and save it
        Image<openMVG::image::RGBColor> imageRGB, imageRGB_ud;
        ReadImage(srcImage.c_str(), &imageRGB);
        UndistortImage(imageRGB, cam, imageRGB_ud, BLACK);
        WriteImage(image.name.c_str(), imageRGB_ud);
      }
      else
      {
        // just copy image
        stlplus::file_copy(srcImage, image.name);
      }
      platform.poses.push_back(pose);
      ++nPoses;
    }
    else
    {
      // image have not valid pose, so set an undefined pose
      image.poseID = NO_ID;
      // just copy the image
      stlplus::file_copy(srcImage, image.name);
    }
    scene.images.push_back(image);
    ++my_progress_bar;
  }

  // define structure
  scene.vertices.reserve(sfm_data.GetLandmarks().size());
  for (const auto& vertex: sfm_data.GetLandmarks())
  {
    const Landmark & landmark = vertex.second;
    MVS::Interface::Vertex vert;
    MVS::Interface::Vertex::ViewArr& views = vert.views;
    for (const auto& observation: landmark.obs)
    {
      const auto it(map_view.find(observation.first));
      if (it != map_view.end()) {
        MVS::Interface::Vertex::View view;
        view.imageID = it->second;
        view.confidence = 0;
        views.push_back(view);
      }
    }
    if (views.size() < 2)
      continue;
    std::sort(
      views.begin(), views.end(),
      [] (const MVS::Interface::Vertex::View& view0, const MVS::Interface::Vertex::View& view1)
      {
        return view0.imageID < view1.imageID;
      }
    );
    vert.X = landmark.X.cast<float>();
    scene.vertices.push_back(vert);
  }

  // normalize camera intrinsics
  for (size_t p=0; p<scene.platforms.size(); ++p)
  {
    MVS::Interface::Platform& platform = scene.platforms[p];
    for (size_t c=0; c<platform.cameras.size(); ++c) {
      MVS::Interface::Platform::Camera& camera = platform.cameras[c];
      // find one image using this camera
      MVS::Interface::Image* pImage(NULL);
      for (MVS::Interface::Image& image: scene.images)
      {
        if (image.platformID == p && image.cameraID == c && image.poseID != NO_ID)
        {
          pImage = ℑ
          break;
        }
      }
      if (pImage == NULL)
      {
        std::cerr << "error: no image using camera " << c << " of platform " << p << std::endl;
        continue;
      }
      // read image meta-data
      ImageHeader imageHeader;
      ReadImageHeader(pImage->name.c_str(), &imageHeader);
      const double fScale(1.0/std::max(imageHeader.width, imageHeader.height));
      camera.K(0, 0) *= fScale;
      camera.K(1, 1) *= fScale;
      camera.K(0, 2) *= fScale;
      camera.K(1, 2) *= fScale;
    }
  }

  // write OpenMVS data
  if (!ARCHIVE::SerializeSave(scene, sOutFile))
    return false;

  std::cout
    << "Scene saved to OpenMVS interface format:\n"
    << "\t" << scene.images.size() << " images (" << nPoses << " calibrated)\n"
    << "\t" << scene.vertices.size() << " Landmarks\n";
  return true;
}

int main(int argc, char *argv[])
{
  CmdLine cmd;
  std::string sSfM_Data_Filename;
  std::string sOutFile = "scene.mvs";
  std::string sOutDir = "undistorted_images";

  cmd.add( make_option('i', sSfM_Data_Filename, "sfmdata") );
  cmd.add( make_option('o', sOutFile, "outfile") );
  cmd.add( make_option('d', sOutDir, "outdir") );

  try {
      if (argc == 1) throw std::string("Invalid command line parameter.");
      cmd.process(argc, argv);
  } catch(const std::string& s) {
      std::cerr << "Usage: " << argv[0] << '\n'
      << "[-i|--sfmdata] filename, the SfM_Data file to convert\n"
      << "[-o|--outfile] OpenMVS scene file\n"
      << "[-d|--outdir] undistorted images path\n"
      << std::endl;

      std::cerr << s << std::endl;
      return EXIT_FAILURE;
  }

  // Read the input SfM scene
  SfM_Data sfm_data;
  if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(ALL))) {
    std::cerr << std::endl
      << "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read." << std::endl;
    return EXIT_FAILURE;
  }

  if (exportToOpenMVS(sfm_data, sOutFile, sOutDir))
  {
    return EXIT_SUCCESS;
  }
  return EXIT_FAILURE;
}
<commit_msg>Enhancement: OpenMVS file format versioning #869<commit_after>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.

// Copyright (c) 2016 cDc <cdc.seacave@gmail.com>, Pierre MOULON

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/cameras/Camera_Pinhole.hpp"
#include "openMVG/cameras/Camera_undistort_image.hpp"
#include "openMVG/image/image_io.hpp"
#include "openMVG/sfm/sfm_data.hpp"
#include "openMVG/sfm/sfm_data_io.hpp"

#define _USE_EIGEN
#include "InterfaceMVS.h"

#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include "third_party/progress/progress.hpp"

using namespace openMVG;
using namespace openMVG::cameras;
using namespace openMVG::geometry;
using namespace openMVG::image;
using namespace openMVG::sfm;

#include <cstdlib>
#include <string>

bool exportToOpenMVS(
  const SfM_Data & sfm_data,
  const std::string & sOutFile,
  const std::string & sOutDir
  )
{
  // Create undistorted images directory structure
  if (!stlplus::is_folder(sOutDir))
  {
    stlplus::folder_create(sOutDir);
    if (!stlplus::is_folder(sOutDir))
    {
      std::cerr << "Cannot access to one of the desired output directory" << std::endl;
      return false;
    }
  }

  // Export data :
  MVS::Interface scene;
  size_t nPoses(0);
  const uint32_t nViews((uint32_t)sfm_data.GetViews().size());

  C_Progress_display my_progress_bar(nViews);

  // OpenMVG can have not contiguous index, use a map to create the required OpenMVS contiguous ID index
  std::map<openMVG::IndexT, uint32_t> map_intrinsic, map_view;

  // define a platform with all the intrinsic group
  for (const auto& intrinsic: sfm_data.GetIntrinsics())
  {
    if (isPinhole(intrinsic.second->getType()))
    {
      const Pinhole_Intrinsic * cam = dynamic_cast<const Pinhole_Intrinsic*>(intrinsic.second.get());
      if (map_intrinsic.count(intrinsic.first) == 0)
        map_intrinsic.insert(std::make_pair(intrinsic.first, scene.platforms.size()));
      MVS::Interface::Platform platform;
      // add the camera
      MVS::Interface::Platform::Camera camera;
      camera.K = cam->K();
      // sub-pose
      camera.R = Mat3::Identity();
      camera.C = Vec3::Zero();
      platform.cameras.push_back(camera);
      scene.platforms.push_back(platform);
    }
  }

  // define images & poses
  scene.images.reserve(nViews);
  for (const auto& view : sfm_data.GetViews())
  {
    map_view[view.first] = scene.images.size();
    MVS::Interface::Image image;
    const std::string srcImage = stlplus::create_filespec(sfm_data.s_root_path, view.second->s_Img_path);
    image.name = stlplus::create_filespec(sOutDir, view.second->s_Img_path);
    image.platformID = map_intrinsic.at(view.second->id_intrinsic);
    MVS::Interface::Platform& platform = scene.platforms[image.platformID];
    image.cameraID = 0;
    if (sfm_data.IsPoseAndIntrinsicDefined(view.second.get()) && stlplus::is_file(srcImage))
    {
      MVS::Interface::Platform::Pose pose;
      image.poseID = platform.poses.size();
      const openMVG::geometry::Pose3 poseMVG(sfm_data.GetPoseOrDie(view.second.get()));
      pose.R = poseMVG.rotation();
      pose.C = poseMVG.center();
      // export undistorted images
      const openMVG::cameras::IntrinsicBase * cam = sfm_data.GetIntrinsics().at(view.second->id_intrinsic).get();
      if (cam->have_disto())
      {
        // undistort image and save it
        Image<openMVG::image::RGBColor> imageRGB, imageRGB_ud;
        ReadImage(srcImage.c_str(), &imageRGB);
        UndistortImage(imageRGB, cam, imageRGB_ud, BLACK);
        WriteImage(image.name.c_str(), imageRGB_ud);
      }
      else
      {
        // just copy image
        stlplus::file_copy(srcImage, image.name);
      }
      platform.poses.push_back(pose);
      ++nPoses;
    }
    else
    {
      // image have not valid pose, so set an undefined pose
      image.poseID = NO_ID;
      // just copy the image
      stlplus::file_copy(srcImage, image.name);
    }
    scene.images.emplace_back(image);
    ++my_progress_bar;
  }

  // define structure
  scene.vertices.reserve(sfm_data.GetLandmarks().size());
  for (const auto& vertex: sfm_data.GetLandmarks())
  {
    const Landmark & landmark = vertex.second;
    MVS::Interface::Vertex vert;
    MVS::Interface::Vertex::ViewArr& views = vert.views;
    for (const auto& observation: landmark.obs)
    {
      const auto it(map_view.find(observation.first));
      if (it != map_view.end()) {
        MVS::Interface::Vertex::View view;
        view.imageID = it->second;
        view.confidence = 0;
        views.push_back(view);
      }
    }
    if (views.size() < 2)
      continue;
    std::sort(
      views.begin(), views.end(),
      [] (const MVS::Interface::Vertex::View& view0, const MVS::Interface::Vertex::View& view1)
      {
        return view0.imageID < view1.imageID;
      }
    );
    vert.X = landmark.X.cast<float>();
    scene.vertices.push_back(vert);
  }

  // normalize camera intrinsics
  for (size_t p=0; p<scene.platforms.size(); ++p)
  {
    MVS::Interface::Platform& platform = scene.platforms[p];
    for (size_t c=0; c<platform.cameras.size(); ++c) {
      MVS::Interface::Platform::Camera& camera = platform.cameras[c];
      // find one image using this camera
      MVS::Interface::Image* pImage(NULL);
      for (MVS::Interface::Image& image: scene.images)
      {
        if (image.platformID == p && image.cameraID == c && image.poseID != NO_ID)
        {
          pImage = ℑ
          break;
        }
      }
      if (pImage == NULL)
      {
        std::cerr << "error: no image using camera " << c << " of platform " << p << std::endl;
        continue;
      }
      // read image meta-data
      ImageHeader imageHeader;
      ReadImageHeader(pImage->name.c_str(), &imageHeader);
      const double fScale(1.0/std::max(imageHeader.width, imageHeader.height));
      camera.K(0, 0) *= fScale;
      camera.K(1, 1) *= fScale;
      camera.K(0, 2) *= fScale;
      camera.K(1, 2) *= fScale;
    }
  }

  // write OpenMVS data
  if (!ARCHIVE::SerializeSave(scene, sOutFile))
    return false;

  std::cout
    << "Scene saved to OpenMVS interface format:\n"
    << "\t" << scene.images.size() << " images (" << nPoses << " calibrated)\n"
    << "\t" << scene.vertices.size() << " Landmarks\n";
  return true;
}

int main(int argc, char *argv[])
{
  CmdLine cmd;
  std::string sSfM_Data_Filename;
  std::string sOutFile = "scene.mvs";
  std::string sOutDir = "undistorted_images";

  cmd.add( make_option('i', sSfM_Data_Filename, "sfmdata") );
  cmd.add( make_option('o', sOutFile, "outfile") );
  cmd.add( make_option('d', sOutDir, "outdir") );

  try {
      if (argc == 1) throw std::string("Invalid command line parameter.");
      cmd.process(argc, argv);
  } catch(const std::string& s) {
      std::cerr << "Usage: " << argv[0] << '\n'
      << "[-i|--sfmdata] filename, the SfM_Data file to convert\n"
      << "[-o|--outfile] OpenMVS scene file\n"
      << "[-d|--outdir] undistorted images path\n"
      << std::endl;

      std::cerr << s << std::endl;
      return EXIT_FAILURE;
  }

  if (stlplus::extension_part(sOutFile) != "mvs") {
    std::cerr << std::endl
      << "Invalid output file extension: " << sOutFile << std::endl
      << "You must use a filename with a .mvs extension." << std::endl;
      return EXIT_FAILURE;
  }

  // Read the input SfM scene
  SfM_Data sfm_data;
  if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(ALL))) {
    std::cerr << std::endl
      << "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read." << std::endl;
    return EXIT_FAILURE;
  }

  if (!exportToOpenMVS(sfm_data, sOutFile, sOutDir))
  {
    std::cerr << std::endl
      << "The output openMVS scene file cannot be written" << std::endl;
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*===================================================================
APM_PLANNER Open Source Ground Control Station

(c) 2013 APM_PLANNER PROJECT <http://www.diydrones.com>

This file is part of the APM_PLANNER project

    APM_PLANNER is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    APM_PLANNER is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with APM_PLANNER. If not, see <http://www.gnu.org/licenses/>.

======================================================================*/

#include "QsLog.h"
#include "RangeFinderConfig.h"
#include <QMessageBox>

#include "QGCCore.h"

RangeFinderConfig::RangeFinderConfig(QWidget *parent) : AP2ConfigWidget(parent)
{
    ui.setupUi(this);

    // Disable scroll wheel from easily triggering settings change
    QList<QWidget*> widgetList = this->findChildren<QWidget*>();
    for (int i=0;i<widgetList.size();i++)
    {
        if (qobject_cast<QComboBox*>(widgetList[i]) || qobject_cast<QAbstractSpinBox*>(widgetList[i]) || qobject_cast<QAbstractSlider*>(widgetList[i]))
        {
            widgetList[i]->installEventFilter(QGCMouseWheelEventFilter::getFilter());
        }
    }

    // Setup Ui
    ui.typeComboBox->addItem("None", 0 );
    ui.typeComboBox->addItem("Analog", 1 );
    ui.typeComboBox->addItem("APM2-MaxbotixI2C", 2 );
    ui.typeComboBox->addItem("APM2-PulsedLightI2C", 3) ;
    ui.typeComboBox->addItem("PX4-I2C", 4 );
    ui.typeComboBox->addItem("PX4-PWM", 5 );

    ui.functionComboBox->addItem("Linear", 0);
    ui.functionComboBox->addItem("Inverted", 1);
    ui.functionComboBox->addItem("Hyperbolic", 2);

    ui.gainSlider->setMinimum(001);
    ui.gainSlider->setMaximum(200);

    enableUi(false);

    AP2ConfigWidget::initConnections();
}

RangeFinderConfig::~RangeFinderConfig()
{
}

void RangeFinderConfig::activeUASSet(UASInterface *uas)
{
    if(m_uas){
        disconnect(m_uas, SIGNAL(rangeFinderUpdate(UASInterface*,double,double)),
                   this, SLOT(rangeFinderUpdate(UASInterface*,double,double)));

        disconnect(m_uas,SIGNAL(parameterChanged(int,int,QString,QVariant)),
                   this,SLOT(parameterChanged(int,int,QString,QVariant)));

        disconnect(ui.functionComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(sendParameterUpdates()));
        disconnect(ui.gainSlider, SIGNAL(valueChanged(int)), this, SLOT(gainSliderChanged(int)));
        disconnect(ui.gainSlider, SIGNAL(sliderReleased()), this, SLOT(sendParameterUpdates()));
        disconnect(ui.maxDistanceEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        disconnect(ui.minDistanceEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        disconnect(ui.offsetEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        disconnect(ui.inputPinEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        disconnect(ui.rmetricCheckBox, SIGNAL(stateChanged(int)), this, SLOT(sendParameterUpdates()));
        disconnect(ui.scalingEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        disconnect(ui.settleTimeEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        disconnect(ui.stopPinEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
    }
    m_uas = uas;
    if(m_uas){
        connect(m_uas, SIGNAL(rangeFinderUpdate(UASInterface*,double,double)),
                this, SLOT(rangeFinderUpdate(UASInterface*,double,double)));

        connect(m_uas,SIGNAL(parameterChanged(int,int,QString,QVariant)),
                   this,SLOT(parameterChanged(int,int,QString,QVariant)));

        connect(ui.typeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(rangeFinderTypeChanged(int)));
        connect(ui.functionComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(sendParameterUpdates()));
        connect(ui.gainSlider, SIGNAL(valueChanged(int)), this, SLOT(gainSliderChanged(int)));
        connect(ui.gainSlider, SIGNAL(sliderReleased()), this, SLOT(sendParameterUpdates()));
        connect(ui.maxDistanceEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        connect(ui.minDistanceEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        connect(ui.offsetEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        connect(ui.inputPinEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        connect(ui.rmetricCheckBox, SIGNAL(stateChanged(int)), this, SLOT(sendParameterUpdates()));
        connect(ui.scalingEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        connect(ui.settleTimeEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        connect(ui.stopPinEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
    }
}

void RangeFinderConfig::sendParameterUpdates()
{
    if (!m_uas)
    {
        QMessageBox::information(0,tr("Error"),tr("Please connect to a MAV before attempting to set configuration"));
        return;
    }

    QGCUASParamManager* pm = m_uas->getParamManager();
    pm->setParameter(1,"RNGFND_TYPE", ui.typeComboBox->currentIndex());
    pm->setParameter(1,"RNGFND_FUNCTION", ui.functionComboBox->currentIndex());
    pm->setParameter(1,"RNGFND_GAIN", ui.gainSlider->value()/100.0);
    pm->setParameter(1,"RNGFND_MAX_CM", ui.maxDistanceEdit->text().toDouble());
    pm->setParameter(1,"RNGFND_MIN_CM", ui.minDistanceEdit->text().toDouble());
    pm->setParameter(1,"RNGFND_OFFSET", ui.offsetEdit->text().toDouble());
    pm->setParameter(1,"RNGFND_PIN", ui.inputPinEdit->text().toInt());
    int rmetric = ui.rmetricCheckBox->checkState() == Qt::Checked ? 1 : 0;
    pm->setParameter(1,"RNGFND_RMETRIC" ,rmetric);
    pm->setParameter(1,"RNGFND_SCALING", ui.scalingEdit->text().toDouble());
    pm->setParameter(1,"RNGFND_SETTLE_MS", ui.settleTimeEdit->text().toDouble());
    pm->setParameter(1,"RNGFND_STOP_PIN", ui.stopPinEdit->text().toInt());
}

void RangeFinderConfig::enableUi(bool state)
{
    ui.functionComboBox->setEnabled(state);
    ui.gainSlider->setEnabled(state);
    ui.maxDistanceEdit->setEnabled(state);
    ui.minDistanceEdit->setEnabled(state);
    ui.offsetEdit->setEnabled(state);
    ui.inputPinEdit->setEnabled(state);
    ui.rmetricCheckBox->setEnabled(state);
    ui.scalingEdit->setEnabled(state);
    ui.settleTimeEdit->setEnabled(state);
    ui.stopPinEdit->setEnabled(state);
}

void RangeFinderConfig::rangeFinderTypeChanged(int index)
{
    Q_UNUSED(index);
    sendParameterUpdates();
}

void RangeFinderConfig::gainSliderChanged(int value)
{
    ui.gainLabel->blockSignals(true);
    ui.gainLabel->setText(QString::number(value/100.0, 'g', 2));
    ui.gainLabel->blockSignals(false);
}

void RangeFinderConfig::parameterChanged(int uas, int component, QString parameterName, QVariant value)
{
    Q_UNUSED(uas);
    Q_UNUSED(component);

    if (parameterName.startsWith("RNGFND")){
        QLOG_DEBUG() << "RNGFND param:" << parameterName << " value:" << value;

        if (parameterName == "RNGFND_TYPE") {
            ui.typeComboBox->blockSignals(true);
            ui.typeComboBox->setCurrentIndex(value.toInt());
            ui.typeComboBox->blockSignals(false);

            if (value.toInt() == 0) {
                enableUi(false);
            } else {
                enableUi(true);
            }

        } else if (parameterName == "RNGFND_FUNCTION") {
            ui.functionComboBox->blockSignals(true);
            ui.functionComboBox->setCurrentIndex(value.toInt());
            ui.functionComboBox->blockSignals(false);

        } else if (parameterName == "RNGFND_GAIN") {
            ui.gainSlider->blockSignals(true);
            ui.gainLabel->blockSignals(true);
            ui.gainSlider->setValue(value.toDouble()*100);
            ui.gainLabel->setText(QString::number(value.toDouble(), 'g', 2));
            ui.gainSlider->blockSignals(false);
            ui.gainLabel->blockSignals(false);

        } else if (parameterName == "RNGFND_MAX_CM") {
            ui.maxDistanceEdit->blockSignals(true);
            ui.maxDistanceEdit->setText(value.toString());
            ui.maxDistanceEdit->blockSignals(false);

        } else if (parameterName == "RNGFND_MIN_CM") {
            ui.minDistanceEdit->blockSignals(true);
            ui.minDistanceEdit->setText(value.toString());
            ui.minDistanceEdit->blockSignals(false);

        } else if (parameterName == "RNGFND_OFFSET") {
            ui.offsetEdit->blockSignals(true);
            ui.offsetEdit->setText(value.toString());
            ui.offsetEdit->blockSignals(false);

        } else if (parameterName == "RNGFND_PIN") {
            ui.inputPinEdit->blockSignals(true);
            ui.inputPinEdit->setText(value.toString());
            ui.inputPinEdit->blockSignals(false);

        } else if (parameterName == "RNGFND_STOP_PIN") {
            ui.stopPinEdit->blockSignals(true);
            ui.stopPinEdit->setText(value.toString());
            ui.stopPinEdit->blockSignals(false);

        } else if (parameterName == "RNGFND_RMETRIC") {
            ui.rmetricCheckBox->blockSignals(true);
            ui.rmetricCheckBox->setChecked(value.toBool());
            ui.rmetricCheckBox->blockSignals(false);

        } else if (parameterName == "RNGFND_SCALING") {
            ui.scalingEdit->blockSignals(true);
            ui.scalingEdit->setText(value.toString());
            ui.scalingEdit->blockSignals(false);

        } else if (parameterName == "RNGFND_SETTLE_MS") {
            ui.settleTimeEdit->blockSignals(true);
            ui.settleTimeEdit->setText(value.toString());
            ui.settleTimeEdit->blockSignals(false);
        }

    }
}

void RangeFinderConfig::rangeFinderUpdate(UASInterface *uas, double distance, double voltage)
{
    Q_UNUSED(uas);
    ui.rangeLineEdit->setText(QString::number(distance, 'g', 2) + "m");
    ui.voltageLineEdit->setText(QString::number(voltage, 'g', 3));
}
<commit_msg>Range Finder: Add BBB-PRU support<commit_after>/*===================================================================
APM_PLANNER Open Source Ground Control Station

(c) 2013 APM_PLANNER PROJECT <http://www.diydrones.com>

This file is part of the APM_PLANNER project

    APM_PLANNER is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    APM_PLANNER is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with APM_PLANNER. If not, see <http://www.gnu.org/licenses/>.

======================================================================*/

#include "QsLog.h"
#include "RangeFinderConfig.h"
#include <QMessageBox>

#include "QGCCore.h"

RangeFinderConfig::RangeFinderConfig(QWidget *parent) : AP2ConfigWidget(parent)
{
    ui.setupUi(this);

    // Disable scroll wheel from easily triggering settings change
    QList<QWidget*> widgetList = this->findChildren<QWidget*>();
    for (int i=0;i<widgetList.size();i++)
    {
        if (qobject_cast<QComboBox*>(widgetList[i]) || qobject_cast<QAbstractSpinBox*>(widgetList[i]) || qobject_cast<QAbstractSlider*>(widgetList[i]))
        {
            widgetList[i]->installEventFilter(QGCMouseWheelEventFilter::getFilter());
        }
    }

    // Setup Ui
    ui.typeComboBox->addItem("None", 0 );
    ui.typeComboBox->addItem("Analog", 1 );
    ui.typeComboBox->addItem("APM2-MaxbotixI2C", 2 );
    ui.typeComboBox->addItem("APM2-PulsedLightI2C", 3) ;
    ui.typeComboBox->addItem("PX4-I2C", 4 );
    ui.typeComboBox->addItem("PX4-PWM", 5 );
    ui.typeComboBox->addItem("BBB-PRU", 6 );

    ui.functionComboBox->addItem("Linear", 0);
    ui.functionComboBox->addItem("Inverted", 1);
    ui.functionComboBox->addItem("Hyperbolic", 2);

    ui.gainSlider->setMinimum(001);
    ui.gainSlider->setMaximum(200);

    enableUi(false);

    AP2ConfigWidget::initConnections();
}

RangeFinderConfig::~RangeFinderConfig()
{
}

void RangeFinderConfig::activeUASSet(UASInterface *uas)
{
    if(m_uas){
        disconnect(m_uas, SIGNAL(rangeFinderUpdate(UASInterface*,double,double)),
                   this, SLOT(rangeFinderUpdate(UASInterface*,double,double)));

        disconnect(m_uas,SIGNAL(parameterChanged(int,int,QString,QVariant)),
                   this,SLOT(parameterChanged(int,int,QString,QVariant)));

        disconnect(ui.functionComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(sendParameterUpdates()));
        disconnect(ui.gainSlider, SIGNAL(valueChanged(int)), this, SLOT(gainSliderChanged(int)));
        disconnect(ui.gainSlider, SIGNAL(sliderReleased()), this, SLOT(sendParameterUpdates()));
        disconnect(ui.maxDistanceEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        disconnect(ui.minDistanceEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        disconnect(ui.offsetEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        disconnect(ui.inputPinEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        disconnect(ui.rmetricCheckBox, SIGNAL(stateChanged(int)), this, SLOT(sendParameterUpdates()));
        disconnect(ui.scalingEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        disconnect(ui.settleTimeEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        disconnect(ui.stopPinEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
    }
    m_uas = uas;
    if(m_uas){
        connect(m_uas, SIGNAL(rangeFinderUpdate(UASInterface*,double,double)),
                this, SLOT(rangeFinderUpdate(UASInterface*,double,double)));

        connect(m_uas,SIGNAL(parameterChanged(int,int,QString,QVariant)),
                   this,SLOT(parameterChanged(int,int,QString,QVariant)));

        connect(ui.typeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(rangeFinderTypeChanged(int)));
        connect(ui.functionComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(sendParameterUpdates()));
        connect(ui.gainSlider, SIGNAL(valueChanged(int)), this, SLOT(gainSliderChanged(int)));
        connect(ui.gainSlider, SIGNAL(sliderReleased()), this, SLOT(sendParameterUpdates()));
        connect(ui.maxDistanceEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        connect(ui.minDistanceEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        connect(ui.offsetEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        connect(ui.inputPinEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        connect(ui.rmetricCheckBox, SIGNAL(stateChanged(int)), this, SLOT(sendParameterUpdates()));
        connect(ui.scalingEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        connect(ui.settleTimeEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
        connect(ui.stopPinEdit, SIGNAL(editingFinished()), this, SLOT(sendParameterUpdates()));
    }
}

void RangeFinderConfig::sendParameterUpdates()
{
    if (!m_uas)
    {
        QMessageBox::information(0,tr("Error"),tr("Please connect to a MAV before attempting to set configuration"));
        return;
    }

    QGCUASParamManager* pm = m_uas->getParamManager();
    pm->setParameter(1,"RNGFND_TYPE", ui.typeComboBox->currentIndex());
    pm->setParameter(1,"RNGFND_FUNCTION", ui.functionComboBox->currentIndex());
    pm->setParameter(1,"RNGFND_GAIN", ui.gainSlider->value()/100.0);
    pm->setParameter(1,"RNGFND_MAX_CM", ui.maxDistanceEdit->text().toDouble());
    pm->setParameter(1,"RNGFND_MIN_CM", ui.minDistanceEdit->text().toDouble());
    pm->setParameter(1,"RNGFND_OFFSET", ui.offsetEdit->text().toDouble());
    pm->setParameter(1,"RNGFND_PIN", ui.inputPinEdit->text().toInt());
    int rmetric = ui.rmetricCheckBox->checkState() == Qt::Checked ? 1 : 0;
    pm->setParameter(1,"RNGFND_RMETRIC" ,rmetric);
    pm->setParameter(1,"RNGFND_SCALING", ui.scalingEdit->text().toDouble());
    pm->setParameter(1,"RNGFND_SETTLE_MS", ui.settleTimeEdit->text().toDouble());
    pm->setParameter(1,"RNGFND_STOP_PIN", ui.stopPinEdit->text().toInt());
}

void RangeFinderConfig::enableUi(bool state)
{
    ui.functionComboBox->setEnabled(state);
    ui.gainSlider->setEnabled(state);
    ui.maxDistanceEdit->setEnabled(state);
    ui.minDistanceEdit->setEnabled(state);
    ui.offsetEdit->setEnabled(state);
    ui.inputPinEdit->setEnabled(state);
    ui.rmetricCheckBox->setEnabled(state);
    ui.scalingEdit->setEnabled(state);
    ui.settleTimeEdit->setEnabled(state);
    ui.stopPinEdit->setEnabled(state);
}

void RangeFinderConfig::rangeFinderTypeChanged(int index)
{
    Q_UNUSED(index);
    sendParameterUpdates();
}

void RangeFinderConfig::gainSliderChanged(int value)
{
    ui.gainLabel->blockSignals(true);
    ui.gainLabel->setText(QString::number(value/100.0, 'g', 2));
    ui.gainLabel->blockSignals(false);
}

void RangeFinderConfig::parameterChanged(int uas, int component, QString parameterName, QVariant value)
{
    Q_UNUSED(uas);
    Q_UNUSED(component);

    if (parameterName.startsWith("RNGFND")){
        QLOG_DEBUG() << "RNGFND param:" << parameterName << " value:" << value;

        if (parameterName == "RNGFND_TYPE") {
            ui.typeComboBox->blockSignals(true);
            ui.typeComboBox->setCurrentIndex(value.toInt());
            ui.typeComboBox->blockSignals(false);

            if (value.toInt() == 0) {
                enableUi(false);
            } else {
                enableUi(true);
            }

        } else if (parameterName == "RNGFND_FUNCTION") {
            ui.functionComboBox->blockSignals(true);
            ui.functionComboBox->setCurrentIndex(value.toInt());
            ui.functionComboBox->blockSignals(false);

        } else if (parameterName == "RNGFND_GAIN") {
            ui.gainSlider->blockSignals(true);
            ui.gainLabel->blockSignals(true);
            ui.gainSlider->setValue(value.toDouble()*100);
            ui.gainLabel->setText(QString::number(value.toDouble(), 'g', 2));
            ui.gainSlider->blockSignals(false);
            ui.gainLabel->blockSignals(false);

        } else if (parameterName == "RNGFND_MAX_CM") {
            ui.maxDistanceEdit->blockSignals(true);
            ui.maxDistanceEdit->setText(value.toString());
            ui.maxDistanceEdit->blockSignals(false);

        } else if (parameterName == "RNGFND_MIN_CM") {
            ui.minDistanceEdit->blockSignals(true);
            ui.minDistanceEdit->setText(value.toString());
            ui.minDistanceEdit->blockSignals(false);

        } else if (parameterName == "RNGFND_OFFSET") {
            ui.offsetEdit->blockSignals(true);
            ui.offsetEdit->setText(value.toString());
            ui.offsetEdit->blockSignals(false);

        } else if (parameterName == "RNGFND_PIN") {
            ui.inputPinEdit->blockSignals(true);
            ui.inputPinEdit->setText(value.toString());
            ui.inputPinEdit->blockSignals(false);

        } else if (parameterName == "RNGFND_STOP_PIN") {
            ui.stopPinEdit->blockSignals(true);
            ui.stopPinEdit->setText(value.toString());
            ui.stopPinEdit->blockSignals(false);

        } else if (parameterName == "RNGFND_RMETRIC") {
            ui.rmetricCheckBox->blockSignals(true);
            ui.rmetricCheckBox->setChecked(value.toBool());
            ui.rmetricCheckBox->blockSignals(false);

        } else if (parameterName == "RNGFND_SCALING") {
            ui.scalingEdit->blockSignals(true);
            ui.scalingEdit->setText(value.toString());
            ui.scalingEdit->blockSignals(false);

        } else if (parameterName == "RNGFND_SETTLE_MS") {
            ui.settleTimeEdit->blockSignals(true);
            ui.settleTimeEdit->setText(value.toString());
            ui.settleTimeEdit->blockSignals(false);
        }

    }
}

void RangeFinderConfig::rangeFinderUpdate(UASInterface *uas, double distance, double voltage)
{
    Q_UNUSED(uas);
    ui.rangeLineEdit->setText(QString::number(distance, 'g', 2) + "m");
    ui.voltageLineEdit->setText(QString::number(voltage, 'g', 3));
}
<|endoftext|>


<commit_before>#include "filebrowserwidget.h"

#include <QFileSystemModel>

#include <QDesktopServices>
#include <QHeaderView>
#include <QSettings>

#define SETTINGS_SORTCOLUMN  "_SortColumn"
#define SETTINGS_SORTORDER   "_SortOrder"
#define SETTINGS_CURRENTPATH "_CurrentPath"

FileBrowserWidget::FileBrowserWidget(QWidget *pParent) :
    QTreeView(pParent),
    CommonWidget(pParent)
{
    mFileSystemModel = new QFileSystemModel;

    // We want acces to the full file system

    mFileSystemModel->setRootPath("");

    // Set some properties for the file browser widget itself

    setModel(mFileSystemModel);   // Associate ourselves to mFileSystemModel
    setSortingEnabled(true);      // Allow sorting
    setUniformRowHeights(true);   // Everything ought to be of the same height,
                                  // so set this property to true since it can
                                  // only speed things up which can't harm!

    // Have the columns resize themselves automatically, based on their contents
//---GRY--- IS IT REALLY WHAT WE WANT?! IDEALLY, IT WOULD BE AUTOMATICALLY
//          RESIZED THE FIRST TIME WE SHOW THE WIDGET (AS A RESULT OF THE CALL
//          TO DefaultSettings), AND THEN IT WOULD BE UP TO THE USER TO RESIZE
//          THEM IF HE SO DESIRES. HOWEVER, TO DO THIS, WE NEED THE WIDGET TO BE
//          VISIBLE, SO ONE MIGHT THINK THAT OVERRIDING paintEvent WOULD DO THE
//          TRICK, BUT NO... (FROM A GOOGLE SEARCH, IT WOULD SEEM THAT OTHERS
//          HAVE THE SAME PROBLEM) SO, FOR NOW, WE LEAVE THINGS AS THEY ARE

    header()->setResizeMode(QHeaderView::ResizeToContents);
}

FileBrowserWidget::~FileBrowserWidget()
{
    delete mFileSystemModel;
}

void FileBrowserWidget::retranslateUi()
{
    // Nothing to do for now...
}

void FileBrowserWidget::defaultSettings()
{
    // Sort by ascending drive letters / paths

    sortByColumn(0, Qt::AscendingOrder);

    // Start in the user's home directory and expand it

    QModelIndex homePathModelIndex = mFileSystemModel->index(QDir::homePath());

    setCurrentIndex(homePathModelIndex);
    setExpanded(homePathModelIndex, true);
}

void FileBrowserWidget::loadSettings(const QSettings &pSettings,
                                     const QString &pKey)
{
    // Retrieve the sorting information

    sortByColumn(pSettings.value(pKey+SETTINGS_SORTCOLUMN, 0).toInt(),
                 Qt::SortOrder(pSettings.value(pKey+SETTINGS_SORTORDER,
                                               Qt::AscendingOrder).toInt()));

    // Retrieve the current path and make it visible to the user

    QString currentPath = pSettings.value(pKey+SETTINGS_CURRENTPATH,
                                          QDir::homePath()).toString();
    QString currentPathDir = currentPath;
    QFileInfo currentPathInfo = currentPath;
    bool currentPathIsDir = currentPathInfo.isDir();

    if (!currentPathIsDir) {
        // The current path is not that of a directory, but that of a file (or
        // it doesn't exist), so retrieve the name of the parent folder
        // Note: indeed, to directly set the current index to that of a file
        //       won't give us the expected behaviour (i.e. the parent folder
        //       being open and expanded, and the file selected), so instead one
        //       must set the current index to that of the parent folder and
        //       then select the file

        QDir filePathUp = currentPath;

        filePathUp.cdUp();

        currentPathDir = filePathUp.path();

        // If the parent folder doesn't exist, then we give up and go for the
        // home path

        if (!QFileInfo(currentPathDir).exists())
            currentPathDir = QDir::homePath();
    }

    QModelIndex currentPathModelIndex = mFileSystemModel->index(currentPathDir);

    setCurrentIndex(currentPathModelIndex);
    scrollTo(currentPathModelIndex);

    if (!currentPathIsDir && currentPathInfo.exists())
    {
        // The current path is that of a file and it exists, so select it (see
        // the above note for the reasoning behind this)

        QModelIndex currentPathIndex = mFileSystemModel->index(currentPath);

        setCurrentIndex(currentPathIndex);
        scrollTo(currentPathIndex);
    }

//---GRY--- scrollTo REQUIRES THE WIDGET TO BE PAINTED TO WORK PROPERLY (ESP.
//          WHEN THE NODE TO SCROLL TO IS REALLY DOWN THE TREE). HOWEVER, EVEN
//          BY OVERRIDING paintEvent, I WAS STILL NOT ABLE TO GET THINGS TO WORK
//          AND IT WOULD SEEM (FROM A GOOGLE SEARCH) THAT I AM NOT THE ONLY ONE
//          IN THIS SITUATION... SO, FOR NOW, WE SHALL LEAVE THINGS AS THEY ARE
//          WHICH IS REALLY NOT GREAT, BUT...
}

void FileBrowserWidget::saveSettings(QSettings &pSettings, const QString &pKey)
{
    // Keep track of the sorting information

    pSettings.setValue(pKey+SETTINGS_SORTCOLUMN,
                       header()->sortIndicatorSection());
    pSettings.setValue(pKey+SETTINGS_SORTORDER, header()->sortIndicatorOrder());

    // Keep track of the current folder/file path

    QString currentPath = mFileSystemModel->filePath(currentIndex());

    pSettings.setValue(pKey+SETTINGS_CURRENTPATH, currentPath);
}

QSize FileBrowserWidget::sizeHint() const
{
    // Suggest a default size for the file browser widget
    // Note: this is critical if we want a docked widget, with a file browser
    //       widget on it, to have a decent size when docked to the main window

    return defaultSize(0.15);
}
<commit_msg>Since we haven't managed to get scrollTo to work as expected, we need to call setExpanded.<commit_after>#include "filebrowserwidget.h"

#include <QFileSystemModel>

#include <QDesktopServices>
#include <QHeaderView>
#include <QSettings>

#define SETTINGS_SORTCOLUMN  "_SortColumn"
#define SETTINGS_SORTORDER   "_SortOrder"
#define SETTINGS_CURRENTPATH "_CurrentPath"

FileBrowserWidget::FileBrowserWidget(QWidget *pParent) :
    QTreeView(pParent),
    CommonWidget(pParent)
{
    mFileSystemModel = new QFileSystemModel;

    // We want acces to the full file system

    mFileSystemModel->setRootPath("");

    // Set some properties for the file browser widget itself

    setModel(mFileSystemModel);   // Associate ourselves to mFileSystemModel
    setSortingEnabled(true);      // Allow sorting
    setUniformRowHeights(true);   // Everything ought to be of the same height,
                                  // so set this property to true since it can
                                  // only speed things up which can't harm!

    // Have the columns resize themselves automatically, based on their contents
//---GRY--- IS IT REALLY WHAT WE WANT?! IDEALLY, IT WOULD BE AUTOMATICALLY
//          RESIZED THE FIRST TIME WE SHOW THE WIDGET (AS A RESULT OF THE CALL
//          TO DefaultSettings), AND THEN IT WOULD BE UP TO THE USER TO RESIZE
//          THEM IF HE SO DESIRES. HOWEVER, TO DO THIS, WE NEED THE WIDGET TO BE
//          VISIBLE, SO ONE MIGHT THINK THAT OVERRIDING paintEvent WOULD DO THE
//          TRICK, BUT NO... (FROM A GOOGLE SEARCH, IT WOULD SEEM THAT OTHERS
//          HAVE THE SAME PROBLEM) SO, FOR NOW, WE LEAVE THINGS AS THEY ARE

    header()->setResizeMode(QHeaderView::ResizeToContents);
}

FileBrowserWidget::~FileBrowserWidget()
{
    delete mFileSystemModel;
}

void FileBrowserWidget::retranslateUi()
{
    // Nothing to do for now...
}

void FileBrowserWidget::defaultSettings()
{
    // Sort by ascending drive letters / paths

    sortByColumn(0, Qt::AscendingOrder);

    // Start in the user's home directory and expand it

    QModelIndex homePathModelIndex = mFileSystemModel->index(QDir::homePath());

    setCurrentIndex(homePathModelIndex);
    setExpanded(homePathModelIndex, true);
}

void FileBrowserWidget::loadSettings(const QSettings &pSettings,
                                     const QString &pKey)
{
    // Retrieve the sorting information

    sortByColumn(pSettings.value(pKey+SETTINGS_SORTCOLUMN, 0).toInt(),
                 Qt::SortOrder(pSettings.value(pKey+SETTINGS_SORTORDER,
                                               Qt::AscendingOrder).toInt()));

    // Retrieve the current path and make it visible to the user

    QString currentPath = pSettings.value(pKey+SETTINGS_CURRENTPATH,
                                          QDir::homePath()).toString();
    QString currentPathDir = currentPath;
    QFileInfo currentPathInfo = currentPath;
    bool currentPathIsDir = currentPathInfo.isDir();

    if (!currentPathIsDir) {
        // The current path is not that of a directory, but that of a file (or
        // it doesn't exist), so retrieve the name of the parent folder
        // Note: indeed, to directly set the current index to that of a file
        //       won't give us the expected behaviour (i.e. the parent folder
        //       being open and expanded, and the file selected), so instead one
        //       must set the current index to that of the parent folder and
        //       then select the file

        QDir filePathUp = currentPath;

        filePathUp.cdUp();

        currentPathDir = filePathUp.path();

        // If the parent folder doesn't exist, then we give up and go for the
        // home path

        if (!QFileInfo(currentPathDir).exists())
            currentPathDir = QDir::homePath();
    }

    QModelIndex currentPathModelIndex = mFileSystemModel->index(currentPathDir);

    setCurrentIndex(currentPathModelIndex);
    setExpanded(currentPathModelIndex, true);
    // Note: setExpanded shouldn't be required because of our call to scrollTo
    //       below, but as the BIG note mentions below, scrollTo is ineffective
    //       here (but we still leave it in for the sake of it, for now at
    //       least), so...
    scrollTo(currentPathModelIndex);

    if (!currentPathIsDir && currentPathInfo.exists())
    {
        // The current path is that of a file and it exists, so select it (see
        // the above note for the reasoning behind this)

        QModelIndex currentPathIndex = mFileSystemModel->index(currentPath);

        setCurrentIndex(currentPathIndex);
        scrollTo(currentPathIndex);
    }

//---GRY--- scrollTo REQUIRES THE WIDGET TO BE PAINTED TO WORK PROPERLY (ESP.
//          WHEN THE NODE TO SCROLL TO IS REALLY DOWN THE TREE). HOWEVER, EVEN
//          BY OVERRIDING paintEvent, I WAS STILL NOT ABLE TO GET THINGS TO WORK
//          AND IT WOULD SEEM (FROM A GOOGLE SEARCH) THAT I AM NOT THE ONLY ONE
//          IN THIS SITUATION... SO, FOR NOW, WE SHALL LEAVE THINGS AS THEY ARE
//          WHICH IS REALLY NOT GREAT, BUT...
}

void FileBrowserWidget::saveSettings(QSettings &pSettings, const QString &pKey)
{
    // Keep track of the sorting information

    pSettings.setValue(pKey+SETTINGS_SORTCOLUMN,
                       header()->sortIndicatorSection());
    pSettings.setValue(pKey+SETTINGS_SORTORDER, header()->sortIndicatorOrder());

    // Keep track of the current folder/file path

    QString currentPath = mFileSystemModel->filePath(currentIndex());

    pSettings.setValue(pKey+SETTINGS_CURRENTPATH, currentPath);
}

QSize FileBrowserWidget::sizeHint() const
{
    // Suggest a default size for the file browser widget
    // Note: this is critical if we want a docked widget, with a file browser
    //       widget on it, to have a decent size when docked to the main window

    return defaultSize(0.15);
}
<|endoftext|>


<commit_before>/**
 * Zillians MMO
 * Copyright (C) 2007-2010 Zillians.com, Inc.
 * For more information see http://www.zillians.com
 *
 * Zillians MMO is the library and runtime for massive multiplayer online game
 * development in utility computing model, which runs as a service for every
 * developer to build their virtual world running on our GPU-assisted machines.
 *
 * This is a close source library intended to be used solely within Zillians.com
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * @date Jul 18, 2011 sdk - Initial version created.
 */

#include "compiler/ThorScriptCompiler.h"
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/value_semantic.hpp>

#define STATUS_SUCCESS 0
#define STATUS_ERROR   1

namespace bp = boost::program_options;

int main(int argc, char** argv)
{
    bp::options_description option_desc;
    bp::positional_options_description pos_options_desc;

    option_desc.add_options()
    ("help,h",                               "this help message")
    ("dump-parse,p",                         "dump parse tree for debugging purpose")
    ("dump-ast,t",                           "dump AST pretty-print for debugging purpose")
    ("filename,f", bp::value<std::string>(), "filename");
    pos_options_desc.add("filename", -1);

	bp::variables_map args;
    try
    {
		bp::store(bp::command_line_parser(argc, argv).options(option_desc).positional(pos_options_desc).run(), args);
		bp::notify(args);
    }
    catch(...)
    {
    	std::cout << "invalid options" << std::endl;
    }

	std::string filename;
	if(args.count("filename")>0)
		filename = args["filename"].as<std::string>();
	bool dump_parse = (args.count("dump-parse")>0);
	bool dump_ast = (args.count("dump-ast")>0);
	if(args.count("help"))
		return STATUS_ERROR;

	if(!filename.empty())
	{
		zillians::compiler::ThorScriptCompiler compiler;
		if(!compiler.do_parse(filename, dump_parse, dump_ast))
		{
			std::cout << "parse fail" << std::endl;
			return STATUS_ERROR;
		}
		std::cout << "parse success" << std::endl;
		return STATUS_SUCCESS;
	}

	std::cout << "no option specified" << std::endl << std::endl;
	std::cout << "command-line options:" << std::endl << std::endl;
	std::cout << option_desc << std::endl;
	return STATUS_ERROR;
}
<commit_msg>fix makefail -- add missing include<commit_after>/**
 * Zillians MMO
 * Copyright (C) 2007-2010 Zillians.com, Inc.
 * For more information see http://www.zillians.com
 *
 * Zillians MMO is the library and runtime for massive multiplayer online game
 * development in utility computing model, which runs as a service for every
 * developer to build their virtual world running on our GPU-assisted machines.
 *
 * This is a close source library intended to be used solely within Zillians.com
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * @date Jul 18, 2011 sdk - Initial version created.
 */

#include "compiler/ThorScriptCompiler.h"
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/value_semantic.hpp>
#include <iostream>

#define STATUS_SUCCESS 0
#define STATUS_ERROR   1

namespace bp = boost::program_options;

int main(int argc, char** argv)
{
    bp::options_description option_desc;
    bp::positional_options_description pos_options_desc;

    option_desc.add_options()
    ("help,h",                               "this help message")
    ("dump-parse,p",                         "dump parse tree for debugging purpose")
    ("dump-ast,t",                           "dump AST pretty-print for debugging purpose")
    ("filename,f", bp::value<std::string>(), "filename");
    pos_options_desc.add("filename", -1);

	bp::variables_map args;
    try
    {
		bp::store(bp::command_line_parser(argc, argv).options(option_desc).positional(pos_options_desc).run(), args);
		bp::notify(args);
    }
    catch(...)
    {
    	std::cout << "invalid options" << std::endl;
    }

	std::string filename;
	if(args.count("filename")>0)
		filename = args["filename"].as<std::string>();
	bool dump_parse = (args.count("dump-parse")>0);
	bool dump_ast = (args.count("dump-ast")>0);
	if(args.count("help"))
		return STATUS_ERROR;

	if(!filename.empty())
	{
		zillians::compiler::ThorScriptCompiler compiler;
		if(!compiler.do_parse(filename, dump_parse, dump_ast))
		{
			std::cout << "parse fail" << std::endl;
			return STATUS_ERROR;
		}
		std::cout << "parse success" << std::endl;
		return STATUS_SUCCESS;
	}

	std::cout << "no option specified" << std::endl << std::endl;
	std::cout << "command-line options:" << std::endl << std::endl;
	std::cout << option_desc << std::endl;
	return STATUS_ERROR;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkImagePriv.h"
#include "SkImage_Base.h"

static SkImage_Base* as_IB(SkImage* image) {
    return static_cast<SkImage_Base*>(image);
}

static const SkImage_Base* as_IB(const SkImage* image) {
    return static_cast<const SkImage_Base*>(image);
}

uint32_t SkImage::NextUniqueID() {
    static int32_t gUniqueID;

    // never return 0;
    uint32_t id;
    do {
        id = sk_atomic_inc(&gUniqueID) + 1;
    } while (0 == id);
    return id;
}

void SkImage::draw(SkCanvas* canvas, SkScalar x, SkScalar y, const SkPaint* paint) const {
    as_IB(this)->onDraw(canvas, x, y, paint);
}

void SkImage::draw(SkCanvas* canvas, const SkRect* src, const SkRect& dst,
                   const SkPaint* paint) const {
    as_IB(this)->onDrawRectToRect(canvas, src, dst, paint);
}

const void* SkImage::peekPixels(SkImageInfo* info, size_t* rowBytes) const {
    SkImageInfo infoStorage;
    size_t rowBytesStorage;
    if (NULL == info) {
        info = &infoStorage;
    }
    if (NULL == rowBytes) {
        rowBytes = &rowBytesStorage;
    }
    return as_IB(this)->onPeekPixels(info, rowBytes);
}

bool SkImage::readPixels(SkBitmap* bitmap, const SkIRect* subset) const {
    if (NULL == bitmap) {
        return false;
    }

    SkIRect bounds = SkIRect::MakeWH(this->width(), this->height());

    // trim against the bitmap, if its already been allocated
    if (bitmap->pixelRef()) {
        bounds.fRight = SkMin32(bounds.fRight, bitmap->width());
        bounds.fBottom = SkMin32(bounds.fBottom, bitmap->height());
        if (bounds.isEmpty()) {
            return false;
        }
    }

    if (subset && !bounds.intersect(*subset)) {
        // perhaps we could return true + empty-bitmap?
        return false;
    }
    return as_IB(this)->onReadPixels(bitmap, bounds);
}

GrTexture* SkImage::getTexture() {
    return as_IB(this)->onGetTexture();
}

SkShader* SkImage::newShader(SkShader::TileMode tileX,
                             SkShader::TileMode tileY,
                             const SkMatrix* localMatrix) const {
    return as_IB(this)->onNewShader(tileX, tileY, localMatrix);
}

SkData* SkImage::encode(SkImageEncoder::Type type, int quality) const {
    SkBitmap bm;
    if (as_IB(this)->getROPixels(&bm)) {
        return SkImageEncoder::EncodeData(bm, type, quality);
    }
    return NULL;
}

///////////////////////////////////////////////////////////////////////////////

static bool raster_canvas_supports(const SkImageInfo& info) {
    switch (info.colorType()) {
        case kN32_SkColorType:
            return kUnpremul_SkAlphaType != info.alphaType();
        case kRGB_565_SkColorType:
            return true;
        case kAlpha_8_SkColorType:
            return true;
        default:
            break;
    }
    return false;
}

bool SkImage_Base::onReadPixels(SkBitmap* bitmap, const SkIRect& subset) const {
    if (bitmap->pixelRef()) {
        const SkImageInfo info = bitmap->info();
        if (kUnknown_SkColorType == info.colorType()) {
            return false;
        }
        if (!raster_canvas_supports(info)) {
            return false;
        }
    } else {
        SkBitmap tmp;
        if (!tmp.tryAllocN32Pixels(subset.width(), subset.height())) {
            return false;
        }
        *bitmap = tmp;
    }

    SkRect srcR, dstR;
    srcR.set(subset);
    dstR = srcR;
    dstR.offset(-dstR.left(), -dstR.top());

    SkCanvas canvas(*bitmap);

    SkPaint paint;
    paint.setXfermodeMode(SkXfermode::kClear_Mode);
    canvas.drawRect(dstR, paint);

    const_cast<SkImage_Base*>(this)->onDrawRectToRect(&canvas, &srcR, dstR, NULL);
    return true;
}
<commit_msg>Replace a forgotten call to SkImage::draw() by SkCanvas::drawImageRect()<commit_after>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkImagePriv.h"
#include "SkImage_Base.h"

static SkImage_Base* as_IB(SkImage* image) {
    return static_cast<SkImage_Base*>(image);
}

static const SkImage_Base* as_IB(const SkImage* image) {
    return static_cast<const SkImage_Base*>(image);
}

uint32_t SkImage::NextUniqueID() {
    static int32_t gUniqueID;

    // never return 0;
    uint32_t id;
    do {
        id = sk_atomic_inc(&gUniqueID) + 1;
    } while (0 == id);
    return id;
}

void SkImage::draw(SkCanvas* canvas, SkScalar x, SkScalar y, const SkPaint* paint) const {
    as_IB(this)->onDraw(canvas, x, y, paint);
}

void SkImage::draw(SkCanvas* canvas, const SkRect* src, const SkRect& dst,
                   const SkPaint* paint) const {
    as_IB(this)->onDrawRectToRect(canvas, src, dst, paint);
}

const void* SkImage::peekPixels(SkImageInfo* info, size_t* rowBytes) const {
    SkImageInfo infoStorage;
    size_t rowBytesStorage;
    if (NULL == info) {
        info = &infoStorage;
    }
    if (NULL == rowBytes) {
        rowBytes = &rowBytesStorage;
    }
    return as_IB(this)->onPeekPixels(info, rowBytes);
}

bool SkImage::readPixels(SkBitmap* bitmap, const SkIRect* subset) const {
    if (NULL == bitmap) {
        return false;
    }

    SkIRect bounds = SkIRect::MakeWH(this->width(), this->height());

    // trim against the bitmap, if its already been allocated
    if (bitmap->pixelRef()) {
        bounds.fRight = SkMin32(bounds.fRight, bitmap->width());
        bounds.fBottom = SkMin32(bounds.fBottom, bitmap->height());
        if (bounds.isEmpty()) {
            return false;
        }
    }

    if (subset && !bounds.intersect(*subset)) {
        // perhaps we could return true + empty-bitmap?
        return false;
    }
    return as_IB(this)->onReadPixels(bitmap, bounds);
}

GrTexture* SkImage::getTexture() {
    return as_IB(this)->onGetTexture();
}

SkShader* SkImage::newShader(SkShader::TileMode tileX,
                             SkShader::TileMode tileY,
                             const SkMatrix* localMatrix) const {
    return as_IB(this)->onNewShader(tileX, tileY, localMatrix);
}

SkData* SkImage::encode(SkImageEncoder::Type type, int quality) const {
    SkBitmap bm;
    if (as_IB(this)->getROPixels(&bm)) {
        return SkImageEncoder::EncodeData(bm, type, quality);
    }
    return NULL;
}

///////////////////////////////////////////////////////////////////////////////

static bool raster_canvas_supports(const SkImageInfo& info) {
    switch (info.colorType()) {
        case kN32_SkColorType:
            return kUnpremul_SkAlphaType != info.alphaType();
        case kRGB_565_SkColorType:
            return true;
        case kAlpha_8_SkColorType:
            return true;
        default:
            break;
    }
    return false;
}

bool SkImage_Base::onReadPixels(SkBitmap* bitmap, const SkIRect& subset) const {
    if (bitmap->pixelRef()) {
        const SkImageInfo info = bitmap->info();
        if (kUnknown_SkColorType == info.colorType()) {
            return false;
        }
        if (!raster_canvas_supports(info)) {
            return false;
        }
    } else {
        SkBitmap tmp;
        if (!tmp.tryAllocN32Pixels(subset.width(), subset.height())) {
            return false;
        }
        *bitmap = tmp;
    }

    SkRect srcR, dstR;
    srcR.set(subset);
    dstR = srcR;
    dstR.offset(-dstR.left(), -dstR.top());

    SkCanvas canvas(*bitmap);

    SkPaint paint;
    paint.setXfermodeMode(SkXfermode::kClear_Mode);
    canvas.drawRect(dstR, paint);

    canvas.drawImageRect(this, &srcR, dstR);
    return true;
}
<|endoftext|>


<commit_before><commit_msg>I was just missing the code for the ARB version<commit_after><|endoftext|>


<commit_before>/*
 * Embed a widget.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "inline_widget.hxx"
#include "widget_http.hxx"
#include "widget-quark.h"
#include "penv.hxx"
#include "widget.hxx"
#include "widget_class.hxx"
#include "widget_resolver.hxx"
#include "widget_approval.hxx"
#include "widget_request.hxx"
#include "async.hxx"
#include "bp_global.hxx"
#include "http_util.hxx"
#include "http_response.hxx"
#include "strmap.hxx"
#include "http_response.hxx"
#include "istream_html_escape.hxx"
#include "istream/istream.hxx"
#include "istream/istream_cat.hxx"
#include "istream/istream_delayed.hxx"
#include "istream/istream_hold.hxx"
#include "istream/istream_iconv.hxx"
#include "istream/istream_null.hxx"
#include "istream/istream_pause.hxx"
#include "istream/istream_string.hxx"
#include "istream/TimeoutIstream.hxx"
#include "session.hxx"
#include "pool.hxx"

#include <daemon/log.h>

#include <assert.h>

const struct timeval inline_widget_timeout = {
    .tv_sec = 10,
    .tv_usec = 0,
};

struct InlineWidget {
    struct pool &pool;
    struct processor_env &env;
    bool plain_text;
    Widget &widget;

    Istream *delayed;

    InlineWidget(struct pool &_pool, struct processor_env &_env,
                 bool _plain_text,
                 Widget &_widget)
        :pool(_pool), env(_env),
         plain_text(_plain_text),
         widget(_widget),
         delayed(istream_delayed_new(&pool)) {}
};

static void
inline_widget_close(InlineWidget *iw, GError *error)
{
    istream_delayed_set_abort(*iw->delayed, error);
}

/**
 * Ensure that a widget has the correct type for embedding it into a
 * HTML/XML document.  Returns nullptr (and closes body) if that is
 * impossible.
 */
static Istream *
widget_response_format(struct pool &pool, const Widget &widget,
                       const struct strmap *headers, Istream &_body,
                       bool plain_text,
                       GError **error_r)
{
    auto *body = &_body;

    const char *p, *content_type;

    assert(body != nullptr);

    p = strmap_get_checked(headers, "content-encoding");
    if (p != nullptr && strcmp(p, "identity") != 0) {
        g_set_error(error_r, widget_quark(), WIDGET_ERROR_UNSUPPORTED_ENCODING,
                    "widget '%s' sent non-identity response, cannot embed",
                    widget.GetLogName());
        body->CloseUnused();
        return nullptr;
    }

    content_type = strmap_get_checked(headers, "content-type");

    if (plain_text) {
        if (content_type == nullptr ||
            memcmp(content_type, "text/plain", 10) != 0) {
            g_set_error(error_r, widget_quark(), WIDGET_ERROR_WRONG_TYPE,
                        "widget '%s' sent non-text/plain response",
                        widget.GetLogName());
            body->CloseUnused();
            return nullptr;
        }

        return body;
    }

    if (content_type == nullptr ||
        (strncmp(content_type, "text/", 5) != 0 &&
         strncmp(content_type, "application/xml", 15) != 0 &&
         strncmp(content_type, "application/xhtml+xml", 21) != 0)) {
        g_set_error(error_r, widget_quark(), WIDGET_ERROR_WRONG_TYPE,
                    "widget '%s' sent non-text response",
                    widget.GetLogName());
        body->CloseUnused();
        return nullptr;
    }

    const auto charset = http_header_param(content_type, "charset");
    if (!charset.IsNull() && !charset.EqualsLiteralIgnoreCase("utf-8") &&
        !charset.EqualsLiteralIgnoreCase("utf8")) {
        /* beng-proxy expects all widgets to send their HTML code in
           utf-8; this widget however used a different charset.
           Automatically convert it with istream_iconv */
        const char *charset2 = p_strdup(pool, charset);
        Istream *ic = istream_iconv_new(&pool, *body, "utf-8", charset2);
        if (ic == nullptr) {
            g_set_error(error_r, widget_quark(), WIDGET_ERROR_WRONG_TYPE,
                        "widget '%s' sent unknown charset '%s'",
                        widget.GetLogName(), charset2);
            body->CloseUnused();
            return nullptr;
        }

        daemon_log(6, "widget '%s': charset conversion '%s' -> utf-8\n",
                   widget.GetLogName(), charset2);
        body = ic;
    }

    if (strncmp(content_type, "text/", 5) == 0 &&
        strncmp(content_type + 5, "html", 4) != 0 &&
        strncmp(content_type + 5, "xml", 3) != 0) {
        /* convert text to HTML */

        daemon_log(6, "widget '%s': converting text to HTML\n",
                   widget.GetLogName());

        body = istream_html_escape_new(pool, *body);
        body = istream_cat_new(pool,
                               istream_string_new(&pool,
                                                  "
"),
                               body,
                               istream_string_new(&pool, "
"));
    }

    return body;
}

/*
 * HTTP response handler
 *
 */

static void
inline_widget_response(http_status_t status,
                       struct strmap *headers,
                       Istream *body, void *ctx)
{
    auto *iw = (InlineWidget *)ctx;

    if (!http_status_is_success(status)) {
        /* the HTTP status code returned by the widget server is
           non-successful - don't embed this widget into the
           template */
        if (body != nullptr)
            body->CloseUnused();

        GError *error =
            g_error_new(widget_quark(), WIDGET_ERROR_UNSPECIFIED,
                        "response status %d from widget '%s'",
                        status, iw->widget.GetLogName());
        inline_widget_close(iw, error);
        return;
    }

    if (body != nullptr) {
        /* check if the content-type is correct for embedding into
           a template, and convert if possible */
        GError *error = nullptr;
        body = widget_response_format(iw->pool, iw->widget,
                                      headers, *body, iw->plain_text, &error);
        if (body == nullptr) {
            inline_widget_close(iw, error);
            return;
        }
    } else
        body = istream_null_new(&iw->pool);

    istream_delayed_set(*iw->delayed, *body);

    if (iw->delayed->HasHandler())
        iw->delayed->Read();
}

static void
inline_widget_abort(GError *error, void *ctx)
{
    auto *iw = (InlineWidget *)ctx;

    inline_widget_close(iw, error);
}

const struct http_response_handler inline_widget_response_handler = {
    .response = inline_widget_response,
    .abort = inline_widget_abort,
};

/*
 * internal
 *
 */

static void
inline_widget_set(InlineWidget *iw)
{
    const auto &env = iw->env;
    auto &widget = iw->widget;

    if (!widget_check_approval(&widget)) {
        GError *error =
            g_error_new(widget_quark(), WIDGET_ERROR_FORBIDDEN,
                        "widget '%s' is not allowed to embed widget class '%s'",
                        widget.parent->GetLogName(),
                        widget.class_name);
        widget_cancel(&widget);
        istream_delayed_set_abort(*iw->delayed, error);
        return;
    }

    if (!widget.CheckHost(env.untrusted_host, env.site_name)) {
        GError *error =
            g_error_new(widget_quark(), WIDGET_ERROR_FORBIDDEN,
                        "untrusted host name mismatch in widget '%s'",
                        widget.GetLogName());
        widget_cancel(&widget);
        istream_delayed_set_abort(*iw->delayed, error);
        return;
    }

    if (!widget.HasDefaultView()) {
        GError *error =
            g_error_new(widget_quark(), WIDGET_ERROR_NO_SUCH_VIEW,
                        "No such view in widget '%s': %s",
                        widget.GetLogName(),
                        widget.view_name);
        widget_cancel(&widget);
        istream_delayed_set_abort(*iw->delayed, error);
        return;
    }

    if (widget.session_sync_pending) {
        auto session = env.GetRealmSession();
        if (session)
            widget_sync_session(widget, *session);
        else
            widget.session_sync_pending = false;
    }

    widget_http_request(iw->pool, widget, iw->env,
                        inline_widget_response_handler, iw,
                        *istream_delayed_async_ref(*iw->delayed));
}

/*
 * Widget resolver callback
 *
 */

static void
class_lookup_callback(void *_ctx)
{
    auto *iw = (InlineWidget *)_ctx;

    if (iw->widget.cls != nullptr) {
        inline_widget_set(iw);
    } else {
        GError *error =
            g_error_new(widget_quark(), WIDGET_ERROR_UNSPECIFIED,
                        "failed to look up widget class '%s'",
                        iw->widget.class_name);
        widget_cancel(&iw->widget);
        inline_widget_close(iw, error);
    }
}

/*
 * Constructor
 *
 */

Istream *
embed_inline_widget(struct pool &pool, struct processor_env &env,
                    bool plain_text,
                    Widget &widget)
{
    Istream *request_body = nullptr;
    if (widget.from_request.body != nullptr) {
        /* use a "paused" stream, to avoid a recursion bug: when
           somebody within this stack frame attempts to read from it,
           and the HTTP server trips on an I/O error, the HTTP request
           gets cancelled, but the event cannot reach this stack
           frame; by preventing reads on the request body, this
           situation is avoided */
        request_body = istream_pause_new(&pool, *widget.from_request.body);

        /* wrap it in istream_hold, because (most likely) the original
           request body was an istream_hold, too */
        widget.from_request.body = istream_hold_new(pool, *request_body);
    }

    auto iw = NewFromPool<InlineWidget>(pool, pool, env, plain_text, widget);

    Istream *timeout = NewTimeoutIstream(pool, *iw->delayed,
                                         *env.event_loop,
                                         inline_widget_timeout);
    Istream *hold = istream_hold_new(pool, *timeout);

    if (widget.cls == nullptr)
        widget_resolver_new(pool, widget,
                            *global_translate_cache,
                            class_lookup_callback, iw,
                            *istream_delayed_async_ref(*iw->delayed));
    else
        inline_widget_set(iw);

    if (request_body != nullptr)
        istream_pause_resume(*request_body);

    return hold;
}
<commit_msg>inline_widget: move functions into the struct<commit_after>/*
 * Embed a widget.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "inline_widget.hxx"
#include "widget_http.hxx"
#include "widget-quark.h"
#include "penv.hxx"
#include "widget.hxx"
#include "widget_class.hxx"
#include "widget_resolver.hxx"
#include "widget_approval.hxx"
#include "widget_request.hxx"
#include "async.hxx"
#include "bp_global.hxx"
#include "http_util.hxx"
#include "http_response.hxx"
#include "strmap.hxx"
#include "http_response.hxx"
#include "istream_html_escape.hxx"
#include "istream/istream.hxx"
#include "istream/istream_cat.hxx"
#include "istream/istream_delayed.hxx"
#include "istream/istream_hold.hxx"
#include "istream/istream_iconv.hxx"
#include "istream/istream_null.hxx"
#include "istream/istream_pause.hxx"
#include "istream/istream_string.hxx"
#include "istream/TimeoutIstream.hxx"
#include "session.hxx"
#include "pool.hxx"

#include <daemon/log.h>

#include <assert.h>

const struct timeval inline_widget_timeout = {
    .tv_sec = 10,
    .tv_usec = 0,
};

struct InlineWidget {
    struct pool &pool;
    struct processor_env &env;
    bool plain_text;
    Widget &widget;

    Istream *delayed;

    InlineWidget(struct pool &_pool, struct processor_env &_env,
                 bool _plain_text,
                 Widget &_widget)
        :pool(_pool), env(_env),
         plain_text(_plain_text),
         widget(_widget),
         delayed(istream_delayed_new(&pool)) {}

    void SendRequest();
};

static void
inline_widget_close(InlineWidget *iw, GError *error)
{
    istream_delayed_set_abort(*iw->delayed, error);
}

/**
 * Ensure that a widget has the correct type for embedding it into a
 * HTML/XML document.  Returns nullptr (and closes body) if that is
 * impossible.
 */
static Istream *
widget_response_format(struct pool &pool, const Widget &widget,
                       const struct strmap *headers, Istream &_body,
                       bool plain_text,
                       GError **error_r)
{
    auto *body = &_body;

    const char *p, *content_type;

    assert(body != nullptr);

    p = strmap_get_checked(headers, "content-encoding");
    if (p != nullptr && strcmp(p, "identity") != 0) {
        g_set_error(error_r, widget_quark(), WIDGET_ERROR_UNSUPPORTED_ENCODING,
                    "widget '%s' sent non-identity response, cannot embed",
                    widget.GetLogName());
        body->CloseUnused();
        return nullptr;
    }

    content_type = strmap_get_checked(headers, "content-type");

    if (plain_text) {
        if (content_type == nullptr ||
            memcmp(content_type, "text/plain", 10) != 0) {
            g_set_error(error_r, widget_quark(), WIDGET_ERROR_WRONG_TYPE,
                        "widget '%s' sent non-text/plain response",
                        widget.GetLogName());
            body->CloseUnused();
            return nullptr;
        }

        return body;
    }

    if (content_type == nullptr ||
        (strncmp(content_type, "text/", 5) != 0 &&
         strncmp(content_type, "application/xml", 15) != 0 &&
         strncmp(content_type, "application/xhtml+xml", 21) != 0)) {
        g_set_error(error_r, widget_quark(), WIDGET_ERROR_WRONG_TYPE,
                    "widget '%s' sent non-text response",
                    widget.GetLogName());
        body->CloseUnused();
        return nullptr;
    }

    const auto charset = http_header_param(content_type, "charset");
    if (!charset.IsNull() && !charset.EqualsLiteralIgnoreCase("utf-8") &&
        !charset.EqualsLiteralIgnoreCase("utf8")) {
        /* beng-proxy expects all widgets to send their HTML code in
           utf-8; this widget however used a different charset.
           Automatically convert it with istream_iconv */
        const char *charset2 = p_strdup(pool, charset);
        Istream *ic = istream_iconv_new(&pool, *body, "utf-8", charset2);
        if (ic == nullptr) {
            g_set_error(error_r, widget_quark(), WIDGET_ERROR_WRONG_TYPE,
                        "widget '%s' sent unknown charset '%s'",
                        widget.GetLogName(), charset2);
            body->CloseUnused();
            return nullptr;
        }

        daemon_log(6, "widget '%s': charset conversion '%s' -> utf-8\n",
                   widget.GetLogName(), charset2);
        body = ic;
    }

    if (strncmp(content_type, "text/", 5) == 0 &&
        strncmp(content_type + 5, "html", 4) != 0 &&
        strncmp(content_type + 5, "xml", 3) != 0) {
        /* convert text to HTML */

        daemon_log(6, "widget '%s': converting text to HTML\n",
                   widget.GetLogName());

        body = istream_html_escape_new(pool, *body);
        body = istream_cat_new(pool,
                               istream_string_new(&pool,
                                                  "
"),
                               body,
                               istream_string_new(&pool, "
"));
    }

    return body;
}

/*
 * HTTP response handler
 *
 */

static void
inline_widget_response(http_status_t status,
                       struct strmap *headers,
                       Istream *body, void *ctx)
{
    auto *iw = (InlineWidget *)ctx;

    if (!http_status_is_success(status)) {
        /* the HTTP status code returned by the widget server is
           non-successful - don't embed this widget into the
           template */
        if (body != nullptr)
            body->CloseUnused();

        GError *error =
            g_error_new(widget_quark(), WIDGET_ERROR_UNSPECIFIED,
                        "response status %d from widget '%s'",
                        status, iw->widget.GetLogName());
        inline_widget_close(iw, error);
        return;
    }

    if (body != nullptr) {
        /* check if the content-type is correct for embedding into
           a template, and convert if possible */
        GError *error = nullptr;
        body = widget_response_format(iw->pool, iw->widget,
                                      headers, *body, iw->plain_text, &error);
        if (body == nullptr) {
            inline_widget_close(iw, error);
            return;
        }
    } else
        body = istream_null_new(&iw->pool);

    istream_delayed_set(*iw->delayed, *body);

    if (iw->delayed->HasHandler())
        iw->delayed->Read();
}

static void
inline_widget_abort(GError *error, void *ctx)
{
    auto *iw = (InlineWidget *)ctx;

    inline_widget_close(iw, error);
}

const struct http_response_handler inline_widget_response_handler = {
    .response = inline_widget_response,
    .abort = inline_widget_abort,
};

/*
 * internal
 *
 */

void
InlineWidget::SendRequest()
{
    if (!widget_check_approval(&widget)) {
        GError *error =
            g_error_new(widget_quark(), WIDGET_ERROR_FORBIDDEN,
                        "widget '%s' is not allowed to embed widget class '%s'",
                        widget.parent->GetLogName(),
                        widget.class_name);
        widget_cancel(&widget);
        istream_delayed_set_abort(*delayed, error);
        return;
    }

    if (!widget.CheckHost(env.untrusted_host, env.site_name)) {
        GError *error =
            g_error_new(widget_quark(), WIDGET_ERROR_FORBIDDEN,
                        "untrusted host name mismatch in widget '%s'",
                        widget.GetLogName());
        widget_cancel(&widget);
        istream_delayed_set_abort(*delayed, error);
        return;
    }

    if (!widget.HasDefaultView()) {
        GError *error =
            g_error_new(widget_quark(), WIDGET_ERROR_NO_SUCH_VIEW,
                        "No such view in widget '%s': %s",
                        widget.GetLogName(),
                        widget.view_name);
        widget_cancel(&widget);
        istream_delayed_set_abort(*delayed, error);
        return;
    }

    if (widget.session_sync_pending) {
        auto session = env.GetRealmSession();
        if (session)
            widget_sync_session(widget, *session);
        else
            widget.session_sync_pending = false;
    }

    widget_http_request(pool, widget, env,
                        inline_widget_response_handler, this,
                        *istream_delayed_async_ref(*delayed));
}

/*
 * Widget resolver callback
 *
 */

static void
class_lookup_callback(void *_ctx)
{
    auto *iw = (InlineWidget *)_ctx;

    if (iw->widget.cls != nullptr) {
        iw->SendRequest();
    } else {
        GError *error =
            g_error_new(widget_quark(), WIDGET_ERROR_UNSPECIFIED,
                        "failed to look up widget class '%s'",
                        iw->widget.class_name);
        widget_cancel(&iw->widget);
        inline_widget_close(iw, error);
    }
}

/*
 * Constructor
 *
 */

Istream *
embed_inline_widget(struct pool &pool, struct processor_env &env,
                    bool plain_text,
                    Widget &widget)
{
    Istream *request_body = nullptr;
    if (widget.from_request.body != nullptr) {
        /* use a "paused" stream, to avoid a recursion bug: when
           somebody within this stack frame attempts to read from it,
           and the HTTP server trips on an I/O error, the HTTP request
           gets cancelled, but the event cannot reach this stack
           frame; by preventing reads on the request body, this
           situation is avoided */
        request_body = istream_pause_new(&pool, *widget.from_request.body);

        /* wrap it in istream_hold, because (most likely) the original
           request body was an istream_hold, too */
        widget.from_request.body = istream_hold_new(pool, *request_body);
    }

    auto iw = NewFromPool<InlineWidget>(pool, pool, env, plain_text, widget);

    Istream *timeout = NewTimeoutIstream(pool, *iw->delayed,
                                         *env.event_loop,
                                         inline_widget_timeout);
    Istream *hold = istream_hold_new(pool, *timeout);

    if (widget.cls == nullptr)
        widget_resolver_new(pool, widget,
                            *global_translate_cache,
                            class_lookup_callback, iw,
                            *istream_delayed_async_ref(*iw->delayed));
    else
        iw->SendRequest();

    if (request_body != nullptr)
        istream_pause_resume(*request_body);

    return hold;
}
<|endoftext|>


<commit_before><commit_msg>typo in Norwegian translations of keyboard shortcuts (fdo#50415)<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: DBTypeWizDlgSetup.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2005-02-17 11:10:00 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DBU_REGHELPER_HXX_
#include "dbu_reghelper.hxx"
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTLISTENER_HPP_
#include <com/sun/star/document/XEventListener.hpp>
#endif
#ifndef DBAUI_DBTYPEWIZDLGSETUP_HXX
#include "DBTypeWizDlgSetup.hxx"
#endif
#ifndef DBAUI_DBWIZSETUP_HXX
#include "dbwizsetup.hxx"
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif

using namespace dbaui;

extern "C" void SAL_CALL createRegistryInfo_ODBTypeWizDialogSetup()
{
    static OMultiInstanceAutoRegistration< ODBTypeWizDialogSetup > aAutoRegistration;
}

//.........................................................................
namespace dbaui
{
//.........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;

//=========================================================================
//-------------------------------------------------------------------------
ODBTypeWizDialogSetup::ODBTypeWizDialogSetup(const Reference< XMultiServiceFactory >& _rxORB)
    :ODatabaseAdministrationDialog(_rxORB)
    ,m_bOpenDatabase(sal_True)
    ,m_bStartTableWizard(sal_False)
{
    registerProperty(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("OpenDatabase")), 3, PropertyAttribute::TRANSIENT,
        &m_bOpenDatabase, getBooleanCppuType());

    registerProperty(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("StartTableWizard")), 4, PropertyAttribute::TRANSIENT,
        &m_bStartTableWizard, getBooleanCppuType());
}
//-------------------------------------------------------------------------
Sequence<sal_Int8> SAL_CALL ODBTypeWizDialogSetup::getImplementationId(  ) throw(RuntimeException)
{
    static ::cppu::OImplementationId aId;
    return aId.getImplementationId();
}

//-------------------------------------------------------------------------
Reference< XInterface > SAL_CALL ODBTypeWizDialogSetup::Create(const Reference< XMultiServiceFactory >& _rxFactory)
{
    Reference < XInterface > xDBContext = _rxFactory->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.DatabaseDocument")));
       Sequence<Any> aSequence(1);
    PropertyValue aPropertyValue;
    Any aTmp;
    aTmp <<= xDBContext;
    aPropertyValue.Name = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("InitialSelection"));
    aPropertyValue.Value = aTmp;
    aSequence[0] <<= aPropertyValue;
    Reference < XInterface > xDBWizard = *(new ODBTypeWizDialogSetup(_rxFactory));
    Reference < XInitialization > xDBWizardInit(xDBWizard, UNO_QUERY);

    xDBWizardInit->initialize(aSequence);

    try
    {
        Reference< ::com::sun::star::document::XEventListener > xDocEventBroadcaster(_rxFactory->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.GlobalEventBroadcaster"))),
            UNO_QUERY);
        if ( xDocEventBroadcaster.is() )
        {
            ::com::sun::star::document::EventObject aEvent(xDBContext, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("OnNew")) );
            xDocEventBroadcaster->notifyEvent(aEvent);
        }
    }
    catch(Exception)
    {
        OSL_ENSURE(0,"Could not create GlobalEventBroadcaster!");
    }
    Reference <com::sun::star::ui::dialogs::XExecutableDialog> xDBWizardExecute( xDBWizard, UNO_QUERY );
    xDBWizardExecute->execute();
    return xDBWizard;
}

//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL ODBTypeWizDialogSetup::getImplementationName() throw(RuntimeException)
{
    return getImplementationName_Static();
}

//-------------------------------------------------------------------------
::rtl::OUString ODBTypeWizDialogSetup::getImplementationName_Static() throw(RuntimeException)
{
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.comp.dbu.ODBTypeWizDialogSetup"));
}

//-------------------------------------------------------------------------
::comphelper::StringSequence SAL_CALL ODBTypeWizDialogSetup::getSupportedServiceNames() throw(RuntimeException)
{
    return getSupportedServiceNames_Static();
}

//-------------------------------------------------------------------------
::comphelper::StringSequence ODBTypeWizDialogSetup::getSupportedServiceNames_Static() throw(RuntimeException)
{
    ::comphelper::StringSequence aSupported(1);
    aSupported.getArray()[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.DatabaseWizardDialog"));
    return aSupported;
}

//-------------------------------------------------------------------------
Reference<XPropertySetInfo>  SAL_CALL ODBTypeWizDialogSetup::getPropertySetInfo() throw(RuntimeException)
{
    return createPropertySetInfo( getInfoHelper() );
}

//-------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& ODBTypeWizDialogSetup::getInfoHelper()
{
    return *const_cast<ODBTypeWizDialogSetup*>(this)->getArrayHelper();
}

//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* ODBTypeWizDialogSetup::createArrayHelper( ) const
{
    Sequence< Property > aProps;
    describeProperties(aProps);
    return new ::cppu::OPropertyArrayHelper(aProps);
}
//------------------------------------------------------------------------------
Dialog* ODBTypeWizDialogSetup::createDialog(Window* _pParent)
{
    return new ODbTypeWizDialogSetup(_pParent, m_pDatasourceItems, m_xORB, m_aInitialSelection);
}
// -----------------------------------------------------------------------------
void ODBTypeWizDialogSetup::executedDialog(sal_Int16 _nExecutionResult)
{
    if ( _nExecutionResult == RET_OK )
    {
        m_bOpenDatabase = static_cast<ODbTypeWizDialogSetup*>(m_pDialog)->IsDatabaseDocumentToBeOpened();
        m_bStartTableWizard = static_cast<ODbTypeWizDialogSetup*>(m_pDialog)->IsTableWizardToBeStarted();
    }
}

//.........................................................................
}   // namespace dbaui
//.........................................................................

<commit_msg>#43245#<commit_after>/*************************************************************************
 *
 *  $RCSfile: DBTypeWizDlgSetup.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2005-02-21 11:57:20 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DBU_REGHELPER_HXX_
#include "dbu_reghelper.hxx"
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTLISTENER_HPP_
#include <com/sun/star/document/XEventListener.hpp>
#endif
#ifndef DBAUI_DBTYPEWIZDLGSETUP_HXX
#include "DBTypeWizDlgSetup.hxx"
#endif
#ifndef DBAUI_DBWIZSETUP_HXX
#include "dbwizsetup.hxx"
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif

using namespace dbaui;

extern "C" void SAL_CALL createRegistryInfo_ODBTypeWizDialogSetup()
{
    static OMultiInstanceAutoRegistration< ODBTypeWizDialogSetup > aAutoRegistration;
}

//.........................................................................
namespace dbaui
{
//.........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;

//=========================================================================
//-------------------------------------------------------------------------
ODBTypeWizDialogSetup::ODBTypeWizDialogSetup(const Reference< XMultiServiceFactory >& _rxORB)
    :ODatabaseAdministrationDialog(_rxORB)
    ,m_bOpenDatabase(sal_True)
    ,m_bStartTableWizard(sal_False)
{
    registerProperty(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("OpenDatabase")), 3, PropertyAttribute::TRANSIENT,
        &m_bOpenDatabase, getBooleanCppuType());

    registerProperty(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("StartTableWizard")), 4, PropertyAttribute::TRANSIENT,
        &m_bStartTableWizard, getBooleanCppuType());
}
//-------------------------------------------------------------------------
Sequence<sal_Int8> SAL_CALL ODBTypeWizDialogSetup::getImplementationId(  ) throw(RuntimeException)
{
    static ::cppu::OImplementationId aId;
    return aId.getImplementationId();
}

//-------------------------------------------------------------------------
Reference< XInterface > SAL_CALL ODBTypeWizDialogSetup::Create(const Reference< XMultiServiceFactory >& _rxFactory)
{
    Reference < XInterface > xDBContext = _rxFactory->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.OfficeDatabaseDocument")));
       Sequence<Any> aSequence(1);
    PropertyValue aPropertyValue;
    Any aTmp;
    aTmp <<= xDBContext;
    aPropertyValue.Name = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("InitialSelection"));
    aPropertyValue.Value = aTmp;
    aSequence[0] <<= aPropertyValue;
    Reference < XInterface > xDBWizard = *(new ODBTypeWizDialogSetup(_rxFactory));
    Reference < XInitialization > xDBWizardInit(xDBWizard, UNO_QUERY);

    xDBWizardInit->initialize(aSequence);

    try
    {
        Reference< ::com::sun::star::document::XEventListener > xDocEventBroadcaster(_rxFactory->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.GlobalEventBroadcaster"))),
            UNO_QUERY);
        if ( xDocEventBroadcaster.is() )
        {
            ::com::sun::star::document::EventObject aEvent(xDBContext, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("OnNew")) );
            xDocEventBroadcaster->notifyEvent(aEvent);
        }
    }
    catch(Exception)
    {
        OSL_ENSURE(0,"Could not create GlobalEventBroadcaster!");
    }
    Reference <com::sun::star::ui::dialogs::XExecutableDialog> xDBWizardExecute( xDBWizard, UNO_QUERY );
    xDBWizardExecute->execute();
    return xDBWizard;
}

//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL ODBTypeWizDialogSetup::getImplementationName() throw(RuntimeException)
{
    return getImplementationName_Static();
}

//-------------------------------------------------------------------------
::rtl::OUString ODBTypeWizDialogSetup::getImplementationName_Static() throw(RuntimeException)
{
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.comp.dbu.ODBTypeWizDialogSetup"));
}

//-------------------------------------------------------------------------
::comphelper::StringSequence SAL_CALL ODBTypeWizDialogSetup::getSupportedServiceNames() throw(RuntimeException)
{
    return getSupportedServiceNames_Static();
}

//-------------------------------------------------------------------------
::comphelper::StringSequence ODBTypeWizDialogSetup::getSupportedServiceNames_Static() throw(RuntimeException)
{
    ::comphelper::StringSequence aSupported(1);
    aSupported.getArray()[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.DatabaseWizardDialog"));
    return aSupported;
}

//-------------------------------------------------------------------------
Reference<XPropertySetInfo>  SAL_CALL ODBTypeWizDialogSetup::getPropertySetInfo() throw(RuntimeException)
{
    return createPropertySetInfo( getInfoHelper() );
}

//-------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& ODBTypeWizDialogSetup::getInfoHelper()
{
    return *const_cast<ODBTypeWizDialogSetup*>(this)->getArrayHelper();
}

//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* ODBTypeWizDialogSetup::createArrayHelper( ) const
{
    Sequence< Property > aProps;
    describeProperties(aProps);
    return new ::cppu::OPropertyArrayHelper(aProps);
}
//------------------------------------------------------------------------------
Dialog* ODBTypeWizDialogSetup::createDialog(Window* _pParent)
{
    return new ODbTypeWizDialogSetup(_pParent, m_pDatasourceItems, m_xORB, m_aInitialSelection);
}
// -----------------------------------------------------------------------------
void ODBTypeWizDialogSetup::executedDialog(sal_Int16 _nExecutionResult)
{
    if ( _nExecutionResult == RET_OK )
    {
        m_bOpenDatabase = static_cast<ODbTypeWizDialogSetup*>(m_pDialog)->IsDatabaseDocumentToBeOpened();
        m_bStartTableWizard = static_cast<ODbTypeWizDialogSetup*>(m_pDialog)->IsTableWizardToBeStarted();
    }
}

//.........................................................................
}   // namespace dbaui
//.........................................................................

<|endoftext|>