<commit_before>#ifndef STDC11_HH
#define STDC11_HH

#include <string>
#include <sstream>
#include <math.h>
#include <cassert>
#include <memory>
#include <iomanip>
#include <type_traits>
#include <limits>

/* **
 * This file is juste a set of convenient standard methods from std11 such
 * as smart pointer and other stuff.
 */

#define sign_form(T) typename std::make_signed<T>::type
#define sign_form_(T) std::make_signed<T>::type

namespace std
{

  template< typename T >
  inline T convert(const std::string& str)
  {
    std::istringstream iss(str);
    T obj;

    iss >> std::ws >> obj >> std::ws;

    if(!iss.eof())
      throw "dammit!";

    return obj;
  }
  const double PI = 3.14159265;

  template<typename T>
  bool is_signed_cast_safe(T a)
  {
    static_assert(std::numeric_limits<T>::is_modulo, "type must be 2 complement");
    static_assert(!std::numeric_limits<T>::is_signed, "type must be unsigned");

    typedef typename std::make_signed<T>::type signed_T;
    typedef typename std::make_unsigned<T>::type unsigned_T;

    return a < (unsigned_T) std::numeric_limits<signed_T>::max() ;
    //&& a < (unsigned)std::numeric_limits<typename std::make_signed<T>::type>::max();
  }

  template<typename C, typename T>
  bool is_cast_lossless(T a)
  {
    if(std::numeric_limits<C>::digits >= std::numeric_limits<T>::digits)
      return true;

    static_assert(std::numeric_limits<C>::is_modulo, "type must be 2 complement");

    return a <= static_cast<T>(std::numeric_limits<C>::max()) &&
           a >= static_cast<T>(std::numeric_limits<C>::min());
  }

  template <bool B, typename T1, typename T2>
  struct IF;
  template <typename T1, typename T2>
  struct IF<false,T1,T2>
  {
    typedef T2 res;
  };
  template <typename T1, typename T2>
  struct IF<true,T1,T2>
  {
    typedef T1 res;
  };

  template <typename T>
  std::string to_string (T num)
  {
    std::ostringstream ss;
    ss << std::setprecision(3) << num;
    return ss.str();
  }

  template<typename T>
  T round(T v)
  {
    return ::round(v);
  }

  template<typename T,typename ContainerT>
  void tokenize(const std::string &str,
                ContainerT &tokens,
                const std::string &delimiters = " ",
                bool trimEmpty = false)
  {
    std::string::size_type pos, lastPos = 0;
    while(true)
    {
      pos = str.find_first_of(delimiters, lastPos);
      if(pos == std::string::npos)
        break;
      else
        if(pos != lastPos || !trimEmpty)
          tokens.push_back(std::string(str.data()+lastPos,
                                       (sizeof(T))*pos-lastPos ));
      lastPos = pos + 1;
    }
  }

}

#endif

<commit_msg>Fix tokenize<commit_after>#ifndef STDC11_HH
#define STDC11_HH

#include <string>
#include <sstream>
#include <math.h>
#include <cassert>
#include <memory>
#include <iomanip>
#include <type_traits>
#include <limits>

/* **
 * This file is juste a set of convenient standard methods from std11 such
 * as smart pointer and other stuff.
 */

#define sign_form(T) typename std::make_signed<T>::type
#define sign_form_(T) std::make_signed<T>::type

namespace std
{

  template< typename T >
  inline T convert(const std::string& str)
  {
    std::istringstream iss(str);
    T obj;

    iss >> std::ws >> obj >> std::ws;

    if(!iss.eof())
      throw "dammit!";

    return obj;
  }
  const double PI = 3.14159265;

  template<typename T>
  bool is_signed_cast_safe(T a)
  {
    static_assert(std::numeric_limits<T>::is_modulo, "type must be 2 complement");
    static_assert(!std::numeric_limits<T>::is_signed, "type must be unsigned");

    typedef typename std::make_signed<T>::type signed_T;
    typedef typename std::make_unsigned<T>::type unsigned_T;

    return a < (unsigned_T) std::numeric_limits<signed_T>::max() ;
    //&& a < (unsigned)std::numeric_limits<typename std::make_signed<T>::type>::max();
  }

  template<typename C, typename T>
  bool is_cast_lossless(T a)
  {
    if(std::numeric_limits<C>::digits >= std::numeric_limits<T>::digits)
      return true;

    static_assert(std::numeric_limits<C>::is_modulo, "type must be 2 complement");

    return a <= static_cast<T>(std::numeric_limits<C>::max()) &&
           a >= static_cast<T>(std::numeric_limits<C>::min());
  }

  template <bool B, typename T1, typename T2>
  struct IF;
  template <typename T1, typename T2>
  struct IF<false,T1,T2>
  {
    typedef T2 res;
  };
  template <typename T1, typename T2>
  struct IF<true,T1,T2>
  {
    typedef T1 res;
  };

  template <typename T>
  std::string to_string (T num)
  {
    std::ostringstream ss;
    ss << std::setprecision(3) << num;
    return ss.str();
  }

  template<typename T>
  T round(T v)
  {
    return ::round(v);
  }

  template<typename T,typename ContainerT>
  void tokenize(const std::string &str,
                ContainerT &tokens,
                const std::string &delimiters = " ",
                bool trimEmpty = false)
  {
    std::string::size_type pos, lastPos = 0;
    while(true)
    {
      pos = str.find_first_of(delimiters, lastPos);
      if(pos == std::string::npos)
      {
        if(lastPos != str.length())
          tokens.push_back(std::string(str.data()+lastPos,
                                       (sizeof(T))*(str.length()-lastPos) ));
          break;
      }
      else
        if(pos != lastPos || !trimEmpty)
          tokens.push_back(std::string(str.data()+lastPos,
                                       (sizeof(T))*(pos-lastPos) ));
      lastPos = pos + 1;
    }
  }

}

#endif

<|endoftext|>


<commit_before><commit_msg>Update Euler Totient.cpp<commit_after><|endoftext|>


<commit_before>// DESCRIPTION:   GenericSLM device adapter
// COPYRIGHT:     2009-2016 Regents of the University of California
//                2016 Open Imaging, Inc.
//
// AUTHOR:        Arthur Edelstein, arthuredelstein@gmail.com, 3/17/2009
//                Mark Tsuchida (refactor/rewrite), 2016
//
// LICENSE:       This file is distributed under the BSD license.
//                License text is included with the source distribution.
//
//                This file is distributed in the hope that it will be useful,
//                but WITHOUT ANY WARRANTY; without even the implied warranty
//                of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
//                IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//                CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//                INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.

#include "GenericSLM.h"

#include "Monitors.h"
#include "OffscreenBuffer.h"
#include "SLMWindow.h"
#include "SleepBlocker.h"

#include "ModuleInterface.h"
#include "DeviceUtils.h"

#include <Windows.h>

#include <algorithm>

const char* g_GenericSLMName = "GenericSLM";
const char* g_PropName_GraphicsPort = "GraphicsPort";
const char* g_PropName_Inversion = "Inversion";
const char* g_PropName_MonoColor = "MonochromeColor";

MODULE_API void InitializeModuleData()
{
   RegisterDevice(g_GenericSLMName, MM::SLMDevice,
         "Spatial light modulator controlled through computer graphics output");
}

MODULE_API MM::Device* CreateDevice(const char* deviceName)
{
   if (deviceName == 0)
      return 0;

   if (strcmp(deviceName, g_GenericSLMName) == 0)
   {
      GenericSLM* pGenericSLM = new GenericSLM(g_GenericSLMName);
      return pGenericSLM;
   }

   return 0;
}

MODULE_API void DeleteDevice(MM::Device* pDevice)
{
   delete pDevice;
}

GenericSLM::GenericSLM(const char* name) :
   name_(name),
   window_(0),
   offscreen_(0),
   sleepBlocker_(0),
   shouldBlitInverted_(false),
   invert_(false),
   inversionStr_("Off"),
   monoColor_(SLM_COLOR_WHITE),
   monoColorStr_("White")
{
   SetErrorText(DEVICE_ERR, "An error occurred");
   // TODO We can do better than that

   availableMonitors_ = GetMonitorNames(true, false);

   // Create pre-init properties

   CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true);
   CreateProperty(MM::g_Keyword_Description, "SLM controlled by computer display adapter output", MM::String, true);

   CreateStringProperty(g_PropName_GraphicsPort, "Undefined", false, 0, true);
   AddAllowedValue(g_PropName_GraphicsPort, "Undefined", 0); // Prevent empty list
   for (unsigned i = 0; i < availableMonitors_.size(); ++i)
   {
      AddAllowedValue(g_PropName_GraphicsPort,
            availableMonitors_[i].c_str(), i + 1);
   }

   CreateStringProperty(g_PropName_Inversion, inversionStr_.c_str(), false,
         new CPropertyAction(this, &GenericSLM::OnInversion), false);
   AddAllowedValue(g_PropName_Inversion, "Off", 0);
   AddAllowedValue(g_PropName_Inversion, "On", 1);

   CreateProperty(g_PropName_MonoColor, monoColorStr_.c_str(), MM::String, false,
         new CPropertyAction(this, &GenericSLM::OnMonochromeColor), false);
   AddAllowedValue(g_PropName_MonoColor, "White", SLM_COLOR_WHITE);
   AddAllowedValue(g_PropName_MonoColor, "Red", SLM_COLOR_RED);
   AddAllowedValue(g_PropName_MonoColor, "Green", SLM_COLOR_GREEN);
   AddAllowedValue(g_PropName_MonoColor, "Blue", SLM_COLOR_BLUE);
   AddAllowedValue(g_PropName_MonoColor, "Cyan", SLM_COLOR_CYAN);
   AddAllowedValue(g_PropName_MonoColor, "Magenta", SLM_COLOR_MAGENTA);
   AddAllowedValue(g_PropName_MonoColor, "Yellow", SLM_COLOR_YELLOW);
}

GenericSLM::~GenericSLM()
{
   Shutdown();
}

void GenericSLM::GetName(char* name) const
{
   CDeviceUtils::CopyLimitedString(name, name_.c_str());
}

int GenericSLM::Initialize()
{
   Shutdown();

   long index;
   int err = GetCurrentPropertyData(g_PropName_GraphicsPort, index);
   if (err != DEVICE_OK)
      return err;
   if (index == 0)
      return DEVICE_ERR; // TODO "Graphics port not selected"
   monitorName_ = availableMonitors_[index - 1];

   if (!DetachMonitorFromDesktop(monitorName_))
   {
      monitorName_ = "";
      return DEVICE_ERR; // TODO "Cannot detach monitor from desktop"
   }

   std::vector<std::string> otherAttachedMonitors(GetMonitorNames(false, true));

   LONG posX, posY;
   GetRightmostMonitorTopRight(otherAttachedMonitors, posX, posY);

   if (!AttachMonitorToDesktop(monitorName_, posX, posY))
   {
      monitorName_ = "";
      return DEVICE_ERR; // TODO "Cannot attach monitor to desktop"
   }

   LONG x, y, w, h;
   GetMonitorRect(monitorName_, x, y, w, h);

   window_ = new SLMWindow("MM_SLM", x, y, w, h);
   window_->Show();

   offscreen_ = new OffscreenBuffer(window_->GetDC(), w, h);

   RECT mouseClipRect;
   if (GetBoundingRect(otherAttachedMonitors, mouseClipRect))
      sleepBlocker_ = new SleepBlocker(mouseClipRect);
   else
      sleepBlocker_ = new SleepBlocker();
   sleepBlocker_->Start();

   return DEVICE_OK;
}

