Ejemplo n.º 1
0
void KonvergoWindow::handleHostCommand(QString hostCommand)
{
  QLOG_DEBUG() << "Got command:" << hostCommand;
  QString arguments = "";
  int arguments_start = hostCommand.indexOf(":");
  if (arguments_start > 0)
  {
    arguments = hostCommand.mid(arguments_start + 1);
    hostCommand = hostCommand.mid(0, arguments_start);
  }
  if (hostCommand == "fullscreen")
  {
    SettingsComponent::Get().setValue(SETTINGS_SECTION_MAIN, "fullscreen", !SettingsComponent::Get().value(SETTINGS_SECTION_MAIN, "fullscreen").toBool());
  }
  else if (hostCommand == "close")
  {
    close();
  }
  else if (hostCommand == "player")
  {
    PlayerComponent::Get().userCommand(arguments);
  }
  else if (hostCommand == "toggleDebug")
  {
    if (property("showDebugLayer").toBool())
    {
      m_infoTimer->stop();
      setProperty("showDebugLayer", false);
    }
    else
    {
      m_infoTimer->start();
      updateDebugInfo();
      setProperty("showDebugLayer", true);
    }
  }
  else if (hostCommand == "recreateRpiUi")
  {
    DisplayManager* display_manager = DisplayComponent::Get().getDisplayManager();
    if (display_manager)
      display_manager->resetRendering();
  }
  else if (hostCommand == "reload")
  {
    emit reloadWebClient();
  }
  else if (hostCommand == "crash!")
  {
    *(volatile int*)0=0;
  }
  else if (hostCommand == "poweroff")
  {
    PowerComponent::Get().PowerOff();
  }
  else if (hostCommand == "suspend")
  {
    PowerComponent::Get().Suspend();
  }
  else if (hostCommand == "reboot")
  {
    PowerComponent::Get().Reboot();
  }
  else
  {
    QLOG_WARN() << "unknown host command" << hostCommand;
  }
}
Ejemplo n.º 2
0
void CSSMutableStyleDeclaration::setProperty(int propertyID, const String& value, bool important, ExceptionCode& ec)
{
    setProperty(propertyID, value, important, true, ec);
}
Ejemplo n.º 3
0
void
HrPwWindow::configChanged(qint32)
{
    setProperty("color", GColor(CPLOTBACKGROUND));
}
Ejemplo n.º 4
0
bool PTIDSensors::start(IOService * provider)
{
	if (!super::start(provider))
        return false;
    
	acpiDevice = (IOACPIPlatformDevice *)provider;
	
	if (!acpiDevice) {
        HWSensorsFatalLog("ACPI device not ready");
        return false;
    }
    
    // On some computers (eg. RehabMan's ProBook 4530s), the system will hang on startup
    // if kernel cache is used, because of the early call to updateTemperatures and/or
    // updateTachometers.  At least that is the case with an SSD and a valid pre-linked
    // kernel, along with kernel cache enabled.  This 1000ms sleep seems to fix the problem,
    // enabling a clean boot with PTIDSensors enabled.
    IOSleep(1000);
    
    // Update timers
    temperaturesLastUpdated = ptimer_read() - NSEC_PER_SEC;
    tachometersLastUpdated = temperaturesLastUpdated;
    
    acpiDevice->evaluateInteger("IVER", &version);
    
    if (version == 0) {
        OSString *name = OSDynamicCast(OSString, provider->getProperty("name"));
        
        if (name && name->isEqualTo("INT3F0D"))
            version = 0x30000;
        else
            return false;
    }
    
    setProperty("version", version, 64);
    
    // Parse sensors
    switch (version) {
        case 0x30000: {
            OSObject *object = NULL;
            
            // Temperatures
            if(kIOReturnSuccess == acpiDevice->evaluateObject("TSDL", &object) && object) {
                if (OSArray *description = OSDynamicCast(OSArray, object)) {
                    HWSensorsDebugLog("Parsing temperatures...");
                    
                    int count = description->getCount();
                    for (int i = 1; i < count; i += 2) {
                        parseTemperatureName(OSDynamicCast(OSString, description->getObject(i)), i/2);
                    }
                }
            }
            else HWSensorsErrorLog("failed to evaluate TSDL table");
            
            // Tachometers
            if(kIOReturnSuccess == acpiDevice->evaluateObject("OSDL", &object) && object) {
                if (OSArray *description = OSDynamicCast(OSArray, object)) {
                    HWSensorsDebugLog("Parsing tachometers...");
                    
                    int count = description->getCount();
                    for (int i = 2; i < count; i += 3) {
                        parseTachometerName(OSDynamicCast(OSString, description->getObject(i)), OSDynamicCast(OSString, description->getObject(i-1)), i/3);
                    }
                }
            }
            else HWSensorsErrorLog("failed to evaluate OSDL table");
            break;
        }
            
        case 0x20001: {
            OSObject *object = NULL;
            
            // Temperatures
            if (kIOReturnSuccess == acpiDevice->evaluateObject("TMPV", &object) && object) {
                if (OSArray *description = OSDynamicCast(OSArray, object)) {
                    HWSensorsDebugLog("Parsing temperatures...");
                    
                    int count = description->getCount();
                    for (int i = 1; i < count; i += 3) {
                        parseTemperatureName(OSDynamicCast(OSString, description->getObject(i)), i+1);
                    }
                }
            }
            else HWSensorsErrorLog("failed to evaluate TMPV table");
            
            // Tachometers
            if (kIOReturnSuccess == acpiDevice->evaluateObject("OSDV", &object) && object) {
                if (OSArray *description = OSDynamicCast(OSArray, object)) {
                    HWSensorsDebugLog("Parsing tachometers...");
                    
                    int count = description->getCount();
                    for (int i = 2; i < count; i += 4) {
                        parseTachometerName(OSDynamicCast(OSString, description->getObject(i)), OSDynamicCast(OSString, description->getObject(i-1)), i+1);
                    }
                }
            }
            else HWSensorsErrorLog("failed to evaluate OSDV table");
            break;
        }
            
        default:
            HWSensorsFatalLog("usupported interface version: 0x%x", (UInt32)version);
            return false;
    }
    
    registerService();
    
    HWSensorsInfoLog("started");
    
	return true;
}
Ejemplo n.º 5
0
    /**
     * Convert the TOF workspace into a monitor workspace. Crops to the monitorIndex and applying flat background correction as part of the process.
     * @param toConvert : TOF wavlength to convert.
     * @param monitorIndex : Monitor index to crop to
     * @param backgroundMinMax : Min and Max Lambda range for Flat background correction.
     * @return The cropped and corrected monitor workspace.
     */
    MatrixWorkspace_sptr ReflectometryWorkflowBase::toLamMonitor(const MatrixWorkspace_sptr& toConvert,
        const int monitorIndex, const MinMax& backgroundMinMax)
    {
      // Convert Units.
      auto convertUnitsAlg = this->createChildAlgorithm("ConvertUnits");
      convertUnitsAlg->initialize();
      convertUnitsAlg->setProperty("InputWorkspace", toConvert);
      convertUnitsAlg->setProperty("Target", "Wavelength");
      convertUnitsAlg->setProperty("AlignBins", true);
      convertUnitsAlg->execute();

      // Crop the to the monitor index.
      MatrixWorkspace_sptr monitorWS = convertUnitsAlg->getProperty("OutputWorkspace");
      auto cropWorkspaceAlg = this->createChildAlgorithm("CropWorkspace");
      cropWorkspaceAlg->initialize();
      cropWorkspaceAlg->setProperty("InputWorkspace", monitorWS);
      cropWorkspaceAlg->setProperty("StartWorkspaceIndex", monitorIndex);
      cropWorkspaceAlg->setProperty("EndWorkspaceIndex", monitorIndex);
      cropWorkspaceAlg->execute();
      monitorWS = cropWorkspaceAlg->getProperty("OutputWorkspace");

      // Flat background correction
      auto correctMonitorsAlg = this->createChildAlgorithm("CalculateFlatBackground");
      correctMonitorsAlg->initialize();
      correctMonitorsAlg->setProperty("InputWorkspace", monitorWS);
      correctMonitorsAlg->setProperty("WorkspaceIndexList",
          boost::assign::list_of(0).convert_to_container<std::vector<int> >());
      correctMonitorsAlg->setProperty("StartX", backgroundMinMax.get<0>());
      correctMonitorsAlg->setProperty("EndX", backgroundMinMax.get<1>());
      correctMonitorsAlg->setProperty("SkipMonitors",false);
      correctMonitorsAlg->execute();
      monitorWS = correctMonitorsAlg->getProperty("OutputWorkspace");

      return monitorWS;
    }
Ejemplo n.º 6
0
  /** Executes the algorithm
  *
  *  @throw runtime_error Thrown if algorithm cannot execute
  */
  void Fit::exec()
  {
    // this is to make it work with AlgorithmProxy
    if (!m_domainCreator)
    {
      setFunction();
      addWorkspaces();
    }

    std::string ties = getPropertyValue("Ties");
    if (!ties.empty())
    {
      m_function->addTies(ties);
    }
    std::string contstraints = getPropertyValue("Constraints");
    if (!contstraints.empty())
    {
      m_function->addConstraints(contstraints);
    }
    
    // prepare the function for a fit
    m_function->setUpForFit();

    API::FunctionDomain_sptr domain;
    API::FunctionValues_sptr values; // TODO: should values be part of domain?
    m_domainCreator->ignoreInvalidData(getProperty("IgnoreInvalidData"));
    m_domainCreator->createDomain(domain,values);

    // do something with the function which may depend on workspace
    m_domainCreator->initFunction(m_function);

    // get the minimizer
    std::string minimizerName = getPropertyValue("Minimizer");
    API::IFuncMinimizer_sptr minimizer = API::FuncMinimizerFactory::Instance().createMinimizer(minimizerName);

    // Try to retrieve optional properties
    const int maxIterations = getProperty("MaxIterations");

    // get the cost function which must be a CostFuncFitting
    boost::shared_ptr<CostFuncFitting> costFunc = boost::dynamic_pointer_cast<CostFuncFitting>(
      API::CostFunctionFactory::Instance().create(getPropertyValue("CostFunction"))
      );

    costFunc->setFittingFunction(m_function,domain,values);
    minimizer->initialize(costFunc);

    const int64_t nsteps = maxIterations*m_function->estimateNoProgressCalls();
    API::Progress prog(this,0.0,1.0,nsteps);
    m_function->setProgressReporter(&prog);

    // do the fitting until success or iteration limit is reached
    size_t iter = 0;
    bool success = false;
    std::string errorString;
    g_log.debug("Starting minimizer iteration\n");
    while (static_cast<int>(iter) < maxIterations)
    {
      iter++;
      g_log.debug() << "Starting iteration " << iter << "\n";
      m_function->iterationStarting();
      if ( !minimizer->iterate() )
      {
        errorString = minimizer->getError();
        g_log.debug() << "Iteration stopped. Minimizer status string=" << errorString << "\n";

        success = errorString.empty() || errorString == "success";
        if (success)
        {
          errorString = "success";
        }
        break;
      }
      prog.report();
      m_function->iterationFinished();
      if(g_log.is(Kernel::Logger::Priority::PRIO_INFORMATION))
      {
        g_log.debug() << "Iteration " << iter << ", cost function = " << minimizer->costFunctionVal() << "\n";
      }
    }
    g_log.debug() << "Number of minimizer iterations=" << iter << "\n";

    if (static_cast<int>(iter) >= maxIterations)
    {
      if ( !errorString.empty() )
      {
        errorString += '\n';
      }
      errorString += "Failed to converge after " + boost::lexical_cast<std::string>(maxIterations) + " iterations.";
    }

    // return the status flag
    setPropertyValue("OutputStatus",errorString);

    // degrees of freedom
    size_t dof = domain->size() - costFunc->nParams();
    if (dof == 0) dof = 1;
    double rawcostfuncval = minimizer->costFunctionVal();
    double finalCostFuncVal = rawcostfuncval / double(dof);

    setProperty("OutputChi2overDoF",finalCostFuncVal);

    // fit ended, creating output

    // get the workspace 
    API::Workspace_const_sptr ws = getProperty("InputWorkspace");

    bool doCreateOutput = getProperty("CreateOutput");
    std::string baseName = getPropertyValue("Output");
    if ( !baseName.empty() )
    {
      doCreateOutput = true;
    }
    bool doCalcErrors = getProperty("CalcErrors");
    if ( doCreateOutput )
    {
      doCalcErrors = true;
    }
    if ( costFunc->nParams() == 0 )
    {
      doCalcErrors = false;
    }

    GSLMatrix covar;
    if ( doCalcErrors )
    {
      // Calculate the covariance matrix and the errors.
      costFunc->calCovarianceMatrix(covar);
      costFunc->calFittingErrors( covar, rawcostfuncval );
    }

    if (doCreateOutput)
    {
      if (baseName.empty())
      {
        baseName = ws->name();
        if (baseName.empty())
        {
          baseName = "Output";
        }
      }
      baseName += "_";

        declareProperty(
          new API::WorkspaceProperty<API::ITableWorkspace>("OutputNormalisedCovarianceMatrix","",Kernel::Direction::Output),
          "The name of the TableWorkspace in which to store the final covariance matrix" );
        setPropertyValue("OutputNormalisedCovarianceMatrix",baseName+"NormalisedCovarianceMatrix");

        Mantid::API::ITableWorkspace_sptr covariance = Mantid::API::WorkspaceFactory::Instance().createTable("TableWorkspace");
        covariance->addColumn("str","Name");
        // set plot type to Label = 6
        covariance->getColumn(covariance->columnCount()-1)->setPlotType(6);
        //std::vector<std::string> paramThatAreFitted; // used for populating 1st "name" column
        for(size_t i=0; i < m_function->nParams(); i++)
        {
          if (m_function->isActive(i)) 
          {
            covariance->addColumn("double",m_function->parameterName(i));
            //paramThatAreFitted.push_back(m_function->parameterName(i));
          }
        }

        size_t np = m_function->nParams();
        size_t ia = 0;
        for(size_t i = 0; i < np; i++)
        {
          if (m_function->isFixed(i)) continue;
          Mantid::API::TableRow row = covariance->appendRow();
          row << m_function->parameterName(i);
          size_t ja = 0;
          for(size_t j = 0; j < np; j++)
          {
            if (m_function->isFixed(j)) continue;
            if (j == i)
              row << 100.0;
            else
            {
              row << 100.0*covar.get(ia,ja)/sqrt(covar.get(ia,ia)*covar.get(ja,ja));
            }
            ++ja;
          }
          ++ia;
        }

        setProperty("OutputNormalisedCovarianceMatrix",covariance);

      // create output parameter table workspace to store final fit parameters 
      // including error estimates if derivative of fitting function defined

      declareProperty(
        new API::WorkspaceProperty<API::ITableWorkspace>("OutputParameters","",Kernel::Direction::Output),
        "The name of the TableWorkspace in which to store the final fit parameters" );

      setPropertyValue("OutputParameters",baseName+"Parameters");

      Mantid::API::ITableWorkspace_sptr result = Mantid::API::WorkspaceFactory::Instance().createTable("TableWorkspace");
      result->addColumn("str","Name");
      // set plot type to Label = 6
      result->getColumn(result->columnCount()-1)->setPlotType(6);
      result->addColumn("double","Value");
      result->addColumn("double","Error");
      // yErr = 5
      result->getColumn(result->columnCount()-1)->setPlotType(5);

      for(size_t i=0;i<m_function->nParams();i++)
      {
        Mantid::API::TableRow row = result->appendRow();
        row << m_function->parameterName(i) 
            << m_function->getParameter(i)
            << m_function->getError(i);
      }
      // Add chi-squared value at the end of parameter table
      Mantid::API::TableRow row = result->appendRow();
#if 1
      std::string costfuncname = getPropertyValue("CostFunction");
      if (costfuncname == "Rwp")
        row << "Cost function value" << rawcostfuncval;
      else
        row << "Cost function value" << finalCostFuncVal;
      setProperty("OutputParameters",result);
#else
      row << "Cost function value" << finalCostFuncVal;
      Mantid::API::TableRow row2 = result->appendRow();
      std::string name(getPropertyValue("CostFunction"));
      name += " value";
      row2 << name << rawcostfuncval;
#endif

      setProperty("OutputParameters",result);

      bool outputParametersOnly = getProperty("OutputParametersOnly");

      if ( !outputParametersOnly )
      {
        const bool unrollComposites = getProperty("OutputCompositeMembers");
        bool convolveMembers = existsProperty("ConvolveMembers");
        if ( convolveMembers )
        {
            convolveMembers = getProperty("ConvolveMembers");
        }
        m_domainCreator->separateCompositeMembersInOutput(unrollComposites,convolveMembers);
        m_domainCreator->createOutputWorkspace(baseName,m_function,domain,values);
      }

    }

  }
