<commit_before>/*=========================================================================

  Library:   CTK

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (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.commontk.org/LICENSE

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

// Qt includes
#include <QColor>
#include <QDebug>
#include <QEvent>
#include <QPainter>
#include <QSize>

// CTK includes
#include "ctkCrosshairLabel.h"
#include "ctkLogger.h"

// STD includes
#include <math.h>

//--------------------------------------------------------------------------
static ctkLogger logger("org.commontk.visualization.vtk.widgets.ctkCrosshairLabel");
//--------------------------------------------------------------------------

//-----------------------------------------------------------------------------
class ctkCrosshairLabelPrivate
{
  Q_DECLARE_PUBLIC(ctkCrosshairLabel);
protected:
  ctkCrosshairLabel* const q_ptr;
public:
  ctkCrosshairLabelPrivate(ctkCrosshairLabel& object);

  void init();
  void drawCrosshair();
  void drawSimpleCrosshair(QPainter& painter);
  void drawBullsEyeCrosshair(QPainter& painter);

  bool      ShowCrosshair;
  QPen      CrosshairPen;
  ctkCrosshairLabel::CrosshairTypes CrosshairType;
  int       BullsEyeWidth;

  static const double BULLS_EYE_BLANK_FRACTION = 0.1;
};

// --------------------------------------------------------------------------
// ctkCrosshairLabelPrivate methods

// --------------------------------------------------------------------------
ctkCrosshairLabelPrivate::ctkCrosshairLabelPrivate(ctkCrosshairLabel& object)
  :q_ptr(&object)
{
  this->ShowCrosshair = true;
  this->CrosshairType = ctkCrosshairLabel::SimpleCrosshair;
  this->BullsEyeWidth = 15;
}

//---------------------------------------------------------------------------
void ctkCrosshairLabelPrivate::init()
{
  Q_Q(ctkCrosshairLabel);
  q->setAutoFillBackground(true);
  q->setAlignment(Qt::AlignCenter);
  this->CrosshairPen.setColor(q->palette().color(QPalette::Highlight));
  this->CrosshairPen.setWidth(0);
  this->CrosshairPen.setJoinStyle(Qt::MiterJoin);
}

//---------------------------------------------------------------------------
void ctkCrosshairLabelPrivate::drawCrosshair()
{
  // Abort if we are not to draw the crosshair
  if (!this->ShowCrosshair)
    {
    return;
    }

  // Setup the painter object to paint on the label
  Q_Q(ctkCrosshairLabel);
  QPainter painter(q);
  painter.setPen(this->CrosshairPen);

  // Draw crosshair (based on current parameters) onto the label
  switch (this->CrosshairType)
    {
    case ctkCrosshairLabel::SimpleCrosshair:
      this->drawSimpleCrosshair(painter);
      break;
    case ctkCrosshairLabel::BullsEyeCrosshair:
      this->drawBullsEyeCrosshair(painter);
      break;
    default:
      qDebug() << "Unsupported crosshair type" << this->CrosshairType;
      break;
    }
}

//---------------------------------------------------------------------------
void ctkCrosshairLabelPrivate::drawSimpleCrosshair(QPainter& painter)
{
  Q_Q(ctkCrosshairLabel);
  QSize size = q->size();
  double halfWidth = (size.width()-1.0) / 2.0;
  double halfHeight = (size.height()-1.0) / 2.0;
  painter.drawLine(QPointF(0, halfHeight), QPointF(size.width(), halfHeight));
  painter.drawLine(QPointF(halfWidth, 0), QPointF(halfWidth, size.height()));
}

// --------------------------------------------------------------------------
void ctkCrosshairLabelPrivate::drawBullsEyeCrosshair(QPainter& painter)
{
  Q_Q(ctkCrosshairLabel);
  QSize size = q->size();

  // Draw rectangle
  double bullsEye = this->BullsEyeWidth;
  double lineWidth = painter.pen().width();
  lineWidth = std::max(lineWidth, 1.0);
  double halfLineWidth = (lineWidth-1.0) / 2.0;
  double x = (size.width()-bullsEye) / 2.0;
  double y = (size.height()-bullsEye) / 2.0;
  double rectWidth = bullsEye;
  if (bullsEye != 1)
    {
    rectWidth = rectWidth - lineWidth;
    }
  rectWidth = std::max(rectWidth, 0.0);
  painter.drawRect(
      QRectF(x+halfLineWidth, y+halfLineWidth, rectWidth, rectWidth));

  // Draw the lines
  double halfWidth = (size.width()-1.0) / 2.0;
  double halfHeight = (size.height()-1.0) / 2.0;
  double blank = round(std::min(halfWidth, halfHeight)
                       * this->BULLS_EYE_BLANK_FRACTION);

  painter.drawLine(QPointF(0, halfHeight), QPointF(x-blank-1.0, halfHeight));
  painter.drawLine(QPointF(x+bullsEye+blank, halfHeight),
                   QPointF(size.width(), halfHeight));
  painter.drawLine(QPointF(halfWidth, 0), QPointF(halfWidth, y-blank-1.0));
  painter.drawLine(QPointF(halfWidth, y+bullsEye+blank),
                   QPointF(halfWidth, size.height()));
}

//---------------------------------------------------------------------------
// ctkCrosshairLabel methods

// --------------------------------------------------------------------------
ctkCrosshairLabel::ctkCrosshairLabel(QWidget* parent)
  : Superclass(parent)
  , d_ptr(new ctkCrosshairLabelPrivate(*this))
{
  Q_D(ctkCrosshairLabel);
  d->init();
}

// --------------------------------------------------------------------------
ctkCrosshairLabel::~ctkCrosshairLabel()
{
}

// --------------------------------------------------------------------------
CTK_GET_CPP(ctkCrosshairLabel, bool, showCrosshair, ShowCrosshair);

// --------------------------------------------------------------------------
void ctkCrosshairLabel::setShowCrosshair(bool newShow)
{
  Q_D(ctkCrosshairLabel);
  if (newShow == d->ShowCrosshair)
    {
    return;
    }

  d->ShowCrosshair = newShow;
  this->update();
}

// --------------------------------------------------------------------------
CTK_GET_CPP(ctkCrosshairLabel, QPen, crosshairPen, CrosshairPen);

// --------------------------------------------------------------------------
void ctkCrosshairLabel::setCrosshairPen(const QPen& newPen)
{
  Q_D(ctkCrosshairLabel);
  if (newPen == d->CrosshairPen)
    {
    return;
    }

  d->CrosshairPen = newPen;
  this->update();
}

// --------------------------------------------------------------------------
QColor ctkCrosshairLabel::crosshairColor() const
{
  Q_D(const ctkCrosshairLabel);
  return d->CrosshairPen.color();
}

// --------------------------------------------------------------------------
void ctkCrosshairLabel::setCrosshairColor(const QColor& newColor)
{
  Q_D(ctkCrosshairLabel);
  if (d->CrosshairPen.color() == newColor)
    {
    return;
    }

  d->CrosshairPen.setColor(newColor);
  this->update();
}

// --------------------------------------------------------------------------
int ctkCrosshairLabel::lineWidth() const
{
  Q_D(const ctkCrosshairLabel);
  return d->CrosshairPen.width();
}

// --------------------------------------------------------------------------
void ctkCrosshairLabel::setLineWidth(int newWidth)
{
  Q_D(ctkCrosshairLabel);
  if (d->CrosshairPen.width() == newWidth || newWidth < 0)
    {
    return;
    }

  d->CrosshairPen.setWidth(newWidth);
  this->update();
}

// --------------------------------------------------------------------------
CTK_GET_CPP(ctkCrosshairLabel, ctkCrosshairLabel::CrosshairTypes,
            crosshairType, CrosshairType);

// --------------------------------------------------------------------------
void ctkCrosshairLabel::setCrosshairType(const CrosshairTypes& newType)
{
  Q_D(ctkCrosshairLabel);
  if (newType == d->CrosshairType)
    {
    return;
    }

  d->CrosshairType = newType;
  this->update();
}

// --------------------------------------------------------------------------
QColor ctkCrosshairLabel::marginColor() const
  {
  return this->palette().color(QPalette::Window);
  }

// --------------------------------------------------------------------------
void ctkCrosshairLabel::setMarginColor(const QColor& newColor)
{
  if (!newColor.isValid())
    {
    return;
    }

  QPalette palette(this->palette());
  QColor solidColor(newColor.rgb());
  if (solidColor != palette.color(QPalette::Window))
    {
    // Ignore alpha channel
    palette.setColor(QPalette::Window, solidColor);
    this->setPalette(palette);
    this->update();
    }
}

// --------------------------------------------------------------------------
CTK_GET_CPP(ctkCrosshairLabel, int, bullsEyeWidth, BullsEyeWidth);

// --------------------------------------------------------------------------
void ctkCrosshairLabel::setBullsEyeWidth(int newWidth)
{
  Q_D(ctkCrosshairLabel);
  if (newWidth == d->BullsEyeWidth || newWidth < 0)
    {
    return;
    }

  d->BullsEyeWidth = newWidth;
  this->update();
}

// --------------------------------------------------------------------------
void ctkCrosshairLabel::paintEvent(QPaintEvent * event)
{
  Superclass::paintEvent(event);
  Q_D(ctkCrosshairLabel);
  d->drawCrosshair();
}

// --------------------------------------------------------------------------
QSize ctkCrosshairLabel::minimumSizeHint()const
{
  // Pretty arbitrary size (matches ctkVTKAbstractView)
  return QSize(50, 50);
}

// --------------------------------------------------------------------------
QSize ctkCrosshairLabel::sizeHint()const
{
  // Pretty arbitrary size (matches ctkVTKAbstractView)
  return QSize(300, 300);
}

//----------------------------------------------------------------------------
bool ctkCrosshairLabel::hasHeightForWidth()const
{
  return true;
}

//----------------------------------------------------------------------------
int ctkCrosshairLabel::heightForWidth(int width)const
{
  // Tends to be square
  return width;
}
<commit_msg>BUG: Initializing class constants of type double is illegal C++.<commit_after>/*=========================================================================

  Library:   CTK

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (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.commontk.org/LICENSE

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

// Qt includes
#include <QColor>
#include <QDebug>
#include <QEvent>
#include <QPainter>
#include <QSize>

// CTK includes
#include "ctkCrosshairLabel.h"
#include "ctkLogger.h"

// STD includes
#include <math.h>

//--------------------------------------------------------------------------
static ctkLogger logger("org.commontk.visualization.vtk.widgets.ctkCrosshairLabel");
//--------------------------------------------------------------------------

//-----------------------------------------------------------------------------
class ctkCrosshairLabelPrivate
{
  Q_DECLARE_PUBLIC(ctkCrosshairLabel);
protected:
  ctkCrosshairLabel* const q_ptr;
public:
  ctkCrosshairLabelPrivate(ctkCrosshairLabel& object);

  void init();
  void drawCrosshair();
  void drawSimpleCrosshair(QPainter& painter);
  void drawBullsEyeCrosshair(QPainter& painter);

  bool      ShowCrosshair;
  QPen      CrosshairPen;
  ctkCrosshairLabel::CrosshairTypes CrosshairType;
  int       BullsEyeWidth;

  static const double BULLS_EYE_BLANK_FRACTION;
};

const double ctkCrosshairLabelPrivate::BULLS_EYE_BLANK_FRACTION = 0.1;

// --------------------------------------------------------------------------
// ctkCrosshairLabelPrivate methods

// --------------------------------------------------------------------------
ctkCrosshairLabelPrivate::ctkCrosshairLabelPrivate(ctkCrosshairLabel& object)
  :q_ptr(&object)
{
  this->ShowCrosshair = true;
  this->CrosshairType = ctkCrosshairLabel::SimpleCrosshair;
  this->BullsEyeWidth = 15;
}

//---------------------------------------------------------------------------
void ctkCrosshairLabelPrivate::init()
{
  Q_Q(ctkCrosshairLabel);
  q->setAutoFillBackground(true);
  q->setAlignment(Qt::AlignCenter);
  this->CrosshairPen.setColor(q->palette().color(QPalette::Highlight));
  this->CrosshairPen.setWidth(0);
  this->CrosshairPen.setJoinStyle(Qt::MiterJoin);
}

//---------------------------------------------------------------------------
void ctkCrosshairLabelPrivate::drawCrosshair()
{
  // Abort if we are not to draw the crosshair
  if (!this->ShowCrosshair)
    {
    return;
    }

  // Setup the painter object to paint on the label
  Q_Q(ctkCrosshairLabel);
  QPainter painter(q);
  painter.setPen(this->CrosshairPen);

  // Draw crosshair (based on current parameters) onto the label
  switch (this->CrosshairType)
    {
    case ctkCrosshairLabel::SimpleCrosshair:
      this->drawSimpleCrosshair(painter);
      break;
    case ctkCrosshairLabel::BullsEyeCrosshair:
      this->drawBullsEyeCrosshair(painter);
      break;
    default:
      qDebug() << "Unsupported crosshair type" << this->CrosshairType;
      break;
    }
}

//---------------------------------------------------------------------------
void ctkCrosshairLabelPrivate::drawSimpleCrosshair(QPainter& painter)
{
  Q_Q(ctkCrosshairLabel);
  QSize size = q->size();
  double halfWidth = (size.width()-1.0) / 2.0;
  double halfHeight = (size.height()-1.0) / 2.0;
  painter.drawLine(QPointF(0, halfHeight), QPointF(size.width(), halfHeight));
  painter.drawLine(QPointF(halfWidth, 0), QPointF(halfWidth, size.height()));
}

// --------------------------------------------------------------------------
void ctkCrosshairLabelPrivate::drawBullsEyeCrosshair(QPainter& painter)
{
  Q_Q(ctkCrosshairLabel);
  QSize size = q->size();

  // Draw rectangle
  double bullsEye = this->BullsEyeWidth;
  double lineWidth = painter.pen().width();
  lineWidth = std::max(lineWidth, 1.0);
  double halfLineWidth = (lineWidth-1.0) / 2.0;
  double x = (size.width()-bullsEye) / 2.0;
  double y = (size.height()-bullsEye) / 2.0;
  double rectWidth = bullsEye;
  if (bullsEye != 1)
    {
    rectWidth = rectWidth - lineWidth;
    }
  rectWidth = std::max(rectWidth, 0.0);
  painter.drawRect(
      QRectF(x+halfLineWidth, y+halfLineWidth, rectWidth, rectWidth));

  // Draw the lines
  double halfWidth = (size.width()-1.0) / 2.0;
  double halfHeight = (size.height()-1.0) / 2.0;
  double blank = round(std::min(halfWidth, halfHeight)
                       * this->BULLS_EYE_BLANK_FRACTION);

  painter.drawLine(QPointF(0, halfHeight), QPointF(x-blank-1.0, halfHeight));
  painter.drawLine(QPointF(x+bullsEye+blank, halfHeight),
                   QPointF(size.width(), halfHeight));
  painter.drawLine(QPointF(halfWidth, 0), QPointF(halfWidth, y-blank-1.0));
  painter.drawLine(QPointF(halfWidth, y+bullsEye+blank),
                   QPointF(halfWidth, size.height()));
}

//---------------------------------------------------------------------------
// ctkCrosshairLabel methods

// --------------------------------------------------------------------------
ctkCrosshairLabel::ctkCrosshairLabel(QWidget* parent)
  : Superclass(parent)
  , d_ptr(new ctkCrosshairLabelPrivate(*this))
{
  Q_D(ctkCrosshairLabel);
  d->init();
}

// --------------------------------------------------------------------------
ctkCrosshairLabel::~ctkCrosshairLabel()
{
}

// --------------------------------------------------------------------------
CTK_GET_CPP(ctkCrosshairLabel, bool, showCrosshair, ShowCrosshair);

// --------------------------------------------------------------------------
void ctkCrosshairLabel::setShowCrosshair(bool newShow)
{
  Q_D(ctkCrosshairLabel);
  if (newShow == d->ShowCrosshair)
    {
    return;
    }

  d->ShowCrosshair = newShow;
  this->update();
}

// --------------------------------------------------------------------------
CTK_GET_CPP(ctkCrosshairLabel, QPen, crosshairPen, CrosshairPen);

// --------------------------------------------------------------------------
void ctkCrosshairLabel::setCrosshairPen(const QPen& newPen)
{
  Q_D(ctkCrosshairLabel);
  if (newPen == d->CrosshairPen)
    {
    return;
    }

  d->CrosshairPen = newPen;
  this->update();
}

// --------------------------------------------------------------------------
QColor ctkCrosshairLabel::crosshairColor() const
{
  Q_D(const ctkCrosshairLabel);
  return d->CrosshairPen.color();
}

// --------------------------------------------------------------------------
void ctkCrosshairLabel::setCrosshairColor(const QColor& newColor)
{
  Q_D(ctkCrosshairLabel);
  if (d->CrosshairPen.color() == newColor)
    {
    return;
    }

  d->CrosshairPen.setColor(newColor);
  this->update();
}

// --------------------------------------------------------------------------
int ctkCrosshairLabel::lineWidth() const
{
  Q_D(const ctkCrosshairLabel);
  return d->CrosshairPen.width();
}

// --------------------------------------------------------------------------
void ctkCrosshairLabel::setLineWidth(int newWidth)
{
  Q_D(ctkCrosshairLabel);
  if (d->CrosshairPen.width() == newWidth || newWidth < 0)
    {
    return;
    }

  d->CrosshairPen.setWidth(newWidth);
  this->update();
}

// --------------------------------------------------------------------------
CTK_GET_CPP(ctkCrosshairLabel, ctkCrosshairLabel::CrosshairTypes,
            crosshairType, CrosshairType);

// --------------------------------------------------------------------------
void ctkCrosshairLabel::setCrosshairType(const CrosshairTypes& newType)
{
  Q_D(ctkCrosshairLabel);
  if (newType == d->CrosshairType)
    {
    return;
    }

  d->CrosshairType = newType;
  this->update();
}

// --------------------------------------------------------------------------
QColor ctkCrosshairLabel::marginColor() const
  {
  return this->palette().color(QPalette::Window);
  }

// --------------------------------------------------------------------------
void ctkCrosshairLabel::setMarginColor(const QColor& newColor)
{
  if (!newColor.isValid())
    {
    return;
    }

  QPalette palette(this->palette());
  QColor solidColor(newColor.rgb());
  if (solidColor != palette.color(QPalette::Window))
    {
    // Ignore alpha channel
    palette.setColor(QPalette::Window, solidColor);
    this->setPalette(palette);
    this->update();
    }
}

// --------------------------------------------------------------------------
CTK_GET_CPP(ctkCrosshairLabel, int, bullsEyeWidth, BullsEyeWidth);

// --------------------------------------------------------------------------
void ctkCrosshairLabel::setBullsEyeWidth(int newWidth)
{
  Q_D(ctkCrosshairLabel);
  if (newWidth == d->BullsEyeWidth || newWidth < 0)
    {
    return;
    }

  d->BullsEyeWidth = newWidth;
  this->update();
}

// --------------------------------------------------------------------------
void ctkCrosshairLabel::paintEvent(QPaintEvent * event)
{
  Superclass::paintEvent(event);
  Q_D(ctkCrosshairLabel);
  d->drawCrosshair();
}

// --------------------------------------------------------------------------
QSize ctkCrosshairLabel::minimumSizeHint()const
{
  // Pretty arbitrary size (matches ctkVTKAbstractView)
  return QSize(50, 50);
}

// --------------------------------------------------------------------------
QSize ctkCrosshairLabel::sizeHint()const
{
  // Pretty arbitrary size (matches ctkVTKAbstractView)
  return QSize(300, 300);
}

//----------------------------------------------------------------------------
bool ctkCrosshairLabel::hasHeightForWidth()const
{
  return true;
}

//----------------------------------------------------------------------------
int ctkCrosshairLabel::heightForWidth(int width)const
{
  // Tends to be square
  return width;
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

// $Id$
//
// --------------------------------------
// Class AliMUONGeometryDetElement
// --------------------------------------
// The class defines the detection element.
// Author: Ivana Hrivnacova, IPN Orsay

#include "AliMUONGeometryDetElement.h"

#include "AliLog.h"

#include <TGeoMatrix.h>
#include <Riostream.h>

#include <sstream>

/// \cond CLASSIMP
ClassImp(AliMUONGeometryDetElement)
/// \endcond

const TString AliMUONGeometryDetElement::fgkDENamePrefix = "DE";

//______________________________________________________________________________
AliMUONGeometryDetElement::AliMUONGeometryDetElement(
                                        Int_t detElemId,
                                        const TString& volumePath)
 : TObject(),
   fDEName(),
   fVolumePath(volumePath),
   fLocalTransformation(0),
   fGlobalTransformation(0)
{
/// Standard constructor

  SetUniqueID(detElemId);

  fDEName = fgkDENamePrefix;
  fDEName += detElemId;
}

//______________________________________________________________________________
AliMUONGeometryDetElement::AliMUONGeometryDetElement()
 : TObject(),
   fVolumePath(),
   fLocalTransformation(0),
   fGlobalTransformation(0)
{
/// Default constructor
}

//______________________________________________________________________________
AliMUONGeometryDetElement::~AliMUONGeometryDetElement()
{
/// Destructor

  delete fLocalTransformation;
  delete fGlobalTransformation;
}

//
// private methods
//

//______________________________________________________________________________
void  AliMUONGeometryDetElement::PrintTransform(
                                            const TGeoHMatrix* transform) const
{
/// Print the detection element transformation

  cout << "DetElemId: " << GetUniqueID();
  cout << "  name: " << fVolumePath << endl;

  if ( !transform ) {
    cout << "    Transformation not defined." << endl;
    return;
  }

  const double* translation = transform->GetTranslation();
  cout << "   translation: "
#if defined (__DECCXX)
       << translation[0] << ", "
       << translation[1] << ", "
       << translation[2] << endl;
#else
       << std::fixed
       << std::setw(7) << std::setprecision(4) << translation[0] << ", "
       << std::setw(7) << std::setprecision(4) << translation[1] << ", "
       << std::setw(7) << std::setprecision(4) << translation[2] << endl;
#endif

  const double* rotation = transform->GetRotationMatrix();
  cout << "   rotation matrix:  "
#if defined (__DECCXX)
       << rotation[0] << ", " << rotation[1] << ", " << rotation[2] << endl
       << "                     "
       << rotation[3] << ", " << rotation[4] << ", " << rotation[5] << endl
       << "                     "
       << rotation[6] << ", " << rotation[7] << ", " << rotation[8] << endl;
#else
       << std::fixed
       << std::setw(7) << std::setprecision(4)
       << rotation[0] << ", " << rotation[1] << ", " << rotation[2] << endl
       << "                     "
       << rotation[3] << ", " << rotation[4] << ", " << rotation[5] << endl
       << "                     "
       << rotation[6] << ", " << rotation[7] << ", " << rotation[8] << endl;
#endif
}

//
// public methods
//

//______________________________________________________________________________
void  AliMUONGeometryDetElement::Global2Local(
                                  Float_t xg, Float_t yg, Float_t zg,
                                  Float_t& xl, Float_t& yl, Float_t& zl) const
{
/// Transform point from the global reference frame (ALIC)
/// to the local reference frame of this detection element.

  Double_t dxg = xg;
  Double_t dyg = yg;
  Double_t dzg = zg;

  Double_t dxl, dyl, dzl;
  Global2Local(dxg, dyg, dzg, dxl, dyl, dzl);

  xl = dxl;
  yl = dyl;
  zl = dzl;
}

//______________________________________________________________________________
void  AliMUONGeometryDetElement::Global2Local(
                                  Double_t xg, Double_t yg, Double_t zg,
                                  Double_t& xl, Double_t& yl, Double_t& zl) const
{
/// Transform point from the global reference frame (ALIC)
/// to the local reference frame of this detection element

   // Check transformation
   if (!fGlobalTransformation) {
     AliError(Form("Global transformation for detection element %d not defined.",
                    GetUniqueID()));
     return;
   }

   // Transform point
   Double_t pg[3] = { xg, yg, zg };
   Double_t pl[3] = { 0., 0., 0. };
   fGlobalTransformation->MasterToLocal(pg, pl);

   // Return transformed point
   xl = pl[0];
   yl = pl[1];
   zl = pl[2];
}

//______________________________________________________________________________
void  AliMUONGeometryDetElement::Local2Global(
                 Float_t xl, Float_t yl, Float_t zl,
                 Float_t& xg, Float_t& yg, Float_t& zg) const
{
/// Transform point from the local reference frame of this detection element
/// to the global reference frame (ALIC).

  Double_t dxl = xl;
  Double_t dyl = yl;
  Double_t dzl = zl;

  Double_t dxg, dyg, dzg;
  Local2Global(dxl, dyl, dzl, dxg, dyg, dzg);

  xg = dxg;
  yg = dyg;
  zg = dzg;
}

//______________________________________________________________________________
void  AliMUONGeometryDetElement::Local2Global(
                 Double_t xl, Double_t yl, Double_t zl,
                 Double_t& xg, Double_t& yg, Double_t& zg) const
{
/// Transform point from the local reference frame of this detection element
/// to the global reference frame (ALIC).

   // Check transformation
   if (!fGlobalTransformation) {
     AliError(Form("Global transformation for detection element %d not defined.",
                    GetUniqueID()));
     return;
   }

   // Transform point
   Double_t pl[3] = { xl, yl, zl };
   Double_t pg[3] = { 0., 0., 0. };
   fGlobalTransformation->LocalToMaster(pl, pg);

   // Return transformed point
   xg = pg[0];
   yg = pg[1];
   zg = pg[2];
}

//______________________________________________________________________________
void AliMUONGeometryDetElement::SetLocalTransformation(
                                                const TGeoHMatrix& transform)
{
/// Set local transformation;
/// give warning if the global transformation is already defined.

  if (fLocalTransformation) {
    delete fLocalTransformation;
    AliWarning("Local transformation already defined was deleted.");
  }

  fLocalTransformation = new TGeoHMatrix(transform);
}

//______________________________________________________________________________
void AliMUONGeometryDetElement::SetGlobalTransformation(
                                                const TGeoHMatrix& transform)
{
/// Set global transformation;
/// give warning if the global transformation is already defined.

  if (fGlobalTransformation) {
    delete fGlobalTransformation;
    AliWarning("Global transformation already defined was deleted.");
  }

  fGlobalTransformation = new TGeoHMatrix(transform);
}

//______________________________________________________________________________
void AliMUONGeometryDetElement::PrintLocalTransform() const
{
/// Print detection element relative transformation
/// (the transformation wrt module frame)

  PrintTransform(fLocalTransformation);
}

//______________________________________________________________________________
void AliMUONGeometryDetElement::PrintGlobalTransform() const
{
/// Print detection element global transformation
/// (the transformation wrt global frame)

  PrintTransform(fGlobalTransformation);
}

//______________________________________________________________________________
TString AliMUONGeometryDetElement::GetVolumeName() const
{
/// Extract volume name from the path

  std::string volPath = fVolumePath.Data();
  std::string::size_type first = volPath.rfind('/')+1;
  std::string::size_type last = volPath.rfind('_');

  return volPath.substr(first, last-first );
}

//______________________________________________________________________________
Int_t AliMUONGeometryDetElement::GetVolumeCopyNo() const
{
/// Extract volume copyNo from the path

  string volPath = fVolumePath.Data();
  std::string::size_type first = volPath.rfind('_');
  std::string copyNoStr = volPath.substr(first+1, volPath.length());
  std::istringstream in(copyNoStr);
  Int_t copyNo;
  in >> copyNo;

  return copyNo;
}

<commit_msg>Corrested data members initialization in ctor<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

// $Id$
//
// --------------------------------------
// Class AliMUONGeometryDetElement
// --------------------------------------
// The class defines the detection element.
// Author: Ivana Hrivnacova, IPN Orsay

#include "AliMUONGeometryDetElement.h"

#include "AliLog.h"

#include <TGeoMatrix.h>
#include <Riostream.h>

#include <sstream>

/// \cond CLASSIMP
ClassImp(AliMUONGeometryDetElement)
/// \endcond

const TString AliMUONGeometryDetElement::fgkDENamePrefix = "DE";

//______________________________________________________________________________
AliMUONGeometryDetElement::AliMUONGeometryDetElement(
                                        Int_t detElemId,
                                        const TString& volumePath)
 : TObject(),
   fDEName(),
   fVolumePath(volumePath),
   fLocalTransformation(0),
   fGlobalTransformation(0)
{
/// Standard constructor

  SetUniqueID(detElemId);

  fDEName = fgkDENamePrefix;
  fDEName += detElemId;
}

//______________________________________________________________________________
AliMUONGeometryDetElement::AliMUONGeometryDetElement()
 : TObject(),
   fDEName(),
   fVolumePath(),
   fLocalTransformation(0),
   fGlobalTransformation(0)
{
/// Default constructor
}

//______________________________________________________________________________
AliMUONGeometryDetElement::~AliMUONGeometryDetElement()
{
/// Destructor

  delete fLocalTransformation;
  delete fGlobalTransformation;
}

//
// private methods
//

//______________________________________________________________________________
void  AliMUONGeometryDetElement::PrintTransform(
                                            const TGeoHMatrix* transform) const
{
/// Print the detection element transformation

  cout << "DetElemId: " << GetUniqueID();
  cout << "  name: " << fVolumePath << endl;

  if ( !transform ) {
    cout << "    Transformation not defined." << endl;
    return;
  }

  const double* translation = transform->GetTranslation();
  cout << "   translation: "
#if defined (__DECCXX)
       << translation[0] << ", "
       << translation[1] << ", "
       << translation[2] << endl;
#else
       << std::fixed
       << std::setw(7) << std::setprecision(4) << translation[0] << ", "
       << std::setw(7) << std::setprecision(4) << translation[1] << ", "
       << std::setw(7) << std::setprecision(4) << translation[2] << endl;
#endif

  const double* rotation = transform->GetRotationMatrix();
  cout << "   rotation matrix:  "
#if defined (__DECCXX)
       << rotation[0] << ", " << rotation[1] << ", " << rotation[2] << endl
       << "                     "
       << rotation[3] << ", " << rotation[4] << ", " << rotation[5] << endl
       << "                     "
       << rotation[6] << ", " << rotation[7] << ", " << rotation[8] << endl;
#else
       << std::fixed
       << std::setw(7) << std::setprecision(4)
       << rotation[0] << ", " << rotation[1] << ", " << rotation[2] << endl
       << "                     "
       << rotation[3] << ", " << rotation[4] << ", " << rotation[5] << endl
       << "                     "
       << rotation[6] << ", " << rotation[7] << ", " << rotation[8] << endl;
#endif
}

//
// public methods
//

//______________________________________________________________________________
void  AliMUONGeometryDetElement::Global2Local(
                                  Float_t xg, Float_t yg, Float_t zg,
                                  Float_t& xl, Float_t& yl, Float_t& zl) const
{
/// Transform point from the global reference frame (ALIC)
/// to the local reference frame of this detection element.

  Double_t dxg = xg;
  Double_t dyg = yg;
  Double_t dzg = zg;

  Double_t dxl, dyl, dzl;
  Global2Local(dxg, dyg, dzg, dxl, dyl, dzl);

  xl = dxl;
  yl = dyl;
  zl = dzl;
}

//______________________________________________________________________________
void  AliMUONGeometryDetElement::Global2Local(
                                  Double_t xg, Double_t yg, Double_t zg,
                                  Double_t& xl, Double_t& yl, Double_t& zl) const
{
/// Transform point from the global reference frame (ALIC)
/// to the local reference frame of this detection element

   // Check transformation
   if (!fGlobalTransformation) {
     AliError(Form("Global transformation for detection element %d not defined.",
                    GetUniqueID()));
     return;
   }

   // Transform point
   Double_t pg[3] = { xg, yg, zg };
   Double_t pl[3] = { 0., 0., 0. };
   fGlobalTransformation->MasterToLocal(pg, pl);

   // Return transformed point
   xl = pl[0];
   yl = pl[1];
   zl = pl[2];
}

//______________________________________________________________________________
void  AliMUONGeometryDetElement::Local2Global(
                 Float_t xl, Float_t yl, Float_t zl,
                 Float_t& xg, Float_t& yg, Float_t& zg) const
{
/// Transform point from the local reference frame of this detection element
/// to the global reference frame (ALIC).

  Double_t dxl = xl;
  Double_t dyl = yl;
  Double_t dzl = zl;

  Double_t dxg, dyg, dzg;
  Local2Global(dxl, dyl, dzl, dxg, dyg, dzg);

  xg = dxg;
  yg = dyg;
  zg = dzg;
}

//______________________________________________________________________________
void  AliMUONGeometryDetElement::Local2Global(
                 Double_t xl, Double_t yl, Double_t zl,
                 Double_t& xg, Double_t& yg, Double_t& zg) const
{
/// Transform point from the local reference frame of this detection element
/// to the global reference frame (ALIC).

   // Check transformation
   if (!fGlobalTransformation) {
     AliError(Form("Global transformation for detection element %d not defined.",
                    GetUniqueID()));
     return;
   }

   // Transform point
   Double_t pl[3] = { xl, yl, zl };
   Double_t pg[3] = { 0., 0., 0. };
   fGlobalTransformation->LocalToMaster(pl, pg);

   // Return transformed point
   xg = pg[0];
   yg = pg[1];
   zg = pg[2];
}

//______________________________________________________________________________
void AliMUONGeometryDetElement::SetLocalTransformation(
                                                const TGeoHMatrix& transform)
{
/// Set local transformation;
/// give warning if the global transformation is already defined.

  if (fLocalTransformation) {
    delete fLocalTransformation;
    AliWarning("Local transformation already defined was deleted.");
  }

  fLocalTransformation = new TGeoHMatrix(transform);
}

//______________________________________________________________________________
void AliMUONGeometryDetElement::SetGlobalTransformation(
                                                const TGeoHMatrix& transform)
{
/// Set global transformation;
/// give warning if the global transformation is already defined.

  if (fGlobalTransformation) {
    delete fGlobalTransformation;
    AliWarning("Global transformation already defined was deleted.");
  }

  fGlobalTransformation = new TGeoHMatrix(transform);
}

//______________________________________________________________________________
void AliMUONGeometryDetElement::PrintLocalTransform() const
{
/// Print detection element relative transformation
/// (the transformation wrt module frame)

  PrintTransform(fLocalTransformation);
}

//______________________________________________________________________________
void AliMUONGeometryDetElement::PrintGlobalTransform() const
{
/// Print detection element global transformation
/// (the transformation wrt global frame)

  PrintTransform(fGlobalTransformation);
}

//______________________________________________________________________________
TString AliMUONGeometryDetElement::GetVolumeName() const
{
/// Extract volume name from the path

  std::string volPath = fVolumePath.Data();
  std::string::size_type first = volPath.rfind('/')+1;
  std::string::size_type last = volPath.rfind('_');

  return volPath.substr(first, last-first );
}

//______________________________________________________________________________
Int_t AliMUONGeometryDetElement::GetVolumeCopyNo() const
{
/// Extract volume copyNo from the path

  string volPath = fVolumePath.Data();
  std::string::size_type first = volPath.rfind('_');
  std::string copyNoStr = volPath.substr(first+1, volPath.length());
  std::istringstream in(copyNoStr);
  Int_t copyNo;
  in >> copyNo;

  return copyNo;
}

<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "plugin.h"
#include "pluginmanager.h"
#include "pluginswindow.h"

#include "ui_pluginswindow.h"

#include <QDesktopServices>
#include <QUrl>

namespace OpenCOR {

PluginDelegate::PluginDelegate(QStandardItemModel *pDataModel,
                               QObject *pParent) :
    QStyledItemDelegate(pParent),
    mDataModel(pDataModel)
{
}

void PluginDelegate::paint(QPainter *pPainter,
                           const QStyleOptionViewItem &pOption,
                           const QModelIndex &pIndex) const
{
    // Paint the item as normal, except for the items which are not checkable
    // (i.e. plugins which the user cannot decide whether to load) in which case
    // we paint them as if they were disabled

    QStandardItem *pluginItem = mDataModel->itemFromIndex(pIndex);

    QStyleOptionViewItemV4 option(pOption);

    initStyleOption(&option, pIndex);

    if (!pluginItem->isCheckable())
        option.state &= ~QStyle::State_Enabled;

    QStyledItemDelegate::paint(pPainter, option, pIndex);
}

PluginsWindow::PluginsWindow(PluginManager *pPluginManager,
                             QWidget *pParent) :
    QDialog(pParent),
    mUi(new Ui::PluginsWindow),
    mPluginManager(pPluginManager)
{
    // Set up the UI

    mUi->setupUi(this);

    // Update the note label

    mUi->noteLabel->setText(mUi->noteLabel->text().arg(qApp->applicationName()));

    // Set up the tree view with a delegate, so that we can select plugins that
    // are shown as 'disabled' (to reflect the fact that users cannot decide
    // whether they should be loaded)

    mDataModel = new QStandardItemModel;
    mPluginDelegate = new PluginDelegate(mDataModel);

    mUi->listView->setModel(mDataModel);
    mUi->listView->setItemDelegate(mPluginDelegate);

    // Populate the data model

    foreach (Plugin *plugin, mPluginManager->plugins()) {
        QStandardItem *pluginItem = new QStandardItem(plugin->name());

        if (plugin->info().manageable()) {
            // Only manageable plugins are checkable

            pluginItem->setCheckable(true);

            // Retrieve the loading state of the plugin

            pluginItem->setCheckState((Plugin::load(mPluginManager->settings(),
                                                    plugin->name()))?
                                          Qt::Checked:
                                          Qt::Unchecked);

            // We are dealing with a manageable plugin, so add it to our list of
            // manageable plugins

            mManageablePlugins << pluginItem;
        } else {
            // We are dealing with an unmanageable plugin, so add it to our list
            // of unmanageable plugins

            mUnmanageablePlugins << pluginItem;
        }

        // Add the plugin to our data model

        mDataModel->invisibleRootItem()->appendRow(pluginItem);
    }

    // Make sure that the loading state of all the plugins is right, including
    // that of the plugins which the user cannot manage

    updatePluginsLoadingState();

    // Select the first plugin

    mUi->listView->selectionModel()->select(mDataModel->index(0, 0),
                                            QItemSelectionModel::Select);

    // Make sure that the list view only takes as much width as necessary
    // Note: for some reasons (maybe because we have check boxes?), the
    //       retrieved column size gives us a width that is slightly too small
    //       and therefore requires a horizontal scroll bar, hence we add 15% to
    //       it (the extra 15% seems to be enough to even account for a big
    //       number of plugins which would then require a vertical scroll bar)

    mUi->listView->setMinimumWidth(1.15*mUi->listView->sizeHintForColumn(0));
    mUi->listView->setMaximumWidth(mUi->listView->minimumWidth());

    // Make, through the note label, sure that the window has a minimum width

    mUi->noteLabel->setMinimumWidth(2.75*mUi->listView->minimumWidth());

    // Connection to handle a plugin's information

    connect(mUi->listView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
            this, SLOT(updatePluginInfo(const QModelIndex &, const QModelIndex &)));

    // Connection to handle the activation of a link in the description

    connect(mUi->descriptionValue, SIGNAL(linkActivated(const QString &)),
            this, SLOT(openLink(const QString &)));

    // Make sure that the window has a reasonable starting size

    mUi->verticalLayout->setSizeConstraint(QLayout::SetMinimumSize);
}

PluginsWindow::~PluginsWindow()
{
    // Delete some internal objects

    delete mDataModel;
    delete mPluginDelegate;
    delete mUi;
}

void PluginsWindow::retranslateUi()
{
    // Retranslate the whole window

    mUi->retranslateUi(this);
}

void PluginsWindow::updatePluginInfo(const QModelIndex &pNewIndex,
                                     const QModelIndex &) const
{
    // Update the information view with the plugin's information

    QString pluginName = mDataModel->itemFromIndex(pNewIndex)->text();
    Plugin *plugin = mPluginManager->plugin(pluginName);
    PluginInfo pluginInfo = plugin->info();

    // The plugin's name

    mUi->nameValue->setText(pluginName);

    // The plugin's type

    switch (pluginInfo.type()) {
    case PluginInfo::General:
        mUi->typeValue->setText(tr("General"));

        break;
    case PluginInfo::Console:
        mUi->typeValue->setText(tr("Console"));

        break;
    case PluginInfo::Gui:
        mUi->typeValue->setText(tr("GUI"));

        break;
    default:
        mUi->typeValue->setText(tr("Undefined"));

        break;
    }

    // The plugin's dependencies

    QStringList dependencies = pluginInfo.dependencies();

    if (dependencies.isEmpty())
        dependencies << tr("None");

    if (dependencies.count() > 1)
        mUi->dependenciesValue->setText("- "+dependencies.join("\n- "));
    else
        mUi->dependenciesValue->setText(dependencies.first());

    // The plugin's description

    QString description = pluginInfo.description(qobject_cast<MainWindow *>(parent())->locale());

    mUi->descriptionValue->setText(description.isEmpty()?
                                       tr("None"):
                                       description);

    // The plugin's status

    mUi->statusValue->setText(plugin->statusDescription());
}

void PluginsWindow::updatePluginsLoadingState(QStandardItem *pChangedPluginItem) const
{
    // Disable the connection that handles a change in a plugin's loading state

    disconnect(mDataModel, SIGNAL(itemChanged(QStandardItem *)),
               this, SLOT(updatePluginsLoadingState(QStandardItem *)));

    // Prevent the list view from being updated, since we may change a few
    // things

    mUi->listView->setUpdatesEnabled(false);

    // Check whether we came here as a result of checking a plugin and, if so,
    // then make sure that all of that plugin's dependencies are also checked

    if (   pChangedPluginItem
        && (pChangedPluginItem->checkState() == Qt::Checked))
        foreach (const QString &requiredPlugin,
                 mPluginManager->plugin(pChangedPluginItem->text())->info().fullDependencies())
            foreach (QStandardItem *pluginItem, mManageablePlugins)
                if (!pluginItem->text().compare(requiredPlugin))
                    // We are dealing with one of the plugin's dependencies, so
                    // make sure it's checked

                    pluginItem->setCheckState(Qt::Checked);

    // At this stage, all the plugins which should be checked are checked, so
    // now we must update the manageable plugins that are currently checked to
    // make sure that their loading state is consistent with that of the others.
    // This means going through each of the plugins and have them checked only
    // if all of their dependencies are checked. Note that it is fine to do it
    // this way since all we need is for one of a plugin's dependencies to be
    // unchecked for the plugin to also be unchecked, so...

    foreach (QStandardItem *pluginItem, mManageablePlugins)
        if (pluginItem->checkState() == Qt::Checked)
            foreach (const QString &requiredPlugin,
                     mPluginManager->plugin(pluginItem->text())->info().fullDependencies())
                foreach (QStandardItem *otherPluginItem, mManageablePlugins)
                    if (!otherPluginItem->text().compare(requiredPlugin)) {
                        // We have found the plugin's dependency

                        if (otherPluginItem->checkState() == Qt::Unchecked)
                            // The plugin's dependency is unchecked, meaning the
                            // plugin must also be unchecked

                            pluginItem->setCheckState(Qt::Unchecked);

                        break;
                    }

    // Finally, we need to see whether any of the unmanageable plugins should be
    // checked

    foreach (QStandardItem *pluginItem, mUnmanageablePlugins) {
        // First, reset the loading state of the unamangeable plugin

        pluginItem->setCheckState(Qt::Unchecked);

        // Next, go through the manageable plugins' dependencies

        foreach (QStandardItem *otherPluginItem, mManageablePlugins)
            if (otherPluginItem->checkState() == Qt::Checked)
                // The manageable plugin is checked, so carry on...

                foreach (const QString &requiredPlugin,
                         mPluginManager->plugin(otherPluginItem->text())->info().fullDependencies())
                    if (!requiredPlugin.compare(pluginItem->text())) {
                        // The manageable plugin does require the unamanageable
                        // plugin, so...

                        pluginItem->setCheckState(Qt::Checked);

                        break;
                    }
    }

    // Re-enable the the list view from being updated

    mUi->listView->setUpdatesEnabled(true);

    // Re-enable the connection that handles a change in a plugin's loading
    // state

    connect(mDataModel, SIGNAL(itemChanged(QStandardItem *)),
            this, SLOT(updatePluginsLoadingState(QStandardItem *)));
}

void PluginsWindow::openLink(const QString &pLink) const
{
    // Open the link in the user's browser

    QDesktopServices::openUrl(QUrl(pLink));
}

void PluginsWindow::on_buttonBox_accepted()
{
    // Keep track of the loading state of the various plugins over which the
    // user has control (i.e. the ones that are checkable)

    foreach (QStandardItem *pluginItem, mManageablePlugins)
        if (pluginItem->isCheckable())
            Plugin::setLoad(mPluginManager->settings(), pluginItem->text(),
                            pluginItem->checkState() == Qt::Checked);

    // Confirm that we accepted the changes

    accept();
}

void PluginsWindow::on_buttonBox_rejected()
{
    // Simple cancel whatever was done here

    reject();
}

}
<commit_msg>Minor editing.<commit_after>#include "mainwindow.h"
#include "plugin.h"
#include "pluginmanager.h"
#include "pluginswindow.h"

#include "ui_pluginswindow.h"

#include <QDesktopServices>
#include <QUrl>

namespace OpenCOR {

PluginDelegate::PluginDelegate(QStandardItemModel *pDataModel,
                               QObject *pParent) :
    QStyledItemDelegate(pParent),
    mDataModel(pDataModel)
{
}

void PluginDelegate::paint(QPainter *pPainter,
                           const QStyleOptionViewItem &pOption,
                           const QModelIndex &pIndex) const
{
    // Paint the item as normal, except for the items which are not checkable
    // (i.e. plugins which the user cannot decide whether to load) in which case
    // we paint them as if they were disabled

    QStandardItem *pluginItem = mDataModel->itemFromIndex(pIndex);

    QStyleOptionViewItemV4 option(pOption);

    initStyleOption(&option, pIndex);

    if (!pluginItem->isCheckable())
        option.state &= ~QStyle::State_Enabled;

    QStyledItemDelegate::paint(pPainter, option, pIndex);
}

PluginsWindow::PluginsWindow(PluginManager *pPluginManager,
                             QWidget *pParent) :
    QDialog(pParent),
    mUi(new Ui::PluginsWindow),
    mPluginManager(pPluginManager)
{
    // Set up the UI

    mUi->setupUi(this);

    // Update the note label

    mUi->noteLabel->setText(mUi->noteLabel->text().arg(qApp->applicationName()));

    // Set up the tree view with a delegate, so that we can select plugins that
    // are shown as 'disabled' (to reflect the fact that users cannot decide
    // whether they should be loaded)

    mDataModel = new QStandardItemModel;
    mPluginDelegate = new PluginDelegate(mDataModel);

    mUi->listView->setModel(mDataModel);
    mUi->listView->setItemDelegate(mPluginDelegate);

    // Populate the data model

    foreach (Plugin *plugin, mPluginManager->plugins()) {
        QStandardItem *pluginItem = new QStandardItem(plugin->name());

        if (plugin->info().manageable()) {
            // Only manageable plugins are checkable

            pluginItem->setCheckable(true);

            // Retrieve the loading state of the plugin

            pluginItem->setCheckState((Plugin::load(mPluginManager->settings(),
                                                    plugin->name()))?
                                          Qt::Checked:
                                          Qt::Unchecked);

            // We are dealing with a manageable plugin, so add it to our list of
            // manageable plugins

            mManageablePlugins << pluginItem;
        } else {
            // We are dealing with an unmanageable plugin, so add it to our list
            // of unmanageable plugins

            mUnmanageablePlugins << pluginItem;
        }

        // Add the plugin to our data model

        mDataModel->invisibleRootItem()->appendRow(pluginItem);
    }

    // Make sure that the loading state of all the plugins is right, including
    // that of the plugins which the user cannot manage

    updatePluginsLoadingState();

    // Select the first plugin

    mUi->listView->selectionModel()->select(mDataModel->index(0, 0),
                                            QItemSelectionModel::Select);

    // Make sure that the list view only takes as much width as necessary
    // Note: for some reasons (maybe because we have check boxes?), the
    //       retrieved column size gives us a width that is slightly too small
    //       and therefore requires a horizontal scroll bar, hence we add 15% to
    //       it (the extra 15% seems to be enough to even account for a big
    //       number of plugins which would then require a vertical scroll bar)

    mUi->listView->setMinimumWidth(1.15*mUi->listView->sizeHintForColumn(0));
    mUi->listView->setMaximumWidth(mUi->listView->minimumWidth());

    // Make, through the note label, sure that the window has a minimum width

    mUi->noteLabel->setMinimumWidth(2.75*mUi->listView->minimumWidth());

    // Connection to handle a plugin's information

    connect(mUi->listView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
            this, SLOT(updatePluginInfo(const QModelIndex &, const QModelIndex &)));

    // Connection to handle the activation of a link in the description

    connect(mUi->descriptionValue, SIGNAL(linkActivated(const QString &)),
            this, SLOT(openLink(const QString &)));

    // Make sure that the window has a reasonable starting size

    mUi->verticalLayout->setSizeConstraint(QLayout::SetMinimumSize);
}

PluginsWindow::~PluginsWindow()
{
    // Delete some internal objects

    delete mDataModel;
    delete mPluginDelegate;
    delete mUi;
}

void PluginsWindow::retranslateUi()
{
    // Retranslate the whole window

    mUi->retranslateUi(this);
}

void PluginsWindow::updatePluginInfo(const QModelIndex &pNewIndex,
                                     const QModelIndex &) const
{
    // Update the information view with the plugin's information

    QString pluginName = mDataModel->itemFromIndex(pNewIndex)->text();
    Plugin *plugin = mPluginManager->plugin(pluginName);
    PluginInfo pluginInfo = plugin->info();

    // The plugin's name

    mUi->nameValue->setText(pluginName);

    // The plugin's type

    switch (pluginInfo.type()) {
    case PluginInfo::General:
        mUi->typeValue->setText(tr("General"));

        break;
    case PluginInfo::Console:
        mUi->typeValue->setText(tr("Console"));

        break;
    case PluginInfo::Gui:
        mUi->typeValue->setText(tr("GUI"));

        break;
    default:
        mUi->typeValue->setText(tr("Undefined"));

        break;
    }

    // The plugin's dependencies

    QStringList dependencies = pluginInfo.dependencies();

    if (dependencies.isEmpty())
        dependencies << tr("None");

    if (dependencies.count() > 1)
        mUi->dependenciesValue->setText("- "+dependencies.join("\n- "));
    else
        mUi->dependenciesValue->setText(dependencies.first());

    // The plugin's description

    QString description = pluginInfo.description(qobject_cast<MainWindow *>(parent())->locale());

    mUi->descriptionValue->setText(description.isEmpty()?
                                       tr("None"):
                                       description);

    // The plugin's status

    mUi->statusValue->setText(plugin->statusDescription());
}

void PluginsWindow::updatePluginsLoadingState(QStandardItem *pChangedPluginItem) const
{
    // Disable the connection that handles a change in a plugin's loading state
    // (otherwise what we are doing here is going to be completely uneffective)

    disconnect(mDataModel, SIGNAL(itemChanged(QStandardItem *)),
               this, SLOT(updatePluginsLoadingState(QStandardItem *)));

    // Prevent the list view from being updated, since we may end up changing
    // quite a bit of its visual contents

    mUi->listView->setUpdatesEnabled(false);

    // Check whether we came here as a result of checking a plugin and, if so,
    // then make sure that all of that plugin's dependencies are also checked

    if (   pChangedPluginItem
        && (pChangedPluginItem->checkState() == Qt::Checked))
        foreach (const QString &requiredPlugin,
                 mPluginManager->plugin(pChangedPluginItem->text())->info().fullDependencies())
            foreach (QStandardItem *pluginItem, mManageablePlugins)
                if (!pluginItem->text().compare(requiredPlugin))
                    // We are dealing with one of the plugin's dependencies, so
                    // make sure it's checked

                    pluginItem->setCheckState(Qt::Checked);

    // At this stage, all the plugins which should be checked are checked, so
    // now we must update the manageable plugins that are currently checked to
    // make sure that they should still be checked indeed. This means going
    // through each of the plugins and keep them checked only if all of their
    // dependencies are checked. Note that it is fine to do it this way since
    // all we need is one plugin's dependency to be unchecked for the plugin
    // itself to also be unchecked, so...

    foreach (QStandardItem *pluginItem, mManageablePlugins)
        if (pluginItem->checkState() == Qt::Checked)
            foreach (const QString &requiredPlugin,
                     mPluginManager->plugin(pluginItem->text())->info().fullDependencies())
                foreach (QStandardItem *otherPluginItem, mManageablePlugins)
                    if (!otherPluginItem->text().compare(requiredPlugin)) {
                        // We have found the plugin's dependency

                        if (otherPluginItem->checkState() == Qt::Unchecked)
                            // The plugin's dependency is unchecked which means
                            // that the plugin cannot be checked, so...

                            pluginItem->setCheckState(Qt::Unchecked);

                        break;
                    }

    // Finally, we need to see whether our unmanageable plugins should be
    // checked or unchecked

    foreach (QStandardItem *pluginItem, mUnmanageablePlugins) {
        // First, reset the loading state of the unamanageable plugin

        pluginItem->setCheckState(Qt::Unchecked);

        // Next, go through the checked manageable plugins' dependencies

        foreach (QStandardItem *otherPluginItem, mManageablePlugins)
            if (otherPluginItem->checkState() == Qt::Checked)
                // The manageable plugin is checked, so carry on...

                foreach (const QString &requiredPlugin,
                         mPluginManager->plugin(otherPluginItem->text())->info().fullDependencies())
                    if (!requiredPlugin.compare(pluginItem->text())) {
                        // The manageable plugin does require the unamanageable
                        // plugin, so...

                        pluginItem->setCheckState(Qt::Checked);

                        break;
                    }
    }

    // Re-enable the updating of the list view

    mUi->listView->setUpdatesEnabled(true);

    // Re-enable the connection that handles a change in a plugin's loading
    // state

    connect(mDataModel, SIGNAL(itemChanged(QStandardItem *)),
            this, SLOT(updatePluginsLoadingState(QStandardItem *)));
}

void PluginsWindow::openLink(const QString &pLink) const
{
    // Open the link in the user's browser

    QDesktopServices::openUrl(QUrl(pLink));
}

void PluginsWindow::on_buttonBox_accepted()
{
    // Keep track of the loading state of the various plugins over which the
    // user has control (i.e. the ones that are checkable)

    foreach (QStandardItem *pluginItem, mManageablePlugins)
        if (pluginItem->isCheckable())
            Plugin::setLoad(mPluginManager->settings(), pluginItem->text(),
                            pluginItem->checkState() == Qt::Checked);

    // Confirm that we accepted the changes

    accept();
}

void PluginsWindow::on_buttonBox_rejected()
{
    // Simple cancel whatever was done here

    reject();
}

}
<|endoftext|>


<commit_before>/*
 * Copyright 2014-2015 CyberVision, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef KAATIMER_HPP_
#define KAATIMER_HPP_

#include <chrono>
#include <mutex>
#include <thread>
#include <functional>
#include <condition_variable>

#include "kaa/KaaThread.hpp"
#include "kaa/logging/Log.hpp"

namespace kaa {

template<class Signature, class Function = std::function<Signature>>
class KaaTimer {
    typedef std::chrono::system_clock TimerClock;
public:
    KaaTimer(const std::string& timerName) :
        timerName_(timerName), isThreadRun_(false), isTimerRun_(false), callback_([]{})
    {

    }
    ~KaaTimer()
    {
        //KAA_LOG_TRACE(boost::format("Timer[%1%] destroying ...") % timerName_);
        if (isThreadRun_ && timerThread_.joinable()) {
            //KAA_MUTEX_LOCKING("timerGuard_");
            KAA_MUTEX_UNIQUE_DECLARE(timerLock, timerGuard_);
            //KAA_MUTEX_LOCKED("timerGuard_");

            isThreadRun_ = false;
            condition_.notify_one();

            //KAA_MUTEX_UNLOCKING("timerGuard_");
            KAA_UNLOCK(timerLock);
            //KAA_MUTEX_UNLOCKED("timerGuard_");

            timerThread_.join();
        }
    }

    void start(std::size_t seconds, const Function& callback)
    {

        KAA_LOG_TRACE(boost::format("Timer[%1%] scheduling for %2% sec ...") % timerName_ % seconds );

        KAA_MUTEX_LOCKING("timerGuard_");
        KAA_MUTEX_UNIQUE_DECLARE(timerLock, timerGuard_);
        KAA_MUTEX_LOCKED("timerGuard_");

        if (!isThreadRun_) {
            isThreadRun_ = true;
            timerThread_ = std::thread([&] { run(); });
        }

        if (!isTimerRun_) {
            endTS_ = TimerClock::now() + std::chrono::seconds(seconds);
            isTimerRun_ = true;
            callback_ = callback;
            condition_.notify_one();
        }
    }

    void stop()
    {
        KAA_LOG_TRACE(boost::format("Timer[%1%] stopping ...") % timerName_);

        KAA_MUTEX_LOCKING("timerGuard_");
        KAA_MUTEX_UNIQUE_DECLARE(timerLock, timerGuard_);
        KAA_MUTEX_LOCKED("timerGuard_");

        if (isTimerRun_) {
            isTimerRun_ = false;
            condition_.notify_one();
        }
    }

private:
    void run()
    {
        KAA_LOG_TRACE(boost::format("Timer[%1%] starting thread ...") % timerName_);

        KAA_MUTEX_LOCKING("timerGuard_");
        KAA_MUTEX_UNIQUE_DECLARE(timerLock, timerGuard_);
        KAA_MUTEX_LOCKED("timerGuard_");

        while (isThreadRun_) {

            if (isTimerRun_) {
                auto now = TimerClock::now();
                if (now >= endTS_) {
                    KAA_LOG_TRACE(boost::format("Timer[%1%] executing callback ...") % timerName_);
                    isTimerRun_ = false;

                    auto currentCallback = callback_;

                    KAA_MUTEX_UNLOCKING("timerGuard_");
                    KAA_UNLOCK(timerLock);
                    KAA_MUTEX_UNLOCKED("timerGuard_");

                    currentCallback();

                    KAA_MUTEX_LOCKING("timer_mutex_");
                    KAA_LOCK(timerLock);
                    KAA_MUTEX_LOCKED("timer_mutex_");
                } else {
                    KAA_MUTEX_UNLOCKING("timerGuard_");
                    condition_.wait_for(timerLock, (endTS_ - now));
                    KAA_MUTEX_UNLOCKED("timerGuard_");
                }
            } else {
                KAA_MUTEX_UNLOCKING("timerGuard_");
                condition_.wait(timerLock);
                KAA_MUTEX_UNLOCKED("timerGuard_");
            }
        }
    }

private:

    const std::string timerName_;

    bool isThreadRun_;
    bool isTimerRun_;

    std::thread timerThread_;
    std::condition_variable condition_;

    KAA_MUTEX_DECLARE(timerGuard_);

    std::chrono::time_point<TimerClock> endTS_;

    Function callback_;
};

} /* namespace kaa */