int GenericSLM::Shutdown()
{
   if (sleepBlocker_)
   {
      sleepBlocker_->Stop();
      delete sleepBlocker_;
      sleepBlocker_ = 0;
   }

   if (offscreen_)
   {
      delete offscreen_;
      offscreen_ = 0;
   }

   if (window_)
   {
      delete window_;
      window_ = 0;
   }

   if (!monitorName_.empty())
   {
      DetachMonitorFromDesktop(monitorName_);
      monitorName_ = "";
   }

   return DEVICE_OK;
}

bool GenericSLM::Busy()
{
   // TODO We _could_ make the wait for vertical sync asynchronous
   // (Make sure first that Projector knows to wait for non-busy)
   return false;
}

unsigned int GenericSLM::GetWidth()
{
   return offscreen_ ? offscreen_->GetWidth() : 0;
}

unsigned int GenericSLM::GetHeight()
{
   return offscreen_ ? offscreen_->GetHeight() : 0;
}

unsigned int GenericSLM::GetNumberOfComponents()
{
   return 3;
}

unsigned int GenericSLM::GetBytesPerPixel()
{
   return 4;
}

int GenericSLM::SetExposure(double)
{
   // ignore for now.
   return DEVICE_OK;
}

double GenericSLM::GetExposure()
{
   return 0;
}

int GenericSLM::SetImage(unsigned char* pixels)
{
   if (!offscreen_)
      return DEVICE_ERR;

   offscreen_->DrawImage(pixels, monoColor_, invert_);
   return DEVICE_OK;
}

int GenericSLM::SetImage(unsigned int* pixels)
{
   if (!offscreen_)
      return DEVICE_ERR;

   offscreen_->DrawImage(pixels);
   shouldBlitInverted_ = invert_;
   return DEVICE_OK;
}

int GenericSLM::SetPixelsTo(unsigned char intensity)
{
   if (!offscreen_)
      return DEVICE_ERR;

   intensity ^= (invert_ ? 0xff : 0x00);

   unsigned char redMask = (monoColor_ & SLM_COLOR_RED) ? 0xff : 0x00;
   unsigned char greenMask = (monoColor_ & SLM_COLOR_GREEN) ? 0xff : 0x00;
   unsigned char blueMask = (monoColor_ & SLM_COLOR_BLUE) ? 0xff : 0x00;

   COLORREF color(RGB(intensity & redMask,
            intensity & greenMask,
            intensity & blueMask));

   offscreen_->FillWithColor(color);
   shouldBlitInverted_ = false;
   return DisplayImage();
}

int GenericSLM::SetPixelsTo(unsigned char red, unsigned char green, unsigned char blue)
{
   if (!offscreen_)
      return DEVICE_ERR;

   unsigned char xorMask = invert_ ? 0xff : 0x00;

   COLORREF color(RGB(red ^ xorMask, green ^ xorMask, blue ^ xorMask));

   offscreen_->FillWithColor(color);
   shouldBlitInverted_ = false;
   return DisplayImage();
}

int GenericSLM::DisplayImage()
{
   if (!offscreen_)
      return DEVICE_ERR;

   HDC onscreenDC = window_->GetDC();
   DWORD op = shouldBlitInverted_ ? NOTSRCCOPY : SRCCOPY;

   refreshWaiter_.WaitForVerticalBlank();
   offscreen_->BlitTo(onscreenDC, op);
   return DEVICE_OK;
}

int GenericSLM::OnInversion(MM::PropertyBase* pProp, MM::ActionType eAct)
{
   if (eAct == MM::BeforeGet)
   {
      pProp->Set(inversionStr_.c_str());
   }
   else if (eAct == MM::AfterSet)
   {
      pProp->Get(inversionStr_);
      long data;
      int ret = GetPropertyData(g_PropName_Inversion, inversionStr_.c_str(),
            data);
      if (ret != DEVICE_OK)
         return ret;
      invert_ = (data != 0);
   }

   return DEVICE_OK;
}

int GenericSLM::OnMonochromeColor(MM::PropertyBase* pProp, MM::ActionType eAct)
{
   if (eAct == MM::BeforeGet)
   {
      pProp->Set(monoColorStr_.c_str());
   }
   else if (eAct == MM::AfterSet)
   {
      pProp->Get(monoColorStr_);
      long data;
      int ret = GetPropertyData(g_PropName_MonoColor,
            monoColorStr_.c_str(), data);
      if (ret != DEVICE_OK)
         return ret;
      monoColor_ = (SLMColor)data;
   }

   return DEVICE_OK;
}
<commit_msg>GenericSLM: Add a simple test mode<commit_after>// DESCRIPTION:   GenericSLM device adapter
// COPYRIGHT:     2009-2016 Regents of the University of California
//                2016 Open Imaging, Inc.
//
// AUTHOR:        Arthur Edelstein, arthuredelstein@gmail.com, 3/17/2009
//                Mark Tsuchida (refactor/rewrite), 2016
//
// LICENSE:       This file is distributed under the BSD license.
//                License text is included with the source distribution.
//
//                This file is distributed in the hope that it will be useful,
//                but WITHOUT ANY WARRANTY; without even the implied warranty
//                of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
//                IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//                CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//                INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.

#include "GenericSLM.h"

#include "Monitors.h"
#include "OffscreenBuffer.h"
#include "SLMWindow.h"
#include "SleepBlocker.h"

#include "ModuleInterface.h"
#include "DeviceUtils.h"

#include <Windows.h>

#include <algorithm>

const char* g_GenericSLMName = "GenericSLM";
const char* g_PropName_GraphicsPort = "GraphicsPort";
const char* g_PropName_Inversion = "Inversion";
const char* g_PropName_MonoColor = "MonochromeColor";

MODULE_API void InitializeModuleData()
{
   RegisterDevice(g_GenericSLMName, MM::SLMDevice,
         "Spatial light modulator controlled through computer graphics output");
}

MODULE_API MM::Device* CreateDevice(const char* deviceName)
{
   if (deviceName == 0)
      return 0;

   if (strcmp(deviceName, g_GenericSLMName) == 0)
   {
      GenericSLM* pGenericSLM = new GenericSLM(g_GenericSLMName);
      return pGenericSLM;
   }

   return 0;
}

MODULE_API void DeleteDevice(MM::Device* pDevice)
{
   delete pDevice;
}

GenericSLM::GenericSLM(const char* name) :
   name_(name),
   window_(0),
   offscreen_(0),
   sleepBlocker_(0),
   shouldBlitInverted_(false),
   invert_(false),
   inversionStr_("Off"),
   monoColor_(SLM_COLOR_WHITE),
   monoColorStr_("White")
{
   SetErrorText(DEVICE_ERR, "An error occurred");
   // TODO We can do better than that

   availableMonitors_ = GetMonitorNames(true, false);

   // Create pre-init properties

   CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true);
   CreateProperty(MM::g_Keyword_Description, "SLM controlled by computer display adapter output", MM::String, true);

   CreateStringProperty(g_PropName_GraphicsPort, "Test128x128", false, 0, true);
   AddAllowedValue(g_PropName_GraphicsPort, "Test128x128", 0); // Prevent empty list
   for (unsigned i = 0; i < availableMonitors_.size(); ++i)
   {
      AddAllowedValue(g_PropName_GraphicsPort,
            availableMonitors_[i].c_str(), i + 1);
   }

   CreateStringProperty(g_PropName_Inversion, inversionStr_.c_str(), false,
         new CPropertyAction(this, &GenericSLM::OnInversion), false);
   AddAllowedValue(g_PropName_Inversion, "Off", 0);
   AddAllowedValue(g_PropName_Inversion, "On", 1);

   CreateProperty(g_PropName_MonoColor, monoColorStr_.c_str(), MM::String, false,
         new CPropertyAction(this, &GenericSLM::OnMonochromeColor), false);
   AddAllowedValue(g_PropName_MonoColor, "White", SLM_COLOR_WHITE);
   AddAllowedValue(g_PropName_MonoColor, "Red", SLM_COLOR_RED);
   AddAllowedValue(g_PropName_MonoColor, "Green", SLM_COLOR_GREEN);
   AddAllowedValue(g_PropName_MonoColor, "Blue", SLM_COLOR_BLUE);
   AddAllowedValue(g_PropName_MonoColor, "Cyan", SLM_COLOR_CYAN);
   AddAllowedValue(g_PropName_MonoColor, "Magenta", SLM_COLOR_MAGENTA);
   AddAllowedValue(g_PropName_MonoColor, "Yellow", SLM_COLOR_YELLOW);
}

GenericSLM::~GenericSLM()
{
   Shutdown();
}

void GenericSLM::GetName(char* name) const
{
   CDeviceUtils::CopyLimitedString(name, name_.c_str());
}

int GenericSLM::Initialize()
{
   Shutdown();

   long index;
   int err = GetCurrentPropertyData(g_PropName_GraphicsPort, index);
   if (err != DEVICE_OK)
      return err;
   if (index > 0) // Unless test mode
      monitorName_ = availableMonitors_[index - 1];

   if (!monitorName_.empty() && !DetachMonitorFromDesktop(monitorName_))
   {
      monitorName_ = "";
      return DEVICE_ERR; // TODO "Cannot detach monitor from desktop"
   }

   std::vector<std::string> otherAttachedMonitors(GetMonitorNames(false, true));

   LONG posX, posY;
   GetRightmostMonitorTopRight(otherAttachedMonitors, posX, posY);

   if (!monitorName_.empty() &&
         !AttachMonitorToDesktop(monitorName_, posX, posY))
   {
      monitorName_ = "";
      return DEVICE_ERR; // TODO "Cannot attach monitor to desktop"
   }

   LONG x, y, w, h;
   if (!monitorName_.empty())
   {
      GetMonitorRect(monitorName_, x, y, w, h);
   }
   else // Test mode
   {
      x = y = 0;
      w = h = 128;
   }

   window_ = new SLMWindow("MM_SLM", x, y, w, h);
   window_->Show();

   offscreen_ = new OffscreenBuffer(window_->GetDC(), w, h);

   RECT mouseClipRect;
   if (GetBoundingRect(otherAttachedMonitors, mouseClipRect))
      sleepBlocker_ = new SleepBlocker(mouseClipRect);
   else
      sleepBlocker_ = new SleepBlocker();
   sleepBlocker_->Start();

   return DEVICE_OK;
}

int GenericSLM::Shutdown()
{
   if (sleepBlocker_)
   {
      sleepBlocker_->Stop();
      delete sleepBlocker_;
      sleepBlocker_ = 0;
   }

   if (offscreen_)
   {
      delete offscreen_;
      offscreen_ = 0;
   }

   if (window_)
   {
      delete window_;
      window_ = 0;
   }

   if (!monitorName_.empty())
   {
      DetachMonitorFromDesktop(monitorName_);
      monitorName_ = "";
   }

   return DEVICE_OK;
}

bool GenericSLM::Busy()
{
   // TODO We _could_ make the wait for vertical sync asynchronous
   // (Make sure first that Projector knows to wait for non-busy)
   return false;
}