Ejemplo n.º 7
0
void ModeratorTzero::execEvent(const std::string &emode) {
  g_log.information("Processing event workspace");

  const MatrixWorkspace_const_sptr matrixInputWS =
      getProperty("InputWorkspace");

  // generate the output workspace pointer
  API::MatrixWorkspace_sptr matrixOutputWS = getProperty("OutputWorkspace");
  if (matrixOutputWS != matrixInputWS) {
    matrixOutputWS = matrixInputWS->clone();
    setProperty("OutputWorkspace", matrixOutputWS);
  }
  auto outputWS = boost::dynamic_pointer_cast<EventWorkspace>(matrixOutputWS);

  // calculate tof shift once for all neutrons if emode==Direct
  double t0_direct(-1);
  if (emode == "Direct") {
    Kernel::Property *eiprop = outputWS->run().getProperty("Ei");
    double Ei = boost::lexical_cast<double>(eiprop->value());
    mu::Parser parser;
    parser.DefineVar("incidentEnergy", &Ei); // associate E1 to this parser
    parser.SetExpr(m_formula);
    t0_direct = parser.Eval();
  }

  const auto &spectrumInfo = outputWS->spectrumInfo();
  const double Lss = spectrumInfo.l1();

  // Loop over the spectra
  const size_t numHists = static_cast<size_t>(outputWS->getNumberHistograms());
  Progress prog(this, 0.0, 1.0, numHists); // report progress of algorithm
  PARALLEL_FOR_IF(Kernel::threadSafe(*outputWS))
  for (int i = 0; i < static_cast<int>(numHists); ++i) {
    PARALLEL_START_INTERUPT_REGION
    size_t wsIndex = static_cast<size_t>(i);
    EventList &evlist = outputWS->getSpectrum(wsIndex);
    if (evlist.getNumberEvents() > 0) // don't bother with empty lists
    {
      double L1(Lss); // distance from source to sample
      double L2(-1);  // distance from sample to detector

      if (spectrumInfo.hasDetectors(i)) {
        if (spectrumInfo.isMonitor(i)) {
          // redefine the sample as the monitor
          L1 = Lss + spectrumInfo.l2(i); // L2 in SpectrumInfo defined negative
          L2 = 0;
        } else {
          L2 = spectrumInfo.l2(i);
        }
      } else {
        g_log.error() << "Unable to calculate distances to/from detector" << i
                      << '\n';
      }

      if (L2 >= 0) {
        // One parser for each parallel processor needed (except Edirect mode)
        double E1;
        mu::Parser parser;
        parser.DefineVar("incidentEnergy", &E1); // associate E1 to this parser
        parser.SetExpr(m_formula);

        // fast neutrons are shifted by min_t0_next, irrespective of tof
        double v1_max = L1 / m_t1min;
        E1 = m_convfactor * v1_max * v1_max;
        double min_t0_next = parser.Eval();

        if (emode == "Indirect") {
          double t2(-1.0); // time from sample to detector. (-1) signals error
          if (spectrumInfo.isMonitor(i)) {
            t2 = 0.0;
          } else {
            static const double convFact =
                1.0e-6 * sqrt(2 * PhysicalConstants::meV /
                              PhysicalConstants::NeutronMass);
            std::vector<double> wsProp =
                spectrumInfo.detector(i).getNumberParameter("Efixed");
            if (!wsProp.empty()) {
              double E2 = wsProp.at(0);        //[E2]=meV
              double v2 = convFact * sqrt(E2); //[v2]=meter/microsec
              t2 = L2 / v2;
            } else {
              // t2 is kept to -1 if no Efixed is found
              g_log.debug() << "Efixed not found for detector " << i << '\n';
            }
          }
          if (t2 >= 0) // t2 < 0 when no detector info is available
          {
            // fix the histogram bins
            auto &x = evlist.mutableX();
            for (double &tof : x) {
              if (tof < m_t1min + t2)
                tof -= min_t0_next;
              else
                tof -= CalculateT0indirect(tof, L1, t2, E1, parser);
            }

            MantidVec tofs = evlist.getTofs();
            for (double &tof : tofs) {
              if (tof < m_t1min + t2)
                tof -= min_t0_next;
              else
                tof -= CalculateT0indirect(tof, L1, t2, E1, parser);
            }
            evlist.setTofs(tofs);
            evlist.setSortOrder(Mantid::DataObjects::EventSortType::UNSORTED);
          } // end of if( t2>= 0)
        }   // end of if(emode=="Indirect")
        else if (emode == "Elastic") {
          // Apply t0 correction to histogram bins
          auto &x = evlist.mutableX();
          for (double &tof : x) {
            if (tof < m_t1min * (L1 + L2) / L1)
              tof -= min_t0_next;
            else
              tof -= CalculateT0elastic(tof, L1 + L2, E1, parser);
          }

          MantidVec tofs = evlist.getTofs();
          for (double &tof : tofs) {
            // add a [-0.1,0.1] microsecond noise to avoid artifacts
            // resulting from original tof data
            if (tof < m_t1min * (L1 + L2) / L1)
              tof -= min_t0_next;
            else
              tof -= CalculateT0elastic(tof, L1 + L2, E1, parser);
          }
          evlist.setTofs(tofs);
          evlist.setSortOrder(Mantid::DataObjects::EventSortType::UNSORTED);
        } // end of else if(emode=="Elastic")
        else if (emode == "Direct") {
          // fix the histogram bins
          evlist.mutableX() -= t0_direct;

          MantidVec tofs = evlist.getTofs();
          for (double &tof : tofs) {
            tof -= t0_direct;
          }
          evlist.setTofs(tofs);
          evlist.setSortOrder(Mantid::DataObjects::EventSortType::UNSORTED);
        } // end of else if(emode=="Direct")
      }   // end of if(L2 >= 0)
    }     // end of if (evlist.getNumberEvents() > 0)
    prog.report();
    PARALLEL_END_INTERUPT_REGION
  } // end of for (int i = 0; i < static_cast<int>(numHists); ++i)
  PARALLEL_CHECK_INTERUPT_REGION
  outputWS->clearMRU(); // Clears the Most Recent Used lists */
} // end of void ModeratorTzero::execEvent()
Ejemplo n.º 8
0
	LoginPage::LoginPage(QWidget* parent)
		: QWidget(parent)
		, country_code_(new LineEditEx(this))
		, phone_(new LineEditEx(this))
		, combobox_(new CountrySearchCombobox(this))
		, remaining_seconds_(0)
		, timer_(new QTimer(this))
	{
        setStyleSheet(Utils::LoadStyle(":/main_window/login_page.qss", Utils::get_scale_coefficient(), true));
        if (objectName().isEmpty())
            setObjectName(QStringLiteral("login_page"));
        setProperty("LoginPageWidget", QVariant(true));
        QVBoxLayout* verticalLayout = new QVBoxLayout(this);
        verticalLayout->setSpacing(0);
        verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
        verticalLayout->setContentsMargins(0, 0, 0, 0);
        
        auto back_button_widget = new QWidget(this);
        auto back_button_layout = new QHBoxLayout(back_button_widget);
        Utils::ApplyStyle(back_button_widget, "background-color: transparent;");
        back_button_widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
        back_button_layout->setSpacing(0);
        back_button_layout->setContentsMargins(Utils::scale_value(14), Utils::scale_value(14), 0, 0);
        back_button_layout->setAlignment(Qt::AlignLeft);
        {
            prev_page_link_ = new BackButton(back_button_widget);
            prev_page_link_->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
            prev_page_link_->setFlat(true);
            prev_page_link_->setFocusPolicy(Qt::NoFocus);
            prev_page_link_->setCursor(Qt::PointingHandCursor);
            {
                const QString s = "QPushButton { width: 20dip; height: 20dip; border: none; background-color: transparent; border-image: url(:/resources/contr_back_100.png); margin: 10dip; } QPushButton:hover { border-image: url(:/resources/contr_back_100_hover.png); } QPushButton#back_button:pressed { border-image: url(:/resources/contr_back_100_active.png); }";
                Utils::ApplyStyle(prev_page_link_, s);
            }
            back_button_layout->addWidget(prev_page_link_);
        }
        verticalLayout->addWidget(back_button_widget);
        
        /*
        QWidget* back_button_widget = new QWidget(this);
        back_button_widget->setObjectName(QStringLiteral("back_button_widget"));
        back_button_widget->setProperty("BackButtonWidget", QVariant(true));
        QHBoxLayout* back_button_layout = new QHBoxLayout(back_button_widget);
        back_button_layout->setSpacing(0);
        back_button_layout->setObjectName(QStringLiteral("back_button_layout"));
        back_button_layout->setContentsMargins(Utils::scale_value(14), Utils::scale_value(14), 0, 0);
        prev_page_link_ = new BackButton(back_button_widget);
        prev_page_link_->setObjectName(QStringLiteral("prev_page_link"));
        prev_page_link_->setCursor(QCursor(Qt::PointingHandCursor));
        prev_page_link_->setProperty("LoginBackButton", QVariant(true));
        back_button_layout->addWidget(prev_page_link_);
        
        QSpacerItem* horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
        back_button_layout->addItem(horizontalSpacer_3);

        verticalLayout->addWidget(back_button_widget);
        */
         
        QSpacerItem* verticalSpacer = new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);
        
        verticalLayout->addItem(verticalSpacer);
        
        QWidget* main_widget = new QWidget(this);
        main_widget->setObjectName(QStringLiteral("main_widget"));
        QSizePolicy sizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding);
        sizePolicy.setHorizontalStretch(0);
        sizePolicy.setVerticalStretch(0);
        sizePolicy.setHeightForWidth(main_widget->sizePolicy().hasHeightForWidth());
        main_widget->setSizePolicy(sizePolicy);
        main_widget->setProperty("CenterControlWidgetBack", QVariant(true));
        QHBoxLayout* main_layout = new QHBoxLayout(main_widget);
        main_layout->setSpacing(0);
        main_layout->setObjectName(QStringLiteral("main_layout"));
        main_layout->setContentsMargins(0, 0, 0, 0);
        QSpacerItem* horizontalSpacer_6 = new QSpacerItem(0, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
        
        main_layout->addItem(horizontalSpacer_6);
        
        QWidget* controls_widget = new QWidget(main_widget);
        controls_widget->setObjectName(QStringLiteral("controls_widget"));
        QSizePolicy sizePolicy1(QSizePolicy::Minimum, QSizePolicy::Minimum);
        sizePolicy1.setHorizontalStretch(0);
        sizePolicy1.setVerticalStretch(0);
        sizePolicy1.setHeightForWidth(controls_widget->sizePolicy().hasHeightForWidth());
        controls_widget->setSizePolicy(sizePolicy1);
        controls_widget->setProperty("CenterContolWidget", QVariant(true));
        QVBoxLayout* controls_layout = new QVBoxLayout(controls_widget);
        controls_layout->setSpacing(0);
        controls_layout->setObjectName(QStringLiteral("controls_layout"));
        controls_layout->setContentsMargins(0, 0, 0, 0);
        PictureWidget* logo_widget = new PictureWidget(controls_widget, ":/resources/main_window/content_logo_100.png");
        logo_widget->setFixedHeight(Utils::scale_value(80));
        logo_widget->setFixedWidth(Utils::scale_value(80));
        controls_layout->addWidget(logo_widget);
        controls_layout->setAlignment(logo_widget, Qt::AlignHCenter);
        
        QLabel* welcome_label = new QLabel(controls_widget);
        welcome_label->setObjectName(QStringLiteral("welcome_label"));
        welcome_label->setAlignment(Qt::AlignCenter);
        welcome_label->setProperty("WelcomeTitle", QVariant(true));
        
        controls_layout->addWidget(welcome_label);
        
        hint_label_ = new QLabel(controls_widget);
        hint_label_->setObjectName(QStringLiteral("hint_label"));
        hint_label_->setAlignment(Qt::AlignCenter);
        hint_label_->setProperty("ActionHintLabel", QVariant(true));
        
        controls_layout->addWidget(hint_label_);
        
        QWidget * center_widget = new QWidget(controls_widget);
        center_widget->setObjectName(QStringLiteral("center_widget"));
        QSizePolicy sizePolicy2(QSizePolicy::Expanding, QSizePolicy::Preferred);
        sizePolicy2.setHorizontalStretch(0);
        sizePolicy2.setVerticalStretch(0);
        sizePolicy2.setHeightForWidth(center_widget->sizePolicy().hasHeightForWidth());
        center_widget->setSizePolicy(sizePolicy2);
        QHBoxLayout * horizontalLayout = new QHBoxLayout(center_widget);
        horizontalLayout->setSpacing(0);
        horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
        horizontalLayout->setContentsMargins(0, 0, 0, 0);
        QSpacerItem* horizontalSpacer_9 = new QSpacerItem(0, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
        
        horizontalLayout->addItem(horizontalSpacer_9);
        
        login_staked_widget_ = new QStackedWidget(center_widget);
        login_staked_widget_->setObjectName(QStringLiteral("login_staked_widget"));
        login_staked_widget_->setProperty("LoginStackedWidget", QVariant(true));
        QSizePolicy sizePolicy3(QSizePolicy::Fixed, QSizePolicy::Preferred);
        sizePolicy3.setHorizontalStretch(0);
        sizePolicy3.setVerticalStretch(0);
        sizePolicy3.setHeightForWidth(login_staked_widget_->sizePolicy().hasHeightForWidth());
        login_staked_widget_->setSizePolicy(sizePolicy3);
        QWidget* phone_login_widget = new QWidget();
        phone_login_widget->setObjectName(QStringLiteral("phone_login_widget"));
        sizePolicy3.setHeightForWidth(phone_login_widget->sizePolicy().hasHeightForWidth());
        phone_login_widget->setSizePolicy(sizePolicy3);
        QVBoxLayout* phone_login_layout = new QVBoxLayout(phone_login_widget);
        phone_login_layout->setSpacing(0);
        phone_login_layout->setObjectName(QStringLiteral("phone_login_layout"));
        phone_login_layout->setContentsMargins(0, 0, 0, 0);
        
        country_search_widget_ = new QWidget(phone_login_widget);
        country_search_widget_->setObjectName(QStringLiteral("country_search_widget"));
        country_search_widget_->setProperty("CountrySearchWidget", QVariant(true));
        QVBoxLayout* country_search_layout = new QVBoxLayout(country_search_widget_);
        country_search_layout->setSpacing(0);
        country_search_layout->setObjectName(QStringLiteral("country_search_layout"));
        country_search_layout->setContentsMargins(0, 0, 0, 0);
        
        phone_login_layout->addWidget(country_search_widget_);
        
        phone_widget_ = new QFrame(phone_login_widget);
        phone_widget_->setObjectName(QStringLiteral("phone_widget"));
        phone_widget_->setFocusPolicy(Qt::ClickFocus);
        phone_widget_->setFrameShape(QFrame::NoFrame);
        phone_widget_->setFrameShadow(QFrame::Plain);
        phone_widget_->setLineWidth(0);
        phone_widget_->setProperty("EnterPhoneWidget", QVariant(true));
        QHBoxLayout* phone_widget_layout = new QHBoxLayout(phone_widget_);
        phone_widget_layout->setSpacing(0);
        phone_widget_layout->setObjectName(QStringLiteral("phone_widget_layout"));
        phone_widget_layout->setContentsMargins(0, 0, 0, 0);
        
        phone_login_layout->addWidget(phone_widget_);
        
        QSpacerItem* verticalSpacer_3 = new QSpacerItem(20, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);
        
        phone_login_layout->addItem(verticalSpacer_3);
        
        login_staked_widget_->addWidget(phone_login_widget);
        QWidget* phone_confirm_widget = new QWidget();
        phone_confirm_widget->setObjectName(QStringLiteral("phone_confirm_widget"));
        sizePolicy3.setHeightForWidth(phone_confirm_widget->sizePolicy().hasHeightForWidth());
        phone_confirm_widget->setSizePolicy(sizePolicy3);
        QVBoxLayout* phone_confirm_layout = new QVBoxLayout(phone_confirm_widget);
        phone_confirm_layout->setSpacing(0);
        phone_confirm_layout->setObjectName(QStringLiteral("phone_confirm_layout"));
        phone_confirm_layout->setContentsMargins(0, 0, 0, 0);
        
        QWidget* entered_phone_widget = new QWidget(phone_confirm_widget);
        entered_phone_widget->setObjectName(QStringLiteral("entered_phone_widget"));
        entered_phone_widget->setProperty("EnteredPhoneWidget", QVariant(true));
        QHBoxLayout* horizontalLayout_6 = new QHBoxLayout(entered_phone_widget);
        horizontalLayout_6->setSpacing(0);
        horizontalLayout_6->setObjectName(QStringLiteral("horizontalLayout_6"));
        horizontalLayout_6->setContentsMargins(0, 0, 0, 0);
        QSpacerItem* horizontalSpacer_4 = new QSpacerItem(0, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
        
        horizontalLayout_6->addItem(horizontalSpacer_4);
        
        entered_phone_ = new QLabel(entered_phone_widget);
        entered_phone_->setObjectName(QStringLiteral("entered_phone"));
        entered_phone_->setProperty("EnteredPhoneNumber", QVariant(true));
        
        horizontalLayout_6->addWidget(entered_phone_);
        
        edit_phone_button_ = new QPushButton(entered_phone_widget);
        edit_phone_button_->setObjectName(QStringLiteral("edit_phone_button"));
        edit_phone_button_->setCursor(QCursor(Qt::PointingHandCursor));
        edit_phone_button_->setProperty("EditPhoneButton", QVariant(true));
        
        horizontalLayout_6->addWidget(edit_phone_button_);
        
        QSpacerItem* horizontalSpacer_5 = new QSpacerItem(0, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
        
        horizontalLayout_6->addItem(horizontalSpacer_5);
        
        phone_confirm_layout->addWidget(entered_phone_widget);
        
        resend_button_ = new QPushButton(phone_confirm_widget);
        resend_button_->setObjectName(QStringLiteral("resendButton"));
        resend_button_->setCursor(QCursor(Qt::PointingHandCursor));
        resend_button_->setFocusPolicy(Qt::StrongFocus);
        resend_button_->setProperty("ResendCodeButton", QVariant(true));
        
        phone_confirm_layout->addWidget(resend_button_);
        
        code_edit_ = new QLineEdit(phone_confirm_widget);
        code_edit_->setObjectName(QStringLiteral("code_edit"));
        code_edit_->setAlignment(Qt::AlignCenter);
        code_edit_->setProperty("EnteredCode", QVariant(true));
        code_edit_->setAttribute(Qt::WA_MacShowFocusRect, false);
        Testing::setAccessibleName(code_edit_, "StartWindowSMScodeField");
        
        phone_confirm_layout->addWidget(code_edit_);
        
        QSpacerItem* verticalSpacer_4 = new QSpacerItem(20, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);
        
        phone_confirm_layout->addItem(verticalSpacer_4);
        
        login_staked_widget_->addWidget(phone_confirm_widget);
        QWidget* uin_login_widget = new QWidget();
        uin_login_widget->setObjectName(QStringLiteral("uin_login_widget"));
        sizePolicy3.setHeightForWidth(uin_login_widget->sizePolicy().hasHeightForWidth());
        uin_login_widget->setSizePolicy(sizePolicy3);
        QVBoxLayout * uin_login_layout = new QVBoxLayout(uin_login_widget);
        uin_login_layout->setSpacing(0);
        uin_login_layout->setObjectName(QStringLiteral("uin_login_layout"));
        uin_login_layout->setContentsMargins(0, 0, 0, 0);
        
        uin_login_edit_ = new QLineEdit(uin_login_widget);
        uin_login_edit_->setObjectName(QStringLiteral("uin_login_edit"));
        uin_login_edit_->setAlignment(Qt::AlignLeft);
        uin_login_edit_->setProperty("Uin", QVariant(true));
        Testing::setAccessibleName(uin_login_edit_, "StartWindowUinField");
        
        uin_login_layout->addWidget(uin_login_edit_);
        
        uin_password_edit_ = new QLineEdit(uin_login_widget);
        uin_password_edit_->setObjectName(QStringLiteral("uin_password_edit"));
        uin_password_edit_->setEchoMode(QLineEdit::Password);
        uin_password_edit_->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter);
        uin_password_edit_->setProperty("Password", QVariant(true));
        Testing::setAccessibleName(uin_password_edit_, "StartWindowPasswordField");
        
        uin_login_layout->addWidget(uin_password_edit_);
        
        keep_logged_ = new QCheckBox(uin_login_widget);
        keep_logged_->setObjectName(QStringLiteral("keep_logged"));
        uin_login_layout->addWidget(keep_logged_);
        
        login_staked_widget_->addWidget(uin_login_widget);
        
        horizontalLayout->addWidget(login_staked_widget_);
        
        QSpacerItem* horizontalSpacer_8 = new QSpacerItem(0, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
        
        horizontalLayout->addItem(horizontalSpacer_8);
        
        controls_layout->addWidget(center_widget);
        
        QWidget* next_button_widget = new QWidget(controls_widget);
        next_button_widget->setObjectName(QStringLiteral("next_button_widget"));
        next_button_widget->setProperty("NextButtonWidget", QVariant(true));
        QVBoxLayout* verticalLayout_8 = new QVBoxLayout(next_button_widget);
        verticalLayout_8->setSpacing(0);
        verticalLayout_8->setObjectName(QStringLiteral("verticalLayout_8"));
        verticalLayout_8->setContentsMargins(0, 0, 0, 0);
        next_page_link_ = new QPushButton(next_button_widget);
        next_page_link_->setObjectName(QStringLiteral("next_page_link"));
        next_page_link_->setCursor(QCursor(Qt::PointingHandCursor));
        next_page_link_->setAutoDefault(true);
        next_page_link_->setDefault(false);
		Utils::ApplyStyle(next_page_link_, main_button_style);
        Testing::setAccessibleName(next_page_link_, "StartWindowLoginButton");
        
        verticalLayout_8->addWidget(next_page_link_);
        
        controls_layout->addWidget(next_button_widget);
		controls_layout->setAlignment(next_button_widget, Qt::AlignHCenter);

        QWidget* widget = new QWidget(controls_widget);
        widget->setObjectName(QStringLiteral("widget"));
        widget->setProperty("ErrorWIdget", QVariant(true));
        QVBoxLayout* verticalLayout_7 = new QVBoxLayout(widget);
        verticalLayout_7->setSpacing(0);
        verticalLayout_7->setObjectName(QStringLiteral("verticalLayout_7"));
        verticalLayout_7->setContentsMargins(0, 0, 0, 0);
        error_label_ = new QLabel(widget);
        error_label_->setObjectName(QStringLiteral("error_label"));
        error_label_->setAlignment(Qt::AlignCenter);
        error_label_->setProperty("ErrorLabel", QVariant(true));
        
        verticalLayout_7->addWidget(error_label_);
        
        controls_layout->addWidget(widget);
        
        main_layout->addWidget(controls_widget);
        
        QSpacerItem* horizontalSpacer_7 = new QSpacerItem(0, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
        
        main_layout->addItem(horizontalSpacer_7);
        
        verticalLayout->addWidget(main_widget);
        
        QSpacerItem* verticalSpacer_2 = new QSpacerItem(0, 3, QSizePolicy::Minimum, QSizePolicy::Expanding);
        
        verticalLayout->addItem(verticalSpacer_2);
        
        QWidget* switch_login_widget = new QWidget(this);
        switch_login_widget->setObjectName(QStringLiteral("switch_login_widget"));
        switch_login_widget->setProperty("LoginButtonWidget", QVariant(true));
        QHBoxLayout* switch_login_layout = new QHBoxLayout(switch_login_widget);
        switch_login_layout->setSpacing(0);
        switch_login_layout->setObjectName(QStringLiteral("switch_login_layout"));
        switch_login_layout->setContentsMargins(0, 0, 0, 0);
        QSpacerItem* horizontalSpacer = new QSpacerItem(0, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
        
        switch_login_layout->addItem(horizontalSpacer);
        
        switch_login_link_ = new QPushButton(switch_login_widget);
        switch_login_link_->setObjectName(QStringLiteral("switch_login_link"));
        sizePolicy1.setHeightForWidth(switch_login_link_->sizePolicy().hasHeightForWidth());
        switch_login_link_->setSizePolicy(sizePolicy1);
        switch_login_link_->setCursor(QCursor(Qt::PointingHandCursor));
        switch_login_link_->setProperty("SwitchLoginButton", QVariant(true));
        Testing::setAccessibleName(switch_login_link_, "StartWindowChangeLoginType");
        
        switch_login_layout->addWidget(switch_login_link_);
        
        QSpacerItem* horizontalSpacer_2 = new QSpacerItem(0, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
        
        switch_login_layout->addItem(horizontalSpacer_2);
        
        verticalLayout->addWidget(switch_login_widget);
        
        login_staked_widget_->setCurrentIndex(2);
        
        QMetaObject::connectSlotsByName(this);
        
        //prev_page_link_->setText(QString());
        welcome_label->setText(QT_TRANSLATE_NOOP("login_page","Welcome to ICQ"));
        edit_phone_button_->setText(QT_TRANSLATE_NOOP("login_page","Edit"));
        code_edit_->setPlaceholderText(QT_TRANSLATE_NOOP("login_page","Your code"));
        uin_login_edit_->setPlaceholderText(QT_TRANSLATE_NOOP("login_page","UIN or Email"));
        uin_login_edit_->setAttribute(Qt::WA_MacShowFocusRect, false);
        uin_password_edit_->setPlaceholderText(QT_TRANSLATE_NOOP("login_page","Password"));
        uin_password_edit_->setAttribute(Qt::WA_MacShowFocusRect, false);
        
        keep_logged_->setText(QT_TRANSLATE_NOOP("login_page","Keep me signed in"));
        keep_logged_->setChecked(get_gui_settings()->get_value(settings_keep_logged_in, true));
        connect(keep_logged_, &QCheckBox::toggled, [](bool v)
        {
            if (get_gui_settings()->get_value(settings_keep_logged_in, true) != v)
                get_gui_settings()->set_value(settings_keep_logged_in, v);
        });
        
        next_page_link_->setText(QT_TRANSLATE_NOOP("login_page","Continue"));
        Q_UNUSED(this);
        
        login_staked_widget_->setCurrentIndex(2);
        next_page_link_->setDefault(false);
        
        QMetaObject::connectSlotsByName(this);
		init();
	}
 /** Constructs @a medium enumeration task. */
 UITaskMediumEnumeration(const UIMedium &medium)
     : UITask(UITask::Type_MediumEnumeration)
 {
     /* Store medium as property: */
     setProperty("medium", QVariant::fromValue(medium));
 }
Ejemplo n.º 10
0
	/**
	 * Remove the options menu from this screen.
	 * @return True if success, false otherwise ( for instance the options
	 * menu has no content.
	 */
	void Screen::removeOptionsMenu()
	{
		setProperty(MAW_SCREEN_REMOVE_OPTIONS_MENU,"");
	}
Ejemplo n.º 11
0
	/**
	 * Set the title of the screen.
	 * The title is used by tab screen to display a text on the tab indicator.
	 * @param title The screen title.
	 */
	void Screen::setTitle(const MAUtil::String& title)
	{
		setProperty(MAW_SCREEN_TITLE, title.c_str());
	}
Ejemplo n.º 12
0
int patchEntities(double versionFile, char *mapName)
{
	char patchFile[MAX_PATH_LENGTH], *line, *savePtr, itemName[MAX_VALUE_LENGTH];
	char key[MAX_VALUE_LENGTH], value[MAX_VALUE_LENGTH];
	int skipping = FALSE, x, y, read, found, saveMap;
	unsigned char *buffer;
	Entity *e;
	EntityList *el, *entities;
	Target *t;

	savePtr = NULL;

	snprintf(patchFile, sizeof(patchFile), "data/patch/%0.2f.dat", versionFile);

	saveMap = TRUE;

	if (existsInPak(patchFile) == TRUE)
	{
		buffer = loadFileFromPak(patchFile);

		line = strtok_r((char *)buffer, "\n", &savePtr);

		while (line != NULL)
		{
			if (line[strlen(line) - 1] == '\n')
			{
				line[strlen(line) - 1] = '\0';
			}

			if (line[strlen(line) - 1] == '\r')
			{
				line[strlen(line) - 1] = '\0';
			}

			sscanf(line, "%s", itemName);

			if (strcmpignorecase(itemName, "MAP_NAME") == 0)
			{
				sscanf(line, "%*s %s\n", itemName);

				skipping = strcmpignorecase(itemName, mapName) == 0 ? FALSE : TRUE;
			}

			else if (strcmpignorecase(itemName, "MODIFY_OBJECTIVE") == 0 && skipping == FALSE)
			{
				sscanf(line, "%*s \"%[^\"]\" \"%[^\"]\"", key, value);

				modifyObjective(key, value);
			}

			else if (strcmpignorecase(itemName, "REMOVE_OBJECTIVE") == 0 && skipping == FALSE)
			{
				sscanf(line, "%*s \"%[^\"]\"", key);

				removeObjective(key);
			}

			else if (strcmpignorecase(itemName, "REMOVE_TRIGGER") == 0 && skipping == FALSE)
			{
				sscanf(line, "%*s \"%[^\"]\"", key);

				removeGlobalTrigger(key);

				removeTrigger(key);
			}

			else if (strcmpignorecase(line, "ADD_ENTITY") == 0 && skipping == FALSE)
			{
				loadResources(savePtr);
			}

			else if (strcmpignorecase(itemName, "REMOVE_ENTITY") == 0 && skipping == FALSE)
			{
				read = sscanf(line, "%*s %s %d %d", itemName, &x, &y);

				found = FALSE;

				e = getEntityByObjectiveName(itemName);

				if (e != NULL)
				{
					e->inUse = FALSE;

					found = TRUE;
				}

				if (found == FALSE)
				{
					t = getTargetByName(itemName);

					if (t != NULL)
					{
						t->active = FALSE;

						found = TRUE;
					}
				}

				if (found == FALSE && read == 3)
				{
					e = getEntityByStartXY(x, y);

					if (e != NULL)
					{
						e->inUse = FALSE;

						found = TRUE;
					}
				}
			}

			else if (strcmpignorecase(itemName, "UPDATE_ENTITY") == 0 && skipping == FALSE)
			{
				read = sscanf(line, "%*s %s %s %s", itemName, key, value);

				if (strcmpignorecase(itemName, "PLAYER") == 0)
				{
					e = &player;
				}

				else
				{
					e = getEntityByObjectiveName(itemName);
				}

				if (e != NULL)
				{
					if (strcmpignorecase(value, "NULL") == 0)
					{
						STRNCPY(value, "", sizeof(value));
					}

					setProperty(e, key, value);
				}
			}

			else if (strcmpignorecase(itemName, "UPDATE_ENTITY_BY_START") == 0 && skipping == FALSE)
			{
				read = sscanf(line, "%*s %d %d %s %[^\n]s", &x, &y, key, value);

				if (strcmpignorecase(itemName, "PLAYER") == 0)
				{
					e = &player;
				}

				else
				{
					e = getEntityByStartXY(x, y);
				}

				if (e != NULL)
				{
					setProperty(e, key, value);
				}
			}

			else if (strcmpignorecase(itemName, "UPDATE_ENTITY_BY_XY") == 0 && skipping == FALSE)
			{
				read = sscanf(line, "%*s %d %d %s %[^\n]s", &x, &y, key, value);

				if (strcmpignorecase(itemName, "PLAYER") == 0)
				{
					e = &player;
				}

				else
				{
					e = getEntityByXY(x, y);
				}

				if (e != NULL)
				{
					setProperty(e, key, value);
				}
			}

			else if (strcmpignorecase(itemName, "TRANSLATE_ENTITIES") == 0 && skipping == FALSE)
			{
				read = sscanf(line, "%*s %d %d", &x, &y);

				entities = getEntities();

				player.x -= x;
				player.y -= y;

				for (el=entities->next;el!=NULL;el=el->next)
				{
					e = el->entity;

					e->x -= x;
					e->y -= y;

					if (e->startX - x > 0)
					{
						e->startX -= x;
					}

					if (e->startY - y > 0)
					{
						e->startY -= y;
					}

					if (e->endX - x > 0)
					{
						e->endX -= x;
					}

					if (e->endY - y > 0)
					{
						e->endY -= y;
					}
				}

				t = getTargets();

				for (x=0;x<MAX_TARGETS;x++)
				{
					if (t[x].active == TRUE)
					{
						if (t[x].x - x > 0)
						{
							t[x].x -= x;
						}

						if (t[x].y - y > 0)
						{
							t[x].y -= y;
						}
					}
				}
			}

			else if (strcmpignorecase(itemName, "RENAME_MAP") == 0 && skipping == FALSE)
			{
				saveMap = FALSE;
			}

			line = strtok_r(NULL, "\n", &savePtr);
		}

		free(buffer);
	}

	return saveMap;
}
Ejemplo n.º 13
0
char *loadResources(char *buffer)
{
	int i, startX, startY, type, name, resourceType;
	char *token, *line, itemName[MAX_VALUE_LENGTH], *savePtr2, *savePtr;
	Entity *e;

	savePtr = NULL;

	resourceType = ENTITY_DATA;

	if (key == NULL || value == NULL)
	{
		key = malloc(sizeof(char *) * MAX_PROPS_FILES);
		value = malloc(sizeof(char *) * MAX_PROPS_FILES);

		if (key == NULL || value == NULL)
		{
			showErrorAndExit("Ran out of memory when loading properties");
		}

		for (i=0;i<MAX_PROPS_FILES;i++)
		{
			key[i] = malloc(MAX_VALUE_LENGTH);
			value[i] = malloc(MAX_VALUE_LENGTH);

			if (key[i] == NULL || value[i] == NULL)
			{
				showErrorAndExit("Ran out of memory when loading properties");
			}
		}
	}

	for (i=0;i<MAX_PROPS_FILES;i++)
	{
		key[i][0] = '\0';
		value[i][0] = '\0';
	}

	i = 0;

	name = type = startX = startY = -1;

	e = NULL;

	line = strtok_r(buffer, "\n", &savePtr);

	while (line != NULL)
	{
		if (line[strlen(line) - 1] == '\n')
		{
			line[strlen(line) - 1] = '\0';
		}

		if (line[strlen(line) - 1] == '\r')
		{
			line[strlen(line) - 1] = '\0';
		}

		if (line[0] == '#' || line[0] == '\n')
		{
			line = strtok_r(NULL, "\n", &savePtr);

			continue;
		}

		else if (line[0] == ' ')
		{
			printf("WARNING: Line starts with a space\n");

			#if DEV == 1
				exit(0);
			#endif

			line = strtok_r(NULL, "\n", &savePtr);

			continue;
		}

		sscanf(line, "%s", itemName);

		if (strcmpignorecase(itemName, "MAP_NAME") == 0)
		{
			break;
		}

		else if (strcmpignorecase(itemName, "UPDATE_ENTITY") == 0 || strcmpignorecase(itemName, "REMOVE_ENTITY") == 0)
		{
			break;
		}

		else if (strcmpignorecase(line, "PLAYER_INVENTORY") == 0)
		{
			resourceType = PLAYER_INVENTORY;
		}

		else if (strstr(line, "INVENTORY_INDEX") != NULL)
		{
			sscanf(line, "%*s %d", &startX);

			setInventoryIndex(startX);
		}

		else if (strcmpignorecase(line, "ENTITY_DATA") == 0)
		{
			resourceType = ENTITY_DATA;
		}

		else if (strcmpignorecase(line, "{") == 0)
		{
			i = 0;

			name = type = startX = startY = -1;

			e = NULL;
		}

		else if (strcmpignorecase(line, "}") == 0)
		{
			e = addEntityFromResource(value[type], value[name], startX == -1 ? 0 : atoi(value[startX]), startY == -1 ? 0 : atoi(value[startY]));

			if (e != NULL)
			{
				for (i=0;i<MAX_PROPS_FILES;i++)
				{
					if (strlen(key[i]) > 0)
					{
						setProperty(e, key[i], value[i]);
					}
				}

				if (resourceType == PLAYER_INVENTORY)
				{
					addToInventory(e);
				}
			}

			for (i=0;i<MAX_PROPS_FILES;i++)
			{
				key[i][0] = '\0';

				value[i][0] = '\0';
			}

			i = 0;
		}

		else
		{
			token = strtok_r(line, " ", &savePtr2);

			STRNCPY(key[i], token, MAX_VALUE_LENGTH);

			token = strtok_r(NULL, "\0", &savePtr2);

			if (token != NULL)
			{
				STRNCPY(value[i], token, MAX_VALUE_LENGTH);
			}

			else
			{
				key[i][0] = '\0';
			}

			if (strcmpignorecase(key[i], "TYPE") == 0)
			{
				type = i;
			}

			else if (strcmpignorecase(key[i], "START_X") == 0)
			{
				startX = i;
			}

			else if (strcmpignorecase(key[i], "START_Y") == 0)
			{
				startY = i;
			}

			else if (strcmpignorecase(key[i], "NAME") == 0)
			{
				name = i;
			}

			i++;
		}

		line = strtok_r(NULL, "\n", &savePtr);
	}

	loadInventoryItems();

	return line;
}
Ejemplo n.º 14
0
/**
 * Executes the algorithm
 */
void ScaleX::exec()
{
  //Get input workspace and offset
  const MatrixWorkspace_sptr inputW = getProperty("InputWorkspace");
  m_algFactor = getProperty("Factor");
  m_parname = getPropertyValue("InstrumentParameter");
  m_combine = getProperty("Combine");
  if(m_combine && m_parname.empty())
  {
    throw std::invalid_argument("Combine behaviour requested but the InstrumentParameter argument is blank.");
  }

  const std::string op = getPropertyValue("Operation");
  API::MatrixWorkspace_sptr outputW = createOutputWS(inputW);
  //Get number of histograms
  int histnumber = static_cast<int>(inputW->getNumberHistograms());
  m_progress = new API::Progress(this, 0.0, 1.0, histnumber+1);
  m_progress->report("Scaling X");
  m_wi_min = 0;
  m_wi_max = histnumber-1;
  //check if workspace indexes have been set
  int tempwi_min = getProperty("IndexMin");
  int tempwi_max = getProperty("IndexMax");
  if ( tempwi_max != Mantid::EMPTY_INT() )
  {
    if ((m_wi_min <= tempwi_min) && (tempwi_min <= tempwi_max) && (tempwi_max <= m_wi_max))
    {
      m_wi_min = tempwi_min;
      m_wi_max = tempwi_max;
    }
    else
    {
      g_log.error("Invalid Workspace Index min/max properties");
      throw std::invalid_argument("Inconsistent properties defined");
    }
  }
  // Setup appropriate binary function
  const bool multiply = (op=="Multiply");
  if(multiply) m_binOp = std::multiplies<double>();
  else m_binOp = std::plus<double>();

  //Check if its an event workspace
  EventWorkspace_const_sptr eventWS = boost::dynamic_pointer_cast<const EventWorkspace>(inputW);
  if (eventWS != NULL)
  {
    this->execEvent();
    return;
  }

  // do the shift in X
  PARALLEL_FOR2(inputW, outputW)
  for (int i = 0; i < histnumber; ++i)
  {
    PARALLEL_START_INTERUPT_REGION

    //Copy y and e data
    auto & outY = outputW->dataY(i);
    outY = inputW->dataY(i);
    auto & outE = outputW->dataE(i);
    outE = inputW->dataE(i);

    auto & outX = outputW->dataX(i);
    const auto & inX = inputW->readX(i);
    //Change bin value by offset
    if ((i >= m_wi_min) && (i <= m_wi_max))
    {
      double factor = getScaleFactor(inputW, i);
      // Do the offsetting
      std::transform(inX.begin(), inX.end(), outX.begin(), std::bind2nd(m_binOp, factor));
      // reverse the vector if multiplicative factor was negative
      if(multiply && factor < 0.0)
      {
        std::reverse( outX.begin(), outX.end() );
        std::reverse( outY.begin(), outY.end() );
        std::reverse( outE.begin(), outE.end() );
      }
    }
    else
    {
      outX = inX; //copy
    }
    m_progress->report("Scaling X");

    PARALLEL_END_INTERUPT_REGION
  }
  PARALLEL_CHECK_INTERUPT_REGION

  // Copy units
  if (outputW->getAxis(0)->unit().get())
    outputW->getAxis(0)->unit() = inputW->getAxis(0)->unit();
  try
  {
    if (inputW->getAxis(1)->unit().get())
      outputW->getAxis(1)->unit() = inputW->getAxis(1)->unit();
  }
  catch(Exception::IndexError &)
  {
    // OK, so this isn't a Workspace2D
  }
  // Assign it to the output workspace property
  setProperty("OutputWorkspace",outputW);
}
RendererImage::RendererImage() : DataAbstractModule(1,0,0) {
  //FIXME add DataPorts here instead of Model.cpp
  setProperty("FIXME", 112); // FIXME setting properties should be done via makros
}
Ejemplo n.º 16
0
			Config(int port) {
				setProperty("listen.port", port);
			}
Ejemplo n.º 17
0
	QMenu* SeparateTabWidget::GetTabMenu (int index)
	{
		QMenu *menu = new QMenu ();

		const auto widget = Widget (index);
		const auto imtw = qobject_cast<ITabWidget*> (widget);

		if (XmlSettingsManager::Instance ()->
				property ("ShowPluginMenuInTabs").toBool ())
		{
			bool asSub = XmlSettingsManager::Instance ()->
				property ("ShowPluginMenuInTabsAsSubmenu").toBool ();
			if (imtw)
			{
				const auto& tabActions = imtw->GetTabBarContextMenuActions ();

				QMenu *subMenu = asSub ?
						new QMenu (TabText (index), menu) :
						nullptr;
				for (auto act : tabActions)
					(asSub ? subMenu : menu)->addAction (act);

				if (asSub)
					menu->addMenu (subMenu);

				if (tabActions.size ())
					menu->addSeparator ();
			}
		}

		auto rootWM = Core::Instance ().GetRootWindowsManager ();
		const int windowIndex = rootWM->GetWindowIndex (Window_);

		auto moveMenu = menu->addMenu (tr ("Move tab to"));
		auto toNew = moveMenu->addAction (tr ("New window"),
				rootWM, SLOT (moveTabToNewWindow ()));
		toNew->setProperty ("TabIndex", index);
		toNew->setProperty ("FromWindowIndex", windowIndex);
		if (rootWM->GetWindowsCount () > 1)
		{
			moveMenu->addSeparator ();

			for (int i = 0; i < rootWM->GetWindowsCount (); ++i)
			{
				auto thatWin = rootWM->GetMainWindow (i);
				if (thatWin == Window_)
					continue;

				const auto& actTitle = tr ("To window %1 (%2)")
							.arg (i + 1)
							.arg (thatWin->windowTitle ());
				auto toExisting = moveMenu->addAction (actTitle,
						rootWM, SLOT (moveTabToExistingWindow ()));
				toExisting->setProperty ("TabIndex", index);
				toExisting->setProperty ("FromWindowIndex", windowIndex);
				toExisting->setProperty ("ToWindowIndex", i);
			}
		}

		const auto irt = qobject_cast<IRecoverableTab*> (widget);
		if (imtw &&
				irt &&
				(imtw->GetTabClassInfo ().Features_ & TabFeature::TFOpenableByRequest) &&
				!(imtw->GetTabClassInfo ().Features_ & TabFeature::TFSingle))
		{
			const auto cloneAct = menu->addAction (tr ("Clone tab"),
					this, SLOT (handleCloneTab ()));
			cloneAct->setProperty ("TabIndex", index);
			cloneAct->setProperty ("ActionIcon", "tab-duplicate");
		}

		for (auto act : TabBarActions_)
		{
			if (!act)
			{
				qWarning () << Q_FUNC_INFO
						<< "detected null pointer";
				continue;
			}
			menu->addAction (act);
		}

		Util::DefaultHookProxy_ptr proxy (new Util::DefaultHookProxy);
		emit hookTabContextMenuFill (proxy, menu, index,
				Core::Instance ().GetRootWindowsManager ()->GetWindowIndex (Window_));

		return menu;
	}
Ejemplo n.º 18
0
void PlaylistView::ReloadSettings() {
  QSettings s;
  s.beginGroup(Playlist::kSettingsGroup);
  glow_enabled_ = s.value("glow_effect", true).toBool();

  if (setting_initial_header_layout_ || upgrading_from_qheaderview_) {
    header_->SetStretchEnabled(s.value("stretch", true).toBool());
    upgrading_from_qheaderview_ = false;
  }

  if (currently_glowing_ && glow_enabled_ && isVisible()) StartGlowing();
  if (!glow_enabled_) StopGlowing();

  if (setting_initial_header_layout_) {
    header_->SetColumnWidth(Playlist::Column_Length, 0.06);
    header_->SetColumnWidth(Playlist::Column_Track, 0.05);
    setting_initial_header_layout_ = false;
  }

  if (upgrading_from_version_ != -1) {
    if (upgrading_from_version_ < 4) {
      header_->SetColumnWidth(Playlist::Column_Source, 0.05);
    }
    upgrading_from_version_ = -1;
  }

  column_alignment_ = s.value("column_alignments").value<ColumnAlignmentMap>();
  if (column_alignment_.isEmpty()) {
    column_alignment_ = DefaultColumnAlignment();
  }

  emit ColumnAlignmentChanged(column_alignment_);

  // Background:
  QVariant q_playlistview_background_type =
      s.value(kSettingBackgroundImageType);
  BackgroundImageType background_type(Default);
  // bg_enabled should also be checked for backward compatibility (in releases
  // <= 1.0, there was just a boolean to activate/deactivate the background)
  QVariant bg_enabled = s.value("bg_enabled");
  if (q_playlistview_background_type.isValid()) {
    background_type = static_cast<BackgroundImageType>(
        q_playlistview_background_type.toInt());
  } else if (bg_enabled.isValid()) {
    if (bg_enabled.toBool()) {
      background_type = Default;
    } else {
      background_type = None;
    }
  }
  QString background_image_filename =
      s.value(kSettingBackgroundImageFilename).toString();
  int blur_radius = s.value("blur_radius", kDefaultBlurRadius).toInt();
  int opacity_level = s.value("opacity_level", kDefaultOpacityLevel).toInt();
  // Check if background properties have changed.
  // We change properties only if they have actually changed, to avoid to call
  // set_background_image when it is not needed, as this will cause the fading
  // animation to start again. This also avoid to do useless
  // "force_background_redraw".
  if (background_image_filename != background_image_filename_ ||
      background_type != background_image_type_ ||
      blur_radius_ != blur_radius || opacity_level_ != opacity_level) {
    // Store background properties
    background_image_type_ = background_type;
    background_image_filename_ = background_image_filename;
    blur_radius_ = blur_radius;
    opacity_level_ = opacity_level;
    if (background_image_type_ == Custom) {
      set_background_image(QImage(background_image_filename));
    } else if (background_image_type_ == AlbumCover) {
      set_background_image(current_song_cover_art_);
    } else {
      // User changed background image type to something that will not be
      // painted through paintEvent: reset all background images.
      // This avoid to use old (deprecated) images for fading when selecting
      // AlbumCover or Custom background image type later.
      set_background_image(QImage());
      cached_scaled_background_image_ = QPixmap();
      previous_background_image_ = QPixmap();
    }
    setProperty("default_background_enabled",
                background_image_type_ == Default);
    emit BackgroundPropertyChanged();
    force_background_redraw_ = true;
  }
}
Ejemplo n.º 19
0
/**
 * Apply the detector test criterion
 * @param counts1 :: A workspace containing the integrated counts of the first
 * white beam run
 * @param counts2 :: A workspace containing the integrated counts of the first
 * white beam run
 * @param average :: The computed median
 * @param variation :: The allowed variation in terms of number of medians, i.e
 * those spectra where
 * the ratio of the counts outside this range will fail the tests and will be
 * masked on counts1
 * @return number of detectors for which tests failed
 */
int DetectorEfficiencyVariation::doDetectorTests(
    API::MatrixWorkspace_const_sptr counts1,
    API::MatrixWorkspace_const_sptr counts2, const double average,
    double variation) {
  // DIAG in libISIS did this.  A variation of less than 1 doesn't make sense in
  // this algorithm
  if (variation < 1) {
    variation = 1.0 / variation;
  }
  // criterion for if the the first spectrum is larger than expected
  double largest = average * variation;
  // criterion for if the the first spectrum is lower than expected
  double lowest = average / variation;

  const int numSpec = static_cast<int>(counts1->getNumberHistograms());
  const int progStep = static_cast<int>(std::ceil(numSpec / 30.0));

  // Create a workspace for the output
  MaskWorkspace_sptr maskWS = this->generateEmptyMask(counts1);

  bool checkForMask = false;
  Geometry::Instrument_const_sptr instrument = counts1->getInstrument();
  if (instrument != nullptr) {
    checkForMask = ((instrument->getSource() != nullptr) &&
                    (instrument->getSample() != nullptr));
  }

  const double deadValue(1.0);
  int numFailed(0);
  PARALLEL_FOR3(counts1, counts2, maskWS)
  for (int i = 0; i < numSpec; ++i) {
    PARALLEL_START_INTERUPT_REGION
    // move progress bar
    if (i % progStep == 0) {
      advanceProgress(progStep * static_cast<double>(RTMarkDetects) / numSpec);
      progress(m_fracDone);
      interruption_point();
    }

    if (checkForMask) {
      const std::set<detid_t> &detids =
          counts1->getSpectrum(i).getDetectorIDs();
      if (instrument->isMonitor(detids))
        continue;
      if (instrument->isDetectorMasked(detids)) {
        // Ensure it is masked on the output
        maskWS->mutableY(i)[0] = deadValue;
        continue;
      }
    }

    const double signal1 = counts1->y(i)[0];
    const double signal2 = counts2->y(i)[0];

    // Mask out NaN and infinite
    if (boost::math::isinf(signal1) || boost::math::isnan(signal1) ||
        boost::math::isinf(signal2) || boost::math::isnan(signal2)) {
      maskWS->mutableY(i)[0] = deadValue;
      PARALLEL_ATOMIC
      ++numFailed;
      continue;
    }

    // Check the ratio is within the given range
    const double ratio = signal1 / signal2;
    if (ratio < lowest || ratio > largest) {
      maskWS->mutableY(i)[0] = deadValue;
      PARALLEL_ATOMIC
      ++numFailed;
    }

    PARALLEL_END_INTERUPT_REGION
  }
  PARALLEL_CHECK_INTERUPT_REGION

  // Register the results with the ADS
  setProperty("OutputWorkspace", maskWS);

  return numFailed;
}
Ejemplo n.º 20
0
/*!
    \internal
    Set the value of the property \a propname to \a value.
*/
void QDBusAbstractInterface::internalPropSet(const char *propname, const QVariant &value)
{
    setProperty(propname, value);
}
Ejemplo n.º 21
0
/** Execute the algorithm.
 */
void ResampleX::exec() {
  // generically having access to the input workspace is a good idea
  MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace");
  MatrixWorkspace_sptr outputWS = getProperty("OutputWorkspace");
  bool inPlace = (inputWS == outputWS); // Rebinning in-place
  m_isDistribution = inputWS->isDistribution();
  m_isHistogram = inputWS->isHistogramData();
  int numSpectra = static_cast<int>(inputWS->getNumberHistograms());

  // the easy parameters
  m_useLogBinning = getProperty("LogBinning");
  m_numBins = getProperty("NumberBins");
  m_preserveEvents = getProperty("PreserveEvents");

  // determine the xmin/xmax for the workspace
  vector<double> xmins = getProperty("XMin");
  vector<double> xmaxs = getProperty("XMax");
  string error = determineXMinMax(inputWS, xmins, xmaxs);
  if (!error.empty())
    throw std::runtime_error(error);

  bool common_limits = true;
  {
    double xmin_common = xmins[0];
    double xmax_common = xmaxs[0];
    for (size_t i = 1; i < xmins.size(); ++i) {
      if (xmins[i] != xmin_common) {
        common_limits = false;
        break;
      }
      if (xmaxs[i] != xmax_common) {
        common_limits = false;
        break;
      }
    }
  }
  if (common_limits) {
    g_log.debug() << "Common limits between all spectra\n";
  } else {
    g_log.debug() << "Does not have common limits between all spectra\n";
  }

  // start doing actual work
  EventWorkspace_const_sptr inputEventWS =
      boost::dynamic_pointer_cast<const EventWorkspace>(inputWS);
  if (inputEventWS != nullptr) {
    if (m_preserveEvents) {
      if (inPlace) {
        g_log.debug() << "Rebinning event workspace in place\n";
      } else {
        g_log.debug() << "Rebinning event workspace out of place\n";
        outputWS = inputWS->clone();
      }
      auto outputEventWS =
          boost::dynamic_pointer_cast<EventWorkspace>(outputWS);

      if (common_limits) {
        // get the delta from the first since they are all the same
        BinEdges xValues(0);
        double delta = this->determineBinning(xValues.mutableRawData(),
                                              xmins[0], xmaxs[0]);
        g_log.debug() << "delta = " << delta << "\n";
        outputEventWS->setAllX(xValues);
      } else {
        // initialize progress reporting.
        Progress prog(this, 0.0, 1.0, numSpectra);

        // do the rebinning
        PARALLEL_FOR_IF(Kernel::threadSafe(*inputEventWS, *outputWS))
        for (int wkspIndex = 0; wkspIndex < numSpectra; ++wkspIndex) {
          PARALLEL_START_INTERUPT_REGION
          BinEdges xValues(0);
          double delta = this->determineBinning(
              xValues.mutableRawData(), xmins[wkspIndex], xmaxs[wkspIndex]);
          g_log.debug() << "delta[wkspindex=" << wkspIndex << "] = " << delta
                        << " xmin=" << xmins[wkspIndex]
                        << " xmax=" << xmaxs[wkspIndex] << "\n";
          outputEventWS->setHistogram(wkspIndex, xValues);
          prog.report(name()); // Report progress
          PARALLEL_END_INTERUPT_REGION
        }
        PARALLEL_CHECK_INTERUPT_REGION
      }
    }    // end if (m_preserveEvents)
    else // event workspace -> matrix workspace
    {
      //--------- Different output, OR you're inplace but not preserving Events
      g_log.information() << "Creating a Workspace2D from the EventWorkspace "
                          << inputEventWS->getName() << ".\n";
      outputWS = create<DataObjects::Workspace2D>(
          *inputWS, numSpectra, HistogramData::BinEdges(m_numBins));

      // Initialize progress reporting.
      Progress prog(this, 0.0, 1.0, numSpectra);

      // Go through all the histograms and set the data
      PARALLEL_FOR_IF(Kernel::threadSafe(*inputEventWS, *outputWS))
      for (int wkspIndex = 0; wkspIndex < numSpectra; ++wkspIndex) {
        PARALLEL_START_INTERUPT_REGION

        // Set the X axis for each output histogram
        MantidVec xValues;
        double delta =
            this->determineBinning(xValues, xmins[wkspIndex], xmaxs[wkspIndex]);
        g_log.debug() << "delta[wkspindex=" << wkspIndex << "] = " << delta
                      << "\n";
        outputWS->setBinEdges(wkspIndex, xValues);

        // Get a const event list reference. inputEventWS->dataY() doesn't work.
        const EventList &el = inputEventWS->getSpectrum(wkspIndex);
        MantidVec y_data, e_data;
        // The EventList takes care of histogramming.
        el.generateHistogram(xValues, y_data, e_data);

        // Copy the data over.
        outputWS->mutableY(wkspIndex) = std::move(y_data);
        outputWS->mutableE(wkspIndex) = std::move(e_data);

        // Report progress
        prog.report(name());
        PARALLEL_END_INTERUPT_REGION
      }
      PARALLEL_CHECK_INTERUPT_REGION

      // Copy all the axes
      for (int i = 1; i < inputWS->axes(); i++) {
        outputWS->replaceAxis(i, inputWS->getAxis(i)->clone(outputWS.get()));
        outputWS->getAxis(i)->unit() = inputWS->getAxis(i)->unit();
      }

      // Copy the units over too.
      for (int i = 0; i < outputWS->axes(); ++i) {
        outputWS->getAxis(i)->unit() = inputWS->getAxis(i)->unit();
      }
      outputWS->setYUnit(inputEventWS->YUnit());
      outputWS->setYUnitLabel(inputEventWS->YUnitLabel());
    }
    // Assign it to the output workspace property
    setProperty("OutputWorkspace", outputWS);
    return;
  } else // (inputeventWS != NULL)
Ejemplo n.º 22
0
//start method
bool com_objective_see_firewall::start(IOService *provider)
{
    //return var
    bool result = false;
    
    //dbg msg
    IOLog("LULU: in %s\n", __FUNCTION__);
    
    //super
    if(TRUE != super::start(provider))
    {
        //bail
        goto bail;
    }
    
    //alloc memory tag
    allocTag = OSMalloc_Tagalloc(BUNDLE_ID, OSMT_DEFAULT);
    if(NULL == allocTag)
    {
        //err msg
        IOLog("LULU ERROR: OSMalloc_Tagalloc() failed\n");
        
        //bail
        goto bail;
    }
    
    //alloc
    // ->rule locks, etc
    if(true != initRules())
    {
        //err msg
        IOLog("LULU ERROR: failed to init rules/locks\n");
        
        //bail
        goto bail;
    }
    
    //init shared data queue
    sharedDataQueue = IOSharedDataQueue::withCapacity(sizeof(firewallEvent) * (MAX_FIREWALL_EVENTS + DATA_QUEUE_ENTRY_HEADER_SIZE));
    if(NULL == sharedDataQueue)
    {
        //bail
        goto bail;
    }
    
    //get memory descriptor
    sharedMemoryDescriptor = sharedDataQueue->getMemoryDescriptor();
    if(NULL == sharedMemoryDescriptor)
    {
        //bail
        goto bail;
    }
    
    //register service
    // allows clients to connect
    registerService();
    
    //dbg msg
    IOLog("LULU: registered service %s\n",  LULU_SERVICE_NAME);
    
    //set user class
    setProperty("IOUserClientClass", LULU_USER_CLIENT_CLASS);
    
    //init broadcast
    if(true != initBroadcast())
    {
        //err msg
        IOLog("LULU ERROR: initBroadcast() failed\n");
        
        //bail
        goto bail;
    }
    
    //all happy
    result = true;
    
bail:
    
    return result;
}
Ejemplo n.º 23
0
WorkoutWindow::WorkoutWindow(Context *context) :
    GcWindow(context), draw(true), context(context), active(false), recording(false)
{
    setContentsMargins(0,0,0,0);
    setProperty("color", GColor(CTRAINPLOTBACKGROUND));

    setControls(NULL);
    ergFile = NULL;

    QVBoxLayout *main = new QVBoxLayout(this);
    QHBoxLayout *layout = new QHBoxLayout;
    QVBoxLayout *editor = new QVBoxLayout;

    connect(context, SIGNAL(configChanged(qint32)), this, SLOT(configChanged(qint32)));

    // the workout scene
    workout = new WorkoutWidget(this, context);

    // paint the TTE curve
    mmp = new WWMMPCurve(workout);

    // add a line between the dots
    line = new WWLine(workout);

    // block cursos
    bcursor = new WWBlockCursor(workout);

    // block selection
    brect = new WWBlockSelection(workout);

    // paint the W'bal curve
    wbline = new WWWBLine(workout, context);

    // add the power, W'bal scale
    powerscale = new WWPowerScale(workout, context);
    wbalscale = new WWWBalScale(workout, context);

    // lap markers
    lap = new WWLap(workout);

    // tte warning bar at bottom
    tte = new WWTTE(workout);

    // selection tool
    rect = new WWRect(workout);

    // guides always on top!
    guide = new WWSmartGuide(workout);

    // recording ...
    now = new WWNow(workout, context);
    telemetry = new WWTelemetry(workout, context);

    // scroller, hidden until needed
    scroll = new QScrollBar(Qt::Horizontal, this);
    scroll->hide();

    // setup the toolbar
    toolbar = new QToolBar(this);
    toolbar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    toolbar->setFloatable(true);
    toolbar->setIconSize(QSize(18,18));

    QIcon newIcon(":images/toolbar/new doc.png");
    newAct = new QAction(newIcon, tr("New"), this);
    connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));
    toolbar->addAction(newAct);

    QIcon saveIcon(":images/toolbar/save.png");
    saveAct = new QAction(saveIcon, tr("Save"), this);
    connect(saveAct, SIGNAL(triggered()), this, SLOT(saveFile()));
    toolbar->addAction(saveAct);

    QIcon saveAsIcon(":images/toolbar/saveas.png");
    saveAsAct = new QAction(saveAsIcon, tr("Save As"), this);
    connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs()));
    toolbar->addAction(saveAsAct);

    toolbar->addSeparator();

    //XXX TODO
    //XXXHelpWhatsThis *helpToolbar = new HelpWhatsThis(toolbar);
    //XXXtoolbar->setWhatsThis(helpToolbar->getWhatsThisText(HelpWhatsThis::ChartRides_Editor));

    // undo and redo deliberately at a distance from the
    // save icon, since accidentally hitting the wrong
    // icon in that instance would be horrible
    QIcon undoIcon(":images/toolbar/undo.png");
    undoAct = new QAction(undoIcon, tr("Undo"), this);
    connect(undoAct, SIGNAL(triggered()), workout, SLOT(undo()));
    toolbar->addAction(undoAct);

    QIcon redoIcon(":images/toolbar/redo.png");
    redoAct = new QAction(redoIcon, tr("Redo"), this);
    connect(redoAct, SIGNAL(triggered()), workout, SLOT(redo()));
    toolbar->addAction(redoAct);
    
    toolbar->addSeparator();

    QIcon drawIcon(":images/toolbar/edit.png");
    drawAct = new QAction(drawIcon, tr("Draw"), this);
    connect(drawAct, SIGNAL(triggered()), this, SLOT(drawMode()));
    toolbar->addAction(drawAct);

    QIcon selectIcon(":images/toolbar/select.png");
    selectAct = new QAction(selectIcon, tr("Select"), this);
    connect(selectAct, SIGNAL(triggered()), this, SLOT(selectMode()));
    toolbar->addAction(selectAct);

    selectAct->setEnabled(true);
    drawAct->setEnabled(false);

    toolbar->addSeparator();

    QIcon cutIcon(":images/toolbar/cut.png");
    cutAct = new QAction(cutIcon, tr("Cut"), this);
    cutAct->setEnabled(true);
    toolbar->addAction(cutAct);
    connect(cutAct, SIGNAL(triggered()), workout, SLOT(cut()));

    QIcon copyIcon(":images/toolbar/copy.png");
    copyAct = new QAction(copyIcon, tr("Copy"), this);
    copyAct->setEnabled(true);
    toolbar->addAction(copyAct);
    connect(copyAct, SIGNAL(triggered()), workout, SLOT(copy()));

    QIcon pasteIcon(":images/toolbar/paste.png");
    pasteAct = new QAction(pasteIcon, tr("Paste"), this);
    pasteAct->setEnabled(false);
    toolbar->addAction(pasteAct);
    connect(pasteAct, SIGNAL(triggered()), workout, SLOT(paste()));

    toolbar->addSeparator();

    QIcon propertiesIcon(":images/toolbar/properties.png");
    propertiesAct = new QAction(propertiesIcon, tr("Properties"), this);
    connect(propertiesAct, SIGNAL(triggered()), this, SLOT(properties()));
    toolbar->addAction(propertiesAct);

    QIcon zoomInIcon(":images/toolbar/zoom in.png");
    zoomInAct = new QAction(zoomInIcon, tr("Zoom In"), this);
    connect(zoomInAct, SIGNAL(triggered()), this, SLOT(zoomIn()));
    toolbar->addAction(zoomInAct);

    QIcon zoomOutIcon(":images/toolbar/zoom out.png");
    zoomOutAct = new QAction(zoomOutIcon, tr("Zoom Out"), this);
    connect(zoomOutAct, SIGNAL(triggered()), this, SLOT(zoomOut()));
    toolbar->addAction(zoomOutAct);

    // stretch the labels to the right hand side
    QWidget *empty = new QWidget(this);
    empty->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred);
    toolbar->addWidget(empty);


    xlabel = new QLabel("00:00");
    toolbar->addWidget(xlabel);

    ylabel = new QLabel("150w");
    toolbar->addWidget(ylabel);

    IFlabel = new QLabel("0 IF");
    toolbar->addWidget(IFlabel);

    TSSlabel = new QLabel("0 TSS");
    toolbar->addWidget(TSSlabel);

#if 0 // not yet!
    // get updates..
    connect(context, SIGNAL(telemetryUpdate(RealtimeData)), this, SLOT(telemetryUpdate(RealtimeData)));
    telemetryUpdate(RealtimeData());
#endif

    // editing the code...
    code = new CodeEditor(this);
    code->setContextMenuPolicy(Qt::NoContextMenu); // no context menu
    code->installEventFilter(this); // filter the undo/redo stuff
    code->hide();

    // WATTS and Duration for the cursor
    main->addWidget(toolbar);
    editor->addWidget(workout);
    editor->addWidget(scroll);
    layout->addLayout(editor);
    layout->addWidget(code);
    main->addLayout(layout);

    // make it look right
    saveAct->setEnabled(false);
    undoAct->setEnabled(false);
    redoAct->setEnabled(false);

    // watch for erg file selection
    connect(context, SIGNAL(ergFileSelected(ErgFile*)), this, SLOT(ergFileSelected(ErgFile*)));

    // watch for erg run/stop
    connect(context, SIGNAL(start()), this, SLOT(start()));
    connect(context, SIGNAL(stop()), this, SLOT(stop()));

    // text changed
    connect(code, SIGNAL(textChanged()), this, SLOT(qwkcodeChanged()));
    connect(code, SIGNAL(cursorPositionChanged()), workout, SLOT(hoverQwkcode()));

    // scrollbar
    connect(scroll, SIGNAL(sliderMoved(int)), this, SLOT(scrollMoved()));

    // set the widgets etc
    configChanged(CONFIG_APPEARANCE);
}
Ejemplo n.º 24
0
juced_ComboBox::juced_ComboBox()  : ComboBox ()
{
	setText("Combo Box", false);
	setName("Box");
	setProperty(Attributes::objectType, Modules::ComboBox.toString());
	setProperty(Attributes::text, getText());
	//setProperty(Attributes::font, getFont().toString());
	setProperty(Attributes::backgroundColour, findColour(backgroundColourId).toDisplayString(true));
	setProperty(Attributes::textColour, findColour(textColourId).toDisplayString(true));
	setProperty(Attributes::height, getHeight());
	setProperty(Attributes::width, getWidth());
	setProperty(Attributes::itemList, "");
	setProperty(Attributes::name, getName());
	++_numObjects;
	setProperty(Attributes::varName, getName() + String(_numObjects));
	setProperty(Attributes::className, "ComboBox");
	setProperty(Attributes::toolName, "juced_ComboBox");
	setProperty(Attributes::declareExtended, false);
	setComponentID(Uuid().toString());
	setProperty(Attributes::ID, getComponentID());
}
Ejemplo n.º 25
0
/** Execute the algorithm.
 */
void CreateMDWorkspace::exec() {
  // Get the properties and validate them
  std::string eventType = getPropertyValue("EventType");
  int ndims_prop = getProperty("Dimensions");
  if (ndims_prop <= 0)
    throw std::invalid_argument(
        "You must specify a number of dimensions >= 1.");
  int mind = this->getProperty("MinRecursionDepth");
  int maxd = this->getProperty("MaxRecursionDepth");
  if (mind > maxd)
    throw std::invalid_argument(
        "MinRecursionDepth must be <= MaxRecursionDepth.");
  if (mind < 0 || maxd < 0)
    throw std::invalid_argument(
        "MinRecursionDepth and MaxRecursionDepth must be positive.");

  size_t ndims = static_cast<size_t>(ndims_prop);

  std::vector<double> extents = getProperty("Extents");
  std::vector<std::string> names = getProperty("Names");
  std::vector<std::string> units = getProperty("Units");
  std::vector<std::string> frames = getProperty("Frames");

  if (extents.size() != ndims * 2)
    throw std::invalid_argument("You must specify twice as many extents "
                                "(min,max) as there are dimensions.");
  if (names.size() != ndims)
    throw std::invalid_argument(
        "You must specify as many names as there are dimensions.");
  if (units.size() != ndims)
    throw std::invalid_argument(
        "You must specify as many units as there are dimensions.");
  // If no frames are specified we want to default to the General Frame,
  // to ensure backward compatibility. But if they are only partly specified,
  // then we want to throw an error. It should be either used correctly or not
  // at all
  if (!frames.empty() && frames.size() != ndims) {
    throw std::invalid_argument(
        "You must specify as many frames as there are dimensions.");
  }

  if (frames.empty()) {
    frames.resize(ndims);
    std::fill(frames.begin(), frames.end(), GeneralFrame::GeneralFrameName);
  }

  // Have the factory create it
  IMDEventWorkspace_sptr out =
      MDEventFactory::CreateMDWorkspace(ndims, eventType);

  // Give all the dimensions
  for (size_t d = 0; d < ndims; d++) {
    auto frame = createMDFrame(frames[d], units[d]);
    MDHistoDimension *dim = new MDHistoDimension(
        names[d], names[d], *frame, static_cast<coord_t>(extents[d * 2]),
        static_cast<coord_t>(extents[d * 2 + 1]), 1);
    out->addDimension(MDHistoDimension_sptr(dim));
  }

  // Initialize it using the dimension
  out->initialize();

  // Call the templated function to finish ints
  CALL_MDEVENT_FUNCTION(this->finish, out);

  // --- File back end ? ----------------
  std::string filename = getProperty("Filename");
  if (!filename.empty()) {
    // First save to the NXS file
    g_log.notice() << "Running SaveMD" << std::endl;
    IAlgorithm_sptr alg = createChildAlgorithm("SaveMD");
    alg->setPropertyValue("Filename", filename);
    alg->setProperty("InputWorkspace",
                     boost::dynamic_pointer_cast<IMDWorkspace>(out));
    alg->executeAsChildAlg();
    // And now re-load it with this file as the backing.
    g_log.notice() << "Running LoadMD" << std::endl;
    alg = createChildAlgorithm("LoadMD");
    alg->setPropertyValue("Filename", filename);
    alg->setProperty("FileBackEnd", true);
    alg->setPropertyValue("Memory", getPropertyValue("Memory"));
    alg->executeAsChildAlg();
    // Replace the workspace with the loaded, file-backed one
    IMDWorkspace_sptr temp;
    temp = alg->getProperty("OutputWorkspace");
    out = boost::dynamic_pointer_cast<IMDEventWorkspace>(temp);
  }

  // Save it on the output.
  setProperty("OutputWorkspace", boost::dynamic_pointer_cast<Workspace>(out));
}
Ejemplo n.º 26
0
Ui::VideoPanelHeader::VideoPanelHeader(QWidget* _parent, int _items)
    : MoveablePanel(_parent)
    , itemsToShow_(_items)
    , callName_(nullptr)
    , callTime_(nullptr)
    , btnMin_(nullptr)
    , btnClose_(nullptr)
    , lowWidget_(nullptr)
    , secureCallEnabled_(false)
{
#ifdef __linux__
    setStyleSheet(Utils::LoadStyle(":/qss/video_panel_linux"));
#else
    setStyleSheet(Utils::LoadStyle(":/qss/video_panel"));
#endif
    setProperty("VideoPanelHeader", true);
    setContentsMargins(0, 0, 0, 0);

    QHBoxLayout* layout = Utils::emptyHLayout();
    lowWidget_ = new QFrame(this);
    { // low widget. it makes background panel coloured
        lowWidget_->setContentsMargins(DEFAULT_BORDER, 0, 0, 0);
#ifdef __APPLE__
        lowWidget_->setProperty("VideoPanelHeaderMac", true);
#else
        lowWidget_->setProperty("VideoPanelHeader", true);
#endif

        lowWidget_->setLayout(layout);

        QVBoxLayout* vLayoutParent = Utils::emptyVLayout();
        vLayoutParent->setAlignment(Qt::AlignVCenter);
        vLayoutParent->addWidget(lowWidget_);
        setLayout(vLayoutParent);

        layout->setAlignment(Qt::AlignVCenter);

        //layout->addSpacing(DEFAULT_BORDER);
    }

    auto addWidget = [] (QWidget* _parent)
    {
        QWidget* w = new QWidget(_parent);
        w->setContentsMargins(0, 0, 0, 0);
        w->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
        return w;
    };

    auto addLayout = [] (QWidget* _w, Qt::Alignment _align)
    {
        assert(_w);
        if (_w)
        {
            QHBoxLayout* layout = Utils::emptyHLayout();
            layout->setAlignment(_align);
            _w->setLayout(layout);
        }
    };

    QWidget* leftWidg    = addWidget(lowWidget_);
    QWidget* centerWidg  = addWidget(lowWidget_);
    QWidget* rightWidg   = addWidget(lowWidget_);

    layout->addWidget(leftWidg, 1);
    layout->addWidget(centerWidg);
    layout->addWidget(rightWidg, 1);

    addLayout(leftWidg,   Qt::AlignLeft | Qt::AlignVCenter);
    addLayout(centerWidg, Qt::AlignCenter);
    addLayout(rightWidg,  Qt::AlignRight | Qt::AlignVCenter);

    QFont font = QApplication::font();
    font.setStyleStrategy(QFont::PreferAntialias);
    if (itemsToShow_ & kVPH_ShowName)
    {
        callName_ = new NameWidget(leftWidg, Utils::scale_value(18));
        callName_->setFont(font);
        callName_->layout()->setAlignment(Qt::AlignVCenter | Qt::AlignLeft);
        callName_->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding));
        callName_->setNameProperty("VideoPanelHeaderText", true);

        leftWidg->layout()->addWidget(callName_);
    }

    if (itemsToShow_ & kVPH_ShowTime)
    {
        callTime_ = new voipTools::BoundBox<PushButton_t>(centerWidg);
        callTime_->setPostfixColor(CommonStyle::getColor(CommonStyle::Color::TEXT_PRIMARY));
        callTime_->setFont(font);
        callTime_->setEnabled(false);
        callTime_->setAlignment(Qt::AlignCenter);
        callTime_->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding));
        callTime_->setFixedWidth(SECURE_BTN_TEXT_W);
        callTime_->setIconSize(SECURE_BTN_ICON_W, SECURE_BTN_ICON_H);

        QObject::connect(callTime_, SIGNAL(clicked()), this, SLOT(_onSecureCallClicked()), Qt::QueuedConnection);
        Utils::ApplyStyle(callTime_, secureCallButton);
        centerWidg->layout()->addWidget(callTime_);
    }

    QWidget* parentWidget = rightWidg;
    auto addButton = [this, parentWidget] (const QString& _propertyName, const char* _slot)->QPushButton*
    {
        QPushButton* btn = new voipTools::BoundBox<QPushButton>(parentWidget);

        Utils::ApplyStyle(btn, _propertyName);
        btn->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding));
        btn->setCursor(QCursor(Qt::PointingHandCursor));
        btn->setFlat(true);
        parentWidget->layout()->addWidget(btn);
        connect(btn, SIGNAL(clicked()), this, _slot, Qt::QueuedConnection);
        return btn;
    };
    if (itemsToShow_ & kVPH_ShowMin)
    {
        btnMin_ = addButton(CommonStyle::getMinimizeButtonStyle(), SLOT(_onMinimize()));
    }

    if (itemsToShow_ & kVPH_ShowClose)
    {
        btnClose_ = addButton(CommonStyle::getCloseButtonStyle(), SLOT(_onClose()));
    }
}
Ejemplo n.º 27
0
  /** Execute the algorithm.
   */
  void ResampleX::exec()
  {
    // generically having access to the input workspace is a good idea
    MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace");
    MatrixWorkspace_sptr outputWS = getProperty("OutputWorkspace");
    bool inPlace = (inputWS == outputWS); // Rebinning in-place
    m_isDistribution = inputWS->isDistribution();
    m_isHistogram = inputWS->isHistogramData();
    int numSpectra = static_cast<int>(inputWS->getNumberHistograms());

    // the easy parameters
    m_useLogBinning  = getProperty("LogBinning");
    m_numBins        = getProperty("NumberBins");
    m_preserveEvents = getProperty("PreserveEvents");

    // determine the xmin/xmax for the workspace
    vector<double> xmins = getProperty("XMin");
    vector<double> xmaxs = getProperty("XMax");
    string error = determineXMinMax(inputWS, xmins, xmaxs);
    if (!error.empty())
      throw std::runtime_error(error);

    // start doing actual work
    EventWorkspace_const_sptr inputEventWS = boost::dynamic_pointer_cast<const EventWorkspace>(inputWS);
    if (inputEventWS != NULL)
    {
      if (m_preserveEvents)
      {
        EventWorkspace_sptr outputEventWS = boost::dynamic_pointer_cast<EventWorkspace>(outputWS);
        if (inPlace)
        {
          g_log.debug() << "Rebinning event workspace in place\n";
        }
        else
        {
          g_log.debug() << "Rebinning event workspace in place\n";

          // copy the event workspace to a new EventWorkspace
          outputEventWS = boost::dynamic_pointer_cast<EventWorkspace>(
              API::WorkspaceFactory::Instance().create("EventWorkspace", inputWS->getNumberHistograms(), 2, 1));
          // copy geometry over.
          API::WorkspaceFactory::Instance().initializeFromParent(inputEventWS, outputEventWS, false);
          // copy over the data as well.
          outputEventWS->copyDataFrom( (*inputEventWS) );
        }

        // initialize progress reporting.
        Progress prog(this,0.0,1.0, numSpectra);

        // do the rebinning
        PARALLEL_FOR2(inputEventWS, outputWS)
        for (int wkspIndex = 0; wkspIndex < numSpectra; ++wkspIndex)
        {
          PARALLEL_START_INTERUPT_REGION
          MantidVec xValues;
          double delta = this->determineBinning(xValues, xmins[wkspIndex], xmaxs[wkspIndex]);
          g_log.debug() << "delta[wkspindex=" << wkspIndex << "] = " << delta << "\n";
          outputEventWS->getSpectrum(wkspIndex)->setX(xValues);
          prog.report(name()); //Report progress
          PARALLEL_END_INTERUPT_REGION
        }
        PARALLEL_CHECK_INTERUPT_REGION

        this->setProperty("OutputWorkspace", boost::dynamic_pointer_cast<MatrixWorkspace>(outputEventWS));
      } // end if (m_preserveEvents)
      else // event workspace -> matrix workspace
      {
        //--------- Different output, OR you're inplace but not preserving Events --- create a Workspace2D -------
        g_log.information() << "Creating a Workspace2D from the EventWorkspace " << inputEventWS->getName() << ".\n";

        //Create a Workspace2D
        // This creates a new Workspace2D through a torturous route using the WorkspaceFactory.
        // The Workspace2D is created with an EMPTY CONSTRUCTOR
        outputWS = WorkspaceFactory::Instance().create("Workspace2D",numSpectra,m_numBins,m_numBins-1);
        WorkspaceFactory::Instance().initializeFromParent(inputWS, outputWS, true);

        //Initialize progress reporting.
        Progress prog(this,0.0,1.0, numSpectra);

        //Go through all the histograms and set the data
        PARALLEL_FOR2(inputEventWS, outputWS)
        for (int wkspIndex=0; wkspIndex < numSpectra; ++wkspIndex)
        {
          PARALLEL_START_INTERUPT_REGION

          //Set the X axis for each output histogram
          MantidVec xValues;
          double delta = this->determineBinning(xValues, xmins[wkspIndex], xmaxs[wkspIndex]);
          g_log.debug() << "delta[wkspindex=" << wkspIndex << "] = " << delta << "\n";
          outputWS->setX(wkspIndex, xValues);

          //Get a const event list reference. inputEventWS->dataY() doesn't work.
          const EventList& el = inputEventWS->getEventList(wkspIndex);
          MantidVec y_data, e_data;
          // The EventList takes care of histogramming.
          el.generateHistogram(xValues, y_data, e_data);

          //Copy the data over.
          outputWS->dataY(wkspIndex).assign(y_data.begin(), y_data.end());
          outputWS->dataE(wkspIndex).assign(e_data.begin(), e_data.end());

          //Report progress
          prog.report(name());
          PARALLEL_END_INTERUPT_REGION
        }
        PARALLEL_CHECK_INTERUPT_REGION

        //Copy all the axes
        for (int i=1; i<inputWS->axes(); i++)
        {
          outputWS->replaceAxis( i, inputWS->getAxis(i)->clone(outputWS.get()) );
          outputWS->getAxis(i)->unit() = inputWS->getAxis(i)->unit();
        }

        //Copy the units over too.
        for (int i=0; i < outputWS->axes(); ++i)
          outputWS->getAxis(i)->unit() = inputWS->getAxis(i)->unit();
        outputWS->setYUnit(inputEventWS->YUnit());
        outputWS->setYUnitLabel(inputEventWS->YUnitLabel());

        // Assign it to the output workspace property
        setProperty("OutputWorkspace", outputWS);
      }
      return;
    }
Ejemplo n.º 28
0
    Application(int &argc, char **argv)
        : QApplication(argc, argv)
    {
        QDir dir(applicationDirPath());
#ifdef Q_OS_MAC
        dir.cdUp();
        dir.cd("PlugIns");
        dir.cd("qt");
#else
        dir.cd("lib");
        dir.cd("qt5");
#endif
        addLibraryPath(dir.absolutePath());
        setOrganizationName("Meltytech");
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
        setOrganizationDomain("shotcut.org");
        setDesktopFileName("org.shotcut.Shotcut");
#else
        setOrganizationDomain("meltytech.com");
#endif
        setApplicationName("Shotcut");
        setApplicationVersion(SHOTCUT_VERSION);
        setAttribute(Qt::AA_UseHighDpiPixmaps);
        setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
#if defined(Q_OS_MAC)
        setAttribute(Qt::AA_DontShowIconsInMenus);
#endif

        // Process command line options.
        QCommandLineParser parser;
        parser.addHelpOption();
        parser.addVersionOption();
#ifndef Q_OS_WIN
        QCommandLineOption fullscreenOption("fullscreen",
            QCoreApplication::translate("main", "Fill the screen with the Shotcut window."));
        parser.addOption(fullscreenOption);
#endif
        QCommandLineOption noupgradeOption("noupgrade",
            QCoreApplication::translate("main", "Hide upgrade prompt and menu item."));
        parser.addOption(noupgradeOption);
        QCommandLineOption gpuOption("gpu",
            QCoreApplication::translate("main", "Use GPU processing."));
        parser.addOption(gpuOption);
        QCommandLineOption clearRecentOption("clear-recent",
            QCoreApplication::translate("main", "Clear Recent on Exit"));
        parser.addOption(clearRecentOption);
        QCommandLineOption appDataOption("appdata",
            QCoreApplication::translate("main", "The directory for app configuration and data."),
            QCoreApplication::translate("main", "directory"));
        parser.addOption(appDataOption);
        QCommandLineOption scaleOption("QT_SCALE_FACTOR",
            QCoreApplication::translate("main", "The scale factor for a high-DPI screen"),
            QCoreApplication::translate("main", "number"));
        parser.addOption(scaleOption);
        scaleOption = QCommandLineOption("QT_SCREEN_SCALE_FACTORS",
            QCoreApplication::translate("main", "A semicolon-separated list of scale factors for each screen"),
            QCoreApplication::translate("main", "list"));
        parser.addOption(scaleOption);
        parser.addPositionalArgument("[FILE]...",
            QCoreApplication::translate("main", "Zero or more files or folders to open"));
        parser.process(arguments());
#ifdef Q_OS_WIN
        isFullScreen = false;
#else
        isFullScreen = parser.isSet(fullscreenOption);
#endif
        setProperty("noupgrade", parser.isSet(noupgradeOption));
        setProperty("clearRecent", parser.isSet(clearRecentOption));
        if (!parser.value(appDataOption).isEmpty()) {
            appDirArg = parser.value(appDataOption);
            ShotcutSettings::setAppDataForSession(appDirArg);
        }
        if (parser.isSet(gpuOption))
            Settings.setPlayerGPU(true);
        if (!parser.positionalArguments().isEmpty())
            resourceArg = parser.positionalArguments();

        // Startup logging.
        dir = Settings.appDataLocation();
        if (!dir.exists()) dir.mkpath(dir.path());
        const QString logFileName = dir.filePath("shotcut-log.txt");
        QFile::remove(logFileName);
        FileAppender* fileAppender = new FileAppender(logFileName);
        fileAppender->setFormat("[%{type:-7}] <%{function}> %{message}\n");
        cuteLogger->registerAppender(fileAppender);
#ifndef NDEBUG
        // Only log to console in dev debug builds.
        ConsoleAppender* consoleAppender = new ConsoleAppender();
        consoleAppender->setFormat(fileAppender->format());
        cuteLogger->registerAppender(consoleAppender);

        mlt_log_set_level(MLT_LOG_VERBOSE);
#else
        mlt_log_set_level(MLT_LOG_INFO);
#endif
        mlt_log_set_callback(mlt_log_handler);
        cuteLogger->logToGlobalInstance("qml", true);

        // Log some basic info.
        LOG_INFO() << "Starting Shotcut version" << SHOTCUT_VERSION;
#if defined (Q_OS_WIN)
        LOG_INFO() << "Windows version" << QSysInfo::windowsVersion();
#elif defined(Q_OS_MAC)
        LOG_INFO() << "macOS version" << QSysInfo::macVersion();
#else
        LOG_INFO() << "Linux version";
#endif
        LOG_INFO() << "number of logical cores =" << QThread::idealThreadCount();
        LOG_INFO() << "locale =" << QLocale();
        LOG_INFO() << "install dir =" <<  applicationDirPath();
        LOG_INFO() << "device pixel ratio =" << devicePixelRatio();
        Settings.log();

#if defined(Q_OS_WIN)
        if (Settings.playerGPU()) {
            QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL);
        } else if (Settings.drawMethod() >= Qt::AA_UseDesktopOpenGL &&
                   Settings.drawMethod() <= Qt::AA_UseSoftwareOpenGL) {
            QCoreApplication::setAttribute(Qt::ApplicationAttribute(Settings.drawMethod()));
        }
#endif
        // Load translations
        QString locale = Settings.language();
        dir = applicationDirPath();
    #if defined(Q_OS_MAC)
        dir.cdUp();
        dir.cd("Resources");
        dir.cd("translations");
    #elif defined(Q_OS_WIN)
        dir.cd("share");
        dir.cd("translations");
    #else
        dir.cdUp();
        dir.cd("share");
        dir.cd("shotcut");
        dir.cd("translations");
    #endif
        if (locale.startsWith("pt_"))
            locale = "pt";
        else if (locale.startsWith("en_"))
            locale = "en";
        if (qtTranslator.load("qt_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
            installTranslator(&qtTranslator);
        else if (qtTranslator.load("qt_" + locale, dir.absolutePath()))
            installTranslator(&qtTranslator);
        if (qtBaseTranslator.load("qtbase_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
            installTranslator(&qtBaseTranslator);
        else if (qtBaseTranslator.load("qtbase_" + locale, dir.absolutePath()))
            installTranslator(&qtBaseTranslator);
        if (shotcutTranslator.load("shotcut_" + Settings.language(), dir.absolutePath()))
            installTranslator(&shotcutTranslator);
    }
Ejemplo n.º 29
0
/** Execute the algorithm.
 */
void VesuvioL1ThetaResolution::exec() {
  // Set up random number generator
  m_generator.seed(static_cast<boost::mt19937::result_type>(
      static_cast<int>(getProperty("Seed"))));

  // Load the instrument workspace
  loadInstrument();

  const std::string l1DistributionWsName = getPropertyValue("L1Distribution");
  const std::string thetaDistributionWsName =
      getPropertyValue("ThetaDistribution");
  const size_t numHist = m_instWorkspace->getNumberHistograms();
  const int numEvents = getProperty("NumEvents");

  // Create output workspace of resolution
  m_outputWorkspace =
      WorkspaceFactory::Instance().create("Workspace2D", 4, numHist, numHist);

  // Set vertical axis to statistic labels
  auto specAxis = new TextAxis(4);
  specAxis->setLabel(0, "l1_Mean");
  specAxis->setLabel(1, "l1_StdDev");
  specAxis->setLabel(2, "theta_Mean");
  specAxis->setLabel(3, "theta_StdDev");
  m_outputWorkspace->replaceAxis(1, specAxis);

  // Set X axis to spectrum numbers
  m_outputWorkspace->getAxis(0)->setUnit("Label");
  auto xAxis = boost::dynamic_pointer_cast<Units::Label>(
      m_outputWorkspace->getAxis(0)->unit());
  if (xAxis)
    xAxis->setLabel("Spectrum Number");

  // Create output workspaces for distributions if required
  if (!l1DistributionWsName.empty()) {
    m_l1DistributionWs = WorkspaceFactory::Instance().create(
        m_instWorkspace, numHist, numEvents, numEvents);

    // Set Y axis
    m_l1DistributionWs->setYUnitLabel("Events");

    // Set X axis
    auto xAxis = m_l1DistributionWs->getAxis(0);
    xAxis->setUnit("Label");
    auto labelUnit = boost::dynamic_pointer_cast<Units::Label>(xAxis->unit());
    if (labelUnit)
      labelUnit->setLabel("l1");
  }

  if (!thetaDistributionWsName.empty()) {
    m_thetaDistributionWs = WorkspaceFactory::Instance().create(
        m_instWorkspace, numHist, numEvents, numEvents);

    // Set Y axis
    m_thetaDistributionWs->setYUnitLabel("Events");

    // Set X axis
    auto xAxis = m_thetaDistributionWs->getAxis(0);
    xAxis->setUnit("Label");
    auto labelUnit = boost::dynamic_pointer_cast<Units::Label>(xAxis->unit());
    if (labelUnit)
      labelUnit->setLabel("theta");
  }

  // Set up progress reporting
  Progress prog(this, 0.0, 1.0, numHist);

  // Loop for all detectors
  for (size_t i = 0; i < numHist; i++) {
    std::vector<double> l1;
    std::vector<double> theta;
    IDetector_const_sptr det = m_instWorkspace->getDetector(i);

    // Report progress
    std::stringstream report;
    report << "Detector " << det->getID();
    prog.report(report.str());
    g_log.information() << "Detector ID " << det->getID() << '\n';

    // Do simulation
    calculateDetector(det, l1, theta);

    // Calculate statistics for L1 and theta
    Statistics l1Stats = getStatistics(l1);
    Statistics thetaStats = getStatistics(theta);

    g_log.information() << "l0: mean=" << l1Stats.mean
                        << ", std.dev.=" << l1Stats.standard_deviation
                        << "\ntheta: mean=" << thetaStats.mean
                        << ", std.dev.=" << thetaStats.standard_deviation
                        << '\n';

    // Set values in output workspace
    const int specNo = m_instWorkspace->getSpectrum(i).getSpectrumNo();
    m_outputWorkspace->dataX(0)[i] = specNo;
    m_outputWorkspace->dataX(1)[i] = specNo;
    m_outputWorkspace->dataX(2)[i] = specNo;
    m_outputWorkspace->dataX(3)[i] = specNo;
    m_outputWorkspace->dataY(0)[i] = l1Stats.mean;
    m_outputWorkspace->dataY(1)[i] = l1Stats.standard_deviation;
    m_outputWorkspace->dataY(2)[i] = thetaStats.mean;
    m_outputWorkspace->dataY(3)[i] = thetaStats.standard_deviation;

    // Process data for L1 distribution
    if (m_l1DistributionWs) {
      std::vector<double> &x = m_l1DistributionWs->dataX(i);
      std::vector<double> y(numEvents, 1.0);

      std::sort(l1.begin(), l1.end());
      std::copy(l1.begin(), l1.end(), x.begin());

      m_l1DistributionWs->dataY(i) = y;

      auto &spec = m_l1DistributionWs->getSpectrum(i);
      spec.setSpectrumNo(specNo);
      spec.addDetectorID(det->getID());
    }

    // Process data for theta distribution
    if (m_thetaDistributionWs) {
      std::vector<double> &x = m_thetaDistributionWs->dataX(i);
      std::vector<double> y(numEvents, 1.0);

      std::sort(theta.begin(), theta.end());
      std::copy(theta.begin(), theta.end(), x.begin());

      m_thetaDistributionWs->dataY(i) = y;

      auto &spec = m_thetaDistributionWs->getSpectrum(i);
      spec.setSpectrumNo(specNo);
      spec.addDetectorID(det->getID());
    }
  }

  // Process the L1 distribution workspace
  if (m_l1DistributionWs) {
    const double binWidth = getProperty("L1BinWidth");
    setProperty("L1Distribution",
                processDistribution(m_l1DistributionWs, binWidth));
  }

  // Process the theta distribution workspace
  if (m_thetaDistributionWs) {
    const double binWidth = getProperty("ThetaBinWidth");
    setProperty("ThetaDistribution",
                processDistribution(m_thetaDistributionWs, binWidth));
  }

  setProperty("OutputWorkspace", m_outputWorkspace);
}
Ejemplo n.º 30
0
VideoWindow::VideoWindow(Context *context, const QDir &home)  :
    GcWindow(context), home(home), context(context), m_MediaChanged(false)
{
    setControls(NULL);
    setProperty("color", QColor(Qt::black));

    QHBoxLayout *layout = new QHBoxLayout();
    setLayout(layout);

    // config paramaters to libvlc
    const char * const vlc_args[] = {
                    "-I", "dummy", /* Don't use any interface */
                    "--ignore-config", /* Don't use VLC's config */
                    "--disable-screensaver", /* disable screensaver during playback */
#ifdef Q_OS_LINUX
                    "--no-xlib", // avoid xlib thread error messages
#endif
                    "--verbose=-1", // -1 = no output at all
                    "--quiet"
                };

    /* create an exception handler */
    //libvlc_exception_init(&exceptions);
    //vlc_exceptions(&exceptions);

    /* Load the VLC engine */
    inst = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args);
    //vlc_exceptions(&exceptions);

    /* Create a new item */

    m = NULL;
    //vlc_exceptions(&exceptions);
        
    /* Create a media player playing environement */
    mp = libvlc_media_player_new (inst);
    //vlc_exceptions(&exceptions);

    //vlc_exceptions(&exceptions);

 
    /* This is a non working code that show how to hooks into a window,
     * if we have a window around */
#ifdef Q_OS_LINUX
#if QT_VERSION > 0x050000
     x11Container = new QWidget(this); //XXX PORT TO 5.1 BROKEN CODE XXX
#else
     x11Container = new QX11EmbedContainer(this);
#endif
     layout->addWidget(x11Container);
     libvlc_media_player_set_xwindow (mp, x11Container->winId());
#endif

#ifdef WIN32
     container = new QWidget(this);
     layout->addWidget(container);
     libvlc_media_player_set_hwnd (mp, (HWND)(container->winId()));
#endif

    connect(context, SIGNAL(stop()), this, SLOT(stopPlayback()));
    connect(context, SIGNAL(start()), this, SLOT(startPlayback()));
    connect(context, SIGNAL(pause()), this, SLOT(pausePlayback()));
    connect(context, SIGNAL(seek(long)), this, SLOT(seekPlayback(long)));
    connect(context, SIGNAL(unpause()), this, SLOT(resumePlayback()));
    connect(context, SIGNAL(mediaSelected(QString)), this, SLOT(mediaSelected(QString)));

}