#endif /* KAATIMER_HPP_ */
<commit_msg>KAA-565: Get rid off thread-macros in the timer class.<commit_after>/*
 * Copyright 2014-2015 CyberVision, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef KAATIMER_HPP_
#define KAATIMER_HPP_

#include <chrono>
#include <mutex>
#include <thread>
#include <functional>
#include <condition_variable>

#include "kaa/KaaThread.hpp"
#include "kaa/logging/Log.hpp"

namespace kaa {

template<class Signature, class Function = std::function<Signature>>
class KaaTimer {
    typedef std::chrono::system_clock TimerClock;
public:
    KaaTimer(const std::string& timerName) :
        timerName_(timerName), isThreadRun_(false), isTimerRun_(false), callback_([]{})
    {

    }
    ~KaaTimer()
    {
        /*
         * Do not add the mutex logging it may cause crashes.
         */
        if (isThreadRun_ && timerThread_.joinable()) {
            std::unique_lock<std::mutex> timerLock(timerGuard_);

            isThreadRun_ = false;
            condition_.notify_one();

            timerLock.unlock();

            timerThread_.join();
        }
    }

    void start(std::size_t seconds, const Function& callback)
    {

        KAA_LOG_TRACE(boost::format("Timer[%1%] scheduling for %2% sec ...") % timerName_ % seconds );

        KAA_MUTEX_LOCKING("timerGuard_");
        std::unique_lock<std::mutex> timerLock(timerGuard_);
        KAA_MUTEX_LOCKED("timerGuard_");

        if (!isThreadRun_) {
            isThreadRun_ = true;
            timerThread_ = std::thread([&] { run(); });
        }

        if (!isTimerRun_) {
            endTS_ = TimerClock::now() + std::chrono::seconds(seconds);
            isTimerRun_ = true;
            callback_ = callback;
            condition_.notify_one();
        }
    }

    void stop()
    {
        KAA_LOG_TRACE(boost::format("Timer[%1%] stopping ...") % timerName_);

        KAA_MUTEX_LOCKING("timerGuard_");
        std::unique_lock<std::mutex> timerLock(timerGuard_);
        KAA_MUTEX_LOCKED("timerGuard_");

        if (isTimerRun_) {
            isTimerRun_ = false;
            condition_.notify_one();
        }
    }