unsigned int GenericSLM::GetWidth()
{
   return offscreen_ ? offscreen_->GetWidth() : 0;
}

unsigned int GenericSLM::GetHeight()
{
   return offscreen_ ? offscreen_->GetHeight() : 0;
}

unsigned int GenericSLM::GetNumberOfComponents()
{
   return 3;
}

unsigned int GenericSLM::GetBytesPerPixel()
{
   return 4;
}

int GenericSLM::SetExposure(double)
{
   // ignore for now.
   return DEVICE_OK;
}

double GenericSLM::GetExposure()
{
   return 0;
}

int GenericSLM::SetImage(unsigned char* pixels)
{
   if (!offscreen_)
      return DEVICE_ERR;

   offscreen_->DrawImage(pixels, monoColor_, invert_);
   return DEVICE_OK;
}

int GenericSLM::SetImage(unsigned int* pixels)
{
   if (!offscreen_)
      return DEVICE_ERR;

   offscreen_->DrawImage(pixels);
   shouldBlitInverted_ = invert_;
   return DEVICE_OK;
}

int GenericSLM::SetPixelsTo(unsigned char intensity)
{
   if (!offscreen_)
      return DEVICE_ERR;

   intensity ^= (invert_ ? 0xff : 0x00);

   unsigned char redMask = (monoColor_ & SLM_COLOR_RED) ? 0xff : 0x00;
   unsigned char greenMask = (monoColor_ & SLM_COLOR_GREEN) ? 0xff : 0x00;
   unsigned char blueMask = (monoColor_ & SLM_COLOR_BLUE) ? 0xff : 0x00;

   COLORREF color(RGB(intensity & redMask,
            intensity & greenMask,
            intensity & blueMask));

   offscreen_->FillWithColor(color);
   shouldBlitInverted_ = false;
   return DisplayImage();
}

int GenericSLM::SetPixelsTo(unsigned char red, unsigned char green, unsigned char blue)
{
   if (!offscreen_)
      return DEVICE_ERR;

   unsigned char xorMask = invert_ ? 0xff : 0x00;

   COLORREF color(RGB(red ^ xorMask, green ^ xorMask, blue ^ xorMask));

   offscreen_->FillWithColor(color);
   shouldBlitInverted_ = false;
   return DisplayImage();
}

int GenericSLM::DisplayImage()
{
   if (!offscreen_)
      return DEVICE_ERR;

   HDC onscreenDC = window_->GetDC();
   DWORD op = shouldBlitInverted_ ? NOTSRCCOPY : SRCCOPY;

   refreshWaiter_.WaitForVerticalBlank();
   offscreen_->BlitTo(onscreenDC, op);
   return DEVICE_OK;
}

int GenericSLM::OnInversion(MM::PropertyBase* pProp, MM::ActionType eAct)
{
   if (eAct == MM::BeforeGet)
   {
      pProp->Set(inversionStr_.c_str());
   }
   else if (eAct == MM::AfterSet)
   {
      pProp->Get(inversionStr_);
      long data;
      int ret = GetPropertyData(g_PropName_Inversion, inversionStr_.c_str(),
            data);
      if (ret != DEVICE_OK)
         return ret;
      invert_ = (data != 0);
   }

   return DEVICE_OK;
}

int GenericSLM::OnMonochromeColor(MM::PropertyBase* pProp, MM::ActionType eAct)
{
   if (eAct == MM::BeforeGet)
   {
      pProp->Set(monoColorStr_.c_str());
   }
   else if (eAct == MM::AfterSet)
   {
      pProp->Get(monoColorStr_);
      long data;
      int ret = GetPropertyData(g_PropName_MonoColor,
            monoColorStr_.c_str(), data);
      if (ret != DEVICE_OK)
         return ret;
      monoColor_ = (SLMColor)data;
   }

   return DEVICE_OK;
}
<|endoftext|>


<commit_before>//
//  generateSimulatedData.cpp
//  cPWP
//
//  Created by Evan McCartney-Melstad on 12/31/14.
//  Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.
//

#include "generateSimulatedData.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <random>

int createReferenceGenome (int totalBases, double gcContent, std::string genomeOutFile) {
    std::ofstream genomeOut(genomeOutFile);
    genomeOut << ">Fake_scaffold0";
    // Set up the random number generator:
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<> dis(0, 1);

    std::string genomeString; // Will store the genome

    for (int position; position < totalBases; position++) {
        float rando = dis(gen);
        if (rando < gcContent) {
            if (dis(gen) < 0.50) {
                genomeString += "C";
            } else {
                genomeString += "G";
            }
        } else {
            if (dis(gen) < 0.50) {
                genomeString += "A";
            } else {
                genomeString += "T";
            }
        }
    }

    int baseCounter = 0;
    for(char& singleBase : genomeString) {
        if (baseCounter % 80 == 0) {
            genomeOut << "\n";
        }
        genomeOut << singleBase;
        baseCounter++;
    }

    // Now index the genome for bwa
    std::cout << "**********\nChecking if processor is available to run bwa index...";
    if (system(NULL)) puts ("OK");
    else exit (EXIT_FAILURE);
    std::string bwaIndexCommand = "bwa index " + genomeOutFile;
    system(bwaIndexCommand);
    if (system((bwaIndexCommand).c_str()) != 0) {
        std::cout << "**********\nFailure running the following command: " << bwaIndexCommand << "\n**********\n";
        exit(EXIT_FAILURE);
    } else {
        std::cout << "**********\nExecuted the following command: " << bwaIndexCommand << "\n**********\n";
    }
    return 0;
}

int generateReadsAndMap (int numIndividuals, double mutationRateStepSize, std::string libFragmentSize, std::string stdevLibFragmentSize, std::string depth, std::string readLengths, std::string randomSeed, std::string reference, std::string threads) {
/*// supply 1) number of individuals, 2) the mutation rate steps between them, 3) the base error rate, 4) the average library fragment size, 5) the standard deviation of the library fragment size, 6) the number of read pairs for each individual, 7) read lengths (per read), 8) random number generator seed

    So, for instance, if numIndividuals is 5, and mutationRateSteps is 0.01, then there will be four individuals generated with mutation rate steps of 0.01, 0.02, 0.03, and 0.04 away from the reference genome. Individual 0 is created as being identical to the reference genome (mutation rate parameter set to 0.00).
*/

    std::ofstream bamsFile;
    bamsFile.open("bamlist.txt", std::ios::out | std::ios::app);

    std::cout << "**********\nChecking if processor is available to run pirs...";
    if (system(NULL)) puts ("OK");
    else exit (EXIT_FAILURE);

    int pirsInd = 0;
    while(pirsInd <= numIndividuals) {
        double mutRate = pirsInd * mutationRateStepSize;
        // Covert the mutation rate into a string for the system command
        std::ostringstream mutStr;
        mutStr << mutRate;
        std::string mutRateString = mutStr.str();

        std::cout << "**********\nGenerating reference genome for individual " << pirsInd << " using a mutation rate of " << mutRateString << " from the reference genome\n**********\n";

        // Since we're identifying individuals by the looping variable (an int), we need to convert that to a string to use it in the file names
        std::ostringstream pirsIndSS;
        std::ostringstream pirsIndNumSS;
        pirsIndSS << "ind" << pirsInd;
        pirsIndNumSS << pirsInd;
        std::string pirsIndNum = pirsIndNumSS.str();
        std::string indName = pirsIndSS.str();
        std::string pirsGenomeSTDOUT = indName + "_genome.stdout";
        std::string pirsGenomeSTDERR = indName + "_genome.stderr";

        // Simulate the other strand of the mutated reference genome. On the first individual it should be identical to the reference (because mutStr = 0 * mutationRateStepSize
        // For this individual, we are not simulating any polymorphisms. So instead of the diploid pirs simulate command, we can use a haploid simulate command on the original reference
        std::string pirsSimSTDOUT = indName + "_reads.stdout";
        std::string pirsSimSTDERR = indName + "_reads.stderr";
        std::string indReadsPrefix = indName + "_reads";

        if (pirsInd == 0) {
            std::string pirsSimulateCommandToRun = "pirs simulate " + reference + " -l " + readLengths + " -x " + depth + " -m " + libFragmentSize + " -v " + stdevLibFragmentSize + " --no-substitution-errors --no-indel-errors --no-gc-content-bias -o " + indReadsPrefix + " >" + pirsSimSTDOUT + " 2>" + pirsSimSTDERR;
            if (system((pirsSimulateCommandToRun).c_str()) != 0) {
                std::cout << "**********\nFailure running the following command: " << pirsSimulateCommandToRun << "\n**********\n";
                exit(EXIT_FAILURE);
            } else {
                std::cout << "**********\nExecuted the following command: " << pirsSimulateCommandToRun << "\n**********\n";
            }
        } else {
            std::string pirsCommandToRun = "pirs diploid -s " + mutRateString + " -d 0.00 -v 0.00 -S 1234 -o " + indName + " " + reference + " >" + pirsGenomeSTDOUT + " 2>" + pirsGenomeSTDERR;
            if (system((pirsCommandToRun).c_str()) != 0) {
                std::cout << "**********\nFailure running the following command: " << pirsCommandToRun << "\n**********\n";
                exit(EXIT_FAILURE);
            } else {
                std::cout << "**********\nExecuted the following command: " << pirsCommandToRun << "\n**********\n";
            }
            // The following file is output by the pirs diploid command:
            std::string mutatedChromosome = indName + ".snp.fa";

            // After generating the mutated strand for each individual, we simulate reads from both strands for each individual. Parameterize the
            std::string pirsSimSTDOUT = indName + "_reads.stdout";
            std::string pirsSimSTDERR = indName + "_reads.stderr";
            std::string indReadsPrefix = indName + "_reads";
            std::string pirsSimulateCommandToRun = "pirs simulate --diploid " + reference + " " + mutatedChromosome + " -l " + readLengths + " -x " + depth + " -m " + libFragmentSize + " -v " + stdevLibFragmentSize + " --no-substitution-errors --no-indel-errors --no-gc-content-bias -o " + indReadsPrefix + " >" + pirsSimSTDOUT + " 2>" + pirsSimSTDERR;
            if (system((pirsSimulateCommandToRun).c_str()) != 0) {
                std::cout << "**********\nFailure running the following command: " << pirsSimulateCommandToRun << "\n**********\n";
                exit(EXIT_FAILURE);
            } else {
                std::cout << "**********\nExecuted the following command: " << pirsSimulateCommandToRun << "\n**********\n";
            }
        }
        // Generate the bwa mem command and then run it using a system call
        std::string R1 = indReadsPrefix + "_" + readLengths + "_" + libFragmentSize + "_1.fq";
        std::string R2 = indReadsPrefix + "_" + readLengths + "_" + libFragmentSize + "_2.fq";
        std::string bamOut = "ind" + pirsIndNum + ".bam";
        std::string bwaCommandToRun = "bwa mem -t " + threads + " " + reference + " " + R1 + " " + R2 + " | samtools view -bS - | samtools sort -T temp -o " + bamOut + " -";
        if (system((bwaCommandToRun).c_str()) != 0) {
            std::cout << "**********\nFailure running the following command: " << bwaCommandToRun << "\n**********\n";
            exit(EXIT_FAILURE);
        } else {
            std::cout << "**********\nExecuted the following command: " << bwaCommandToRun << "\n**********\n";
        }
        bamsFile << bamOut << std::endl;

        pirsInd++; // Move on to the next individual
    }

    /* Implementation with wgsim
    std::cout << "**********\nChecking if processor is available to run wgsim...";
    if (system(NULL)) puts ("Ok");
    else exit (EXIT_FAILURE);

    int step = 0;
    while(step <= numIndividuals) {
        double mutRate = step * mutationRateStepSize;
        // Covert the mutation rate into a string for the system command
        std::ostringstream mutStrs;
        mutStrs << mutRate;
        std::string mutRateString = mutStrs.str();

        std::cout << "**********\nGenerating sequence reads for individual " << step << " using a mutation rate of " << mutRateString << " from the reference genome\n**********\n";

        // Get the number of the individual as a string
        std::ostringstream stepString;
        stepString << step;
        std::string ind = stepString.str();

        // Generate the output file names as strings
        std::string R1out = "ind" + ind + "_R1.fastq";
        std::string R2out = "ind" + ind + "_R2.fastq";
        std::string polymorphismFile = "ind" + ind + "_polymorphisms.txt";

        // Generate the wgsim command and then run it using a system call
        std::string wgsimCommandToRun = "wgsim -N " + numReadPairs + " -r " + mutRateString + " -R 0.00 -X 0.00 -d " + libFragmentSize + " -s " + stdevLibFragmentSize +  " -1 " + readLengths + " -2 " + readLengths + " -S " + randomSeed + " -e0 " + reference + " " + R1out + " " + R2out + " > " + polymorphismFile; // No indels, no probability of indel extension, no base call error rates
        if (system((wgsimCommandToRun).c_str()) != 0) {
            std::cout << "**********\nFailure running the following command: " << wgsimCommandToRun << "\n**********\n";
            exit(EXIT_FAILURE);
        } else {
            std::cout << "**********\nExecuted the following command: " << wgsimCommandToRun << "\n**********\n";

        }

        // Generate the bwa mem command and then run it using a system call
        std::string bamOut = "ind" + ind + ".bam";
        std::string bwaCommandToRun = "bwa mem -t " + threads + " " + reference + " " + R1out + " " + R2out + " | samtools view -bS - | samtools sort -T temp -o " + bamOut + " -";
        if (system((bwaCommandToRun).c_str()) != 0) {
            std::cout << "**********\nFailure running the following command: " << bwaCommandToRun << "\n**********\n";
            exit(EXIT_FAILURE);
        } else {
            std::cout << "**********\nExecuted the following command: " << bwaCommandToRun << "\n**********\n";
        }
        bamsFile << bamOut << std::endl;
        step++; // Move on to the next individual
    }
    */
    bamsFile.close();
    return 0;
}

