<commit_before>// @(#)root/ged:$Name:  $:$Id: TGedMarkerSelect.cxx,v 1.10 2005/10/17 10:20:01 brun Exp $
// Author: Marek Biskup, Ilka Antcheva   22/07/03

/*************************************************************************
 * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TGedMarkerSelect, TGedMarkerPopup                                    //
//                                                                      //
// The TGedMarkerPopup is a popup containing buttons to                 //
// select marker style.                                                 //
//                                                                      //
// The TGedMarkerSelect widget is a button showing selected marker      //
// and a little down arrow. When clicked on the arrow the               //
// TGedMarkerPopup pops up.                                             //
//                                                                      //
// Selecting a marker in this widget will generate the event:           //
// kC_MARKERSEL, kMAR_SELCHANGED, widget id, style.                     //
//                                                                      //
// and the signal:                                                      //
// MarkerSelected(Style_t marker)                                      //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TGedMarkerSelect.h"
#include "TGResourcePool.h"
#include "TGPicture.h"
#include "TGToolTip.h"
#include "TGButton.h"
#include "Riostream.h"

ClassImp(TGedMarkerSelect)
ClassImp(TGedMarkerPopup)

struct MarkerDescription_t {
   const char* fFilename;  // xpm file name
   const char* fName;      // type number for tooltip
   Int_t       fNumber;    // marker type number
};

static MarkerDescription_t  gMarkers[] = {

   {"marker1.xpm", "1", 1},
   {"marker6.xpm", "6", 6},
   {"marker7.xpm", "7", 7},
   {"marker2.xpm", "2", 2},
   {"marker3.xpm", "3", 3},
   {"marker4.xpm", "4", 4},
   {"marker5.xpm", "5", 5},
   {"marker20.xpm", "20", 20},
   {"marker21.xpm", "21", 21},
   {"marker22.xpm", "22", 22},
   {"marker23.xpm", "23", 23},
   {"marker24.xpm", "24", 24},
   {"marker25.xpm", "25", 25},
   {"marker26.xpm", "26", 26},
   {"marker27.xpm", "27", 27},
   {"marker28.xpm", "28", 28},
   {"marker29.xpm", "29", 29},
   {"marker30.xpm", "30", 30},
   {0, 0, 0},
};

static MarkerDescription_t* GetMarkerByNumber(Int_t number)
{
   for (Int_t i = 0; gMarkers[i].fFilename != 0; i++) {
      if (gMarkers[i].fNumber == number)
         return &gMarkers[i];
   }
   return 0;
}

//______________________________________________________________________________
TGedMarkerPopup::TGedMarkerPopup(const TGWindow *p, const TGWindow *m, Style_t markerStyle)
   : TGedPopup(p, m, 30, 30, kDoubleBorder | kRaisedFrame | kOwnBackground,
               GetDefaultFrameBackground())
{
   // Create marker popup window.

   TGButton *b;
   fCurrentStyle = markerStyle;

   Pixel_t white;
   gClient->GetColorByName("white", white); // white background
   SetBackgroundColor(white);

   SetLayoutManager(new TGTileLayout(this, 1));

   for (int i = 0; gMarkers[i].fFilename != 0; i++) {
      AddFrame(b = new TGPictureButton(this, gMarkers[i].fFilename,
               gMarkers[i].fNumber, TGButton::GetDefaultGC()(), kSunkenFrame),
               new TGLayoutHints(kLHintsLeft, 14, 14, 14, 14));
      b->SetToolTipText(gMarkers[i].fName);
   }

   Resize(65, 94);
   MapSubwindows();
}

//______________________________________________________________________________
TGedMarkerPopup::~TGedMarkerPopup()
{
   // Destructor.

   Cleanup();
}

//______________________________________________________________________________
Bool_t TGedMarkerPopup::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)
{
   // Process messages generated by the marker popup window.

   if (GET_MSG(msg) == kC_COMMAND && GET_SUBMSG(msg) == kCM_BUTTON) {
      SendMessage(fMsgWindow, MK_MSG(kC_MARKERSEL, kMAR_SELCHANGED), 0, parm1);
      EndPopup();
   }

   if (parm2)
      ;              // no warning

   return kTRUE;
}

//______________________________________________________________________________
TGedMarkerSelect::TGedMarkerSelect(const TGWindow *p, Style_t markerStyle, Int_t id)
   : TGedSelect(p, id)
{
   // Create and show marker popup window.

   fPicture = 0;
   SetPopup(new TGedMarkerPopup(gClient->GetDefaultRoot(), this, markerStyle));
   SetMarkerStyle(markerStyle);

}

//_____________________________________________________________________________
Bool_t TGedMarkerSelect::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)
{
   // Process messages according to the user input.

   if (GET_MSG(msg) == kC_MARKERSEL && GET_SUBMSG(msg) == kMAR_SELCHANGED) {
      SetMarkerStyle(parm2);
      SendMessage(fMsgWindow, MK_MSG(kC_MARKERSEL, kMAR_SELCHANGED),
                  fWidgetId, parm2);
   }

   if (parm1)     // no warning
      ;
   return kTRUE;
}

//_____________________________________________________________________________
void TGedMarkerSelect::DoRedraw()
{
   // Draw selected marker type as current one.

   TGedSelect::DoRedraw();

   Int_t  x, y;
   UInt_t w, h;

   if (IsEnabled()) {
      // pattern rectangle

      x = fBorderWidth + 2;
      y = fBorderWidth + 2;  // 1;
      h = fHeight - (fBorderWidth * 2) - 4;  // -3;  // 14
      w = h;
      if (fState == kButtonDown) {
         ++x; ++y;
      }
      gVirtualX->DrawRectangle(fId, GetShadowGC()(), x, y, w - 1, h - 1);

      if (fPicture != 0) fPicture->Draw(fId, fDrawGC->GetGC(), x + 1, y + 1);
   } else { // sunken rectangle
      x = fBorderWidth + 2;
      y = fBorderWidth + 2;  // 1;
      w = 42;
      h = fHeight - (fBorderWidth * 2) - 4;  // 3;
      Draw3dRectangle(kSunkenFrame, x, y, w, h);
   }
}

//_____________________________________________________________________________
void TGedMarkerSelect::SetMarkerStyle(Style_t markerStyle)
{
   // Set marker.

   fMarkerStyle = markerStyle;
   gClient->NeedRedraw(this);

   if (fPicture) {
      gClient->FreePicture(fPicture);
      fPicture = 0;
   }

   MarkerDescription_t *md = GetMarkerByNumber(fMarkerStyle);

   if (md)  fPicture = gClient->GetPicture(md->fFilename);

   MarkerSelected(fMarkerStyle);
}

//______________________________________________________________________________
void TGedMarkerSelect::SavePrimitive(ofstream &out, Option_t *)
{
   // Save the pattern select widget as a C++ statement(s) on output stream out

   out <<"   TGedMarkerSelect *";
   out << GetName() << " = new TGedMarkerSelect(" << fParent->GetName()
       << "," << fMarkerStyle << "," << WidgetId() << ");" << endl;
}
<commit_msg>- marker pictures were not removed from the pool<commit_after>// @(#)root/ged:$Name:  $:$Id: TGedMarkerSelect.cxx,v 1.11 2005/11/11 15:38:30 brun Exp $
// Author: Marek Biskup, Ilka Antcheva   22/07/03

/*************************************************************************
 * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TGedMarkerSelect, TGedMarkerPopup                                    //
//                                                                      //
// The TGedMarkerPopup is a popup containing buttons to                 //
// select marker style.                                                 //
//                                                                      //
// The TGedMarkerSelect widget is a button showing selected marker      //
// and a little down arrow. When clicked on the arrow the               //
// TGedMarkerPopup pops up.                                             //
//                                                                      //
// Selecting a marker in this widget will generate the event:           //
// kC_MARKERSEL, kMAR_SELCHANGED, widget id, style.                     //
//                                                                      //
// and the signal:                                                      //
// MarkerSelected(Style_t marker)                                      //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TGedMarkerSelect.h"
#include "TGResourcePool.h"
#include "TGPicture.h"
#include "TGToolTip.h"
#include "TGButton.h"
#include "Riostream.h"

ClassImp(TGedMarkerSelect)
ClassImp(TGedMarkerPopup)

struct MarkerDescription_t {
   const char* fFilename;  // xpm file name
   const char* fName;      // type number for tooltip
   Int_t       fNumber;    // marker type number
};

static MarkerDescription_t  gMarkers[] = {

   {"marker1.xpm", "1", 1},
   {"marker6.xpm", "6", 6},
   {"marker7.xpm", "7", 7},
   {"marker2.xpm", "2", 2},
   {"marker3.xpm", "3", 3},
   {"marker4.xpm", "4", 4},
   {"marker5.xpm", "5", 5},
   {"marker20.xpm", "20", 20},
   {"marker21.xpm", "21", 21},
   {"marker22.xpm", "22", 22},
   {"marker23.xpm", "23", 23},
   {"marker24.xpm", "24", 24},
   {"marker25.xpm", "25", 25},
   {"marker26.xpm", "26", 26},
   {"marker27.xpm", "27", 27},
   {"marker28.xpm", "28", 28},
   {"marker29.xpm", "29", 29},
   {"marker30.xpm", "30", 30},
   {0, 0, 0},
};

static MarkerDescription_t* GetMarkerByNumber(Int_t number)
{
   for (Int_t i = 0; gMarkers[i].fFilename != 0; i++) {
      if (gMarkers[i].fNumber == number)
         return &gMarkers[i];
   }
   return 0;
}

//______________________________________________________________________________
TGedMarkerPopup::TGedMarkerPopup(const TGWindow *p, const TGWindow *m, Style_t markerStyle)
   : TGedPopup(p, m, 30, 30, kDoubleBorder | kRaisedFrame | kOwnBackground,
               GetDefaultFrameBackground())
{
   // Create marker popup window.

   TGButton *b;
   fCurrentStyle = markerStyle;

   Pixel_t white;
   gClient->GetColorByName("white", white); // white background
   SetBackgroundColor(white);

   SetLayoutManager(new TGTileLayout(this, 1));

   for (int i = 0; gMarkers[i].fFilename != 0; i++) {
      AddFrame(b = new TGPictureButton(this, gMarkers[i].fFilename,
               gMarkers[i].fNumber, TGButton::GetDefaultGC()(), kSunkenFrame),
               new TGLayoutHints(kLHintsLeft, 14, 14, 14, 14));
      b->SetToolTipText(gMarkers[i].fName);
   }

   Resize(65, 94);
   MapSubwindows();
}

//______________________________________________________________________________
TGedMarkerPopup::~TGedMarkerPopup()
{
   // Destructor.

   TGFrameElement *el;
   TIter next(GetList());
   while ((el = (TGFrameElement *)next())) {
      if (el->fFrame->InheritsFrom(TGPictureButton::Class()))
         fClient->FreePicture(((TGPictureButton *)el->fFrame)->GetPicture());
   }
   Cleanup();
}

//______________________________________________________________________________
Bool_t TGedMarkerPopup::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)
{
   // Process messages generated by the marker popup window.

   if (GET_MSG(msg) == kC_COMMAND && GET_SUBMSG(msg) == kCM_BUTTON) {
      SendMessage(fMsgWindow, MK_MSG(kC_MARKERSEL, kMAR_SELCHANGED), 0, parm1);
      EndPopup();
   }

   if (parm2)
      ;              // no warning

   return kTRUE;
}

//______________________________________________________________________________
TGedMarkerSelect::TGedMarkerSelect(const TGWindow *p, Style_t markerStyle, Int_t id)
   : TGedSelect(p, id)
{
   // Create and show marker popup window.

   fPicture = 0;
   SetPopup(new TGedMarkerPopup(gClient->GetDefaultRoot(), this, markerStyle));
   SetMarkerStyle(markerStyle);

}

//_____________________________________________________________________________
Bool_t TGedMarkerSelect::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)
{
   // Process messages according to the user input.

   if (GET_MSG(msg) == kC_MARKERSEL && GET_SUBMSG(msg) == kMAR_SELCHANGED) {
      SetMarkerStyle(parm2);
      SendMessage(fMsgWindow, MK_MSG(kC_MARKERSEL, kMAR_SELCHANGED),
                  fWidgetId, parm2);
   }

   if (parm1)     // no warning
      ;
   return kTRUE;
}

//_____________________________________________________________________________
void TGedMarkerSelect::DoRedraw()
{
   // Draw selected marker type as current one.

   TGedSelect::DoRedraw();

   Int_t  x, y;
   UInt_t w, h;

   if (IsEnabled()) {
      // pattern rectangle

      x = fBorderWidth + 2;
      y = fBorderWidth + 2;  // 1;
      h = fHeight - (fBorderWidth * 2) - 4;  // -3;  // 14
      w = h;
      if (fState == kButtonDown) {
         ++x; ++y;
      }
      gVirtualX->DrawRectangle(fId, GetShadowGC()(), x, y, w - 1, h - 1);

      if (fPicture != 0) fPicture->Draw(fId, fDrawGC->GetGC(), x + 1, y + 1);
   } else { // sunken rectangle
      x = fBorderWidth + 2;
      y = fBorderWidth + 2;  // 1;
      w = 42;
      h = fHeight - (fBorderWidth * 2) - 4;  // 3;
      Draw3dRectangle(kSunkenFrame, x, y, w, h);
   }
}

//_____________________________________________________________________________
void TGedMarkerSelect::SetMarkerStyle(Style_t markerStyle)
{
   // Set marker.

   fMarkerStyle = markerStyle;
   gClient->NeedRedraw(this);

   if (fPicture) {
      gClient->FreePicture(fPicture);
      fPicture = 0;
   }

   MarkerDescription_t *md = GetMarkerByNumber(fMarkerStyle);

   if (md)  fPicture = gClient->GetPicture(md->fFilename);

   MarkerSelected(fMarkerStyle);
}

//______________________________________________________________________________
void TGedMarkerSelect::SavePrimitive(ofstream &out, Option_t *)
{
   // Save the pattern select widget as a C++ statement(s) on output stream out

   out <<"   TGedMarkerSelect *";
   out << GetName() << " = new TGedMarkerSelect(" << fParent->GetName()
       << "," << fMarkerStyle << "," << WidgetId() << ");" << endl;
}
<|endoftext|>


<commit_before>//=====================================================================//
/*! @file
	@brief  img メイン関係
	@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <iostream>
#include "img_main.hpp"
#include "core/glcore.hpp"
#include "widgets/widget_utils.hpp"

namespace app {

	//-----------------------------------------------------------------//
	/*!
		@brief  初期化
	*/
	//-----------------------------------------------------------------//
	void img_main::initialize()
	{
		gl::IGLcore* igl = gl::get_glcore();

		using namespace gui;
		widget_director& wd = director_.at().widget_director_;

		{ // 画像ファイル表示用フレーム
			widget::param wp(vtx::srect(30, 30, 256, 256));
			widget_frame::param wp_;
			frame_ = wd.add_widget<widget_frame>(wp, wp_);
		}
		{ // 画像ファイル表示イメージ
			widget::param wp(vtx::srect(0, 0, 256, 256), frame_);
			widget_image::param wp_;
			image_ = wd.add_widget<widget_image>(wp, wp_);
			image_->set_state(widget::state::CLIP_PARENTS);
			image_->set_state(widget::state::RESIZE_ROOT);
		}

		{ // 機能ツールパレット
			widget::param wp(vtx::srect(10, 10, 150, 300));
			widget_frame::param wp_;
			tools_ = wd.add_widget<widget_frame>(wp, wp_);
		}
		{ // ファイラー起動ボタン
			widget::param wp(vtx::srect(10, 10, 100, 40), tools_);
			widget_button::param wp_("file");
			open_ = wd.add_widget<widget_button>(wp, wp_);
		}
		{ // スケールチェックボックス
			widget::param wp(vtx::srect(10, 60, 100, 40), tools_);
			widget_check::param wp_("scale");
			scale_ = wd.add_widget<widget_check>(wp, wp_);
		}

		{ // ファイラー本体
			widget::param wp(vtx::srect(10, 30, 300, 200));
			widget_filer::param wp_(igl->get_current_path());
			filer_ = wd.add_widget<widget_filer>(wp, wp_);
			filer_->enable(false);
		}
		{ // ダイアログ
			widget::param wp(vtx::srect(10, 30, 450, 200));
			widget_dialog::param wp_;
			dialog_ = wd.add_widget<widget_dialog>(wp, wp_);
			dialog_->enable(false);
		}

		mobj_.initialize();

		// プリファレンスの取得
		sys::preference& pre = director_.at().preference_;
		if(filer_) {
			filer_->load(pre);
			frame_->load(pre);
			tools_->load(pre);
			scale_->load(pre);
		}
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  アップデート
	*/
	//-----------------------------------------------------------------//
	void img_main::update()
	{
		gl::IGLcore* igl = gl::get_glcore();
		const vtx::spos& size = igl->get_size();

		gui::widget_director& wd = director_.at().widget_director_;

		if(open_) {
			if(open_->get_selected()) {
				if(filer_) {
					bool f = filer_->get_state(gui::widget::state::ENABLE);
					filer_->enable(!f);
				}
			}
		}

		if(filer_) {
			if(filer_id_ != filer_->get_select_file_id()) {
				filer_id_ = filer_->get_select_file_id();

				img::img_files& imf = wd.at_img_files();
				if(!imf.load(filer_->get_file())) {
					dialog_->set_text("Can't decode image file:\n '"
						+ filer_->get_file() + "'");
					dialog_->enable();
				} else {
					mobj_.destroy();
					mobj_.initialize();
					img_handle_ = mobj_.install(imf.get_image_if());
					image_->at_local_param().mobj_ = mobj_;
					image_->at_local_param().mobj_handle_ = img_handle_;
// imf.set_image_if(imf.get_image_if());
// imf.save("test.tga", "rle");
				}
			}
		}

		// frame 内 image のサイズを設定
		if(frame_ && image_) {
			vtx::spos ofs(frame_->get_local_param().plate_param_.frame_width_);
			image_->at_rect().org = ofs;
			image_->at_rect().size = frame_->get_rect().size - ofs * 2;

			float s = 1.0f;
			if(scale_->get_check()) {
				vtx::fpos is = mobj_.get_size(img_handle_);
				vtx::fpos ss = image_->at_rect().size;
				vtx::fpos sc = ss / is;
				if(sc.x < sc.y) s = sc.x; else s = sc.y;
			}
			image_->at_local_param().scale_ = s;
		}

		wd.update();
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  レンダリング
	*/
	//-----------------------------------------------------------------//
	void img_main::render()
	{
		director_.at().widget_director_.service();
		director_.at().widget_director_.render();
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  廃棄
	*/
	//-----------------------------------------------------------------//
	void img_main::destroy()
	{
		sys::preference& pre = director_.at().preference_;
		if(filer_) {
			filer_->save(pre);
			frame_->save(pre);
			tools_->save(pre);
			scale_->save(pre);
		}
	}
}
<commit_msg>openjpeg セーブ確認<commit_after>//=====================================================================//
/*! @file
	@brief  img メイン関係
	@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <iostream>
#include "img_main.hpp"
#include "core/glcore.hpp"
#include "widgets/widget_utils.hpp"

namespace app {

	//-----------------------------------------------------------------//
	/*!
		@brief  初期化
	*/
	//-----------------------------------------------------------------//
	void img_main::initialize()
	{
		gl::IGLcore* igl = gl::get_glcore();

		using namespace gui;
		widget_director& wd = director_.at().widget_director_;

		{ // 画像ファイル表示用フレーム
			widget::param wp(vtx::srect(30, 30, 256, 256));
			widget_frame::param wp_;
			frame_ = wd.add_widget<widget_frame>(wp, wp_);
		}
		{ // 画像ファイル表示イメージ
			widget::param wp(vtx::srect(0, 0, 256, 256), frame_);
			widget_image::param wp_;
			image_ = wd.add_widget<widget_image>(wp, wp_);
			image_->set_state(widget::state::CLIP_PARENTS);
			image_->set_state(widget::state::RESIZE_ROOT);
		}

		{ // 機能ツールパレット
			widget::param wp(vtx::srect(10, 10, 150, 300));
			widget_frame::param wp_;
			tools_ = wd.add_widget<widget_frame>(wp, wp_);
		}
		{ // ファイラー起動ボタン
			widget::param wp(vtx::srect(10, 10, 100, 40), tools_);
			widget_button::param wp_("file");
			open_ = wd.add_widget<widget_button>(wp, wp_);
		}
		{ // スケールチェックボックス
			widget::param wp(vtx::srect(10, 60, 100, 40), tools_);
			widget_check::param wp_("scale");
			scale_ = wd.add_widget<widget_check>(wp, wp_);
		}

		{ // ファイラー本体
			widget::param wp(vtx::srect(10, 30, 300, 200));
			widget_filer::param wp_(igl->get_current_path());
			filer_ = wd.add_widget<widget_filer>(wp, wp_);
			filer_->enable(false);
		}
		{ // ダイアログ
			widget::param wp(vtx::srect(10, 30, 450, 200));
			widget_dialog::param wp_;
			dialog_ = wd.add_widget<widget_dialog>(wp, wp_);
			dialog_->enable(false);
		}

		mobj_.initialize();

		// プリファレンスの取得
		sys::preference& pre = director_.at().preference_;
		if(filer_) {
			filer_->load(pre);
			frame_->load(pre);
			tools_->load(pre);
			scale_->load(pre);
		}
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  アップデート
	*/
	//-----------------------------------------------------------------//
	void img_main::update()
	{
		gl::IGLcore* igl = gl::get_glcore();
		const vtx::spos& size = igl->get_size();

		gui::widget_director& wd = director_.at().widget_director_;

		if(open_) {
			if(open_->get_selected()) {
				if(filer_) {
					bool f = filer_->get_state(gui::widget::state::ENABLE);
					filer_->enable(!f);
				}
			}
		}

		if(filer_) {
			if(filer_id_ != filer_->get_select_file_id()) {
				filer_id_ = filer_->get_select_file_id();

				img::img_files& imf = wd.at_img_files();
				if(!imf.load(filer_->get_file())) {
					dialog_->set_text("Can't decode image file:\n '"
						+ filer_->get_file() + "'");
					dialog_->enable();
				} else {
					mobj_.destroy();
					mobj_.initialize();
					img_handle_ = mobj_.install(imf.get_image_if());
					image_->at_local_param().mobj_ = mobj_;
					image_->at_local_param().mobj_handle_ = img_handle_;
// imf.set_image_if(imf.get_image_if());
// imf.save("test.jp2");
				}
			}
		}

		// frame 内 image のサイズを設定
		if(frame_ && image_) {
			vtx::spos ofs(frame_->get_local_param().plate_param_.frame_width_);
			image_->at_rect().org = ofs;
			image_->at_rect().size = frame_->get_rect().size - ofs * 2;

			float s = 1.0f;
			if(scale_->get_check()) {
				vtx::fpos is = mobj_.get_size(img_handle_);
				vtx::fpos ss = image_->at_rect().size;
				vtx::fpos sc = ss / is;
				if(sc.x < sc.y) s = sc.x; else s = sc.y;
			}
			image_->at_local_param().scale_ = s;
		}

		wd.update();
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  レンダリング
	*/
	//-----------------------------------------------------------------//
	void img_main::render()
	{
		director_.at().widget_director_.service();
		director_.at().widget_director_.render();
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  廃棄
	*/
	//-----------------------------------------------------------------//
	void img_main::destroy()
	{
		sys::preference& pre = director_.at().preference_;
		if(filer_) {
			filer_->save(pre);
			frame_->save(pre);
			tools_->save(pre);
			scale_->save(pre);
		}
	}
}
<|endoftext|>


<commit_before>/**
 * @file DartLoader.cpp
 */

#include "DartLoader.h"
#include <map>
#include "../urdfdom_headers/urdf_model/link.h"

#include <iostream>
#include <fstream>

/**
 * @function DartLoader
 * @brief Constructor
 */
DartLoader::DartLoader() {
}

/**
 * @function ~DartLoader
 * @brief Destructor
 */
DartLoader::~DartLoader() {

}

/**
 * @function parseSkeleton
 */
dynamics::SkeletonDynamics* DartLoader::parseSkeleton( std::string _urdfFile ) {

  std::string xml_string;
  xml_string = readXmlToString( _urdfFile );

  boost::shared_ptr<urdf::ModelInterface> skeletonModel = urdf::parseURDF( xml_string );

  return modelInterfaceToSkeleton( skeletonModel );

}

/**
 * @function parseRobot
 */
robotics::Robot* DartLoader::parseRobot( std::string _urdfFile ) {

  std::string xml_string;
  xml_string = readXmlToString( _urdfFile );
  boost::shared_ptr<urdf::ModelInterface> robotModel = urdf::parseURDF( xml_string );
  return modelInterfaceToRobot( robotModel );
}

/**
 * @function parseObject
 */
robotics::Object* DartLoader::parseObject( std::string _urdfFile ) {

  std::string xml_string;
  xml_string = readXmlToString( _urdfFile );
  boost::shared_ptr<urdf::ModelInterface> objectModel = urdf::parseURDF( xml_string );
  return modelInterfaceToObject( objectModel );

}

/**
 * @function parseWorld
 */
robotics::World* DartLoader::parseWorld( std::string _urdfFile ) {

  mWorldPath = _urdfFile;

  // Change path to a Unix-style path if given a Windows one
  // Windows can handle Unix-style paths (apparently)
  std::replace( mWorldPath.begin(), mWorldPath.end(), '\\' , '/' );
  mPath = mWorldPath.substr( 0, mWorldPath.rfind("/") + 1 );

  std::cout<< " mPath :" << mPath << std::endl;

  robotics::World* world = new robotics::World();
	robotics::Robot* robot;
  robotics::Object* object;

  std::string xml_string;
  xml_string = readXmlToString( _urdfFile );

  boost::shared_ptr<urdf::World> worldInterface =  urdf::parseWorldURDF(xml_string, mPath );

  double roll, pitch, yaw;
  for( unsigned int i = 0; i < worldInterface->objectModels.size(); ++i ) {

    object = modelInterfaceToObject(  worldInterface->objectModels[i].model );
    // Initialize position and RPY
    worldInterface->objectModels[i].origin.rotation.getRPY( roll, pitch, yaw );
    object->setRotationRPY( roll, pitch, yaw );

    object->setPositionX( worldInterface->objectModels[i].origin.position.x );
    object->setPositionY( worldInterface->objectModels[i].origin.position.y );
    object->setPositionZ( worldInterface->objectModels[i].origin.position.z );
    object->update();
    world->addObject( object );
  }

  for( unsigned int i = 0; i < worldInterface->robotModels.size(); ++i )  {

    robot = modelInterfaceToRobot(  worldInterface->robotModels[i].model );
    // Initialize position and RPY
    worldInterface->robotModels[i].origin.rotation.getRPY( roll, pitch, yaw );
    robot->setRotationRPY( roll, pitch, yaw );

    robot->setPositionX( worldInterface->robotModels[i].origin.position.x );
    robot->setPositionY( worldInterface->robotModels[i].origin.position.y );
    robot->setPositionZ( worldInterface->robotModels[i].origin.position.z );
    robot->update();
    world->addRobot( robot );
  }

  return world;
}

/**
 * @function modelInterfaceToSkeleton
 * @brief Read the ModelInterface and spits out a SkeletonDynamics object
 */
dynamics::SkeletonDynamics* DartLoader::modelInterfaceToSkeleton( boost::shared_ptr<urdf::ModelInterface> _model ) {

  dynamics::SkeletonDynamics* mSkeleton = new dynamics::SkeletonDynamics();
  dynamics::BodyNodeDynamics *node, *rootNode;
  kinematics::Joint *joint, *rootJoint;

  // BodyNode
  mNodes.resize(0);
  for( std::map<std::string, boost::shared_ptr<urdf::Link> >::const_iterator lk = _model->links_.begin();
       lk != _model->links_.end();
       lk++ ) {
    node = createDartNode( (*lk).second, mSkeleton );
    mNodes.push_back( node );
  }
  printf("** Created %d body nodes \n", mNodes.size() );

  // Joint
  mJoints.resize(0);

  for( std::map<std::string, boost::shared_ptr<urdf::Joint> >::const_iterator jt = _model->joints_.begin();
       jt != _model->joints_.end();
       jt++ ) {
    joint = createDartJoint( (*jt).second, mSkeleton );
    mJoints.push_back( joint );

  }

  //-- root joint
  rootNode = getNode( _model->getRoot()->name );
  rootJoint = createDartRootJoint( _model->getRoot(), mSkeleton, false );
  mJoints.push_back( rootJoint );

  printf("** Created %d joints \n", mJoints.size() );

  //-- Save DART structure

  // Push parents first
  std::list<dynamics::BodyNodeDynamics*> nodeStack;
  dynamics::BodyNodeDynamics* u;
  nodeStack.push_back( rootNode );

  int numIter = 0;
  while( !nodeStack.empty() && numIter < mNodes.size() ) {

    // Get front element on stack and add it
    u = nodeStack.front();
    mSkeleton->addNode(u);

    // Pop it out
    nodeStack.pop_front();

    // Add its kids
    for( int idx = 0; idx < u->getNumChildJoints(); ++idx ) {
      nodeStack.push_back( (dynamics::BodyNodeDynamics*)( u->getChildNode(idx) ) );
    }
    numIter++;
  }
  printf("--> Pushed %d nodes in tree-like order \n", numIter );

  // Init skeleton
  mSkeleton->initSkel();

  return mSkeleton;
}

/**
 * @function modelInterfaceToRobot
 */
robotics::Robot* DartLoader::modelInterfaceToRobot( boost::shared_ptr<urdf::ModelInterface> _model ) {

  robotics::Robot* mRobot;
  dynamics::BodyNodeDynamics *node, *rootNode;
  kinematics::Joint *joint, *rootJoint;

	mRobot = new robotics::Robot();
  mRobot->addDefaultRootNode();

  // name
  mRobot->setName( _model->getName() );

  // BodyNode
  mNodes.resize(0);
  for( std::map<std::string, boost::shared_ptr<urdf::Link> >::const_iterator lk = _model->links_.begin();
       lk != _model->links_.end();
       lk++ ) {
    node = createDartNode( (*lk).second, mRobot );
    mNodes.push_back( node );
  }
  printf("** Created %d body nodes \n", mNodes.size() );

  // Joint
  mJoints.resize(0);

  for( std::map<std::string, boost::shared_ptr<urdf::Joint> >::const_iterator jt = _model->joints_.begin();
       jt != _model->joints_.end();
       jt++ ) {
    joint = createDartJoint( (*jt).second, mRobot );
    mJoints.push_back( joint );

  }

  //-- root joint
  rootNode = getNode( _model->getRoot()->name );
  printf("[DartLoader] Root Node: %s \n", rootNode->getName() );
  rootJoint = createDartRootJoint( _model->getRoot(), mRobot, true );
  mJoints.push_back( rootJoint );

  printf("** Created %d joints \n", mJoints.size() );

  //-- Save DART structure
     // Push parents first
    std::list<dynamics::BodyNodeDynamics*> nodeStack;
    dynamics::BodyNodeDynamics* u;
    nodeStack.push_back( rootNode );

    int numIter = 0;
    while( !nodeStack.empty() && numIter < mNodes.size() ) {
      // Get front element on stack and update it
      u = nodeStack.front();
			mRobot->addNode(u);
      // Pop it out
      nodeStack.pop_front();

      // Add its kids
      for( int idx = 0; idx < u->getNumChildJoints(); ++idx ) {
	nodeStack.push_back( (dynamics::BodyNodeDynamics*)( u->getChildNode(idx) ) );
      }
      numIter++;
    }
		printf("Pushed %d nodes in order \n", numIter );

  // Init robot (skeleton)
  mRobot->initSkel();
  mRobot->update();
  return mRobot;
}

/**
 * @function modelInterfaceToObject
 */
robotics::Object* DartLoader::modelInterfaceToObject( boost::shared_ptr<urdf::ModelInterface> _model ) {

  robotics::Object* mObject;
  dynamics::BodyNodeDynamics *node, *rootNode;
  kinematics::Joint *joint, *rootJoint;

  mObject = new robotics::Object();
  mObject->addDefaultRootNode();

  // name
  mObject->setName( _model->getName() );

  // BodyNode
  mNodes.resize(0);
  for( std::map<std::string, boost::shared_ptr<urdf::Link> >::const_iterator lk = _model->links_.begin();
       lk != _model->links_.end();
       lk++ ) {
    node = createDartNode( (*lk).second, mObject );
    mNodes.push_back( node );
  }
  printf("** Created %d body nodes \n", mNodes.size() );

  // Joint
  mJoints.resize(0);

  for( std::map<std::string, boost::shared_ptr<urdf::Joint> >::const_iterator jt = _model->joints_.begin();
       jt != _model->joints_.end();
       jt++ ) {
    joint = createDartJoint( (*jt).second, mObject );
    mJoints.push_back( joint );

  }

  //-- root joint
  rootNode = getNode( _model->getRoot()->name );
  rootJoint = createDartRootJoint( _model->getRoot(), mObject, true );
  mJoints.push_back( rootJoint );

  printf("** Created %d joints \n", mJoints.size() );

  //-- Save DART structure

  // 1. Root node
  mObject->addNode( rootNode );

  // 2. The rest
  for( unsigned int i = 0; i < mNodes.size(); ++i ) {
    if( mNodes[i] != rootNode ) {
      mObject->addNode( mNodes[i] );
    }
  }

  // Init robot (skeleton)
  mObject->initSkel();
  mObject->update();

  return mObject;
}

/**
 * @function getNode
 */
dynamics::BodyNodeDynamics* DartLoader::getNode( std::string _nodeName ) {

  for( unsigned int i = 0; i < mNodes.size(); ++i ) {
    std::string node( mNodes[i]->getName() );
    if( node ==  _nodeName ) {
      return mNodes[i];
    }
  }
  printf("[getNode] ERROR: Returning  NULL for  %s \n", _nodeName.c_str() );
  return NULL;
}

/**
 * @function readXml
 */
std::string  DartLoader::readXmlToString( std::string _xmlFile ) {

  std::string xml_string;

  std::fstream xml_file( _xmlFile.c_str(), std::fstream::in );

  // Read xml
  while( xml_file.good() ) {
    std::string line;
    std::getline( xml_file, line );
    xml_string += (line + "\n");
  }
  xml_file.close();

  return xml_string;
}
<commit_msg>Fix bug introduced by breaking changes in commit be3ee9079e866725eb045dd346c56fcb7d21f41b (Saul, 10/27/2012)<commit_after>/**
 * @file DartLoader.cpp
 */

#include "DartLoader.h"
#include <map>
#include "../urdfdom_headers/urdf_model/link.h"

#include <iostream>
#include <fstream>

/**
 * @function DartLoader
 * @brief Constructor
 */
DartLoader::DartLoader() {
}

/**
 * @function ~DartLoader
 * @brief Destructor
 */
DartLoader::~DartLoader() {

}

/**
 * @function parseSkeleton
 */
dynamics::SkeletonDynamics* DartLoader::parseSkeleton( std::string _urdfFile ) {

  std::string xml_string;
  xml_string = readXmlToString( _urdfFile );

  boost::shared_ptr<urdf::ModelInterface> skeletonModel = urdf::parseURDF( xml_string );

  return modelInterfaceToSkeleton( skeletonModel );

}

/**
 * @function parseRobot
 */
robotics::Robot* DartLoader::parseRobot( std::string _urdfFile ) {

  std::string xml_string;
  xml_string = readXmlToString( _urdfFile );
  boost::shared_ptr<urdf::ModelInterface> robotModel = urdf::parseURDF( xml_string );
  return modelInterfaceToRobot( robotModel );
}

/**
 * @function parseObject
 */
robotics::Object* DartLoader::parseObject( std::string _urdfFile ) {

  std::string xml_string;
  xml_string = readXmlToString( _urdfFile );
  boost::shared_ptr<urdf::ModelInterface> objectModel = urdf::parseURDF( xml_string );
  return modelInterfaceToObject( objectModel );

}

/**
 * @function parseWorld
 */
robotics::World* DartLoader::parseWorld( std::string _urdfFile ) {

  mWorldPath = _urdfFile;

  // Change path to a Unix-style path if given a Windows one
  // Windows can handle Unix-style paths (apparently)
  std::replace( mWorldPath.begin(), mWorldPath.end(), '\\' , '/' );
  mPath = mWorldPath.substr( 0, mWorldPath.rfind("/") + 1 );

  std::cout<< " mPath :" << mPath << std::endl;

  robotics::World* world = new robotics::World();
	robotics::Robot* robot;
  robotics::Object* object;

  std::string xml_string;
  xml_string = readXmlToString( _urdfFile );

  boost::shared_ptr<urdf::World> worldInterface =  urdf::parseWorldURDF(xml_string, mPath );

  double roll, pitch, yaw;
  for( unsigned int i = 0; i < worldInterface->objectModels.size(); ++i ) {

    object = modelInterfaceToObject(  worldInterface->objectModels[i].model );
    // Initialize position and RPY
    worldInterface->objectModels[i].origin.rotation.getRPY( roll, pitch, yaw );
    object->setRotationRPY( roll, pitch, yaw );

    object->setPositionX( worldInterface->objectModels[i].origin.position.x );
    object->setPositionY( worldInterface->objectModels[i].origin.position.y );
    object->setPositionZ( worldInterface->objectModels[i].origin.position.z );
    object->update();
    world->addObject( object );
  }

  for( unsigned int i = 0; i < worldInterface->robotModels.size(); ++i )  {

    robot = modelInterfaceToRobot(  worldInterface->robotModels[i].model );
    // Initialize position and RPY
    worldInterface->robotModels[i].origin.rotation.getRPY( roll, pitch, yaw );
    robot->setRotationRPY( roll, pitch, yaw );

    robot->setPositionX( worldInterface->robotModels[i].origin.position.x );
    robot->setPositionY( worldInterface->robotModels[i].origin.position.y );
    robot->setPositionZ( worldInterface->robotModels[i].origin.position.z );
    robot->update();
    world->addRobot( robot );
  }

  world->rebuildCollision();
  return world;
}

/**
 * @function modelInterfaceToSkeleton
 * @brief Read the ModelInterface and spits out a SkeletonDynamics object
 */
dynamics::SkeletonDynamics* DartLoader::modelInterfaceToSkeleton( boost::shared_ptr<urdf::ModelInterface> _model ) {

  dynamics::SkeletonDynamics* mSkeleton = new dynamics::SkeletonDynamics();
  dynamics::BodyNodeDynamics *node, *rootNode;
  kinematics::Joint *joint, *rootJoint;

  // BodyNode
  mNodes.resize(0);
  for( std::map<std::string, boost::shared_ptr<urdf::Link> >::const_iterator lk = _model->links_.begin();
       lk != _model->links_.end();
       lk++ ) {
    node = createDartNode( (*lk).second, mSkeleton );
    mNodes.push_back( node );
  }
  printf("** Created %d body nodes \n", mNodes.size() );

  // Joint
  mJoints.resize(0);

  for( std::map<std::string, boost::shared_ptr<urdf::Joint> >::const_iterator jt = _model->joints_.begin();
       jt != _model->joints_.end();
       jt++ ) {
    joint = createDartJoint( (*jt).second, mSkeleton );
    mJoints.push_back( joint );

  }

  //-- root joint
  rootNode = getNode( _model->getRoot()->name );
  rootJoint = createDartRootJoint( _model->getRoot(), mSkeleton, false );
  mJoints.push_back( rootJoint );

  printf("** Created %d joints \n", mJoints.size() );

  //-- Save DART structure

  // Push parents first
  std::list<dynamics::BodyNodeDynamics*> nodeStack;
  dynamics::BodyNodeDynamics* u;
  nodeStack.push_back( rootNode );

  int numIter = 0;
  while( !nodeStack.empty() && numIter < mNodes.size() ) {

    // Get front element on stack and add it
    u = nodeStack.front();
    mSkeleton->addNode(u);

    // Pop it out
    nodeStack.pop_front();

    // Add its kids
    for( int idx = 0; idx < u->getNumChildJoints(); ++idx ) {
      nodeStack.push_back( (dynamics::BodyNodeDynamics*)( u->getChildNode(idx) ) );
    }
    numIter++;
  }
  printf("--> Pushed %d nodes in tree-like order \n", numIter );

  // Init skeleton
  mSkeleton->initSkel();

  return mSkeleton;
}

/**
 * @function modelInterfaceToRobot
 */
robotics::Robot* DartLoader::modelInterfaceToRobot( boost::shared_ptr<urdf::ModelInterface> _model ) {

  robotics::Robot* mRobot;
  dynamics::BodyNodeDynamics *node, *rootNode;
  kinematics::Joint *joint, *rootJoint;

	mRobot = new robotics::Robot();
  mRobot->addDefaultRootNode();

  // name
  mRobot->setName( _model->getName() );

  // BodyNode
  mNodes.resize(0);
  for( std::map<std::string, boost::shared_ptr<urdf::Link> >::const_iterator lk = _model->links_.begin();
       lk != _model->links_.end();
       lk++ ) {
    node = createDartNode( (*lk).second, mRobot );
    mNodes.push_back( node );
  }
  printf("** Created %d body nodes \n", mNodes.size() );

  // Joint
  mJoints.resize(0);

  for( std::map<std::string, boost::shared_ptr<urdf::Joint> >::const_iterator jt = _model->joints_.begin();
       jt != _model->joints_.end();
       jt++ ) {
    joint = createDartJoint( (*jt).second, mRobot );
    mJoints.push_back( joint );

  }

  //-- root joint
  rootNode = getNode( _model->getRoot()->name );
  printf("[DartLoader] Root Node: %s \n", rootNode->getName() );
  rootJoint = createDartRootJoint( _model->getRoot(), mRobot, true );
  mJoints.push_back( rootJoint );

  printf("** Created %d joints \n", mJoints.size() );

  //-- Save DART structure
     // Push parents first
    std::list<dynamics::BodyNodeDynamics*> nodeStack;
    dynamics::BodyNodeDynamics* u;
    nodeStack.push_back( rootNode );

    int numIter = 0;
    while( !nodeStack.empty() && numIter < mNodes.size() ) {
      // Get front element on stack and update it
      u = nodeStack.front();
			mRobot->addNode(u);
      // Pop it out
      nodeStack.pop_front();

      // Add its kids
      for( int idx = 0; idx < u->getNumChildJoints(); ++idx ) {
	nodeStack.push_back( (dynamics::BodyNodeDynamics*)( u->getChildNode(idx) ) );
      }
      numIter++;
    }
		printf("Pushed %d nodes in order \n", numIter );

  // Init robot (skeleton)
  mRobot->initSkel();
  mRobot->update();
  return mRobot;
}

/**
 * @function modelInterfaceToObject
 */
robotics::Object* DartLoader::modelInterfaceToObject( boost::shared_ptr<urdf::ModelInterface> _model ) {

  robotics::Object* mObject;
  dynamics::BodyNodeDynamics *node, *rootNode;
  kinematics::Joint *joint, *rootJoint;

  mObject = new robotics::Object();
  mObject->addDefaultRootNode();

  // name
  mObject->setName( _model->getName() );

  // BodyNode
  mNodes.resize(0);
  for( std::map<std::string, boost::shared_ptr<urdf::Link> >::const_iterator lk = _model->links_.begin();
       lk != _model->links_.end();
       lk++ ) {
    node = createDartNode( (*lk).second, mObject );
    mNodes.push_back( node );
  }
  printf("** Created %d body nodes \n", mNodes.size() );

  // Joint
  mJoints.resize(0);

  for( std::map<std::string, boost::shared_ptr<urdf::Joint> >::const_iterator jt = _model->joints_.begin();
       jt != _model->joints_.end();
       jt++ ) {
    joint = createDartJoint( (*jt).second, mObject );
    mJoints.push_back( joint );

  }

  //-- root joint
  rootNode = getNode( _model->getRoot()->name );
  rootJoint = createDartRootJoint( _model->getRoot(), mObject, true );
  mJoints.push_back( rootJoint );

  printf("** Created %d joints \n", mJoints.size() );

  //-- Save DART structure

  // 1. Root node
  mObject->addNode( rootNode );

  // 2. The rest
  for( unsigned int i = 0; i < mNodes.size(); ++i ) {
    if( mNodes[i] != rootNode ) {
      mObject->addNode( mNodes[i] );
    }
  }

  // Init robot (skeleton)
  mObject->initSkel();
  mObject->update();

  return mObject;
}

/**
 * @function getNode
 */
dynamics::BodyNodeDynamics* DartLoader::getNode( std::string _nodeName ) {

  for( unsigned int i = 0; i < mNodes.size(); ++i ) {
    std::string node( mNodes[i]->getName() );
    if( node ==  _nodeName ) {
      return mNodes[i];
    }
  }
  printf("[getNode] ERROR: Returning  NULL for  %s \n", _nodeName.c_str() );
  return NULL;
}

/**
 * @function readXml
 */
std::string  DartLoader::readXmlToString( std::string _xmlFile ) {

  std::string xml_string;

  std::fstream xml_file( _xmlFile.c_str(), std::fstream::in );

  // Read xml
  while( xml_file.good() ) {
    std::string line;
    std::getline( xml_file, line );
    xml_string += (line + "\n");
  }
  xml_file.close();

  return xml_string;
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.13  2001/08/29 20:52:35  tng
 * Schema: xsi:type support
 *
 * Revision 1.12  2001/08/21 16:06:11  tng
 * Schema: Unique Particle Attribution Constraint Checking.
 *
 * Revision 1.11  2001/07/24 18:33:46  knoaman
 * Added support for <group> + extra constraint checking for complexType
 *
 * Revision 1.10  2001/07/09 15:22:43  knoaman
 * complete <any> declaration.
 *
 * Revision 1.9  2001/06/13 20:51:18  peiyongz
 * fIsMixed: to handle mixed Content Model
 *
 * Revision 1.8  2001/05/11 13:27:35  tng
 * Copyright update.
 *
 * Revision 1.7  2001/05/03 20:34:42  tng
 * Schema: SchemaValidator update
 *
 * Revision 1.6  2001/05/03 19:17:59  knoaman
 * TraverseSchema Part II.
 *
 * Revision 1.5  2001/04/19 17:43:16  knoaman
 * More schema implementation classes.
 *
 * Revision 1.4  2001/03/21 21:56:33  tng
 * Schema: Add Schema Grammar, Schema Validator, and split the DTDValidator into DTDValidator, DTDScanner, and DTDGrammar.
 *
 * Revision 1.3  2001/03/21 19:30:15  tng
 * Schema: Content Model Updates, by Pei Yong Zhang.
 *
 * Revision 1.2  2001/03/07 17:42:12  tng
 * fix typo
 *
 * Revision 1.1  2001/02/27 18:48:22  tng
 * Schema: Add SchemaAttDef, SchemaElementDecl, SchemaAttDefList.
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <util/XMLString.hpp>
#include <util/XMLUniDefs.hpp>
#include <util/XMLUni.hpp>
#include <validators/schema/SchemaAttDefList.hpp>
#include <validators/schema/SchemaElementDecl.hpp>

// ---------------------------------------------------------------------------
//  SchemaElementDecl: Constructors and Destructor
// ---------------------------------------------------------------------------
SchemaElementDecl::SchemaElementDecl() :

    fModelType(Any)
    , fDatatypeValidator(0)
    , fEnclosingScope(Grammar::TOP_LEVEL_SCOPE)
    , fBlockSet(0)
    , fFinalSet(0)
    , fMiscFlags(0)
    , fDefaultValue(0)
    , fSubstitutionGroupName(0)
    , fTypeFromAnotherSchemaURI(0)
    , fComplexTypeInfo(0)
    , fXsiComplexTypeInfo(0)
    , fAttDefs(0)
{
}

SchemaElementDecl::SchemaElementDecl(const XMLCh* const                  prefix
                                   , const XMLCh* const                  localPart
                                   , const int                           uriId
                                   , const SchemaElementDecl::ModelTypes type
                                   , const int                           enclosingScope
                                   ) :
    fModelType(type)
    , fDatatypeValidator(0)
    , fEnclosingScope(enclosingScope)
    , fBlockSet(0)
    , fFinalSet(0)
    , fMiscFlags(0)
    , fDefaultValue(0)
    , fSubstitutionGroupName(0)
    , fTypeFromAnotherSchemaURI(0)
    , fComplexTypeInfo(0)
    , fXsiComplexTypeInfo(0)
    , fAttDefs(0)
{
    setElementName(prefix, localPart, uriId);
}

SchemaElementDecl::SchemaElementDecl(const QName* const                  elementName
                                   , const SchemaElementDecl::ModelTypes type
                                   , const int                           enclosingScope
                                   ) :
    fModelType(type)
    , fDatatypeValidator(0)
    , fEnclosingScope(enclosingScope)
    , fBlockSet(0)
    , fFinalSet(0)
    , fMiscFlags(0)
    , fDefaultValue(0)
    , fSubstitutionGroupName(0)
    , fTypeFromAnotherSchemaURI(0)
    , fComplexTypeInfo(0)
    , fXsiComplexTypeInfo(0)
    , fAttDefs(0)
{
    setElementName(elementName);
}

SchemaElementDecl::~SchemaElementDecl()
{
    delete [] fDefaultValue;
    delete [] fSubstitutionGroupName;
    delete [] fTypeFromAnotherSchemaURI;
    delete fAttDefs;
}

// ---------------------------------------------------------------------------
//  SchemaElementDecl: XMLElementDecl virtual interface implementation
// ---------------------------------------------------------------------------
XMLAttDef* SchemaElementDecl::findAttr(const XMLCh* const    qName
                                     , const unsigned int    uriId
                                     , const XMLCh* const    baseName
                                     , const XMLCh* const    prefix
                                     , const LookupOpts      options
                                     , bool&           wasAdded) const
{
    if (fXsiComplexTypeInfo) {
        return fXsiComplexTypeInfo->findAttr(qName, uriId, baseName, prefix, options, wasAdded);
    }
    else if (fComplexTypeInfo) {
        return fComplexTypeInfo->findAttr(qName, uriId, baseName, prefix, options, wasAdded);
    }
    else {
        if (options == XMLElementDecl::AddIfNotFound) {
            SchemaAttDef* retVal = 0;

            // If no att list exist yet, then create one
            if (!fAttDefs) {
                // Use a hash modulus of 29 and tell it owns its elements
                ((SchemaElementDecl*)this)->fAttDefs = new RefHash2KeysTableOf<SchemaAttDef>(29, true);
            }

            retVal = fAttDefs->get(baseName, uriId);

            // Fault it in if not found and ask to add it
            if (!retVal)
            {
                // And add a default attribute for this name
                retVal = new SchemaAttDef(prefix, baseName, uriId);
                retVal->setElemId(getId());
                fAttDefs->put((void*)baseName, uriId, retVal);

                wasAdded = true;
            }
             else
            {
                wasAdded = false;
            }
            return retVal;
        }
        else {
            wasAdded = false;
            return 0;
        }
    }
}

XMLAttDefList& SchemaElementDecl::getAttDefList() const
{
    if (fXsiComplexTypeInfo) {
        return fXsiComplexTypeInfo->getAttDefList();
    }
    else if (fComplexTypeInfo) {
        return fComplexTypeInfo->getAttDefList();
    }
    else {
        throw; // REVISIT: add proper error message
    }
}

XMLElementDecl::CharDataOpts SchemaElementDecl::getCharDataOpts() const
{
    XMLElementDecl::CharDataOpts retVal;
    switch(fModelType)
    {
        case Children :
            retVal = XMLElementDecl::SpacesOk;
            break;

        case Empty :
            retVal = XMLElementDecl::NoCharData;
            break;

        default :
            retVal = XMLElementDecl::AllCharData;
            break;
    }
    return retVal;
}

bool SchemaElementDecl::hasAttDefs() const
{
    if (fXsiComplexTypeInfo) {
        return fXsiComplexTypeInfo->hasAttDefs();
    }
    else if (fComplexTypeInfo) {
        return fComplexTypeInfo->hasAttDefs();
    }

    // If the collection hasn't been faulted in, then no att defs
    return false;

}

bool SchemaElementDecl::resetDefs()
{
    if (fXsiComplexTypeInfo) {
        return fXsiComplexTypeInfo->resetDefs();
    }
    else if (fComplexTypeInfo) {
        return fComplexTypeInfo->resetDefs();
    }

    return false;
}

const XMLCh*
SchemaElementDecl::getFormattedContentModel() const
{
    if (fXsiComplexTypeInfo) {
        return fXsiComplexTypeInfo->getFormattedContentModel();
    }
    else if (fComplexTypeInfo) {
        return fComplexTypeInfo->getFormattedContentModel();
    }
    return 0;
}

// ---------------------------------------------------------------------------
//  SchemaElementDecl: Getter methods
// ---------------------------------------------------------------------------
const SchemaAttDef* SchemaElementDecl::getAttDef(const XMLCh* const baseName, const int uriId) const
{
    if (fXsiComplexTypeInfo) {
        return fXsiComplexTypeInfo->getAttDef(baseName, uriId);
    }
    else if (fComplexTypeInfo) {
        return fComplexTypeInfo->getAttDef(baseName, uriId);
    }

    // If no complex type, then return a null
    return 0;

}

SchemaAttDef* SchemaElementDecl::getAttDef(const XMLCh* const baseName, const int uriId)
{
    if (fXsiComplexTypeInfo) {
        return fXsiComplexTypeInfo->getAttDef(baseName, uriId);
    }
    else if (fComplexTypeInfo) {
        return fComplexTypeInfo->getAttDef(baseName, uriId);
    }

    // If no complex type, then return a null
    return 0;
}

<commit_msg>[Bug 3523] SchemaElementDecl.cpp(242) : error C2202 : not all control paths return a value<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.14  2001/09/11 13:02:40  tng
 * [Bug 3523] SchemaElementDecl.cpp(242) : error C2202 : not all control paths return a value
 *
 * Revision 1.13  2001/08/29 20:52:35  tng
 * Schema: xsi:type support
 *
 * Revision 1.12  2001/08/21 16:06:11  tng
 * Schema: Unique Particle Attribution Constraint Checking.
 *
 * Revision 1.11  2001/07/24 18:33:46  knoaman
 * Added support for <group> + extra constraint checking for complexType
 *
 * Revision 1.10  2001/07/09 15:22:43  knoaman
 * complete <any> declaration.
 *
 * Revision 1.9  2001/06/13 20:51:18  peiyongz
 * fIsMixed: to handle mixed Content Model
 *
 * Revision 1.8  2001/05/11 13:27:35  tng
 * Copyright update.
 *
 * Revision 1.7  2001/05/03 20:34:42  tng
 * Schema: SchemaValidator update
 *
 * Revision 1.6  2001/05/03 19:17:59  knoaman
 * TraverseSchema Part II.
 *
 * Revision 1.5  2001/04/19 17:43:16  knoaman
 * More schema implementation classes.
 *
 * Revision 1.4  2001/03/21 21:56:33  tng
 * Schema: Add Schema Grammar, Schema Validator, and split the DTDValidator into DTDValidator, DTDScanner, and DTDGrammar.
 *
 * Revision 1.3  2001/03/21 19:30:15  tng
 * Schema: Content Model Updates, by Pei Yong Zhang.
 *
 * Revision 1.2  2001/03/07 17:42:12  tng
 * fix typo
 *
 * Revision 1.1  2001/02/27 18:48:22  tng
 * Schema: Add SchemaAttDef, SchemaElementDecl, SchemaAttDefList.
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <util/XMLString.hpp>
#include <util/XMLUniDefs.hpp>
#include <util/XMLUni.hpp>
#include <validators/schema/SchemaAttDefList.hpp>
#include <validators/schema/SchemaElementDecl.hpp>

// ---------------------------------------------------------------------------
//  SchemaElementDecl: Constructors and Destructor
// ---------------------------------------------------------------------------
SchemaElementDecl::SchemaElementDecl() :

    fModelType(Any)
    , fDatatypeValidator(0)
    , fEnclosingScope(Grammar::TOP_LEVEL_SCOPE)
    , fBlockSet(0)
    , fFinalSet(0)
    , fMiscFlags(0)
    , fDefaultValue(0)
    , fSubstitutionGroupName(0)
    , fTypeFromAnotherSchemaURI(0)
    , fComplexTypeInfo(0)
    , fXsiComplexTypeInfo(0)
    , fAttDefs(0)
{
}

SchemaElementDecl::SchemaElementDecl(const XMLCh* const                  prefix
                                   , const XMLCh* const                  localPart
                                   , const int                           uriId
                                   , const SchemaElementDecl::ModelTypes type
                                   , const int                           enclosingScope
                                   ) :
    fModelType(type)
    , fDatatypeValidator(0)
    , fEnclosingScope(enclosingScope)
    , fBlockSet(0)
    , fFinalSet(0)
    , fMiscFlags(0)
    , fDefaultValue(0)
    , fSubstitutionGroupName(0)
    , fTypeFromAnotherSchemaURI(0)
    , fComplexTypeInfo(0)
    , fXsiComplexTypeInfo(0)
    , fAttDefs(0)
{
    setElementName(prefix, localPart, uriId);
}

SchemaElementDecl::SchemaElementDecl(const QName* const                  elementName
                                   , const SchemaElementDecl::ModelTypes type
                                   , const int                           enclosingScope
                                   ) :
    fModelType(type)
    , fDatatypeValidator(0)
    , fEnclosingScope(enclosingScope)
    , fBlockSet(0)
    , fFinalSet(0)
    , fMiscFlags(0)
    , fDefaultValue(0)
    , fSubstitutionGroupName(0)
    , fTypeFromAnotherSchemaURI(0)
    , fComplexTypeInfo(0)
    , fXsiComplexTypeInfo(0)
    , fAttDefs(0)
{
    setElementName(elementName);
}

SchemaElementDecl::~SchemaElementDecl()
{
    delete [] fDefaultValue;
    delete [] fSubstitutionGroupName;
    delete [] fTypeFromAnotherSchemaURI;
    delete fAttDefs;
}

// ---------------------------------------------------------------------------
//  SchemaElementDecl: XMLElementDecl virtual interface implementation
// ---------------------------------------------------------------------------
XMLAttDef* SchemaElementDecl::findAttr(const XMLCh* const    qName
                                     , const unsigned int    uriId
                                     , const XMLCh* const    baseName
                                     , const XMLCh* const    prefix
                                     , const LookupOpts      options
                                     , bool&           wasAdded) const
{
    if (fXsiComplexTypeInfo) {
        return fXsiComplexTypeInfo->findAttr(qName, uriId, baseName, prefix, options, wasAdded);
    }
    else if (fComplexTypeInfo) {
        return fComplexTypeInfo->findAttr(qName, uriId, baseName, prefix, options, wasAdded);
    }
    else {
        if (options == XMLElementDecl::AddIfNotFound) {
            SchemaAttDef* retVal = 0;

            // If no att list exist yet, then create one
            if (!fAttDefs) {
                // Use a hash modulus of 29 and tell it owns its elements
                ((SchemaElementDecl*)this)->fAttDefs = new RefHash2KeysTableOf<SchemaAttDef>(29, true);
            }

            retVal = fAttDefs->get(baseName, uriId);

            // Fault it in if not found and ask to add it
            if (!retVal)
            {
                // And add a default attribute for this name
                retVal = new SchemaAttDef(prefix, baseName, uriId);
                retVal->setElemId(getId());
                fAttDefs->put((void*)baseName, uriId, retVal);

                wasAdded = true;
            }
             else
            {
                wasAdded = false;
            }
            return retVal;
        }
        else {
            wasAdded = false;
            return 0;
        }
    }
}

XMLAttDefList& SchemaElementDecl::getAttDefList() const
{
    if (fXsiComplexTypeInfo) {
        return fXsiComplexTypeInfo->getAttDefList();
    }
    else if (fComplexTypeInfo) {
        return fComplexTypeInfo->getAttDefList();
    }
    else {
        throw; // REVISIT: add proper error message
    }

    return *(XMLAttDefList*)0 ;
}

XMLElementDecl::CharDataOpts SchemaElementDecl::getCharDataOpts() const
{
    XMLElementDecl::CharDataOpts retVal;
    switch(fModelType)
    {
        case Children :
            retVal = XMLElementDecl::SpacesOk;
            break;

        case Empty :
            retVal = XMLElementDecl::NoCharData;
            break;

        default :
            retVal = XMLElementDecl::AllCharData;
            break;
    }
    return retVal;
}

bool SchemaElementDecl::hasAttDefs() const
{
    if (fXsiComplexTypeInfo) {
        return fXsiComplexTypeInfo->hasAttDefs();
    }
    else if (fComplexTypeInfo) {
        return fComplexTypeInfo->hasAttDefs();
    }

    // If the collection hasn't been faulted in, then no att defs
    return false;

}

bool SchemaElementDecl::resetDefs()
{
    if (fXsiComplexTypeInfo) {
        return fXsiComplexTypeInfo->resetDefs();
    }
    else if (fComplexTypeInfo) {
        return fComplexTypeInfo->resetDefs();
    }

    return false;
}

const XMLCh*
SchemaElementDecl::getFormattedContentModel() const
{
    if (fXsiComplexTypeInfo) {
        return fXsiComplexTypeInfo->getFormattedContentModel();
    }
    else if (fComplexTypeInfo) {
        return fComplexTypeInfo->getFormattedContentModel();
    }
    return 0;
}

// ---------------------------------------------------------------------------
//  SchemaElementDecl: Getter methods
// ---------------------------------------------------------------------------
const SchemaAttDef* SchemaElementDecl::getAttDef(const XMLCh* const baseName, const int uriId) const
{
    if (fXsiComplexTypeInfo) {
        return fXsiComplexTypeInfo->getAttDef(baseName, uriId);
    }
    else if (fComplexTypeInfo) {
        return fComplexTypeInfo->getAttDef(baseName, uriId);
    }

    // If no complex type, then return a null
    return 0;

}

SchemaAttDef* SchemaElementDecl::getAttDef(const XMLCh* const baseName, const int uriId)
{
    if (fXsiComplexTypeInfo) {
        return fXsiComplexTypeInfo->getAttDef(baseName, uriId);
    }
    else if (fComplexTypeInfo) {
        return fComplexTypeInfo->getAttDef(baseName, uriId);
    }

    // If no complex type, then return a null
    return 0;
}

<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_PROB_ORDERED_PROBIT_LPMF_HPP
#define STAN_MATH_PRIM_PROB_ORDERED_PROBIT_LPMF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/log_diff_exp.hpp>
#include <stan/math/prim/fun/log1m_exp.hpp>
#include <stan/math/prim/fun/size_mvt.hpp>
#include <stan/math/prim/fun/to_ref.hpp>
#include <stan/math/prim/prob/std_normal_lcdf.hpp>
#include <vector>
#include <cmath>

namespace stan {
namespace math {

/** \ingroup multivar_dists
 * Returns the (natural) log probability of the specified array
 * of integers given the vector of continuous locations and
 * array of specified cutpoints in an ordered probit model.
 *
 *
Typically the continuous location
 * will be the dot product of a vector of regression coefficients
 * and a vector of predictors for the outcome.
 *
 * @tparam propto True if calculating up to a proportion.
 * @tparam T_y Type of y variable - `int` or `std::vector<int>`.
 * @tparam T_loc Location type - Eigen vector or scalar.
 * @tparam T_cut Cut-point type - Eigen vector or a std vector of Eigen vectors.
 * @param y integer or Array of integers
 * @param lambda Location.
 * @param c Positive increasing vectors of cutpoints.
 * @return Log probability of outcome given location and
 * cutpoints.
 * @throw std::domain_error If the outcome is not between 1 and
 * the number of cutpoints plus 2; if the cutpoint vector contains a
 * non-positive or non-finite value; or if the cutpoint vector is not sorted in
 * ascending order.
 * @throw std::invalid_argument If y and lambda are different
 * lengths; if the cutpoint vector is empty; if y and the array of cutpoints are
 * of different lengths.
 */
template <bool propto, typename T_y, typename T_loc, typename T_cut>
return_type_t<T_loc, T_cut> ordered_probit_lpmf(const T_y& y,
                                                const T_loc& lambda,
                                                const T_cut& c) {
  using std::exp;
  using std::log;
  using T_lambda_ref = ref_type_t<T_loc>;
  static const char* function = "ordered_probit";

  check_nonzero_size(function, "Cut-points", c);
  int N = size(lambda);
  int C_l = size_mvt(c);
  vector_seq_view<T_cut> c_vec(c);
  int K = c_vec[0].size() + 1;

  check_consistent_sizes(function, "Integers", y, "Locations", lambda);
  if (C_l > 1) {
    check_size_match(function, "Length of location variables ", N,
                     "Number of cutpoint vectors ", C_l);
  }

  check_bounded(function, "Random variable", y, 1, K);
  scalar_seq_view<T_y> y_vec(y);
  check_nonzero_size(function, "First cutpoint set", c_vec[0]);
  for (int i = 0; i < size_mvt(c); ++i) {
    check_size_match(function, "One cutpoint set", K - 1, "First cutpoint set",
                     c_vec[i].size());
    check_ordered(function, "Cut-points", c_vec[i]);
    if (K > 2) {
      check_finite(function, "Final cut point", c_vec[i].coeff(K - 2));
    }
    check_finite(function, "First cut point", c_vec[i].coeff(0));
  }

  T_lambda_ref lambda_ref = lambda;
  check_finite(function, "Location parameter", lambda_ref);
  scalar_seq_view<T_lambda_ref> lambda_vec(lambda_ref);

  return_type_t<T_loc, T_cut> logp_n(0.0);

  for (int i = 0; i < N; ++i) {
    int K = c_vec[i].size() + 1;

    if (y_vec[i] == 1) {
      logp_n += log1m_exp(std_normal_lcdf(lambda_vec[i] - c_vec[i].coeff(0)));
    } else if (y_vec[i] == K) {
      logp_n += std_normal_lcdf(lambda_vec[i] - c_vec[i].coeff(K - 2));
    } else {
      logp_n += log_diff_exp(
                  std_normal_lcdf(lambda_vec[i] - c_vec[i].coeff(y_vec[i] - 2)),
                  std_normal_lcdf(lambda_vec[i] - c_vec[i].coeff(y_vec[i] - 1)));
    }
  }
  return logp_n;
}

template <typename T_y, typename T_loc, typename T_cut>
return_type_t<T_loc, T_cut> ordered_probit_lpmf(const T_y& y,
                                                const T_loc& lambda,
                                                const T_cut& c) {
  return ordered_probit_lpmf<false>(y, lambda, c);
}
}  // namespace math
}  // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MATH_PRIM_PROB_ORDERED_PROBIT_LPMF_HPP
#define STAN_MATH_PRIM_PROB_ORDERED_PROBIT_LPMF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/log_diff_exp.hpp>
#include <stan/math/prim/fun/log1m_exp.hpp>
#include <stan/math/prim/fun/size_mvt.hpp>
#include <stan/math/prim/fun/to_ref.hpp>
#include <stan/math/prim/prob/std_normal_lcdf.hpp>
#include <vector>
#include <cmath>

namespace stan {
namespace math {

/** \ingroup multivar_dists
 * Returns the (natural) log probability of the specified array
 * of integers given the vector of continuous locations and
 * array of specified cutpoints in an ordered probit model.
 *
 *
Typically the continuous location
 * will be the dot product of a vector of regression coefficients
 * and a vector of predictors for the outcome.
 *
 * @tparam propto True if calculating up to a proportion.
 * @tparam T_y Type of y variable - `int` or `std::vector<int>`.
 * @tparam T_loc Location type - Eigen vector or scalar.
 * @tparam T_cut Cut-point type - Eigen vector or a std vector of Eigen vectors.
 * @param y integer or Array of integers
 * @param lambda Location.
 * @param c Positive increasing vectors of cutpoints.
 * @return Log probability of outcome given location and
 * cutpoints.
 * @throw std::domain_error If the outcome is not between 1 and
 * the number of cutpoints plus 2; if the cutpoint vector contains a
 * non-positive or non-finite value; or if the cutpoint vector is not sorted in
 * ascending order.
 * @throw std::invalid_argument If y and lambda are different
 * lengths; if the cutpoint vector is empty; if y and the array of cutpoints are
 * of different lengths.
 */
template <bool propto, typename T_y, typename T_loc, typename T_cut>
return_type_t<T_loc, T_cut> ordered_probit_lpmf(const T_y& y,
                                                const T_loc& lambda,
                                                const T_cut& c) {
  using std::exp;
  using std::log;
  using T_lambda_ref = ref_type_t<T_loc>;
  static const char* function = "ordered_probit";

  check_nonzero_size(function, "Cut-points", c);
  int N = size(lambda);
  int C_l = size_mvt(c);
  vector_seq_view<T_cut> c_vec(c);
  int K = c_vec[0].size() + 1;

  check_consistent_sizes(function, "Integers", y, "Locations", lambda);
  if (C_l > 1) {
    check_size_match(function, "Length of location variables ", N,
                     "Number of cutpoint vectors ", C_l);
  }

  check_bounded(function, "Random variable", y, 1, K);
  scalar_seq_view<T_y> y_vec(y);
  check_nonzero_size(function, "First cutpoint set", c_vec[0]);
  for (int i = 0; i < size_mvt(c); ++i) {
    check_size_match(function, "One cutpoint set", K - 1, "First cutpoint set",
                     c_vec[i].size());
    check_ordered(function, "Cut-points", c_vec[i]);
    if (K > 2) {
      check_finite(function, "Final cut point", c_vec[i].coeff(K - 2));
    }
    check_finite(function, "First cut point", c_vec[i].coeff(0));
  }

  T_lambda_ref lambda_ref = lambda;
  check_finite(function, "Location parameter", lambda_ref);
  scalar_seq_view<T_lambda_ref> lambda_vec(lambda_ref);

  return_type_t<T_loc, T_cut> logp_n(0.0);

  for (int i = 0; i < N; ++i) {
    int K = c_vec[i].size() + 1;

    if (y_vec[i] == 1) {
      logp_n += log1m_exp(std_normal_lcdf(lambda_vec[i] - c_vec[i].coeff(0)));
    } else if (y_vec[i] == K) {
      logp_n += std_normal_lcdf(lambda_vec[i] - c_vec[i].coeff(K - 2));
    } else {
      logp_n += log_diff_exp(
          std_normal_lcdf(lambda_vec[i] - c_vec[i].coeff(y_vec[i] - 2)),
          std_normal_lcdf(lambda_vec[i] - c_vec[i].coeff(y_vec[i] - 1)));
    }
  }
  return logp_n;
}

template <typename T_y, typename T_loc, typename T_cut>
return_type_t<T_loc, T_cut> ordered_probit_lpmf(const T_y& y,
                                                const T_loc& lambda,
                                                const T_cut& c) {
  return ordered_probit_lpmf<false>(y, lambda, c);
}
}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>// IFC SDK : IFC2X3 C++ Early Classes
// Copyright (C) 2009 CSTB
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full license is in Licence.txt file included with this
// distribution or is available at :
//     http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

#include <ifc2x3/SPFReader.h>
#include <ifc2x3/SPFWriter.h>
#include <ifc2x3/ExpressDataSet.h>
#include <ifc2x3/IfcProject.h>
#include <ifc2x3/IfcLocalPlacement.h>
#include <ifc2x3/IfcAxis2Placement.h>
#include <ifc2x3/IfcAxis2Placement2D.h>
#include <ifc2x3/IfcAxis2Placement3D.h>

#include <Step/CallBack.h>

#include <iostream>

class ConsoleCallBack : public Step::CallBack
{
public:
    ConsoleCallBack() : _max(1) {}
    virtual void setMaximum(unsigned long max) { _max = max; }
    virtual void setProgress(unsigned long progress) { std::cerr << double(progress)/double(_max)*100.0 << "%" << std::endl; }
protected:
    unsigned long _max;
};

int main(int argc, char **argv)
{
    std::cout << "Simple read/write example of Ifc2x3 SDK" << std::endl;

    if (argc < 2)
    {
        std::cout << "no ifc file to read in command line ." << std::endl;
        return 1;
    }

    // ** open, load, close the file
    std::ifstream ifcFile;
    ifcFile.open(argv[1]);

    ifc2x3::SPFReader reader;
    ConsoleCallBack cb;
    reader.setCallBack(&cb);

    if ( ifcFile.is_open() )
    {
        std::cout << "reading file ..." << std::endl;
    }
    else
    {
        std::cout << "ERROR: failed to open <" << argv[1] << ">" << std::endl;
        return 1;
    }
    bool result = reader.read(ifcFile);
    ifcFile.close();

    if (result)
        std::cout << "OK!!" << std::endl;
    else
    {
        std::cout << "Ho no, there is a PROBLEM!!" << std::endl;
        std::vector<std::string> errors = reader.errors();
        std::vector<std::string>::iterator it = errors.begin();
        while(it != errors.end())
        {
            std::cout << *it << std::endl;
            ++it;
        }

        return 1;
    }

    // ** get the model
    ifc2x3::ExpressDataSet * expressDataSet = dynamic_cast<ifc2x3::ExpressDataSet*>(reader.getExpressDataSet());

    if (expressDataSet == NULL)
    {
        std::cout << "Ho no ... there is no ExpressDataSet." << std::endl;
        return (2);
    }

    // ** Instantiate the model
    expressDataSet->instantiateAll();

    // ** Check the root of the model
    Step::RefLinkedList< ifc2x3::IfcProject > projects = expressDataSet->getAllIfcProject();
    if ( projects.size() == 0 ) {
        std::cout << "Strange ... there is no IfcProject" << std::endl;
    } else if ( projects.size() > 1 ) {
        std::cout << "Strange ... there more than one IfcProject" << std::endl;
    } else {
        Step::RefPtr< ifc2x3::IfcProject > project = &*(projects.begin());
        std::cout << "Project name is: " << project->getName().toLatin1() << std::endl;
        if ( Step::isUnset(project->getLongName().toLatin1()) ) {
            project->setLongName("Je lui donne le nom que je veux");
        }
        std::cout << "Project long name is: " << project->getLongName().toLatin1() << std::endl;
    }

    // ** Write the file
    ifc2x3::SPFWriter writer(expressDataSet);
    writer.setCallBack(&cb);
    std::ofstream filestream;
    if (argc==3)
    {
        filestream.open(argv[2]);
    }
    else
    {
        filestream.open("saved.ifc");
    }
    bool status = writer.write(filestream);
    filestream.close();
    return status;
}
<commit_msg>Changed 'long' by 'int' and 'unsigned long' by 'size_t' when necessary. long is 64 bit in GCC when compiling in 64 bits.<commit_after>// IFC SDK : IFC2X3 C++ Early Classes
// Copyright (C) 2009 CSTB
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full license is in Licence.txt file included with this
// distribution or is available at :
//     http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

#include <ifc2x3/SPFReader.h>
#include <ifc2x3/SPFWriter.h>
#include <ifc2x3/ExpressDataSet.h>
#include <ifc2x3/IfcProject.h>
#include <ifc2x3/IfcLocalPlacement.h>
#include <ifc2x3/IfcAxis2Placement.h>
#include <ifc2x3/IfcAxis2Placement2D.h>
#include <ifc2x3/IfcAxis2Placement3D.h>

#include <Step/CallBack.h>

#include <iostream>

class ConsoleCallBack : public Step::CallBack
{
public:
    ConsoleCallBack() : _max(1) {}
    virtual void setMaximum(size_t max) { _max = max; }
    virtual void setProgress(size_t progress) { std::cerr << double(progress)/double(_max)*100.0 << "%" << std::endl; }
protected:
    unsigned long _max;
};

int main(int argc, char **argv)
{
    std::cout << "Simple read/write example of Ifc2x3 SDK" << std::endl;

    if (argc < 2)
    {
        std::cout << "no ifc file to read in command line ." << std::endl;
        return 1;
    }

    // ** open, load, close the file
    std::ifstream ifcFile;
    ifcFile.open(argv[1]);

    ifc2x3::SPFReader reader;
    ConsoleCallBack cb;
    reader.setCallBack(&cb);

    if ( ifcFile.is_open() )
    {
        std::cout << "reading file ..." << std::endl;
    }
    else
    {
        std::cout << "ERROR: failed to open <" << argv[1] << ">" << std::endl;
        return 1;
    }
    bool result = reader.read(ifcFile);
    ifcFile.close();

    if (result)
        std::cout << "OK!!" << std::endl;
    else
    {
        std::cout << "Ho no, there is a PROBLEM!!" << std::endl;
        std::vector<std::string> errors = reader.errors();
        std::vector<std::string>::iterator it = errors.begin();
        while(it != errors.end())
        {
            std::cout << *it << std::endl;
            ++it;
        }

        return 1;
    }

    // ** get the model
    ifc2x3::ExpressDataSet * expressDataSet = dynamic_cast<ifc2x3::ExpressDataSet*>(reader.getExpressDataSet());

    if (expressDataSet == NULL)
    {
        std::cout << "Ho no ... there is no ExpressDataSet." << std::endl;
        return (2);
    }

    // ** Instantiate the model
    expressDataSet->instantiateAll();

    // ** Check the root of the model
    Step::RefLinkedList< ifc2x3::IfcProject > projects = expressDataSet->getAllIfcProject();
    if ( projects.size() == 0 ) {
        std::cout << "Strange ... there is no IfcProject" << std::endl;
    } else if ( projects.size() > 1 ) {
        std::cout << "Strange ... there more than one IfcProject" << std::endl;
    } else {
        Step::RefPtr< ifc2x3::IfcProject > project = &*(projects.begin());
        std::cout << "Project name is: " << project->getName().toLatin1() << std::endl;
        if ( Step::isUnset(project->getLongName().toLatin1()) ) {
            project->setLongName("Je lui donne le nom que je veux");
        }
        std::cout << "Project long name is: " << project->getLongName().toLatin1() << std::endl;
    }

    // ** Write the file
    ifc2x3::SPFWriter writer(expressDataSet);
    writer.setCallBack(&cb);
    std::ofstream filestream;
    if (argc==3)
    {
        filestream.open(argv[2]);
    }
    else
    {
        filestream.open("saved.ifc");
    }
    bool status = writer.write(filestream);
    filestream.close();
    return status;
}
<|endoftext|>


<commit_before>#ifndef CPS_SEARCHRESPONSE_HPP
#define CPS_SEARCHRESPONSE_HPP

#include <string>
#include <vector>
#include <map>

#include "../Response.hpp"
#include "../Utils.hpp"

namespace CPS
{
class SearchResponse;
typedef SearchResponse SimilarResponse;
typedef SearchResponse SimilarDocumentResponse;
typedef SearchResponse SimilarTextResponse;

class SearchFacet
{
public:
    class Term
    {
    public:
        /**
         * @param name term name
         * @param hits how many documents match this facet
         */
        Term(const string &name, int hits) {
            this->name = name;
            this->hits = hits;
        }
        virtual ~Term() {
        }

        /** Term name */
        string name;
        /** How many documents match this facet */
        int hits;
    };

    /** @param path Facet path */
    SearchFacet(const string &path = "") {
        this->path = path;
    }
    virtual ~SearchFacet() {
    }

    /** Facet path */
    string path;
    /** Vector of terms for this facet */
    vector<Term> terms;
};

class SearchResponse: public Response
{
public:
    /**
     * Constructs Response object.
     * Response object cannot exist without response text to work on,
     * so no default constructor is provided
     * @param rawResponse string of raw response from CPS server. This should be valid XML
     */
    SearchResponse(string rawResponse) :
        Response(rawResponse) {
    }
    virtual ~SearchResponse() {
        _documentsString.clear();
        for (unsigned int i = 0; i < _documentsXML.size(); i++) delete _documentsXML[i];
        _documentsXML.clear();
    }

    /**
     * Returns the number of documents found by lookup command
     */
    int getFound() {
        return getParam<int>("found", 0);
    }

    /**
     * Returns the position of the first document that was returned
     */
    int getFrom() {
        return getParam<int>("from", 0);
    }

    /**
     * Returns the position of the last document that was returned
     */
    int getTo() {
        return getParam<int>("to", 0);
    }

    /**
     * Returns the total number of hits - i.e. total amount of results that match the search query
     */
    int getHits() {
        return getParam<int>("hits", 0);
    }

    /**
     * Returns the map of facets where key is path for facet and value as object of type SearchFacet
     */
    map<string, SearchFacet> getFacets() {
        if (!_facets.empty())
            return _facets;
        NodeSet ns = doc->FindFast("facet", true);
        for (unsigned int i = 0; i < ns.size(); i++) {
            list<Node *> terms = ns[i]->getChildren("term");
            SearchFacet facet(ns[i]->getAttribute("path")->getValue());
            for (list<Node *>::iterator it = terms.begin(); it != terms.end();
                    it++) {
                string name = (*it)->getContent();
                int hits = atoi((*it)->getAttribute("hits")->getContentPtr());
                facet.terms.push_back(SearchFacet::Term(name, hits));
            }
            _facets[facet.path] = facet;
        }
        return _facets;
    }

    /**
     * Returns the documents from the response as vector of documents represented as strings
     * @param documentTagName string that identifies root of document
     * @param formatted boolean, true if document should be formatted with spaces for better readability
     */
    vector<string> getDocumentsString(bool formatted = true) {
        if (!_documentsString.empty())
            return _documentsString;
        NodeSet ns = doc->FindFast("cps:reply/cps:content/results/" + documentRootXpath, true);
        for (unsigned int i = 0; i < ns.size(); i++) {
            _documentsString.push_back(ns[i]->toString(!formatted));
        }
        return _documentsString;
    }

    /**
     * Returns the documents from the response as vector of documents represented as XMLDocument
     * @param documentTagName string that identifies root of document
     * @see XMLDocument
     */
    vector<XMLDocument*> getDocumentsXML() {
        if (!_documentsXML.empty())
            return _documentsXML;
        NodeSet ns = doc->FindFast("cps:reply/cps:content/results/" + documentRootXpath, true);
        for (int i = 0; i < (int) ns.size(); i++) {
            _documentsXML.push_back(XMLDocument::parseFromMemory(ns[i]->toString(false)));
        }
        return _documentsXML;
    }

private:
    vector<string> _documentsString;
    vector<XMLDocument*> _documentsXML;
    map<string, SearchFacet> _facets;
};
}

#endif /* CPS_SEARCHRESPONSE_HPP */
<commit_msg>Fix C++ API<commit_after>#ifndef CPS_SEARCHRESPONSE_HPP
#define CPS_SEARCHRESPONSE_HPP

#include <string>
#include <vector>
#include <map>

#include "../Response.hpp"
#include "../Utils.hpp"

namespace CPS
{
class SearchResponse;
typedef SearchResponse SimilarResponse;
typedef SearchResponse SimilarDocumentResponse;
typedef SearchResponse SimilarTextResponse;

class SearchFacet
{
public:
    class Term
    {
    public:
        /**
         * @param name term name
         * @param hits how many documents match this facet
         */
        Term(const string &name, int hits) {
            this->name = name;
            this->hits = hits;
        }
        virtual ~Term() {
        }

        /** Term name */
        string name;
        /** How many documents match this facet */
        int hits;
    };

    /** @param path Facet path */
    SearchFacet(const string &path = "") {
        this->path = path;
    }
    virtual ~SearchFacet() {
    }

    /** Facet path */
    string path;
    /** Vector of terms for this facet */
    vector<Term> terms;
};

class SearchResponse: public Response
{
public:
    /**
     * Constructs Response object.
     * Response object cannot exist without response text to work on,
     * so no default constructor is provided
     * @param rawResponse string of raw response from CPS server. This should be valid XML
     */
    SearchResponse(string rawResponse) :
        Response(rawResponse) {
    }
    virtual ~SearchResponse() {
        _documentsString.clear();
        for (unsigned int i = 0; i < _documentsXML.size(); i++) delete _documentsXML[i];
        _documentsXML.clear();
    }

    /**
     * Returns the number of documents found by lookup command
     */
    int getFound() {
        return getParam<int>("found", 0);
    }

    /**
     * Returns the position of the first document that was returned
     */
    int getFrom() {
        return getParam<int>("from", 0);
    }

    /**
     * Returns the position of the last document that was returned
     */
    int getTo() {
        return getParam<int>("to", 0);
    }

    /**
     * Returns the total number of hits - i.e. total amount of results that match the search query
     */
    int getHits() {
        return getParam<int>("hits", 0);
    }

    /**
     * Returns the map of facets where key is path for facet and value as object of type SearchFacet
     */
    map<string, SearchFacet> getFacets() {
        if (!_facets.empty())
            return _facets;
        NodeSet ns = doc->FindFast("cps:reply/cps:content/facet", true);
        for (unsigned int i = 0; i < ns.size(); i++) {
            list<Node *> terms = ns[i]->getChildren("term");
            SearchFacet facet(ns[i]->getAttribute("path")->getValue());
            for (list<Node *>::iterator it = terms.begin(); it != terms.end();
                    it++) {
                string name = (*it)->getContent();
                int hits = atoi((*it)->getAttribute("hits")->getContentPtr());
                facet.terms.push_back(SearchFacet::Term(name, hits));
            }
            _facets[facet.path] = facet;
        }
        return _facets;
    }

    /**
     * Returns the documents from the response as vector of documents represented as strings
     * @param documentTagName string that identifies root of document
     * @param formatted boolean, true if document should be formatted with spaces for better readability
     */
    vector<string> getDocumentsString(bool formatted = true) {
        if (!_documentsString.empty())
            return _documentsString;
        NodeSet ns = doc->FindFast("cps:reply/cps:content/results/" + documentRootXpath, true);
        for (unsigned int i = 0; i < ns.size(); i++) {
            _documentsString.push_back(ns[i]->toString(!formatted));
        }
        return _documentsString;
    }

    /**
     * Returns the documents from the response as vector of documents represented as XMLDocument
     * @param documentTagName string that identifies root of document
     * @see XMLDocument
     */
    vector<XMLDocument*> getDocumentsXML() {
        if (!_documentsXML.empty())
            return _documentsXML;
        NodeSet ns = doc->FindFast("cps:reply/cps:content/results/" + documentRootXpath, true);
        for (int i = 0; i < (int) ns.size(); i++) {
            _documentsXML.push_back(XMLDocument::parseFromMemory(ns[i]->toString(false)));
        }
        return _documentsXML;
    }

private:
    vector<string> _documentsString;
    vector<XMLDocument*> _documentsXML;
    map<string, SearchFacet> _facets;
};
}

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


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once
#ifndef DASHBOARD_COMPONENTS_CPUSAGE_HPP
#define DASHBOARD_COMPONENTS_CPUSAGE_HPP

#include "../component.hpp"

#include <kernel/irq_manager.hpp>
#include <timers>
#include <delegate>

namespace dashboard {

class CPUsage : public Component {

public:

  CPUsage(::IRQ_manager& manager, Timers::duration_t when, Timers::duration_t interval)
   :  manager_{manager},
      interval_{interval}
  {
    using OnTimeout = Timers::handler_t;

    timer_id_ = Timers::periodic(when, interval,
      OnTimeout::from<CPUsage, &CPUsage::update_values>(this));
  }

  ~CPUsage() {
    Timers::stop(timer_id_);
  }

  std::string key() const override
  { return "cpu_usage"; }

  void serialize(Writer& writer) override {
    writer.StartObject();

    writer.Key("halt");

    if(new_halt_ > old_halt_)
      serialized_halt_ = new_halt_ - old_halt_;

    writer.Uint64(serialized_halt_);

    writer.Key("total");

    if(new_total_ > old_total_)
      serialized_total_ = new_total_ - old_total_;

    writer.Uint64(serialized_total_);

    writer.Key("interval");
    writer.Double(interval_.count());

    writer.EndObject();
  }

private:
  uint64_t old_halt_ = 0;
  uint64_t new_halt_ = 0;
  uint64_t old_total_ = 0;
  uint64_t new_total_ = 0;

  uint64_t serialized_halt_ = 0;
  uint64_t serialized_total_ = 0;

  ::IRQ_manager& manager_;
  Timers::duration_t interval_;
  Timers::id_t timer_id_;

  void update_values(Timers::id_t) {
    uint64_t temp_halt = new_halt_;
    uint64_t temp_total = new_total_;

    new_halt_ = manager_.cycles_hlt();
    new_total_ = manager_.cycles_total();
    old_halt_ = temp_halt;
    old_total_ = temp_total;
  }
};

} // < namespace dashboard

#endif
<commit_msg>Delegate init update<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once
#ifndef DASHBOARD_COMPONENTS_CPUSAGE_HPP
#define DASHBOARD_COMPONENTS_CPUSAGE_HPP

#include "../component.hpp"

#include <kernel/irq_manager.hpp>
#include <timers>
#include <delegate>

namespace dashboard {

class CPUsage : public Component {

public:

  CPUsage(::IRQ_manager& manager, Timers::duration_t when, Timers::duration_t interval)
   :  manager_{manager},
      interval_{interval},
      timer_id_{Timers::periodic(when, interval, {this, &CPUsage::update_values})}
  {}

  ~CPUsage() {
    Timers::stop(timer_id_);
  }

  std::string key() const override
  { return "cpu_usage"; }

  void serialize(Writer& writer) override {
    writer.StartObject();

    writer.Key("halt");

    if(new_halt_ > old_halt_)
      serialized_halt_ = new_halt_ - old_halt_;

    writer.Uint64(serialized_halt_);

    writer.Key("total");

    if(new_total_ > old_total_)
      serialized_total_ = new_total_ - old_total_;

    writer.Uint64(serialized_total_);

    writer.Key("interval");
    writer.Double(interval_.count());

    writer.EndObject();
  }

private:
  uint64_t old_halt_ = 0;
  uint64_t new_halt_ = 0;
  uint64_t old_total_ = 0;
  uint64_t new_total_ = 0;

  uint64_t serialized_halt_ = 0;
  uint64_t serialized_total_ = 0;

  ::IRQ_manager& manager_;
  Timers::duration_t interval_;
  Timers::id_t timer_id_;

  void update_values(Timers::id_t) {
    uint64_t temp_halt = new_halt_;
    uint64_t temp_total = new_total_;

    new_halt_ = manager_.cycles_hlt();
    new_total_ = manager_.cycles_total();
    old_halt_ = temp_halt;
    old_total_ = temp_total;
  }
};

} // < namespace dashboard

#endif
<|endoftext|>