private:
    void run()
    {
        KAA_LOG_TRACE(boost::format("Timer[%1%] starting thread ...") % timerName_);

        KAA_MUTEX_LOCKING("timerGuard_");
        std::unique_lock<std::mutex> timerLock(timerGuard_);
        KAA_MUTEX_LOCKED("timerGuard_");

        while (isThreadRun_) {

            if (isTimerRun_) {
                auto now = TimerClock::now();
                if (now >= endTS_) {
                    KAA_LOG_TRACE(boost::format("Timer[%1%] executing callback ...") % timerName_);
                    isTimerRun_ = false;

                    auto currentCallback = callback_;

                    KAA_MUTEX_UNLOCKING("timerGuard_");
                    timerLock.unlock();
                    KAA_MUTEX_UNLOCKED("timerGuard_");

                    currentCallback();

                    KAA_MUTEX_LOCKING("timer_mutex_");
                    timerLock.lock();
                    KAA_MUTEX_LOCKED("timer_mutex_");
                } else {
                    KAA_MUTEX_UNLOCKING("timerGuard_");
                    condition_.wait_for(timerLock, (endTS_ - now));
                    KAA_MUTEX_UNLOCKED("timerGuard_");
                }
            } else {
                KAA_MUTEX_UNLOCKING("timerGuard_");
                condition_.wait(timerLock);
                KAA_MUTEX_UNLOCKED("timerGuard_");
            }
        }
    }