/*
 /home/evan/bin/angsd0.613/angsd -bam bamlist272.txt -out 272torts_allCounts_minmapq20minq30 -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 272tortsangsdMapQ30_allSites.log 2>&1

*/

/*
 wgsim -N 10000000 -r 0.01 -R 0.00 -X 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq > 1perc_polymorphisms.txt
 wgsim -N 10000000 -r 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq

 bwa mem -t 10 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq
 bwa mem -t 10 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq

 samtools sort -T noMut -o 1XcoverageNoErrNoMutSorted.bam 1XcoverageNoErrNoMut.bam
 samtools sort -T mut -o 1XcoverageNoErr1PercentDivergentSorted.bam 1XcoverageNoErr1PercDivergent.bam

 echo -e "1XcoverageNoErrNoMutSorted.bam\n1XcoverageNoErr1PercentDivergentSorted.bam" > bamlist2sim.txt

 /home/evan/bin/angsd0.613/angsd -bam bamlist2sim.txt -out 2tortsim1perDiv -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 2tortANGSD.log 2>&1 &

*/

/*
 Usage:   wgsim [options] <in.ref.fa> <out.read1.fq> <out.read2.fq>

 Options:
 -e FLOAT      base error rate [0.000]
 -d INT        outer distance between the two ends [500]
 -s INT        standard deviation [50]
 -N INT        number of read pairs [1000000]
 -1 INT        length of the first read [70]
 -2 INT        length of the second read [70]
 -r FLOAT      rate of mutations [0.0010]
 -R FLOAT      fraction of indels [0.15]
 -X FLOAT      probability an indel is extended [0.30]
 -S INT        seed for random generator [-1]
 -h            haplotype mode

 */

<commit_msg>Minor change<commit_after>//
//  generateSimulatedData.cpp
//  cPWP
//
//  Created by Evan McCartney-Melstad on 12/31/14.
//  Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.
//

#include "generateSimulatedData.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <random>

int createReferenceGenome (int totalBases, double gcContent, std::string genomeOutFile) {
    std::ofstream genomeOut(genomeOutFile);
    genomeOut << ">Fake_scaffold0";
    // Set up the random number generator:
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<> dis(0, 1);

    std::string genomeString; // Will store the genome

    for (int position; position < totalBases; position++) {
        float rando = dis(gen);
        if (rando < gcContent) {
            if (dis(gen) < 0.50) {
                genomeString += "C";
            } else {
                genomeString += "G";
            }
        } else {
            if (dis(gen) < 0.50) {
                genomeString += "A";
            } else {
                genomeString += "T";
            }
        }
    }

    int baseCounter = 0;
    for(char& singleBase : genomeString) {
        if (baseCounter % 80 == 0) {
            genomeOut << "\n";
        }
        genomeOut << singleBase;
        baseCounter++;
    }

    // Now index the genome for bwa
    std::cout << "**********\nChecking if processor is available to run bwa index...";
    if (system(NULL)) puts ("OK");
    else exit (EXIT_FAILURE);
    std::string bwaIndexCommand = "bwa index " + genomeOutFile;
    if (system((bwaIndexCommand).c_str()) != 0) {
        std::cout << "**********\nFailure running the following command: " << bwaIndexCommand << "\n**********\n";
        exit(EXIT_FAILURE);
    } else {
        std::cout << "**********\nExecuted the following command: " << bwaIndexCommand << "\n**********\n";
    }
    return 0;
}

int generateReadsAndMap (int numIndividuals, double mutationRateStepSize, std::string libFragmentSize, std::string stdevLibFragmentSize, std::string depth, std::string readLengths, std::string randomSeed, std::string reference, std::string threads) {
/*// supply 1) number of individuals, 2) the mutation rate steps between them, 3) the base error rate, 4) the average library fragment size, 5) the standard deviation of the library fragment size, 6) the number of read pairs for each individual, 7) read lengths (per read), 8) random number generator seed

    So, for instance, if numIndividuals is 5, and mutationRateSteps is 0.01, then there will be four individuals generated with mutation rate steps of 0.01, 0.02, 0.03, and 0.04 away from the reference genome. Individual 0 is created as being identical to the reference genome (mutation rate parameter set to 0.00).
*/

    std::ofstream bamsFile;
    bamsFile.open("bamlist.txt", std::ios::out | std::ios::app);

    std::cout << "**********\nChecking if processor is available to run pirs...";
    if (system(NULL)) puts ("OK");
    else exit (EXIT_FAILURE);

    int pirsInd = 0;
    while(pirsInd <= numIndividuals) {
        double mutRate = pirsInd * mutationRateStepSize;
        // Covert the mutation rate into a string for the system command
        std::ostringstream mutStr;
        mutStr << mutRate;
        std::string mutRateString = mutStr.str();

        std::cout << "**********\nGenerating reference genome for individual " << pirsInd << " using a mutation rate of " << mutRateString << " from the reference genome\n**********\n";

        // Since we're identifying individuals by the looping variable (an int), we need to convert that to a string to use it in the file names
        std::ostringstream pirsIndSS;
        std::ostringstream pirsIndNumSS;
        pirsIndSS << "ind" << pirsInd;
        pirsIndNumSS << pirsInd;
        std::string pirsIndNum = pirsIndNumSS.str();
        std::string indName = pirsIndSS.str();
        std::string pirsGenomeSTDOUT = indName + "_genome.stdout";
        std::string pirsGenomeSTDERR = indName + "_genome.stderr";

        // Simulate the other strand of the mutated reference genome. On the first individual it should be identical to the reference (because mutStr = 0 * mutationRateStepSize
        // For this individual, we are not simulating any polymorphisms. So instead of the diploid pirs simulate command, we can use a haploid simulate command on the original reference
        std::string pirsSimSTDOUT = indName + "_reads.stdout";
        std::string pirsSimSTDERR = indName + "_reads.stderr";
        std::string indReadsPrefix = indName + "_reads";

        if (pirsInd == 0) {
            std::string pirsSimulateCommandToRun = "pirs simulate " + reference + " -l " + readLengths + " -x " + depth + " -m " + libFragmentSize + " -v " + stdevLibFragmentSize + " --no-substitution-errors --no-indel-errors --no-gc-content-bias -o " + indReadsPrefix + " >" + pirsSimSTDOUT + " 2>" + pirsSimSTDERR;
            if (system((pirsSimulateCommandToRun).c_str()) != 0) {
                std::cout << "**********\nFailure running the following command: " << pirsSimulateCommandToRun << "\n**********\n";
                exit(EXIT_FAILURE);
            } else {
                std::cout << "**********\nExecuted the following command: " << pirsSimulateCommandToRun << "\n**********\n";
            }
        } else {
            std::string pirsCommandToRun = "pirs diploid -s " + mutRateString + " -d 0.00 -v 0.00 -S 1234 -o " + indName + " " + reference + " >" + pirsGenomeSTDOUT + " 2>" + pirsGenomeSTDERR;
            if (system((pirsCommandToRun).c_str()) != 0) {
                std::cout << "**********\nFailure running the following command: " << pirsCommandToRun << "\n**********\n";
                exit(EXIT_FAILURE);
            } else {
                std::cout << "**********\nExecuted the following command: " << pirsCommandToRun << "\n**********\n";
            }
            // The following file is output by the pirs diploid command:
            std::string mutatedChromosome = indName + ".snp.fa";

            // After generating the mutated strand for each individual, we simulate reads from both strands for each individual. Parameterize the
            std::string pirsSimSTDOUT = indName + "_reads.stdout";
            std::string pirsSimSTDERR = indName + "_reads.stderr";
            std::string indReadsPrefix = indName + "_reads";
            std::string pirsSimulateCommandToRun = "pirs simulate --diploid " + reference + " " + mutatedChromosome + " -l " + readLengths + " -x " + depth + " -m " + libFragmentSize + " -v " + stdevLibFragmentSize + " --no-substitution-errors --no-indel-errors --no-gc-content-bias -o " + indReadsPrefix + " >" + pirsSimSTDOUT + " 2>" + pirsSimSTDERR;
            if (system((pirsSimulateCommandToRun).c_str()) != 0) {
                std::cout << "**********\nFailure running the following command: " << pirsSimulateCommandToRun << "\n**********\n";
                exit(EXIT_FAILURE);
            } else {
                std::cout << "**********\nExecuted the following command: " << pirsSimulateCommandToRun << "\n**********\n";
            }
        }
        // Generate the bwa mem command and then run it using a system call
        std::string R1 = indReadsPrefix + "_" + readLengths + "_" + libFragmentSize + "_1.fq";
        std::string R2 = indReadsPrefix + "_" + readLengths + "_" + libFragmentSize + "_2.fq";
        std::string bamOut = "ind" + pirsIndNum + ".bam";
        std::string bwaCommandToRun = "bwa mem -t " + threads + " " + reference + " " + R1 + " " + R2 + " | samtools view -bS - | samtools sort -T temp -o " + bamOut + " -";
        if (system((bwaCommandToRun).c_str()) != 0) {
            std::cout << "**********\nFailure running the following command: " << bwaCommandToRun << "\n**********\n";
            exit(EXIT_FAILURE);
        } else {
            std::cout << "**********\nExecuted the following command: " << bwaCommandToRun << "\n**********\n";
        }
        bamsFile << bamOut << std::endl;

        pirsInd++; // Move on to the next individual
    }

    /* Implementation with wgsim
    std::cout << "**********\nChecking if processor is available to run wgsim...";
    if (system(NULL)) puts ("Ok");
    else exit (EXIT_FAILURE);

    int step = 0;
    while(step <= numIndividuals) {
        double mutRate = step * mutationRateStepSize;
        // Covert the mutation rate into a string for the system command
        std::ostringstream mutStrs;
        mutStrs << mutRate;
        std::string mutRateString = mutStrs.str();

        std::cout << "**********\nGenerating sequence reads for individual " << step << " using a mutation rate of " << mutRateString << " from the reference genome\n**********\n";

        // Get the number of the individual as a string
        std::ostringstream stepString;
        stepString << step;
        std::string ind = stepString.str();

        // Generate the output file names as strings
        std::string R1out = "ind" + ind + "_R1.fastq";
        std::string R2out = "ind" + ind + "_R2.fastq";
        std::string polymorphismFile = "ind" + ind + "_polymorphisms.txt";

        // Generate the wgsim command and then run it using a system call
        std::string wgsimCommandToRun = "wgsim -N " + numReadPairs + " -r " + mutRateString + " -R 0.00 -X 0.00 -d " + libFragmentSize + " -s " + stdevLibFragmentSize +  " -1 " + readLengths + " -2 " + readLengths + " -S " + randomSeed + " -e0 " + reference + " " + R1out + " " + R2out + " > " + polymorphismFile; // No indels, no probability of indel extension, no base call error rates
        if (system((wgsimCommandToRun).c_str()) != 0) {
            std::cout << "**********\nFailure running the following command: " << wgsimCommandToRun << "\n**********\n";
            exit(EXIT_FAILURE);
        } else {
            std::cout << "**********\nExecuted the following command: " << wgsimCommandToRun << "\n**********\n";

        }

        // Generate the bwa mem command and then run it using a system call
        std::string bamOut = "ind" + ind + ".bam";
        std::string bwaCommandToRun = "bwa mem -t " + threads + " " + reference + " " + R1out + " " + R2out + " | samtools view -bS - | samtools sort -T temp -o " + bamOut + " -";
        if (system((bwaCommandToRun).c_str()) != 0) {
            std::cout << "**********\nFailure running the following command: " << bwaCommandToRun << "\n**********\n";
            exit(EXIT_FAILURE);
        } else {
            std::cout << "**********\nExecuted the following command: " << bwaCommandToRun << "\n**********\n";
        }
        bamsFile << bamOut << std::endl;
        step++; // Move on to the next individual
    }
    */
    bamsFile.close();
    return 0;
}