private:
    const std::string timerName_;

    bool isThreadRun_;
    bool isTimerRun_;

    std::thread timerThread_;
    std::condition_variable condition_;

    std::mutex timerGuard_;

    std::chrono::time_point<TimerClock> endTS_;

    Function callback_;
};

} /* namespace kaa */

#endif /* KAATIMER_HPP_ */
<|endoftext|>


<commit_before>#include <QSettings>

#include "QGCSettingsWidget.h"
#include "MainWindow.h"
#include "ui_QGCSettingsWidget.h"

#include "LinkManager.h"
#include "MAVLinkProtocol.h"
#include "MAVLinkSettingsWidget.h"
#include "GAudioOutput.h"

//, Qt::WindowFlags flags

QGCSettingsWidget::QGCSettingsWidget(QWidget *parent, Qt::WindowFlags flags) :
    QDialog(parent, flags),
    ui(new Ui::QGCSettingsWidget)
{
    m_init = false;
    ui->setupUi(this);

    // Add all protocols
    QList<ProtocolInterface*> protocols = LinkManager::instance()->getProtocols();
    foreach (ProtocolInterface* protocol, protocols) {
        MAVLinkProtocol* mavlink = dynamic_cast<MAVLinkProtocol*>(protocol);
        if (mavlink) {
            MAVLinkSettingsWidget* msettings = new MAVLinkSettingsWidget(mavlink, this);
            ui->tabWidget->addTab(msettings, "MAVLink");
        }
    }

    this->window()->setWindowTitle(tr("APM Planner 2 Settings"));

}
void QGCSettingsWidget::showEvent(QShowEvent *evt)
{
    if (!m_init)
    {
        m_init = true;
        // Audio preferences
        ui->audioMuteCheckBox->setChecked(GAudioOutput::instance()->isMuted());
        connect(ui->audioMuteCheckBox, SIGNAL(toggled(bool)), GAudioOutput::instance(), SLOT(mute(bool)));
        connect(GAudioOutput::instance(), SIGNAL(mutedChanged(bool)), ui->audioMuteCheckBox, SLOT(setChecked(bool)));

        // Reconnect
        ui->reconnectCheckBox->setChecked(MainWindow::instance()->autoReconnectEnabled());
        connect(ui->reconnectCheckBox, SIGNAL(clicked(bool)), MainWindow::instance(), SLOT(enableAutoReconnect(bool)));

        // Low power mode
        ui->lowPowerCheckBox->setChecked(MainWindow::instance()->lowPowerModeEnabled());
        connect(ui->lowPowerCheckBox, SIGNAL(clicked(bool)), MainWindow::instance(), SLOT(enableLowPowerMode(bool)));

        //Dock widget title bars
        ui->titleBarCheckBox->setChecked(MainWindow::instance()->dockWidgetTitleBarsEnabled());
        connect(ui->titleBarCheckBox,SIGNAL(clicked(bool)),MainWindow::instance(),SLOT(enableDockWidgetTitleBars(bool)));

        ui->logDirEdit->setText(QGC::logDirectory());

        ui->appDataDirEdit->setText((QGC::appDataDirectory()));
        ui->paramDirEdit->setText(QGC::parameterDirectory());
        ui->mavlinkLogDirEdit->setText((QGC::MAVLinkLogDirectory()));

        connect(ui->logDirSetButton, SIGNAL(clicked()), this, SLOT(setLogDir()));
        connect(ui->appDirSetButton, SIGNAL(clicked()), this, SLOT(setAppDataDir()));
        connect(ui->paramDirSetButton, SIGNAL(clicked()), this, SLOT(setParamDir()));
        connect(ui->mavlinkDirSetButton, SIGNAL(clicked()), this, SLOT(setMAVLinkLogDir()));

        // Style
        MainWindow::QGC_MAINWINDOW_STYLE style = (MainWindow::QGC_MAINWINDOW_STYLE)MainWindow::instance()->getStyle();
        switch (style) {
        case MainWindow::QGC_MAINWINDOW_STYLE_NATIVE:
            ui->nativeStyle->setChecked(true);
            break;
        case MainWindow::QGC_MAINWINDOW_STYLE_INDOOR:
            ui->indoorStyle->setChecked(true);
            break;
        case MainWindow::QGC_MAINWINDOW_STYLE_OUTDOOR:
            ui->outdoorStyle->setChecked(true);
            break;
        }
        connect(ui->nativeStyle, SIGNAL(clicked()), MainWindow::instance(), SLOT(loadNativeStyle()));
        connect(ui->indoorStyle, SIGNAL(clicked()), MainWindow::instance(), SLOT(loadIndoorStyle()));
        connect(ui->outdoorStyle, SIGNAL(clicked()), MainWindow::instance(), SLOT(loadOutdoorStyle()));

        // Close / destroy
        //connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(deleteLater()));

        // Set layout options
//        ui->generoalPaneGridLayout->setAlignment(Qt::AlignTop);
    }
}

QGCSettingsWidget::~QGCSettingsWidget()
{
    delete ui;
}

void QGCSettingsWidget::setLogDir()
{
    QFileDialog dlg(this);
    dlg.setFileMode(QFileDialog::Directory);
    dlg.setDirectory(QGC::logDirectory());

    if(dlg.exec() == QDialog::Accepted) {
        QDir dir = dlg.directory();
        QString name = dir.absolutePath();
        QGC::setLogDirectory(name);
        ui->logDirEdit->setText(name);
    }
}

void QGCSettingsWidget::setMAVLinkLogDir()
{
    QFileDialog dlg(this);
    dlg.setFileMode(QFileDialog::Directory);
    dlg.setDirectory(QGC::MAVLinkLogDirectory());

    if(dlg.exec() == QDialog::Accepted) {
        QDir dir = dlg.directory();
        QString name = dir.absolutePath();
        QGC::setMAVLinkLogDirectory(name);
        ui->mavlinkLogDirEdit->setText(name);
    }
}

void QGCSettingsWidget::setParamDir()
{
    QFileDialog dlg(this);
    dlg.setFileMode(QFileDialog::Directory);
    dlg.setDirectory(QGC::parameterDirectory());

    if(dlg.exec() == QDialog::Accepted) {
        QDir dir = dlg.directory();
        QString name = dir.absolutePath();
        QGC::setParameterDirectory(name);
        ui->paramDirEdit->setText(name);
    }
}