/*
 /home/evan/bin/angsd0.613/angsd -bam bamlist272.txt -out 272torts_allCounts_minmapq20minq30 -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 272tortsangsdMapQ30_allSites.log 2>&1

*/

/*
 wgsim -N 10000000 -r 0.01 -R 0.00 -X 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq > 1perc_polymorphisms.txt
 wgsim -N 10000000 -r 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq

 bwa mem -t 10 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq
 bwa mem -t 10 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq

 samtools sort -T noMut -o 1XcoverageNoErrNoMutSorted.bam 1XcoverageNoErrNoMut.bam
 samtools sort -T mut -o 1XcoverageNoErr1PercentDivergentSorted.bam 1XcoverageNoErr1PercDivergent.bam

 echo -e "1XcoverageNoErrNoMutSorted.bam\n1XcoverageNoErr1PercentDivergentSorted.bam" > bamlist2sim.txt

 /home/evan/bin/angsd0.613/angsd -bam bamlist2sim.txt -out 2tortsim1perDiv -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 2tortANGSD.log 2>&1 &

*/

/*
 Usage:   wgsim [options] <in.ref.fa> <out.read1.fq> <out.read2.fq>

 Options:
 -e FLOAT      base error rate [0.000]
 -d INT        outer distance between the two ends [500]
 -s INT        standard deviation [50]
 -N INT        number of read pairs [1000000]
 -1 INT        length of the first read [70]
 -2 INT        length of the second read [70]
 -r FLOAT      rate of mutations [0.0010]
 -R FLOAT      fraction of indels [0.15]
 -X FLOAT      probability an indel is extended [0.30]
 -S INT        seed for random generator [-1]
 -h            haplotype mode

 */

<|endoftext|>


<commit_before>/** feature-selection.cc ---
 *
 * Copyright (C) 2011 OpenCog Foundation
 *
 * Author: Nil Geisweiller <nilg@desktop>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <iostream>
#include <fstream>
#include <memory>
#include <stdio.h>

#include <boost/program_options.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/assign/list_of.hpp>

#include <opencog/util/mt19937ar.h>
#include <opencog/util/Logger.h>
#include <opencog/util/lru_cache.h>
#include <opencog/util/algorithm.h>
#include <opencog/util/iostreamContainer.h>
#include <opencog/util/log_prog_name.h>

#include <opencog/comboreduct/combo/table.h>

#include <opencog/learning/moses/moses/optimization.h>

#include "feature-selection.h"
#include "../feature_optimization.h"
#include "../feature_scorer.h"

using namespace boost::program_options;
using boost::lexical_cast;
using boost::assign::list_of;
using namespace std;
using namespace opencog;
using namespace combo;

const static unsigned max_filename_size = 255;

/**
 * Display error message about unsupported type and exit
 */
void unsupported_type_exit(const type_tree& tt) {
    std::cerr << "error: type " << tt << "currently not supported" << std::endl;
    exit(1);
}
void unsupported_type_exit(type_node type) {
    unsupported_type_exit(type_tree(type));
}

int main(int argc, char** argv) {

    unsigned long rand_seed;
    string log_level;
    string log_file;
    bool log_file_dep_opt;
    feature_selection_parameters fs_params;

    // Declare the supported options.
    options_description desc("Allowed options");
    desc.add_options()
        ("help,h", "Produce help message.\n")
        (opt_desc_str(rand_seed_opt).c_str(),
         value<unsigned long>(&rand_seed)->default_value(1),
         "Random seed.\n")
        (opt_desc_str(algo_opt).c_str(),
         value<string>(&fs_params.algorithm)->default_value(hc),
         string("Feature selection algorithm. Supported algorithms are ").append(un).append(" for univariate, ").append(sa).append(" for simulated annealing, ").append(hc).append(" for hillclimbing, ").append(inc).append(" for incremental.").c_str())
        (opt_desc_str(input_data_file_opt).c_str(),
         value<string>(&fs_params.input_file),
         "Input table file, DSV file using comman, whitespace or tabulation as seperator.\n")
        (opt_desc_str(output_file_opt).c_str(),
         value<string>(&fs_params.output_file),
         "File where to save the results. If empty then it outputs on the stdout.\n")
        (opt_desc_str(initial_feature_opt).c_str(), value<vector<string> >(&fs_params.initial_features),
         "Initial feature to search from. This option can be used as many times as features to include in the initial feature set. An initial feature set close to the one maximizing the feature quality measure can greatly increase feature selection speed.\n")
        (opt_desc_str(max_evals_opt).c_str(),
         value<unsigned>(&fs_params.max_evals)->default_value(10000),
         "Maximum number of fitness function evaluations.\n")
        (opt_desc_str(log_level_opt).c_str(),
         value<string>(&log_level)->default_value("DEBUG"),
         "Log level, possible levels are NONE, ERROR, WARN, INFO, DEBUG, FINE. Case does not matter.\n")
        (opt_desc_str(log_file_dep_opt_opt).c_str(),
         string("The name of the log is determined by the options, for instance if feature-selection is called with -r 123 the log name is feature-selection_random-seed_123.log. Note that the name will be truncated in order not to be longer than ").append(lexical_cast<string>(max_filename_size)).append(" characters.\n").c_str())
        (opt_desc_str(log_file_opt).c_str(),
         value<string>(&log_file)->default_value(default_log_file),
         string("File name where to write the log. This option is overwritten by ").append(log_file_dep_opt_opt.first).append(".\n").c_str())
        (opt_desc_str(cache_size_opt).c_str(),
         value<unsigned long>(&fs_params.cache_size)->default_value(1000000),
         "Cache size, so that identical candidates are not re-evaluated, 0 means no cache.\n")
        (opt_desc_str(complexity_penalty_intensity_opt).c_str(),
         value<double>(&fs_params.cpi)->default_value(0.0),
         "Intensity of the feature complexity penalty, in [0,+Inf), 0 means no complexity penalty.\n")
        (opt_desc_str(confidence_penalty_intensity_opt).c_str(),
         value<double>(&fs_params.confi)->default_value(1.0),
         "Intensity of the confidence penalty, in [0,+Inf), 0 means no confidence penalty. This parameter influences how much importance we attribute to the confidence of the feature quality measure. The less samples in the data set, the more features the less confidence in the feature set quality measure.\n")
        (opt_desc_str(resources_opt).c_str(),
         value<double>(&fs_params.resources)->default_value(10000),
         "Resources allocated to the learning algorithm that take in input the selected features. More resource means that the feature set can be larger (as long as it has enough confidence). In this case the algo is supposed to be MOSES and the resources is the number of evaluations.\n")
        (opt_desc_str(max_score_opt).c_str(),
         value<double>(&fs_params.max_score)->default_value(1),
         "For MOSES based algorithms. The max score to reach, once reached feature selection halts.\n")
        (opt_desc_str(hc_fraction_of_remaining_opt).c_str(),
         value<unsigned>(&fs_params.hc_fraction_of_remaining)->default_value(10),
         "Hillclimbing parameter. Determine the fraction of the remaining number of eval to use for the current iteration.\n")
        (opt_desc_str(inc_intensity_opt).c_str(),
         value<double>(&fs_params.inc_intensity)->default_value(0),
         "Incremental Selection parameter. Value between 0 and 1. 0 means all features are selected, 1 corresponds to the stronger selection pressure, probably no features are selected at 1.\n")
        (opt_desc_str(inc_target_size_opt).c_str(),
         value<unsigned>(&fs_params.inc_target_size)->default_value(0),
         "Incremental Selection parameter. The number of features to attempt to select. This option overwrites feature-selection-intensity. 0 means disabled.\n")
        (opt_desc_str(inc_target_size_epsilon_opt).c_str(),
         value<double>(&fs_params.inc_target_size_epsilon)->default_value(0.001),
         "Incremental Selection parameter. Error interval tolerated to control the automatically adjust feature selection intensity when using option -C.\n")
        (opt_desc_str(inc_redundant_intensity_opt).c_str(),
         value<double>(&fs_params.inc_rintensity)->default_value(0.1),
         "Incremental Selection parameter. Value between 0 and 1. 0 means no redundant features are discarded, 1 means redudant features are maximally discarded. This option is only active when feature selection is active.\n")
        (opt_desc_str(inc_interaction_terms_opt).c_str(),
         value<unsigned>(&fs_params.inc_interaction_terms)->default_value(1),
         "Incremental Selection parameter. Maximum number of interaction terms considered during feature selection. Higher values make the feature selection more accurate but is computationally expensive.\n")
        ;

    variables_map vm;
    store(parse_command_line(argc, argv, desc), vm);
    notify(vm);

    // set flags
    log_file_dep_opt = vm.count(log_file_dep_opt_opt.first) > 0;

    // help
    if (vm.count("help") || argc == 1) {
        cout << desc << std::endl;
        return 1;
    }

    // set log
    if(log_file_dep_opt) {
        std::set<std::string> ignore_opt = list_of(log_file_dep_opt_opt.first);
        log_file = determine_log_name(default_log_file_prefix,
                                      vm, ignore_opt,
                                      std::string(".").append(default_log_file_suffix));
    }

    type_node inferred_type = inferDataType(fs_params.input_file);

    // remove log_file
    remove(log_file.c_str());
    logger().setFilename(log_file);
    logger().setLevel(logger().getLevelFromString(log_level));
    logger().setBackTraceLevel(Logger::ERROR);

    // init random generator
    MT19937RandGen rng(rand_seed);

    // Logger
    logger().info("Start feature-selection, read input file");
    // ~Logger

    if(inferred_type == id::boolean_type) {
        // read input_data_file file
        truth_table table(fs_params.input_file);
        feature_selection(table, fs_params, rng);
    } else {
        unsupported_type_exit(inferred_type);
    }
}
<commit_msg>improved feature-selection log<commit_after>/** feature-selection.cc ---
 *
 * Copyright (C) 2011 OpenCog Foundation
 *
 * Author: Nil Geisweiller <nilg@desktop>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <iostream>
#include <fstream>
#include <memory>
#include <stdio.h>

#include <boost/program_options.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/assign/list_of.hpp>

#include <opencog/util/mt19937ar.h>
#include <opencog/util/Logger.h>
#include <opencog/util/lru_cache.h>
#include <opencog/util/algorithm.h>
#include <opencog/util/iostreamContainer.h>
#include <opencog/util/log_prog_name.h>

#include <opencog/comboreduct/combo/table.h>

#include <opencog/learning/moses/moses/optimization.h>

#include "feature-selection.h"
#include "../feature_optimization.h"
#include "../feature_scorer.h"

using namespace boost::program_options;
using boost::lexical_cast;
using boost::assign::list_of;
using namespace std;
using namespace opencog;
using namespace combo;

const static unsigned max_filename_size = 255;

/**
 * Display error message about unsupported type and exit
 */