void QGCSettingsWidget::setAppDataDir()
{
    QFileDialog dlg(this);
    dlg.setFileMode(QFileDialog::Directory);
    dlg.setDirectory(QGC::appDataDirectory());

    if(dlg.exec() ==  QDialog::Accepted) {
        QDir dir = dlg.directory();
        QString name = dir.absolutePath();
        QGC::setAppDataDirectory(name);
        ui->appDataDirEdit->setText(name);
    }
}
<commit_msg>Clean up some old commented out code<commit_after>#include <QSettings>

#include "QGCSettingsWidget.h"
#include "MainWindow.h"
#include "ui_QGCSettingsWidget.h"

#include "LinkManager.h"
#include "MAVLinkProtocol.h"
#include "MAVLinkSettingsWidget.h"
#include "GAudioOutput.h"

//, Qt::WindowFlags flags

QGCSettingsWidget::QGCSettingsWidget(QWidget *parent, Qt::WindowFlags flags) :
    QDialog(parent, flags),
    ui(new Ui::QGCSettingsWidget)
{
    m_init = false;
    ui->setupUi(this);

    // Add all protocols
    QList<ProtocolInterface*> protocols = LinkManager::instance()->getProtocols();
    foreach (ProtocolInterface* protocol, protocols) {
        MAVLinkProtocol* mavlink = dynamic_cast<MAVLinkProtocol*>(protocol);
        if (mavlink) {
            MAVLinkSettingsWidget* msettings = new MAVLinkSettingsWidget(mavlink, this);
            ui->tabWidget->addTab(msettings, "MAVLink");
        }
    }

    this->window()->setWindowTitle(tr("APM Planner 2 Settings"));

}
void QGCSettingsWidget::showEvent(QShowEvent *evt)
{
    if (!m_init)
    {
        m_init = true;
        // Audio preferences
        ui->audioMuteCheckBox->setChecked(GAudioOutput::instance()->isMuted());
        connect(ui->audioMuteCheckBox, SIGNAL(toggled(bool)), GAudioOutput::instance(), SLOT(mute(bool)));
        connect(GAudioOutput::instance(), SIGNAL(mutedChanged(bool)), ui->audioMuteCheckBox, SLOT(setChecked(bool)));

        // Reconnect
        ui->reconnectCheckBox->setChecked(MainWindow::instance()->autoReconnectEnabled());
        connect(ui->reconnectCheckBox, SIGNAL(clicked(bool)), MainWindow::instance(), SLOT(enableAutoReconnect(bool)));

        // Low power mode
        ui->lowPowerCheckBox->setChecked(MainWindow::instance()->lowPowerModeEnabled());
        connect(ui->lowPowerCheckBox, SIGNAL(clicked(bool)), MainWindow::instance(), SLOT(enableLowPowerMode(bool)));

        //Dock widget title bars
        ui->titleBarCheckBox->setChecked(MainWindow::instance()->dockWidgetTitleBarsEnabled());
        connect(ui->titleBarCheckBox,SIGNAL(clicked(bool)),MainWindow::instance(),SLOT(enableDockWidgetTitleBars(bool)));

        ui->logDirEdit->setText(QGC::logDirectory());

        ui->appDataDirEdit->setText((QGC::appDataDirectory()));
        ui->paramDirEdit->setText(QGC::parameterDirectory());
        ui->mavlinkLogDirEdit->setText((QGC::MAVLinkLogDirectory()));

        connect(ui->logDirSetButton, SIGNAL(clicked()), this, SLOT(setLogDir()));
        connect(ui->appDirSetButton, SIGNAL(clicked()), this, SLOT(setAppDataDir()));
        connect(ui->paramDirSetButton, SIGNAL(clicked()), this, SLOT(setParamDir()));
        connect(ui->mavlinkDirSetButton, SIGNAL(clicked()), this, SLOT(setMAVLinkLogDir()));

        // Style
        MainWindow::QGC_MAINWINDOW_STYLE style = (MainWindow::QGC_MAINWINDOW_STYLE)MainWindow::instance()->getStyle();
        switch (style) {
        case MainWindow::QGC_MAINWINDOW_STYLE_NATIVE:
            ui->nativeStyle->setChecked(true);
            break;
        case MainWindow::QGC_MAINWINDOW_STYLE_INDOOR:
            ui->indoorStyle->setChecked(true);
            break;
        case MainWindow::QGC_MAINWINDOW_STYLE_OUTDOOR:
            ui->outdoorStyle->setChecked(true);
            break;
        }
        connect(ui->nativeStyle, SIGNAL(clicked()), MainWindow::instance(), SLOT(loadNativeStyle()));
        connect(ui->indoorStyle, SIGNAL(clicked()), MainWindow::instance(), SLOT(loadIndoorStyle()));
        connect(ui->outdoorStyle, SIGNAL(clicked()), MainWindow::instance(), SLOT(loadOutdoorStyle()));
    }
}