void unsupported_type_exit(const type_tree& tt) {
    std::cerr << "error: type " << tt << "currently not supported" << std::endl;
    exit(1);
}
void unsupported_type_exit(type_node type) {
    unsupported_type_exit(type_tree(type));
}

int main(int argc, char** argv) {

    unsigned long rand_seed;
    string log_level;
    string log_file;
    bool log_file_dep_opt;
    feature_selection_parameters fs_params;

    // Declare the supported options.
    options_description desc("Allowed options");
    desc.add_options()
        ("help,h", "Produce help message.\n")
        (opt_desc_str(rand_seed_opt).c_str(),
         value<unsigned long>(&rand_seed)->default_value(1),
         "Random seed.\n")
        (opt_desc_str(algo_opt).c_str(),
         value<string>(&fs_params.algorithm)->default_value(hc),
         string("Feature selection algorithm. Supported algorithms are ").append(un).append(" for univariate, ").append(sa).append(" for simulated annealing, ").append(hc).append(" for hillclimbing, ").append(inc).append(" for incremental.").c_str())
        (opt_desc_str(input_data_file_opt).c_str(),
         value<string>(&fs_params.input_file),
         "Input table file, DSV file using comman, whitespace or tabulation as seperator.\n")
        (opt_desc_str(output_file_opt).c_str(),
         value<string>(&fs_params.output_file),
         "File where to save the results. If empty then it outputs on the stdout.\n")
        (opt_desc_str(initial_feature_opt).c_str(), value<vector<string> >(&fs_params.initial_features),
         "Initial feature to search from. This option can be used as many times as features to include in the initial feature set. An initial feature set close to the one maximizing the feature quality measure can greatly increase feature selection speed.\n")
        (opt_desc_str(max_evals_opt).c_str(),
         value<unsigned>(&fs_params.max_evals)->default_value(10000),
         "Maximum number of fitness function evaluations.\n")
        (opt_desc_str(log_level_opt).c_str(),
         value<string>(&log_level)->default_value("DEBUG"),
         "Log level, possible levels are NONE, ERROR, WARN, INFO, DEBUG, FINE. Case does not matter.\n")
        (opt_desc_str(log_file_dep_opt_opt).c_str(),
         string("The name of the log is determined by the options, for instance if feature-selection is called with -r 123 the log name is feature-selection_random-seed_123.log. Note that the name will be truncated in order not to be longer than ").append(lexical_cast<string>(max_filename_size)).append(" characters.\n").c_str())
        (opt_desc_str(log_file_opt).c_str(),
         value<string>(&log_file)->default_value(default_log_file),
         string("File name where to write the log. This option is overwritten by ").append(log_file_dep_opt_opt.first).append(".\n").c_str())
        (opt_desc_str(cache_size_opt).c_str(),
         value<unsigned long>(&fs_params.cache_size)->default_value(1000000),
         "Cache size, so that identical candidates are not re-evaluated, 0 means no cache.\n")
        (opt_desc_str(complexity_penalty_intensity_opt).c_str(),
         value<double>(&fs_params.cpi)->default_value(0.0),
         "Intensity of the feature complexity penalty, in [0,+Inf), 0 means no complexity penalty.\n")
        (opt_desc_str(confidence_penalty_intensity_opt).c_str(),
         value<double>(&fs_params.confi)->default_value(1.0),
         "Intensity of the confidence penalty, in [0,+Inf), 0 means no confidence penalty. This parameter influences how much importance we attribute to the confidence of the feature quality measure. The less samples in the data set, the more features the less confidence in the feature set quality measure.\n")
        (opt_desc_str(resources_opt).c_str(),
         value<double>(&fs_params.resources)->default_value(10000),
         "Resources allocated to the learning algorithm that take in input the selected features. More resource means that the feature set can be larger (as long as it has enough confidence). In this case the algo is supposed to be MOSES and the resources is the number of evaluations.\n")
        (opt_desc_str(max_score_opt).c_str(),
         value<double>(&fs_params.max_score)->default_value(1),
         "For MOSES based algorithms. The max score to reach, once reached feature selection halts.\n")
        (opt_desc_str(hc_fraction_of_remaining_opt).c_str(),
         value<unsigned>(&fs_params.hc_fraction_of_remaining)->default_value(10),
         "Hillclimbing parameter. Determine the fraction of the remaining number of eval to use for the current iteration.\n")
        (opt_desc_str(inc_intensity_opt).c_str(),
         value<double>(&fs_params.inc_intensity)->default_value(0),
         "Incremental Selection parameter. Value between 0 and 1. 0 means all features are selected, 1 corresponds to the stronger selection pressure, probably no features are selected at 1.\n")
        (opt_desc_str(inc_target_size_opt).c_str(),
         value<unsigned>(&fs_params.inc_target_size)->default_value(0),
         "Incremental Selection parameter. The number of features to attempt to select. This option overwrites feature-selection-intensity. 0 means disabled.\n")
        (opt_desc_str(inc_target_size_epsilon_opt).c_str(),
         value<double>(&fs_params.inc_target_size_epsilon)->default_value(0.001),
         "Incremental Selection parameter. Error interval tolerated to control the automatically adjust feature selection intensity when using option -C.\n")
        (opt_desc_str(inc_redundant_intensity_opt).c_str(),
         value<double>(&fs_params.inc_rintensity)->default_value(0.1),
         "Incremental Selection parameter. Value between 0 and 1. 0 means no redundant features are discarded, 1 means redudant features are maximally discarded. This option is only active when feature selection is active.\n")
        (opt_desc_str(inc_interaction_terms_opt).c_str(),
         value<unsigned>(&fs_params.inc_interaction_terms)->default_value(1),
         "Incremental Selection parameter. Maximum number of interaction terms considered during feature selection. Higher values make the feature selection more accurate but is computationally expensive.\n")
        ;

    variables_map vm;
    store(parse_command_line(argc, argv, desc), vm);
    notify(vm);

    // set flags
    log_file_dep_opt = vm.count(log_file_dep_opt_opt.first) > 0;

    // help
    if (vm.count("help") || argc == 1) {
        cout << desc << std::endl;
        return 1;
    }

    // set log
    if(log_file_dep_opt) {
        std::set<std::string> ignore_opt = list_of(log_file_dep_opt_opt.first);
        log_file = determine_log_name(default_log_file_prefix,
                                      vm, ignore_opt,
                                      std::string(".").append(default_log_file_suffix));
    }

    type_node inferred_type = inferDataType(fs_params.input_file);

    // remove log_file
    remove(log_file.c_str());
    logger().setFilename(log_file);
    logger().setLevel(logger().getLevelFromString(log_level));
    logger().setBackTraceLevel(Logger::ERROR);

    // init random generator
    MT19937RandGen rng(rand_seed);

    // Logger
    logger().info("Read input file %s", fs_params.input_file.c_str());
    // ~Logger

    if(inferred_type == id::boolean_type) {
        // read input_data_file file
        truth_table table(fs_params.input_file);
        feature_selection(table, fs_params, rng);
    } else {
        unsupported_type_exit(inferred_type);
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"

#include "dp_gui_shared.hxx"
#include "dp_gui.h"
#include "dp_gui_theextmgr.hxx"
#include "cppuhelper/implbase2.hxx"
#include "cppuhelper/implementationentry.hxx"
#include "unotools/configmgr.hxx"
#include "comphelper/servicedecl.hxx"
#include "comphelper/unwrapargs.hxx"
#include <i18npool/mslangid.hxx>
#include "vcl/svapp.hxx"
#include "vcl/msgbox.hxx"
#include "com/sun/star/lang/XServiceInfo.hpp"
#include "com/sun/star/task/XJobExecutor.hpp"
#include "com/sun/star/ui/dialogs/XAsynchronousExecutableDialog.hpp"

#include "boost/bind.hpp"
#include "license_dialog.hxx"
#include "dp_gui_dialog2.hxx"

using namespace ::dp_misc;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

using ::rtl::OUString;

namespace css = ::com::sun::star;
namespace dp_gui {

//==============================================================================
class MyApp : public Application, private boost::noncopyable
{
public:
    MyApp();
    virtual ~MyApp();

    // Application
    virtual void Main();
};

//______________________________________________________________________________
MyApp::~MyApp()
{
}

//______________________________________________________________________________
MyApp::MyApp()
{
}

//______________________________________________________________________________
void MyApp::Main()
{
}

//##############################################################################

namespace
{
    struct ProductName
        : public rtl::Static< String, ProductName > {};
    struct Version
        : public rtl::Static< String, Version > {};
    struct AboutBoxVersion
        : public rtl::Static< String, AboutBoxVersion > {};
    struct OOOVendor
        : public rtl::Static< String, OOOVendor > {};
    struct Extension
        : public rtl::Static< String, Extension > {};
}

void ReplaceProductNameHookProc( String& rStr )
{
    static int nAll = 0, nPro = 0;

    nAll++;
    if ( rStr.SearchAscii( "%PRODUCT" ) != STRING_NOTFOUND )
    {
        String &rProductName = ProductName::get();
        String &rVersion = Version::get();
        String &rAboutBoxVersion = AboutBoxVersion::get();
        String &rExtension = Extension::get();
        String &rOOOVendor = OOOVendor::get();

        if ( !rProductName.Len() )
        {
            rtl::OUString aTmp;
            Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME );
            aRet >>= aTmp;
            rProductName = aTmp;

            aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTVERSION );
            aRet >>= aTmp;
            rVersion = aTmp;

            aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::ABOUTBOXPRODUCTVERSION );
            aRet >>= aTmp;
            rOOOVendor = aTmp;

            aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::OOOVENDOR );
            aRet >>= aTmp;
            rAboutBoxVersion = aTmp;

            if ( !rExtension.Len() )
            {
                aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTEXTENSION );
                aRet >>= aTmp;
                rExtension = aTmp;
            }
        }

        nPro++;
        rStr.SearchAndReplaceAllAscii( "%PRODUCTNAME", rProductName );
        rStr.SearchAndReplaceAllAscii( "%PRODUCTVERSION", rVersion );
        rStr.SearchAndReplaceAllAscii( "%ABOUTBOXPRODUCTVERSION", rAboutBoxVersion );
        rStr.SearchAndReplaceAllAscii( "%OOOVENDOR", rOOOVendor );
        rStr.SearchAndReplaceAllAscii( "%PRODUCTEXTENSION", rExtension );
    }
}

//==============================================================================
class ServiceImpl
    : public ::cppu::WeakImplHelper2<ui::dialogs::XAsynchronousExecutableDialog,
                                     task::XJobExecutor>
{
    Reference<XComponentContext> const m_xComponentContext;
    boost::optional< Reference<awt::XWindow> > /* const */ m_parent;
    boost::optional<OUString> /* const */ m_view;
    /* if true then this service is running in an unopkg process and not in an office process */
    boost::optional<sal_Bool> /* const */ m_unopkg;
    boost::optional<OUString> m_extensionURL;
    OUString m_initialTitle;
    bool m_bShowUpdateOnly;

public:
    ServiceImpl( Sequence<Any> const & args,
                 Reference<XComponentContext> const & xComponentContext );

    // XAsynchronousExecutableDialog
    virtual void SAL_CALL setDialogTitle( OUString const & aTitle )
        throw (RuntimeException);
    virtual void SAL_CALL startExecuteModal(
        Reference< ui::dialogs::XDialogClosedListener > const & xListener )
        throw (RuntimeException);

    // XJobExecutor
    virtual void SAL_CALL trigger( OUString const & event )
        throw (RuntimeException);
};

//______________________________________________________________________________
ServiceImpl::ServiceImpl( Sequence<Any> const& args,
                          Reference<XComponentContext> const& xComponentContext)
    : m_xComponentContext(xComponentContext),
      m_bShowUpdateOnly( false )
{
    try {
        comphelper::unwrapArgs( args, m_parent, m_view, m_unopkg );
        return;
    } catch (css::lang::IllegalArgumentException & ) {
    }
    try {
        comphelper::unwrapArgs( args, m_extensionURL);
    } catch (css::lang::IllegalArgumentException & ) {
    }

    ResHookProc pProc = ResMgr::GetReadStringHook();
    if ( !pProc )
        ResMgr::SetReadStringHook( ReplaceProductNameHookProc );
}

// XAsynchronousExecutableDialog
//______________________________________________________________________________
void ServiceImpl::setDialogTitle( OUString const & title )
    throw (RuntimeException)
{
    if ( dp_gui::TheExtensionManager::s_ExtMgr.is() )
    {
        const ::vos::OGuard guard( Application::GetSolarMutex() );
        ::rtl::Reference< ::dp_gui::TheExtensionManager > dialog(
            ::dp_gui::TheExtensionManager::get( m_xComponentContext,
                                                m_parent ? *m_parent : Reference<awt::XWindow>(),
                                                m_extensionURL ? *m_extensionURL : OUString() ) );
        dialog->SetText( title );
    }
    else
        m_initialTitle = title;
}

//______________________________________________________________________________
void ServiceImpl::startExecuteModal(
    Reference< ui::dialogs::XDialogClosedListener > const & xListener )
    throw (RuntimeException)
{
    bool bCloseDialog = true;  // only used if m_bShowUpdateOnly is true
    ::std::auto_ptr<Application> app;
    //ToDo: synchronize access to s_dialog !!!
    if (! dp_gui::TheExtensionManager::s_ExtMgr.is())
    {
        const bool bAppUp = (GetpApp() != 0);
        bool bOfficePipePresent;
        try {
            bOfficePipePresent = dp_misc::office_is_running();
        }
        catch (Exception & exc) {
            if (bAppUp) {
                const vos::OGuard guard( Application::GetSolarMutex() );
                std::auto_ptr<ErrorBox> box(
                    new ErrorBox( Application::GetActiveTopWindow(),
                                  WB_OK, exc.Message ) );
                box->Execute();
            }
            throw;
        }

        if (! bOfficePipePresent) {
            OSL_ASSERT( ! bAppUp );
            app.reset( new MyApp );
            if (! InitVCL( Reference<lang::XMultiServiceFactory>(
                               m_xComponentContext->getServiceManager(),
                               UNO_QUERY_THROW ) ))
                throw RuntimeException( OUSTR("Cannot initialize VCL!"),
                                        static_cast<OWeakObject *>(this) );
            AllSettings as = app->GetSettings();
            OUString slang;
            if (! (::utl::ConfigManager::GetDirectConfigProperty(
                       ::utl::ConfigManager::LOCALE ) >>= slang))
                throw RuntimeException( OUSTR("Cannot determine language!"),
                                        static_cast<OWeakObject *>(this) );
            as.SetUILanguage( MsLangId::convertIsoStringToLanguage( slang ) );
            app->SetSettings( as );
            String sTitle = ::utl::ConfigManager::GetDirectConfigProperty(
                                ::utl::ConfigManager::PRODUCTNAME).get<OUString>()
                                + String(static_cast<sal_Unicode>(' '))
                                + ::utl::ConfigManager::GetDirectConfigProperty(
                                    ::utl::ConfigManager::PRODUCTVERSION).get<OUString>();
            app->SetDisplayName(sTitle);
        }
    }
    else
    {
        // When m_bShowUpdateOnly is set, we are inside the office and the user clicked
        // the update notification icon in the menu bar. We must not close the extensions
        // dialog after displaying the update dialog when it has been visible before
        if ( m_bShowUpdateOnly )
            bCloseDialog = ! dp_gui::TheExtensionManager::s_ExtMgr->isVisible();
    }

    {
        const ::vos::OGuard guard( Application::GetSolarMutex() );
        ::rtl::Reference< ::dp_gui::TheExtensionManager > myExtMgr(
            ::dp_gui::TheExtensionManager::get(
                m_xComponentContext,
                m_parent ? *m_parent : Reference<awt::XWindow>(),
                m_extensionURL ? *m_extensionURL : OUString() ) );
        myExtMgr->createDialog( false );
        if (m_initialTitle.getLength() > 0) {
            myExtMgr->SetText( m_initialTitle );
            m_initialTitle = OUString();
        }
        if ( m_bShowUpdateOnly )
        {
            myExtMgr->checkUpdates( true, !bCloseDialog );
            if ( bCloseDialog )
                myExtMgr->Close();
            else
                myExtMgr->ToTop( TOTOP_RESTOREWHENMIN );
        }
        else
        {
            myExtMgr->Show();
            myExtMgr->ToTop( TOTOP_RESTOREWHENMIN );
        }
    }

    if (app.get() != 0) {
        Application::Execute();
        DeInitVCL();
    }

    if (xListener.is())
        xListener->dialogClosed(
            ui::dialogs::DialogClosedEvent(
                static_cast< ::cppu::OWeakObject * >(this),
                sal_Int16(0)) );
}

// XJobExecutor
//______________________________________________________________________________
void ServiceImpl::trigger( OUString const &rEvent ) throw (RuntimeException)
{
    if ( rEvent == OUSTR("SHOW_UPDATE_DIALOG") )
        m_bShowUpdateOnly = true;
    else
        m_bShowUpdateOnly = false;

    startExecuteModal( Reference< ui::dialogs::XDialogClosedListener >() );
}

namespace sdecl = comphelper::service_decl;
sdecl::class_<ServiceImpl, sdecl::with_args<true> > serviceSI;
sdecl::ServiceDecl const serviceDecl(
    serviceSI,
    "com.sun.star.comp.deployment.ui.PackageManagerDialog",
    "com.sun.star.deployment.ui.PackageManagerDialog" );

sdecl::class_<LicenseDialog, sdecl::with_args<true> > licenseSI;
sdecl::ServiceDecl const licenseDecl(
    licenseSI,
    "com.sun.star.comp.deployment.ui.LicenseDialog",
    "com.sun.star.deployment.ui.LicenseDialog" );

sdecl::class_<UpdateRequiredDialogService, sdecl::with_args<true> > updateSI;
sdecl::ServiceDecl const updateDecl(
    updateSI,
    "com.sun.star.comp.deployment.ui.UpdateRequiredDialog",
    "com.sun.star.deployment.ui.UpdateRequiredDialog" );
} // namespace dp_gui

extern "C" {

void SAL_CALL component_getImplementationEnvironment(
    const sal_Char ** ppEnvTypeName, uno_Environment ** )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

sal_Bool SAL_CALL component_writeInfo(
    lang::XMultiServiceFactory * pServiceManager,
    registry::XRegistryKey * pRegistryKey )
{
    return component_writeInfoHelper(
        pServiceManager, pRegistryKey, dp_gui::serviceDecl, dp_gui::licenseDecl, dp_gui::updateDecl );
}

void * SAL_CALL component_getFactory(
    sal_Char const * pImplName,
    lang::XMultiServiceFactory * pServiceManager,
    registry::XRegistryKey * pRegistryKey )
{
    return component_getFactoryHelper(
        pImplName, pServiceManager, pRegistryKey, dp_gui::serviceDecl, dp_gui::licenseDecl, dp_gui::updateDecl );
}

} // extern "C"
<commit_msg>cws l10ntooling18: #i110394# confused assignment<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"

#include "dp_gui_shared.hxx"
#include "dp_gui.h"
#include "dp_gui_theextmgr.hxx"
#include "cppuhelper/implbase2.hxx"
#include "cppuhelper/implementationentry.hxx"
#include "unotools/configmgr.hxx"
#include "comphelper/servicedecl.hxx"
#include "comphelper/unwrapargs.hxx"
#include <i18npool/mslangid.hxx>
#include "vcl/svapp.hxx"
#include "vcl/msgbox.hxx"
#include "com/sun/star/lang/XServiceInfo.hpp"
#include "com/sun/star/task/XJobExecutor.hpp"
#include "com/sun/star/ui/dialogs/XAsynchronousExecutableDialog.hpp"

#include "boost/bind.hpp"
#include "license_dialog.hxx"
#include "dp_gui_dialog2.hxx"