QGCSettingsWidget::~QGCSettingsWidget()
{
    delete ui;
}

void QGCSettingsWidget::setLogDir()
{
    QFileDialog dlg(this);
    dlg.setFileMode(QFileDialog::Directory);
    dlg.setDirectory(QGC::logDirectory());

    if(dlg.exec() == QDialog::Accepted) {
        QDir dir = dlg.directory();
        QString name = dir.absolutePath();
        QGC::setLogDirectory(name);
        ui->logDirEdit->setText(name);
    }
}

void QGCSettingsWidget::setMAVLinkLogDir()
{
    QFileDialog dlg(this);
    dlg.setFileMode(QFileDialog::Directory);
    dlg.setDirectory(QGC::MAVLinkLogDirectory());

    if(dlg.exec() == QDialog::Accepted) {
        QDir dir = dlg.directory();
        QString name = dir.absolutePath();
        QGC::setMAVLinkLogDirectory(name);
        ui->mavlinkLogDirEdit->setText(name);
    }
}

void QGCSettingsWidget::setParamDir()
{
    QFileDialog dlg(this);
    dlg.setFileMode(QFileDialog::Directory);
    dlg.setDirectory(QGC::parameterDirectory());

    if(dlg.exec() == QDialog::Accepted) {
        QDir dir = dlg.directory();
        QString name = dir.absolutePath();
        QGC::setParameterDirectory(name);
        ui->paramDirEdit->setText(name);
    }
}

void QGCSettingsWidget::setAppDataDir()
{
    QFileDialog dlg(this);
    dlg.setFileMode(QFileDialog::Directory);
    dlg.setDirectory(QGC::appDataDirectory());

    if(dlg.exec() ==  QDialog::Accepted) {
        QDir dir = dlg.directory();
        QString name = dir.absolutePath();
        QGC::setAppDataDirectory(name);
        ui->appDataDirEdit->setText(name);
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 Luke San Antonio
 * All rights reserved.
 */
#include "element_iterator.h"
namespace game { namespace ui
{
  D_F_Elem_Iter::D_F_Elem_Iter(Shared_Element e) noexcept
  {
    path_.emplace_back(e);
  }
  D_F_Elem_Iter::D_F_Elem_Iter() noexcept
  {
    path_.emplace_back(nullptr);
  }

  D_F_Elem_Iter::D_F_Elem_Iter(D_F_Elem_Iter const& rhs) noexcept
    : path_(rhs.path_) {}
  D_F_Elem_Iter::D_F_Elem_Iter(D_F_Elem_Iter&& rhs) noexcept
    : path_(std::move(rhs.path_)) {}

  D_F_Elem_Iter& D_F_Elem_Iter::operator=(D_F_Elem_Iter const& rhs) noexcept
  {
    path_ = rhs.path_;

    return *this;
  }
  D_F_Elem_Iter& D_F_Elem_Iter::operator=(D_F_Elem_Iter&& rhs) noexcept
  {
    path_ = std::move(rhs.path_);

    return *this;
  }

  D_F_Elem_Iter::reference D_F_Elem_Iter::operator*() const noexcept
  {
    // Get active element pointer and just dereference it.
    return *operator->();
  }
  D_F_Elem_Iter::pointer D_F_Elem_Iter::operator->() const noexcept
  {
    // Return a nullptr in the end-iterator case.
    if(is_end()) return nullptr;

    return path_.back().elem.get();
  }

  D_F_Elem_Iter& D_F_Elem_Iter::operator++() noexcept
  {
    // Get our path.
    auto& cur = path_.back();

    // If we still have children for this element that need exploring.
    if(cur.cur_child + 1 < cur.elem->child_count())
    {
      // Mark the first child as being explored.
      ++cur.cur_child;
      // Add it to our path and note that it hasn't been explored.
      path_.emplace_back(cur.elem->child_at(cur.cur_child), -1);
    }

    // If we are done exploring our current element's children, we can go up
    else if(cur.cur_child + 1 == cur.elem->child_count())
    {
      // Get rid of this one.
      path_.erase(path_.end() - 1);

      // Increment ourselves. This will result in us going to the current
      // elements sibling, or if not that the one above its sibling etc.
      operator++();
    }

    return *this;
  }
  D_F_Elem_Iter D_F_Elem_Iter::operator++(int) noexcept
  {
    auto it = *this;
    ++(*this);
    return it;
  }

  bool D_F_Elem_Iter::operator==(D_F_Elem_Iter const& rhs) const noexcept
  {
    return operator->() == rhs.operator->();
  }
  bool operator!=(D_F_Elem_Iter const& lhs, D_F_Elem_Iter const& rhs) noexcept
  {
    return !(lhs == rhs);
  }
} }
<commit_msg>Fixed up the operator++ to work even if we are a end iter/nullptr.<commit_after>/*
 * Copyright (C) 2015 Luke San Antonio
 * All rights reserved.
 */
#include "element_iterator.h"
namespace game { namespace ui
{
  D_F_Elem_Iter::D_F_Elem_Iter(Shared_Element e) noexcept
  {
    path_.emplace_back(e);
  }
  D_F_Elem_Iter::D_F_Elem_Iter() noexcept
  {
    path_.emplace_back(nullptr);
  }

  D_F_Elem_Iter::D_F_Elem_Iter(D_F_Elem_Iter const& rhs) noexcept
    : path_(rhs.path_) {}
  D_F_Elem_Iter::D_F_Elem_Iter(D_F_Elem_Iter&& rhs) noexcept
    : path_(std::move(rhs.path_)) {}

  D_F_Elem_Iter& D_F_Elem_Iter::operator=(D_F_Elem_Iter const& rhs) noexcept
  {
    path_ = rhs.path_;

    return *this;
  }
  D_F_Elem_Iter& D_F_Elem_Iter::operator=(D_F_Elem_Iter&& rhs) noexcept
  {
    path_ = std::move(rhs.path_);

    return *this;
  }

  D_F_Elem_Iter::reference D_F_Elem_Iter::operator*() const noexcept
  {
    // Get active element pointer and just dereference it.
    return *operator->();
  }
  D_F_Elem_Iter::pointer D_F_Elem_Iter::operator->() const noexcept
  {
    // Return a nullptr in the end-iterator case.
    if(is_end()) return nullptr;

    return path_.back().elem.get();
  }

  D_F_Elem_Iter& D_F_Elem_Iter::operator++() noexcept
  {
    // Get our path.
    auto& cur = path_.back();

    // If we are currently dealing with a nullptr bail out, the logic of this
    // function should prevent this in general unless we are an end iterator
    // or we become an end iterator.
    if(cur.elem == nullptr) return *this;

    // If we still have children for this element that need exploring.
    if(cur.cur_child + 1 < cur.elem->child_count())
    {
      // Mark the first child as being explored.
      ++cur.cur_child;
      // Add it to our path and note that it hasn't been explored.
      path_.emplace_back(cur.elem->child_at(cur.cur_child), -1);
    }

    // If we are done exploring our current element's children, we can go up
    else if(cur.cur_child + 1 == cur.elem->child_count())
    {
      // If we are the root node, we can't go up, just mark ourselves as done
      // by becoming an end iterator.
      if(path_.size() == 1)
      {
        path_.back().elem = nullptr;
        return *this;
      }

      // Get rid of this one.
      path_.erase(path_.end() - 1);

      // Increment ourselves. This will result in us going to the current
      // elements sibling, or if not that the one above its sibling etc.
      operator++();
    }

    return *this;
  }
  D_F_Elem_Iter D_F_Elem_Iter::operator++(int) noexcept
  {
    auto it = *this;
    ++(*this);
    return it;
  }

  bool D_F_Elem_Iter::operator==(D_F_Elem_Iter const& rhs) const noexcept
  {
    return operator->() == rhs.operator->();
  }
  bool operator!=(D_F_Elem_Iter const& lhs, D_F_Elem_Iter const& rhs) noexcept
  {
    return !(lhs == rhs);
  }
} }
<|endoftext|>