using namespace ::dp_misc;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

using ::rtl::OUString;

namespace css = ::com::sun::star;
namespace dp_gui {

//==============================================================================
class MyApp : public Application, private boost::noncopyable
{
public:
    MyApp();
    virtual ~MyApp();

    // Application
    virtual void Main();
};

//______________________________________________________________________________
MyApp::~MyApp()
{
}

//______________________________________________________________________________
MyApp::MyApp()
{
}

//______________________________________________________________________________
void MyApp::Main()
{
}

//##############################################################################

namespace
{
    struct ProductName
        : public rtl::Static< String, ProductName > {};
    struct Version
        : public rtl::Static< String, Version > {};
    struct AboutBoxVersion
        : public rtl::Static< String, AboutBoxVersion > {};
    struct OOOVendor
        : public rtl::Static< String, OOOVendor > {};
    struct Extension
        : public rtl::Static< String, Extension > {};
}

void ReplaceProductNameHookProc( String& rStr )
{
    static int nAll = 0, nPro = 0;

    nAll++;
    if ( rStr.SearchAscii( "%PRODUCT" ) != STRING_NOTFOUND )
    {
        String &rProductName = ProductName::get();
        String &rVersion = Version::get();
        String &rAboutBoxVersion = AboutBoxVersion::get();
        String &rExtension = Extension::get();
        String &rOOOVendor = OOOVendor::get();

        if ( !rProductName.Len() )
        {
            rtl::OUString aTmp;
            Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME );
            aRet >>= aTmp;
            rProductName = aTmp;

            aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTVERSION );
            aRet >>= aTmp;
            rVersion = aTmp;

            aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::ABOUTBOXPRODUCTVERSION );
            aRet >>= aTmp;
            rAboutBoxVersion = aTmp;

            aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::OOOVENDOR );
            aRet >>= aTmp;
            rOOOVendor = aTmp;

            if ( !rExtension.Len() )
            {
                aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTEXTENSION );
                aRet >>= aTmp;
                rExtension = aTmp;
            }
        }

        nPro++;
        rStr.SearchAndReplaceAllAscii( "%PRODUCTNAME", rProductName );
        rStr.SearchAndReplaceAllAscii( "%PRODUCTVERSION", rVersion );
        rStr.SearchAndReplaceAllAscii( "%ABOUTBOXPRODUCTVERSION", rAboutBoxVersion );
        rStr.SearchAndReplaceAllAscii( "%OOOVENDOR", rOOOVendor );
        rStr.SearchAndReplaceAllAscii( "%PRODUCTEXTENSION", rExtension );
    }
}

//==============================================================================
class ServiceImpl
    : public ::cppu::WeakImplHelper2<ui::dialogs::XAsynchronousExecutableDialog,
                                     task::XJobExecutor>
{
    Reference<XComponentContext> const m_xComponentContext;
    boost::optional< Reference<awt::XWindow> > /* const */ m_parent;
    boost::optional<OUString> /* const */ m_view;
    /* if true then this service is running in an unopkg process and not in an office process */
    boost::optional<sal_Bool> /* const */ m_unopkg;
    boost::optional<OUString> m_extensionURL;
    OUString m_initialTitle;
    bool m_bShowUpdateOnly;

public:
    ServiceImpl( Sequence<Any> const & args,
                 Reference<XComponentContext> const & xComponentContext );

    // XAsynchronousExecutableDialog
    virtual void SAL_CALL setDialogTitle( OUString const & aTitle )
        throw (RuntimeException);
    virtual void SAL_CALL startExecuteModal(
        Reference< ui::dialogs::XDialogClosedListener > const & xListener )
        throw (RuntimeException);

    // XJobExecutor
    virtual void SAL_CALL trigger( OUString const & event )
        throw (RuntimeException);
};

//______________________________________________________________________________
ServiceImpl::ServiceImpl( Sequence<Any> const& args,
                          Reference<XComponentContext> const& xComponentContext)
    : m_xComponentContext(xComponentContext),
      m_bShowUpdateOnly( false )
{
    try {
        comphelper::unwrapArgs( args, m_parent, m_view, m_unopkg );
        return;
    } catch (css::lang::IllegalArgumentException & ) {
    }
    try {
        comphelper::unwrapArgs( args, m_extensionURL);
    } catch (css::lang::IllegalArgumentException & ) {
    }

    ResHookProc pProc = ResMgr::GetReadStringHook();
    if ( !pProc )
        ResMgr::SetReadStringHook( ReplaceProductNameHookProc );
}

// XAsynchronousExecutableDialog
//______________________________________________________________________________
void ServiceImpl::setDialogTitle( OUString const & title )
    throw (RuntimeException)
{
    if ( dp_gui::TheExtensionManager::s_ExtMgr.is() )
    {
        const ::vos::OGuard guard( Application::GetSolarMutex() );
        ::rtl::Reference< ::dp_gui::TheExtensionManager > dialog(
            ::dp_gui::TheExtensionManager::get( m_xComponentContext,
                                                m_parent ? *m_parent : Reference<awt::XWindow>(),
                                                m_extensionURL ? *m_extensionURL : OUString() ) );
        dialog->SetText( title );
    }
    else
        m_initialTitle = title;
}

//______________________________________________________________________________
void ServiceImpl::startExecuteModal(
    Reference< ui::dialogs::XDialogClosedListener > const & xListener )
    throw (RuntimeException)
{
    bool bCloseDialog = true;  // only used if m_bShowUpdateOnly is true
    ::std::auto_ptr<Application> app;
    //ToDo: synchronize access to s_dialog !!!
    if (! dp_gui::TheExtensionManager::s_ExtMgr.is())
    {
        const bool bAppUp = (GetpApp() != 0);
        bool bOfficePipePresent;
        try {
            bOfficePipePresent = dp_misc::office_is_running();
        }
        catch (Exception & exc) {
            if (bAppUp) {
                const vos::OGuard guard( Application::GetSolarMutex() );
                std::auto_ptr<ErrorBox> box(
                    new ErrorBox( Application::GetActiveTopWindow(),
                                  WB_OK, exc.Message ) );
                box->Execute();
            }
            throw;
        }

        if (! bOfficePipePresent) {
            OSL_ASSERT( ! bAppUp );
            app.reset( new MyApp );
            if (! InitVCL( Reference<lang::XMultiServiceFactory>(
                               m_xComponentContext->getServiceManager(),
                               UNO_QUERY_THROW ) ))
                throw RuntimeException( OUSTR("Cannot initialize VCL!"),
                                        static_cast<OWeakObject *>(this) );
            AllSettings as = app->GetSettings();
            OUString slang;
            if (! (::utl::ConfigManager::GetDirectConfigProperty(
                       ::utl::ConfigManager::LOCALE ) >>= slang))
                throw RuntimeException( OUSTR("Cannot determine language!"),
                                        static_cast<OWeakObject *>(this) );
            as.SetUILanguage( MsLangId::convertIsoStringToLanguage( slang ) );
            app->SetSettings( as );
            String sTitle = ::utl::ConfigManager::GetDirectConfigProperty(
                                ::utl::ConfigManager::PRODUCTNAME).get<OUString>()
                                + String(static_cast<sal_Unicode>(' '))
                                + ::utl::ConfigManager::GetDirectConfigProperty(
                                    ::utl::ConfigManager::PRODUCTVERSION).get<OUString>();
            app->SetDisplayName(sTitle);
        }
    }
    else
    {
        // When m_bShowUpdateOnly is set, we are inside the office and the user clicked
        // the update notification icon in the menu bar. We must not close the extensions
        // dialog after displaying the update dialog when it has been visible before
        if ( m_bShowUpdateOnly )
            bCloseDialog = ! dp_gui::TheExtensionManager::s_ExtMgr->isVisible();
    }

    {
        const ::vos::OGuard guard( Application::GetSolarMutex() );
        ::rtl::Reference< ::dp_gui::TheExtensionManager > myExtMgr(
            ::dp_gui::TheExtensionManager::get(
                m_xComponentContext,
                m_parent ? *m_parent : Reference<awt::XWindow>(),
                m_extensionURL ? *m_extensionURL : OUString() ) );
        myExtMgr->createDialog( false );
        if (m_initialTitle.getLength() > 0) {
            myExtMgr->SetText( m_initialTitle );
            m_initialTitle = OUString();
        }
        if ( m_bShowUpdateOnly )
        {
            myExtMgr->checkUpdates( true, !bCloseDialog );
            if ( bCloseDialog )
                myExtMgr->Close();
            else
                myExtMgr->ToTop( TOTOP_RESTOREWHENMIN );
        }
        else
        {
            myExtMgr->Show();
            myExtMgr->ToTop( TOTOP_RESTOREWHENMIN );
        }
    }

    if (app.get() != 0) {
        Application::Execute();
        DeInitVCL();
    }

    if (xListener.is())
        xListener->dialogClosed(
            ui::dialogs::DialogClosedEvent(
                static_cast< ::cppu::OWeakObject * >(this),
                sal_Int16(0)) );
}

// XJobExecutor
//______________________________________________________________________________
void ServiceImpl::trigger( OUString const &rEvent ) throw (RuntimeException)
{
    if ( rEvent == OUSTR("SHOW_UPDATE_DIALOG") )
        m_bShowUpdateOnly = true;
    else
        m_bShowUpdateOnly = false;

    startExecuteModal( Reference< ui::dialogs::XDialogClosedListener >() );
}

namespace sdecl = comphelper::service_decl;
sdecl::class_<ServiceImpl, sdecl::with_args<true> > serviceSI;
sdecl::ServiceDecl const serviceDecl(
    serviceSI,
    "com.sun.star.comp.deployment.ui.PackageManagerDialog",
    "com.sun.star.deployment.ui.PackageManagerDialog" );

sdecl::class_<LicenseDialog, sdecl::with_args<true> > licenseSI;
sdecl::ServiceDecl const licenseDecl(
    licenseSI,
    "com.sun.star.comp.deployment.ui.LicenseDialog",
    "com.sun.star.deployment.ui.LicenseDialog" );

sdecl::class_<UpdateRequiredDialogService, sdecl::with_args<true> > updateSI;
sdecl::ServiceDecl const updateDecl(
    updateSI,
    "com.sun.star.comp.deployment.ui.UpdateRequiredDialog",
    "com.sun.star.deployment.ui.UpdateRequiredDialog" );
} // namespace dp_gui

extern "C" {

void SAL_CALL component_getImplementationEnvironment(
    const sal_Char ** ppEnvTypeName, uno_Environment ** )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

sal_Bool SAL_CALL component_writeInfo(
    lang::XMultiServiceFactory * pServiceManager,
    registry::XRegistryKey * pRegistryKey )
{
    return component_writeInfoHelper(
        pServiceManager, pRegistryKey, dp_gui::serviceDecl, dp_gui::licenseDecl, dp_gui::updateDecl );
}

void * SAL_CALL component_getFactory(
    sal_Char const * pImplName,
    lang::XMultiServiceFactory * pServiceManager,
    registry::XRegistryKey * pRegistryKey )
{
    return component_getFactoryHelper(
        pImplName, pServiceManager, pRegistryKey, dp_gui::serviceDecl, dp_gui::licenseDecl, dp_gui::updateDecl );
}

} // extern "C"
<|endoftext|>