<commit_before>/*
 * Copyright (c) 2008, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * 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.
 *     * Neither the name of the Willow Garage, Inc. nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS 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 COPYRIGHT OWNER OR 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.
 */

#include "new_display_dialog.h"

#include <sstream>

#include <wx/msgdlg.h>

namespace rviz
{

class NewDisplayDialogTreeItemData : public wxTreeItemData
{
public:
  int32_t index;
};

NewDisplayDialog::NewDisplayDialog( wxWindow* parent, const L_Plugin& plugins, const S_string& current_display_names )
: NewDisplayDialogGenerated( parent )
, current_display_names_(current_display_names)
{
  wxTreeItemId root = types_->AddRoot(wxT(""));

  L_Plugin::const_iterator pit = plugins.begin();
  L_Plugin::const_iterator pend = plugins.end();
  for (; pit != pend; ++pit)
  {
    const PluginPtr& plugin = *pit;

    wxTreeItemId parent = types_->AppendItem(root, wxString::FromAscii(plugin->getName().c_str()));

    L_DisplayTypeInfo::const_iterator it = plugin->getDisplayTypeInfoList().begin();
    L_DisplayTypeInfo::const_iterator end = plugin->getDisplayTypeInfoList().end();
    for ( ; it != end; ++it )
    {
      const DisplayTypeInfoPtr& info = *it;

      NewDisplayDialogTreeItemData* data = new NewDisplayDialogTreeItemData;
      data->index = typeinfo_.size();
      types_->AppendItem( parent, wxString::FromAscii( info->display_name.c_str() ), -1, -1, data );

      DisplayTypeInfoWithPlugin t;
      t.plugin = plugin;
      t.typeinfo = info;
      typeinfo_.push_back(t);
    }
  }

  type_description_->Connect(wxEVT_COMMAND_HTML_LINK_CLICKED, wxHtmlLinkEventHandler(NewDisplayDialog::onLinkClicked), NULL, this);

  types_->ExpandAll();
}

int32_t NewDisplayDialog::getSelectionIndex()
{
  wxTreeItemId sel = types_->GetSelection();
  if (!sel.IsOk())
  {
    return -1;
  }

  NewDisplayDialogTreeItemData* data = (NewDisplayDialogTreeItemData*)types_->GetItemData(sel);
  if (!data)
  {
    return -1;
  }

  int32_t index = data->index;
  return index;
}

void NewDisplayDialog::onDisplaySelected( wxTreeEvent& event )
{
  int32_t index = getSelectionIndex();
  if (index < 0)
  {
    name_->SetValue(wxT(""));
    type_description_->SetPage(wxT(""));
    return;
  }

  const DisplayTypeInfoPtr& info = typeinfo_[index].typeinfo;
  type_description_->SetPage( wxString::FromAscii( info->help_description.c_str() ) );

  int counter = 1;
  std::string name;
  do
  {
    std::stringstream ss;
    ss << info->display_name;

    if (counter > 1)
    {
      ss << counter;
    }

    ++counter;

    name = ss.str();
  } while(current_display_names_.find(name) != current_display_names_.end());

  name_->SetValue(wxString::FromAscii(name.c_str()));

  Layout();
}

void NewDisplayDialog::onLinkClicked(wxHtmlLinkEvent& event)
{
  wxLaunchDefaultBrowser(event.GetLinkInfo().GetHref());
}

void NewDisplayDialog::onDisplayDClick( wxMouseEvent& event )
{
  int32_t index = getSelectionIndex();
  if (index < 0)
  {
    return;
  }

  if ( name_->GetValue().IsEmpty() )
  {
    wxMessageBox( wxT("You must enter a name!"), wxT("No name"), wxICON_ERROR | wxOK, this );
    return;
  }

  EndModal(wxOK);
}

void NewDisplayDialog::onOK( wxCommandEvent& event )
{
  int32_t index = getSelectionIndex();
  if (index < 0)
  {
    wxMessageBox( wxT("You must select a type!"), wxT("No selection"), wxICON_ERROR | wxOK, this );
    return;
  }

  if ( name_->GetValue().IsEmpty() )
  {
    wxMessageBox( wxT("You must enter a name!"), wxT("No name"), wxICON_ERROR | wxOK, this );
    return;
  }

  std::string name = (const char*)name_->GetValue().fn_str();
  if (current_display_names_.find(name) != current_display_names_.end())
  {
    wxMessageBox( wxT("A display with that name already exists!"), wxT("Name conflict"), wxICON_ERROR | wxOK, this );
    return;
  }

  EndModal(wxOK);
}

void NewDisplayDialog::onCancel( wxCommandEvent& event )
{
  EndModal(wxCANCEL);
}

void NewDisplayDialog::onNameEnter( wxCommandEvent& event )
{
  onOK( event );
}

std::string NewDisplayDialog::getClassName()
{
  int32_t index = getSelectionIndex();
  if (index < 0)
  {
    return "";
  }

  return typeinfo_[index].typeinfo->class_name;
}

std::string NewDisplayDialog::getDisplayName()
{
  return (const char*)name_->GetValue().mb_str();
}

std::string NewDisplayDialog::getPackageName()
{
  int32_t index = getSelectionIndex();
  if (index < 0)
  {
    return "";
  }

  return typeinfo_[index].plugin->getPackageName();
}

} // rviz

<commit_msg>Don't allow creating displays from non-loaded plugins, and sort the display types alphabetically<commit_after>/*
 * Copyright (c) 2008, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * 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.
 *     * Neither the name of the Willow Garage, Inc. nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS 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 COPYRIGHT OWNER OR 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.
 */

#include "new_display_dialog.h"

#include <sstream>

#include <wx/msgdlg.h>

namespace rviz
{

class NewDisplayDialogTreeItemData : public wxTreeItemData
{
public:
  int32_t index;
};

struct DisplayTypeInfoComparator
{
  bool operator()(const DisplayTypeInfoPtr& lhs, const DisplayTypeInfoPtr& rhs) const
  {
    return lhs->display_name < rhs->display_name;
  }
};

NewDisplayDialog::NewDisplayDialog( wxWindow* parent, const L_Plugin& plugins, const S_string& current_display_names )
: NewDisplayDialogGenerated( parent )
, current_display_names_(current_display_names)
{
  wxTreeItemId root = types_->AddRoot(wxT(""));

  L_Plugin::const_iterator pit = plugins.begin();
  L_Plugin::const_iterator pend = plugins.end();
  for (; pit != pend; ++pit)
  {
    const PluginPtr& plugin = *pit;

    if (!plugin->isLoaded())
    {
      continue;
    }

    wxTreeItemId parent = types_->AppendItem(root, wxString::FromAscii(plugin->getName().c_str()));

    L_DisplayTypeInfo typeinfo_list = plugin->getDisplayTypeInfoList();
    typeinfo_list.sort(DisplayTypeInfoComparator());

    L_DisplayTypeInfo::const_iterator it = typeinfo_list.begin();
    L_DisplayTypeInfo::const_iterator end = typeinfo_list.end();
    for ( ; it != end; ++it )
    {
      const DisplayTypeInfoPtr& info = *it;

      NewDisplayDialogTreeItemData* data = new NewDisplayDialogTreeItemData;
      data->index = typeinfo_.size();
      types_->AppendItem( parent, wxString::FromAscii( info->display_name.c_str() ), -1, -1, data );

      DisplayTypeInfoWithPlugin t;
      t.plugin = plugin;
      t.typeinfo = info;
      typeinfo_.push_back(t);
    }
  }

  type_description_->Connect(wxEVT_COMMAND_HTML_LINK_CLICKED, wxHtmlLinkEventHandler(NewDisplayDialog::onLinkClicked), NULL, this);

  types_->ExpandAll();
}

int32_t NewDisplayDialog::getSelectionIndex()
{
  wxTreeItemId sel = types_->GetSelection();
  if (!sel.IsOk())
  {
    return -1;
  }

  NewDisplayDialogTreeItemData* data = (NewDisplayDialogTreeItemData*)types_->GetItemData(sel);
  if (!data)
  {
    return -1;
  }

  int32_t index = data->index;
  return index;
}

void NewDisplayDialog::onDisplaySelected( wxTreeEvent& event )
{
  int32_t index = getSelectionIndex();
  if (index < 0)
  {
    name_->SetValue(wxT(""));
    type_description_->SetPage(wxT(""));
    return;
  }

  const DisplayTypeInfoPtr& info = typeinfo_[index].typeinfo;
  type_description_->SetPage( wxString::FromAscii( info->help_description.c_str() ) );

  int counter = 1;
  std::string name;
  do
  {
    std::stringstream ss;
    ss << info->display_name;

    if (counter > 1)
    {
      ss << counter;
    }

    ++counter;

    name = ss.str();
  } while(current_display_names_.find(name) != current_display_names_.end());

  name_->SetValue(wxString::FromAscii(name.c_str()));

  Layout();
}

void NewDisplayDialog::onLinkClicked(wxHtmlLinkEvent& event)
{
  wxLaunchDefaultBrowser(event.GetLinkInfo().GetHref());
}

void NewDisplayDialog::onDisplayDClick( wxMouseEvent& event )
{
  int32_t index = getSelectionIndex();
  if (index < 0)
  {
    return;
  }

  if ( name_->GetValue().IsEmpty() )
  {
    wxMessageBox( wxT("You must enter a name!"), wxT("No name"), wxICON_ERROR | wxOK, this );
    return;
  }

  EndModal(wxOK);
}

void NewDisplayDialog::onOK( wxCommandEvent& event )
{
  int32_t index = getSelectionIndex();
  if (index < 0)
  {
    wxMessageBox( wxT("You must select a type!"), wxT("No selection"), wxICON_ERROR | wxOK, this );
    return;
  }

  if ( name_->GetValue().IsEmpty() )
  {
    wxMessageBox( wxT("You must enter a name!"), wxT("No name"), wxICON_ERROR | wxOK, this );
    return;
  }

  std::string name = (const char*)name_->GetValue().fn_str();
  if (current_display_names_.find(name) != current_display_names_.end())
  {
    wxMessageBox( wxT("A display with that name already exists!"), wxT("Name conflict"), wxICON_ERROR | wxOK, this );
    return;
  }

  EndModal(wxOK);
}

void NewDisplayDialog::onCancel( wxCommandEvent& event )
{
  EndModal(wxCANCEL);
}

void NewDisplayDialog::onNameEnter( wxCommandEvent& event )
{
  onOK( event );
}

std::string NewDisplayDialog::getClassName()
{
  int32_t index = getSelectionIndex();
  if (index < 0)
  {
    return "";
  }

  return typeinfo_[index].typeinfo->class_name;
}

std::string NewDisplayDialog::getDisplayName()
{
  return (const char*)name_->GetValue().mb_str();
}

std::string NewDisplayDialog::getPackageName()
{
  int32_t index = getSelectionIndex();
  if (index < 0)
  {
    return "";
  }

  return typeinfo_[index].plugin->getPackageName();
}

} // rviz

<|endoftext|>


<commit_before>#include "StrAlgo.h"

unsigned int GetStringHash(const char *str)
{
	unsigned int hash = 5381;
	int c;
	while((c = *str++) != 0)
		hash = ((hash << 5) + hash) + c;
	return hash;
}

unsigned int GetStringHash(const char *str, const char *end)
{
	unsigned int hash = 5381;
	while(str != end)
		hash = ((hash << 5) + hash) + (*str++);
	return hash;
}

unsigned int StringHashContinue(unsigned int hash, const char *str)
{
	int c;
	while((c = *str++) != 0)
		hash = ((hash << 5) + hash) + c;
	return hash;
}

unsigned int StringHashContinue(unsigned int hash, const char *str, const char *end)
{
	while(str != end)
		hash = ((hash << 5) + hash) + (*str++);
	return hash;
}

char* PrintInteger(char* str, int number)
{
	char buf[16];
	char *curr = buf;
	*curr++ = (char)(number % 10 + '0');
	while(number /= 10)
		*curr++ = (char)(number % 10 + '0');
	do
	{
		--curr;
		*str++ = *curr;
	}while(curr != buf);
	return str;
}

int	SafeSprintf(char* dst, size_t size, const char* src, ...)
{
	va_list args;
	va_start(args, src);

	int result = vsnprintf(dst, size, src, args);
	dst[size-1] = '\0';
	return result == -1 ? (int)size : result;
}
<commit_msg>Fixed SafeSprintf for gcc.<commit_after>#include "StrAlgo.h"

unsigned int GetStringHash(const char *str)
{
	unsigned int hash = 5381;
	int c;
	while((c = *str++) != 0)
		hash = ((hash << 5) + hash) + c;
	return hash;
}

unsigned int GetStringHash(const char *str, const char *end)
{
	unsigned int hash = 5381;
	while(str != end)
		hash = ((hash << 5) + hash) + (*str++);
	return hash;
}

unsigned int StringHashContinue(unsigned int hash, const char *str)
{
	int c;
	while((c = *str++) != 0)
		hash = ((hash << 5) + hash) + c;
	return hash;
}

unsigned int StringHashContinue(unsigned int hash, const char *str, const char *end)
{
	while(str != end)
		hash = ((hash << 5) + hash) + (*str++);
	return hash;
}

char* PrintInteger(char* str, int number)
{
	char buf[16];
	char *curr = buf;
	*curr++ = (char)(number % 10 + '0');
	while(number /= 10)
		*curr++ = (char)(number % 10 + '0');
	do
	{
		--curr;
		*str++ = *curr;
	}while(curr != buf);
	return str;
}

int	SafeSprintf(char* dst, size_t size, const char* src, ...)
{
	va_list args;
	va_start(args, src);

	int result = vsnprintf(dst, size, src, args);
	dst[size-1] = '\0';
	return (result == -1 || (size_t)result >= size) ? (int)size : result;
}
<|endoftext|>


<commit_before>/*
 * NoteEvaluator.cpp
 *
 *  Created on: Dec 2, 2012
 *      Author: xo
 */

#include "NoteEvaluator.h"

namespace MidiEngine {

NoteEvaluator::NoteEvaluator() {
    unsigned char j;
    unsigned char i;

    for (j = 0; j < SIGNAL_HISTORY_SIZE; j++) {
        for (i = 0; i < 7; i++) {
            this->old_signals[j][i] = 0;
        }
        this->old_notetimes[j] = 0;
    }
    for (i = 0; i < 7; i++) {
        this->signals[i] = 0;
    }
    this->song_filename = new char[50];
    this->song_filename[0] = 0x00;
    this->input = INPUT_SOURCE_FD; //default fd device;
}

NoteEvaluator::~NoteEvaluator() {
    delete (this->song_filename);
    delete (this->output);
    delete (this->track);
}

int NoteEvaluator::set_fd(int fd) {
    if (fd > -1) {
        this->fd = fd;
        return 1;
    }
    //Invalid fd, return it
    return fd;
}

int NoteEvaluator::set_verbose(char verbose) {
    this->verbose = verbose;
    return 1;
}

int NoteEvaluator::set_input(unsigned char source) {
    char* temp_filename = new char[1];
    temp_filename[0] = 0x00;
    return (this->set_input(source, temp_filename));
}

int NoteEvaluator::set_input(unsigned char source, char* song_filename) {

    SongReader* song;

    this->input = source;
    if (source == INPUT_SOURCE_DEBUG) {
        if (strlen(this->song_filename) == 0) {
            strcpy(this->song_filename, "./debugsong.song");
        } else {
            return 1;
        }
    } else {
        strcpy(this->song_filename, song_filename);
    }
    if (source == INPUT_SOURCE_PLAYER || source == INPUT_SOURCE_DEBUG) {
        //Create a song
        delete (this->track);
        this->track = new MidiSong();
        song = new SongReader();
        if (this->verbose) {
            fprintf(stderr, "Opening %s for playback\n", this->song_filename);
        }
        song->read_file(this->song_filename, this->track);
    }
    return 1;
}

int NoteEvaluator::set_output(char* output,unsigned int newfile_timer) {
    if(this->output != NULL){
        delete(this->output);
    }
    this->output = new SongWriter();
    this->output->set_file(output);
    this->output->set_newfile_timer(newfile_timer);
    return 1;
}

int NoteEvaluator::new_note() {
    struct timespec time;
    unsigned char i;

    if (clock_gettime(CLOCK_MONOTONIC, &time) == -1) {
        return -1;
    }
    this->iLastNoteTime = this->iCurrentNoteTime;
    this->iCurrentNoteTime = time.tv_sec * 1000000000 + time.tv_nsec;
    if (this->verbose) {
        sprintf(this->verb_timestamp, "% 9ld %09ld - ", time.tv_sec, time.tv_nsec);
    }
    for (i = 0; i < 7; i++) {
        this->signals[i] = 0;
    }
    return 1;
}

int NoteEvaluator::save_to_history() {
    unsigned char j;
    unsigned char i;

    for (j = SIGNAL_HISTORY_SIZE - 2; j < 254; j--) {
        for (i = 0; i < 7; i++) {
            this->old_signals[j + 1][i] = this->old_signals[j][i];
        }
        this->old_notetimes[j+1] = this->old_notetimes[j];
    }
    for (i = 0; i < 7; i++) {
        this->old_signals[0][i] = this->signals[i];
    }
    this->old_notetimes[0] = this->iCurrentNoteTime;
    return 1;
}

int NoteEvaluator::get_input(unsigned char& ch) {
    if (this->input == INPUT_SOURCE_FD) {
        if (read(this->fd, &ch, 1) > 0) {
            return 1;
        } else {
            return -1;
        }
    } else {
        ch = this->track->get_stream();
        return 1;
    }
    return 0;
}

int NoteEvaluator::process_input_as_loop(char*& message) {

    unsigned char ch;
    unsigned char iBitCount = 0;
    unsigned char iColumnWidth;
    char verb_buffer[60];
    char msg_buffer[20];
    unsigned char sending;
    static unsigned long long delay = 0;
    static unsigned long long threshold = 0;
    static unsigned int j;
    unsigned char midibuffer[7];
    unsigned char midibuffer2[7];
    static unsigned long long temp = 0;
    unsigned char nextSig = 0;

    while (1) {
        if (nextSig > 0 || this->get_input(ch) == 1) {
            if(nextSig > 0){
                ch = nextSig;
                nextSig = 0x00;
            }
            if (ch != 0xf8 && ch != 0xfe) {
                //Reset
                if (iBitCount == 0) {
                    if (this->new_note() == -1) {
                        sprintf(message, "Error getting time\n");
                        return -1;
                    }
                    iColumnWidth = 6;
                }
                if (iBitCount == 1) {
                    //Hi Hat depressed (single 99 04 7F message)
                    if (ch == 0x04) {
                        iColumnWidth = 3;
                    }
                }
                if ((iBitCount == 0 || iBitCount == 3) && ch != 0x99){
                    nextSig = ch;
                    ch = 0x99;
                }
                if(iBitCount == 4 && ch == 0x99){
                    continue;
                }
                if((iBitCount == 1 || iBitCount == 4) && ch == 0x90){
                    continue;
                }
                if (this->verbose) {
                    if (iBitCount == 0) {
                        strcpy(verb_buffer, this->verb_timestamp);
                    }
                    sprintf(msg_buffer, "%02x ", ch);
                    strcat(verb_buffer, msg_buffer);
                }
                this->signals[iBitCount] = ch;
                iBitCount = (iBitCount + 1) % iColumnWidth;
                if (iBitCount == 0) {
                    //Pass the signal for processing
                    sending = 1;
                    //if (this->fd > 0) {
                        delay = (this->iCurrentNoteTime - this->iLastNoteTime) / 1000;
                        //Hi Hat Splash
                        if(this->signals[1] == 0x2E && (this->old_signals[0][2] == 0x04 || this->old_signals[0][1] == 0x04) && delay < 3000){
                            sending = 0;
                        }
                        //Hi Hat Sensitivity
                        if((this->signals[1] == 0x2E || this->signals[1] == 0x2F) && this->signals[2] < 0x37){
                            sending = 0;
                        }
                        //Crash Sensitivity
                        if(this->signals[1] == 0x31 && this->signals[2] < 0x38){
                            sending = 0;
                        }
                        //Hi Hat Pedal press
                        if(this->signals[0] == 0xB9 && this->signals[1] == 0x04){
                            sending = 0;
                        }
                        //Ride double hits
                        if(this->signals[1] == 0x33 && this->signals[2] < 55){
                            sending = 0;
                        }
                        //Cymbal/hihat Doubles
                        if(sending && (this->signals[1] == 0x2E || this->signals[1] == 0x2F || this->signals[1] == 0x31 || this->signals[1] == 0x33)){
                            threshold = 60000;//Time threshold
                            for(j=0;j<SIGNAL_HISTORY_SIZE;j++){
                                //If the delay is already greater than our threshold, it's not a double hit
                                if(delay >= threshold){
                                    break;
                                }
                                //If the old signal was a hit hat hit
                                if(this->old_signals[j][1] == this->signals[1]){
                                    sending = 0;
                                    break;
                                }
                                //If it was not within a hi hat hit, increase the delay by it's delay (making future checks harder because there were longer ago)
                                if(j==(SIGNAL_HISTORY_SIZE-1)){
                                    break;
                                }
                                temp = (this->iCurrentNoteTime-this->old_notetimes[j+1]) / 1000;
                                delay = temp;
                            }
                        }
                        //Any double hits
                        threshold = 9000;//Time threshold
                        for(j=0;j<SIGNAL_HISTORY_SIZE;j++){
                            //If the delay is already greater than our threshold, it's not a double hit
                            if(delay >= threshold){
                                break;
                            }
                            //If the old signal was a hit hat hit
                            if(this->old_signals[j][1] == this->signals[1]){
                                sending = 0;
                                break;
                            }
                            //If it was not within a hi hat hit, increase the delay by it's delay (making future checks harder because there were longer ago)
                            if(j==(SIGNAL_HISTORY_SIZE-1)){
                                break;
                            }
                            temp = (this->iCurrentNoteTime-this->old_notetimes[j+1])/1000;
                            delay = delay+temp;
                        }

                        //If the note is valid, pass it through
                        if(sending){
                            for(j=0;j<6;j++){
                                midibuffer[j] = this->signals[j];
                            }
                            //Substitution
                            if(this->signals[1] == 0x2F){
                                midibuffer[1] = 0x33;
                                midibuffer[4] = 0x33;
                            }
                            //If we somehow got two velocity notes on the same signal, split them
                            if(midibuffer[5] > 0x00 && midibuffer[1] != 0xB9){
                                midibuffer2[0] = midibuffer[3];
                                midibuffer2[1] = midibuffer[4];
                                midibuffer2[2] = midibuffer[5];
                                midibuffer2[3] = 0x00;
                                midibuffer2[4] = 0x00;
                                midibuffer2[5] = 0x00;
                                midibuffer[3] = 0x00;
                                midibuffer[4] = 0x00;
                                midibuffer[5] = 0x00;
                            }else{
                                memset(midibuffer2,0,7);
                            }
                            if (write(fd, midibuffer, 5) == -1) {
                                sprintf(message, "Error writing to device\n");
                                return -1;
                            }
                            write(fd, midibuffer2, 5);midibuffer[4] = 0x00;
                            midibuffer[5] = 0x00;
                        }
                    //}
                    if(sending || (this->signals[1] == 0x04)){
                        //If recording, save the entry
                        if(this->output != NULL && this->signals[1] != 0x04){
                            this->save_note();
                        }
                        this->save_to_history();
                    }
                    if (this->verbose){// && sending) {
                        while (iColumnWidth < 6) {
                            strcat(verb_buffer, "   ");
                            iColumnWidth++;
                        }
                        if (this->iCurrentNoteTime - this->iLastNoteTime < 5000000000) {
                            sprintf(msg_buffer, " - % 9lld µs",(this->iCurrentNoteTime - this->iLastNoteTime) / 1000);
                            strcat(verb_buffer, msg_buffer);
                        }
                        if(sending == 0){
                            fprintf(stderr,"    ");
                        }
                        fprintf(stderr, "%s\n", verb_buffer);
                    }
                }
            }
        }
    }
    return 1;
}

int NoteEvaluator::save_note(){

    unsigned long long delay;
    delay = (this->iCurrentNoteTime - this->iLastNoteTime) / 1000;
    if(this->iLastNoteTime == 0){
        delay = 0;
    }

    if(this->output != NULL){
        this->output->write_note(delay,this->signals);
        return 1;
    }
    return 0;
}

} /* namespace MidiEngine */
<commit_msg>Add signal 0x30 to the mix (to differentiate from the two "rides")<commit_after>/*
 * NoteEvaluator.cpp
 *
 *  Created on: Dec 2, 2012
 *      Author: xo
 */

#include "NoteEvaluator.h"

namespace MidiEngine {

NoteEvaluator::NoteEvaluator() {
    unsigned char j;
    unsigned char i;

    for (j = 0; j < SIGNAL_HISTORY_SIZE; j++) {
        for (i = 0; i < 7; i++) {
            this->old_signals[j][i] = 0;
        }
        this->old_notetimes[j] = 0;
    }
    for (i = 0; i < 7; i++) {
        this->signals[i] = 0;
    }
    this->song_filename = new char[50];
    this->song_filename[0] = 0x00;
    this->input = INPUT_SOURCE_FD; //default fd device;
}

NoteEvaluator::~NoteEvaluator() {
    delete (this->song_filename);
    delete (this->output);
    delete (this->track);
}

int NoteEvaluator::set_fd(int fd) {
    if (fd > -1) {
        this->fd = fd;
        return 1;
    }
    //Invalid fd, return it
    return fd;
}

int NoteEvaluator::set_verbose(char verbose) {
    this->verbose = verbose;
    return 1;
}

int NoteEvaluator::set_input(unsigned char source) {
    char* temp_filename = new char[1];
    temp_filename[0] = 0x00;
    return (this->set_input(source, temp_filename));
}

int NoteEvaluator::set_input(unsigned char source, char* song_filename) {

    SongReader* song;

    this->input = source;
    if (source == INPUT_SOURCE_DEBUG) {
        if (strlen(this->song_filename) == 0) {
            strcpy(this->song_filename, "./debugsong.song");
        } else {
            return 1;
        }
    } else {
        strcpy(this->song_filename, song_filename);
    }
    if (source == INPUT_SOURCE_PLAYER || source == INPUT_SOURCE_DEBUG) {
        //Create a song
        delete (this->track);
        this->track = new MidiSong();
        song = new SongReader();
        if (this->verbose) {
            fprintf(stderr, "Opening %s for playback\n", this->song_filename);
        }
        song->read_file(this->song_filename, this->track);
    }
    return 1;
}

int NoteEvaluator::set_output(char* output,unsigned int newfile_timer) {
    if(this->output != NULL){
        delete(this->output);
    }
    this->output = new SongWriter();
    this->output->set_file(output);
    this->output->set_newfile_timer(newfile_timer);
    return 1;
}

int NoteEvaluator::new_note() {
    struct timespec time;
    unsigned char i;

    if (clock_gettime(CLOCK_MONOTONIC, &time) == -1) {
        return -1;
    }
    this->iLastNoteTime = this->iCurrentNoteTime;
    this->iCurrentNoteTime = time.tv_sec * 1000000000 + time.tv_nsec;
    if (this->verbose) {
        sprintf(this->verb_timestamp, "% 9ld %09ld - ", time.tv_sec, time.tv_nsec);
    }
    for (i = 0; i < 7; i++) {
        this->signals[i] = 0;
    }
    return 1;
}

int NoteEvaluator::save_to_history() {
    unsigned char j;
    unsigned char i;

    for (j = SIGNAL_HISTORY_SIZE - 2; j < 254; j--) {
        for (i = 0; i < 7; i++) {
            this->old_signals[j + 1][i] = this->old_signals[j][i];
        }
        this->old_notetimes[j+1] = this->old_notetimes[j];
    }
    for (i = 0; i < 7; i++) {
        this->old_signals[0][i] = this->signals[i];
    }
    this->old_notetimes[0] = this->iCurrentNoteTime;
    return 1;
}

int NoteEvaluator::get_input(unsigned char& ch) {
    if (this->input == INPUT_SOURCE_FD) {
        if (read(this->fd, &ch, 1) > 0) {
            return 1;
        } else {
            return -1;
        }
    } else {
        ch = this->track->get_stream();
        return 1;
    }
    return 0;
}

int NoteEvaluator::process_input_as_loop(char*& message) {

    unsigned char ch;
    unsigned char iBitCount = 0;
    unsigned char iColumnWidth;
    char verb_buffer[60];
    char msg_buffer[20];
    unsigned char sending;
    static unsigned long long delay = 0;
    static unsigned long long threshold = 0;
    static unsigned int j;
    unsigned char midibuffer[7];
    unsigned char midibuffer2[7];
    static unsigned long long temp = 0;
    unsigned char nextSig = 0;

    while (1) {
        if (nextSig > 0 || this->get_input(ch) == 1) {
            if(nextSig > 0){
                ch = nextSig;
                nextSig = 0x00;
            }
            if (ch != 0xf8 && ch != 0xfe) {
                //Reset
                if (iBitCount == 0) {
                    if (this->new_note() == -1) {
                        sprintf(message, "Error getting time\n");
                        return -1;
                    }
                    iColumnWidth = 6;
                }
                if (iBitCount == 1) {
                    //Hi Hat depressed (single 99 04 7F message)
                    if (ch == 0x04) {
                        iColumnWidth = 3;
                    }
                }
                if ((iBitCount == 0 || iBitCount == 3) && ch != 0x99){
                    nextSig = ch;
                    ch = 0x99;
                }
                if(iBitCount == 4 && ch == 0x99){
                    continue;
                }
                if((iBitCount == 1 || iBitCount == 4) && ch == 0x90){
                    continue;
                }
                if (this->verbose) {
                    if (iBitCount == 0) {
                        strcpy(verb_buffer, this->verb_timestamp);
                    }
                    sprintf(msg_buffer, "%02x ", ch);
                    strcat(verb_buffer, msg_buffer);
                }
                this->signals[iBitCount] = ch;
                iBitCount = (iBitCount + 1) % iColumnWidth;
                if (iBitCount == 0) {
                    //Pass the signal for processing
                    sending = 1;
                    //if (this->fd > 0) {
                        delay = (this->iCurrentNoteTime - this->iLastNoteTime) / 1000;
                        //Hi Hat Splash
                        if(this->signals[1] == 0x2E && (this->old_signals[0][2] == 0x04 || this->old_signals[0][1] == 0x04) && delay < 3000){
                            sending = 0;
                        }
                        //Hi Hat Sensitivity
                        if((this->signals[1] == 0x2E || this->signals[1] == 0x2F) && this->signals[2] < 0x37){
                            sending = 0;
                        }
                        //Crash Sensitivity
                        if(this->signals[1] == 0x31 && this->signals[2] < 0x38){
                            sending = 0;
                        }
                        //Hi Hat Pedal press
                        if(this->signals[0] == 0xB9 && this->signals[1] == 0x04){
                            sending = 0;
                        }
                        //Ride double hits
                        if(this->signals[1] == 0x33 && this->signals[2] < 55){
                            sending = 0;
                        }
                        //Cymbal/hihat Doubles
                        if(sending && (this->signals[1] == 0x2E || this->signals[1] == 0x2F || this->signals[1] == 0x30 || this->signals[1] == 0x31 || this->signals[1] == 0x33)){
                            threshold = 60000;//Time threshold
                            for(j=0;j<SIGNAL_HISTORY_SIZE;j++){
                                //If the delay is already greater than our threshold, it's not a double hit
                                if(delay >= threshold){
                                    break;
                                }
                                //If the old signal was a hit hat hit
                                if(this->old_signals[j][1] == this->signals[1]){
                                    sending = 0;
                                    break;
                                }
                                //If it was not within a hi hat hit, increase the delay by it's delay (making future checks harder because there were longer ago)
                                if(j==(SIGNAL_HISTORY_SIZE-1)){
                                    break;
                                }
                                temp = (this->iCurrentNoteTime-this->old_notetimes[j+1]) / 1000;
                                delay = temp;
                            }
                        }
                        //Any double hits
                        threshold = 9000;//Time threshold
                        for(j=0;j<SIGNAL_HISTORY_SIZE;j++){
                            //If the delay is already greater than our threshold, it's not a double hit
                            if(delay >= threshold){
                                break;
                            }
                            //If the old signal was a hit hat hit
                            if(this->old_signals[j][1] == this->signals[1]){
                                sending = 0;
                                break;
                            }
                            //If it was not within a hi hat hit, increase the delay by it's delay (making future checks harder because there were longer ago)
                            if(j==(SIGNAL_HISTORY_SIZE-1)){
                                break;
                            }
                            temp = (this->iCurrentNoteTime-this->old_notetimes[j+1])/1000;
                            delay = delay+temp;
                        }

                        //If the note is valid, pass it through
                        if(sending){
                            for(j=0;j<6;j++){
                                midibuffer[j] = this->signals[j];
                            }
                            //Substitution
                            if(this->signals[1] == 0x2F || this->signals[1] == 0x30){
                                midibuffer[1] = 0x33;
                                midibuffer[4] = 0x33;
                            }
                            //If we somehow got two velocity notes on the same signal, split them
                            if(midibuffer[5] > 0x00 && midibuffer[1] != 0xB9){
                                midibuffer2[0] = midibuffer[3];
                                midibuffer2[1] = midibuffer[4];
                                midibuffer2[2] = midibuffer[5];
                                midibuffer2[3] = 0x00;
                                midibuffer2[4] = 0x00;
                                midibuffer2[5] = 0x00;
                                midibuffer[3] = 0x00;
                                midibuffer[4] = 0x00;
                                midibuffer[5] = 0x00;
                            }else{
                                memset(midibuffer2,0,7);
                            }
                            if (write(fd, midibuffer, 5) == -1) {
                                sprintf(message, "Error writing to device\n");
                                return -1;
                            }
                            write(fd, midibuffer2, 5);midibuffer[4] = 0x00;
                            midibuffer[5] = 0x00;
                        }
                    //}
                    if(sending || (this->signals[1] == 0x04)){
                        //If recording, save the entry
                        if(this->output != NULL && this->signals[1] != 0x04){
                            this->save_note();
                        }
                        this->save_to_history();
                    }
                    if (this->verbose){// && sending) {
                        while (iColumnWidth < 6) {
                            strcat(verb_buffer, "   ");
                            iColumnWidth++;
                        }
                        if (this->iCurrentNoteTime - this->iLastNoteTime < 5000000000) {
                            sprintf(msg_buffer, " - % 9lld µs",(this->iCurrentNoteTime - this->iLastNoteTime) / 1000);
                            strcat(verb_buffer, msg_buffer);
                        }
                        if(sending == 0){
                            fprintf(stderr,"    ");
                        }
                        fprintf(stderr, "%s\n", verb_buffer);
                    }
                }
            }
        }
    }
    return 1;
}

int NoteEvaluator::save_note(){

    unsigned long long delay;
    delay = (this->iCurrentNoteTime - this->iLastNoteTime) / 1000;
    if(this->iLastNoteTime == 0){
        delay = 0;
    }

    if(this->output != NULL){
        this->output->write_note(delay,this->signals);
        return 1;
    }
    return 0;
}

} /* namespace MidiEngine */
<|endoftext|>


<commit_before>/*	opendatacon
 *
 *	Copyright (c) 2014:
 *
 *		DCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi
 *		yxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA==
 *
 *	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.
 */
/*
 * IOHandler.cpp
 *
 *  Created on: 20/07/2014
 *      Author: Neil Stephens <dearknarl@gmail.com>
 */

#include <openpal/logging/LogLevels.h>
#include <opendatacon/IOHandler.h>

std::unordered_map<std::string,IOHandler*> IOHandler::IOHandlers;

std::unordered_map<std::string, IOHandler*>& GetIOHandlers()
{
	return IOHandler::IOHandlers;
}

IOHandler::IOHandler(std::string aName):Name(aName),
		pLoggers(new asiopal::LogFanoutHandler()),
		LOG_LEVEL(openpal::logflags::WARN),
		enabled(false)
{
	IOHandlers[Name]=this;
}

void IOHandler::Subscribe(IOHandler* pIOHandler, std::string aName)
{
	this->Subscribers[aName] = pIOHandler;
}

void IOHandler::AddLogSubscriber(openpal::ILogHandler* logger)
{
	pLoggers->Subscribe(logger);
}
void IOHandler::SetLogLevel(openpal::LogFilters LOG_LEVEL)
{
	this->LOG_LEVEL = LOG_LEVEL;
}
void IOHandler::SetIOS(asio::io_service* ios_ptr)
{
	pIOS = ios_ptr;
}

inline bool IOHandler::InDemand()
{
	for(auto demand : connection_demands)
		if(demand.second)
			return true;
	return false;
}

bool IOHandler::MuxConnectionEvents(ConnectState state, const std::string& SenderName)
{
	if (state == ConnectState::DISCONNECTED)
	{
		connection_demands[SenderName] = false;
		return !InDemand();
	}
	else if (state == ConnectState::CONNECTED)
	{
		bool new_demand = !connection_demands[SenderName];
		connection_demands[SenderName] = true;
		return new_demand;
	}
	return true;
}
<commit_msg>Fixed the problem of IOHandler::InDemand() being optimised out of release builds. Can't be inline, because it needs to be called by child classes in external libraries.<commit_after>/*	opendatacon
 *
 *	Copyright (c) 2014:
 *
 *		DCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi
 *		yxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA==
 *
 *	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.
 */
/*
 * IOHandler.cpp
 *
 *  Created on: 20/07/2014
 *      Author: Neil Stephens <dearknarl@gmail.com>
 */

#include <openpal/logging/LogLevels.h>
#include <opendatacon/IOHandler.h>

std::unordered_map<std::string,IOHandler*> IOHandler::IOHandlers;

std::unordered_map<std::string, IOHandler*>& GetIOHandlers()
{
	return IOHandler::IOHandlers;
}

IOHandler::IOHandler(std::string aName):Name(aName),
		pLoggers(new asiopal::LogFanoutHandler()),
		LOG_LEVEL(openpal::logflags::WARN),
		enabled(false)
{
	IOHandlers[Name]=this;
}

void IOHandler::Subscribe(IOHandler* pIOHandler, std::string aName)
{
	this->Subscribers[aName] = pIOHandler;
}

void IOHandler::AddLogSubscriber(openpal::ILogHandler* logger)
{
	pLoggers->Subscribe(logger);
}
void IOHandler::SetLogLevel(openpal::LogFilters LOG_LEVEL)
{
	this->LOG_LEVEL = LOG_LEVEL;
}
void IOHandler::SetIOS(asio::io_service* ios_ptr)
{
	pIOS = ios_ptr;
}

bool IOHandler::InDemand()
{
	for(auto demand : connection_demands)
		if(demand.second)
			return true;
	return false;
}

bool IOHandler::MuxConnectionEvents(ConnectState state, const std::string& SenderName)
{
	if (state == ConnectState::DISCONNECTED)
	{
		connection_demands[SenderName] = false;
		return !InDemand();
	}
	else if (state == ConnectState::CONNECTED)
	{
		bool new_demand = !connection_demands[SenderName];
		connection_demands[SenderName] = true;
		return new_demand;
	}
	return true;
}
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/**
  \file    NRRDConverter.cpp
  \author    Jens Krueger
        SCI Institute
        University of Utah
  \date    December 2008
*/

#include "NRRDConverter.h"
#include "IOManager.h"  // for the size defines
#include <Controller/MasterController.h>
#include <Basics/SysTools.h>
#include <IO/KeyValueFileParser.h>

using namespace std;

NRRDConverter::NRRDConverter()
{
  m_vSupportedExt.push_back("NRRD");
  m_vSupportedExt.push_back("NHDR");
}

bool NRRDConverter::Convert(const std::string& strSourceFilename, const std::string& strTargetFilename, const std::string& strTempDir, MasterController* pMasterController)
{

  pMasterController->DebugOut()->Message("NRRDConverter::Convert","Attempting to convertet NRRD dataset %s to %s", strSourceFilename.c_str(), strTargetFilename.c_str());

  // Check Magic value in NRRD File first
	ifstream fileData(strSourceFilename.c_str());
  string strFirstLine;

	if (fileData.is_open())
	{
		getline (fileData,strFirstLine);
    if (strFirstLine.substr(0,7) != "NRRD000") {
      pMasterController->DebugOut()->Warning("NRRDConverter::Convert","The file %s is not a NRRD file (missing magic)", strSourceFilename.c_str());
      return false;
    }
  } else {
    pMasterController->DebugOut()->Warning("NRRDConverter::Convert","Could not open NRHD file %s", strSourceFilename.c_str());
    return false;
  }
  fileData.close();

  // read data
  UINT64			  iComponentSize=8;
  UINT64			  iComponentCount=1;
  bool          bSigned=false;
  bool          bBigEndian=false;
  UINTVECTOR3		vVolumeSize;
  FLOATVECTOR3	vVolumeAspect(1,1,1);
  string        strRAWFile;

  string strExt = SysTools::ToUpperCase(SysTools::GetExt(strSourceFilename));
  bool bDetachedHeader = (strExt == "NHRD");

  KeyValueFileParser parser(strSourceFilename, !bDetachedHeader);

  if (!parser.FileReadable()) {
    pMasterController->DebugOut()->Warning("NRRDConverter::Convert","Could not open NRRD file %s", strSourceFilename.c_str());
    return false;
  }

  KeyValPair* kvpType = parser.GetData("TYPE");
  if (kvpType == NULL) {
    pMasterController->DebugOut()->Error("NRRDConverter::Convert","Could not open find token \"type\" in file %s", strSourceFilename.c_str());
	  return false;
  } else {
	  if (kvpType->strValueUpper == "SIGNED CHAR" || kvpType->strValueUpper == "INT8" || kvpType->strValueUpper == "INT8_T") {
		  bSigned = true;
      iComponentSize = 8;
	  } else if (kvpType->strValueUpper == "UCHAR" || kvpType->strValueUpper == "UNSIGNED CHAR" ||  kvpType->strValueUpper == "UINT8" || kvpType->strValueUpper == "UINT8_T") {
		  bSigned = false;
      iComponentSize = 8;
	  } else if (kvpType->strValueUpper == "SHORT" || kvpType->strValueUpper == "SHORT INT" ||  kvpType->strValueUpper == "SIGNED SHORT" || kvpType->strValueUpper == "SIGNED SHORT INT" || kvpType->strValueUpper == "INT16" || kvpType->strValueUpper == "INT16_T") {
		  bSigned = true;
		  iComponentSize = 16;
	  } else if (kvpType->strValueUpper == "USHORT" || kvpType->strValueUpper == "UNSIGNED SHORT" || kvpType->strValueUpper == "UNSIGNED SHORT INT" || kvpType->strValueUpper == "UINT16" || kvpType->strValueUpper == "UINT16_T") {
		  bSigned = false;
		  iComponentSize = 16;
	  } else if (kvpType->strValueUpper == "INT" || kvpType->strValueUpper == "SIGNED INT" || kvpType->strValueUpper == "INT32" || kvpType->strValueUpper == "INT32_T") {
		  bSigned = true;
		  iComponentSize = 32;
	  } else if (kvpType->strValueUpper == "UINT" || kvpType->strValueUpper == "UNSIGNED INT" || kvpType->strValueUpper == "UINT32" || kvpType->strValueUpper == "UINT32_T") {
		  bSigned = false;
		  iComponentSize = 32;
	  } else if (kvpType->strValueUpper == "LONGLONG" || kvpType->strValueUpper == "LONG LONG" || kvpType->strValueUpper == "LONG LONG INT" || kvpType->strValueUpper == "SIGNED LONG LONG" || kvpType->strValueUpper == "SIGNED LONG LONG INT" || kvpType->strValueUpper == "INT64" || kvpType->strValueUpper == "INT64_T") {
		  bSigned = true;
		  iComponentSize = 64;
	  } else if (kvpType->strValueUpper == "ULONGLONG" || kvpType->strValueUpper == "UNSIGNED LONG LONG" || kvpType->strValueUpper == "UNSIGNED LONG LONG INT" || kvpType->strValueUpper == "UINT64" || kvpType->strValueUpper == "UINT64_T") {
		  bSigned = true;
		  iComponentSize = 64;
	  } else if (kvpType->strValueUpper == "FLOAT") {
		  bSigned = true;
		  iComponentSize = 32;
	  } else if (kvpType->strValueUpper == "DOUBLE") {
		  bSigned = true;
		  iComponentSize = 64;
	  } else {
      pMasterController->DebugOut()->Error("NRRDConverter::Convert","Unsupported \"type\" in file %s", strSourceFilename.c_str());
	    return false;
    }
  }

  KeyValPair* kvpDim = parser.GetData("DIMENSION");
  if (kvpDim == NULL) {
    pMasterController->DebugOut()->Error("NRRDConverter::Convert","Could not open find token \"dimension\" in file %s", strSourceFilename.c_str());
	  return false;
  } else {
    if (kvpDim->iValue != 3)  {
      pMasterController->DebugOut()->Error("NRRDConverter::Convert","Only 3D NRRDs are supported at the moment");
	    return false;
     }
  }

  KeyValPair* kvpSizes = parser.GetData("SIZES");
  if (kvpSizes == NULL) {
    pMasterController->DebugOut()->Error("NRRDConverter::Convert","Could not open find token \"sizes\" in file %s", strSourceFilename.c_str());
	  return false;
  } else {
    vVolumeSize = kvpSizes->vuiValue;
  }

  UINT64 iHeaderSkip;
  if (bDetachedHeader) {
    KeyValPair* kvpDataFile = parser.GetData("DATA FILE");
    if (kvpDataFile == NULL) {
      pMasterController->DebugOut()->Error("NRRDConverter::Convert","Could not open find token \"data file\" in file %s", strSourceFilename.c_str());
	    return false;
    } else {
      strRAWFile = SysTools::GetPath(strSourceFilename) + kvpDataFile->strValue;
      iHeaderSkip = 0;
    }
  } else {
    iHeaderSkip = UINT64(parser.GetStopPos());
    strRAWFile = strSourceFilename;
  }

  KeyValPair* kvpSpacings = parser.GetData("SPACINGS");
  if (kvpSpacings != NULL) {
    vVolumeAspect = kvpSpacings->vfValue;
  }

  KeyValPair* kvpEndian = parser.GetData("ENDIAN");
  if (kvpEndian != NULL && kvpEndian->strValueUpper == "BIG") bBigEndian = true;

  KeyValPair* kvpEncoding = parser.GetData("ENCODING");
  if (kvpEncoding == NULL) {
    pMasterController->DebugOut()->Error("NRRDConverter::Convert","Could not find token \"encoding\" in file %s", strSourceFilename.c_str());
	  return false;
  } else {
    if (kvpEncoding->strValueUpper == "RAW")  {
      pMasterController->DebugOut()->Message("NRRDConverter::Convert","NRRD data is in RAW format!");

      return ConvertRAWDataset(strRAWFile, strTargetFilename, strTempDir, pMasterController, iHeaderSkip, iComponentSize, iComponentCount, bSigned, bBigEndian != EndianConvert::IsBigEndian(),
                               vVolumeSize, vVolumeAspect, "NRRD data", SysTools::GetFilename(strSourceFilename));
    } else
    if (kvpEncoding->strValueUpper == "TXT" || kvpEncoding->strValueUpper == "TEXT" || kvpEncoding->strValueUpper == "ASCII")  {
      pMasterController->DebugOut()->Error("NRRDConverter::Convert","NRRD data is in text format which is not supported at the moment.");
    } else
    if (kvpEncoding->strValueUpper != "HEX")  {
      pMasterController->DebugOut()->Error("NRRDConverter::Convert","NRRD data is in haxdecimal text format which is not supported at the moment.");
    } else
    if (kvpEncoding->strValueUpper != "GZ" || kvpEncoding->strValueUpper != "GZIP")  {
      pMasterController->DebugOut()->Message("NRRDConverter::Convert","NRRD data is GZIP compressed RAW format.");

      return ConvertGZIPDataset(strRAWFile, strTargetFilename, strTempDir, pMasterController, iHeaderSkip, iComponentSize, iComponentCount, bSigned, bBigEndian != EndianConvert::IsBigEndian(),
                               vVolumeSize, vVolumeAspect, "NRRD data", SysTools::GetFilename(strSourceFilename));

    } else
    if (kvpEncoding->strValueUpper != "BZ" || kvpEncoding->strValueUpper != "BZIP2")  {
      pMasterController->DebugOut()->Message("NRRDConverter::Convert","NRRD data is BZIP2 compressed RAW format.");

      return ConvertBZIP2Dataset(strRAWFile, strTargetFilename, strTempDir, pMasterController, iHeaderSkip, iComponentSize, iComponentCount, bSigned, bBigEndian != EndianConvert::IsBigEndian(),
                               vVolumeSize, vVolumeAspect, "NRRD data", SysTools::GetFilename(strSourceFilename));

    } else {
      pMasterController->DebugOut()->Error("NRRDConverter::Convert","NRRD data is in unknown \"%s\" format.");
    }
    return false;
  }
}
<commit_msg>Fixed a typo in extension name and if statements.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/**
  \file    NRRDConverter.cpp
  \author    Jens Krueger
        SCI Institute
        University of Utah
  \date    December 2008
*/

#include "NRRDConverter.h"
#include "IOManager.h"  // for the size defines
#include <Controller/MasterController.h>
#include <Basics/SysTools.h>
#include <IO/KeyValueFileParser.h>

using namespace std;

NRRDConverter::NRRDConverter()
{
  m_vSupportedExt.push_back("NRRD");
  m_vSupportedExt.push_back("NHDR");
}

bool NRRDConverter::Convert(const std::string& strSourceFilename, const std::string& strTargetFilename, const std::string& strTempDir, MasterController* pMasterController)
{

  pMasterController->DebugOut()->Message("NRRDConverter::Convert","Attempting to convertet NRRD dataset %s to %s", strSourceFilename.c_str(), strTargetFilename.c_str());

  // Check Magic value in NRRD File first
	ifstream fileData(strSourceFilename.c_str());
  string strFirstLine;

	if (fileData.is_open())
	{
		getline (fileData,strFirstLine);
    if (strFirstLine.substr(0,7) != "NRRD000") {
      pMasterController->DebugOut()->Warning("NRRDConverter::Convert","The file %s is not a NRRD file (missing magic)", strSourceFilename.c_str());
      return false;
    }
  } else {
    pMasterController->DebugOut()->Warning("NRRDConverter::Convert","Could not open NRHD file %s", strSourceFilename.c_str());
    return false;
  }
  fileData.close();

  // read data
  UINT64			  iComponentSize=8;
  UINT64			  iComponentCount=1;
  bool          bSigned=false;
  bool          bBigEndian=false;
  UINTVECTOR3		vVolumeSize;
  FLOATVECTOR3	vVolumeAspect(1,1,1);
  string        strRAWFile;

  string strExt = SysTools::ToUpperCase(SysTools::GetExt(strSourceFilename));
  bool bDetachedHeader = (strExt == "NHDR");

  KeyValueFileParser parser(strSourceFilename, !bDetachedHeader);

  if (!parser.FileReadable()) {
    pMasterController->DebugOut()->Warning("NRRDConverter::Convert","Could not open NRRD file %s", strSourceFilename.c_str());
    return false;
  }

  KeyValPair* kvpType = parser.GetData("TYPE");
  if (kvpType == NULL) {
    pMasterController->DebugOut()->Error("NRRDConverter::Convert","Could not open find token \"type\" in file %s", strSourceFilename.c_str());
	  return false;
  } else {
	  if (kvpType->strValueUpper == "SIGNED CHAR" || kvpType->strValueUpper == "INT8" || kvpType->strValueUpper == "INT8_T") {
		  bSigned = true;
      iComponentSize = 8;
	  } else if (kvpType->strValueUpper == "UCHAR" || kvpType->strValueUpper == "UNSIGNED CHAR" ||  kvpType->strValueUpper == "UINT8" || kvpType->strValueUpper == "UINT8_T") {
		  bSigned = false;
      iComponentSize = 8;
	  } else if (kvpType->strValueUpper == "SHORT" || kvpType->strValueUpper == "SHORT INT" ||  kvpType->strValueUpper == "SIGNED SHORT" || kvpType->strValueUpper == "SIGNED SHORT INT" || kvpType->strValueUpper == "INT16" || kvpType->strValueUpper == "INT16_T") {
		  bSigned = true;
		  iComponentSize = 16;
	  } else if (kvpType->strValueUpper == "USHORT" || kvpType->strValueUpper == "UNSIGNED SHORT" || kvpType->strValueUpper == "UNSIGNED SHORT INT" || kvpType->strValueUpper == "UINT16" || kvpType->strValueUpper == "UINT16_T") {
		  bSigned = false;
		  iComponentSize = 16;
	  } else if (kvpType->strValueUpper == "INT" || kvpType->strValueUpper == "SIGNED INT" || kvpType->strValueUpper == "INT32" || kvpType->strValueUpper == "INT32_T") {
		  bSigned = true;
		  iComponentSize = 32;
	  } else if (kvpType->strValueUpper == "UINT" || kvpType->strValueUpper == "UNSIGNED INT" || kvpType->strValueUpper == "UINT32" || kvpType->strValueUpper == "UINT32_T") {
		  bSigned = false;
		  iComponentSize = 32;
	  } else if (kvpType->strValueUpper == "LONGLONG" || kvpType->strValueUpper == "LONG LONG" || kvpType->strValueUpper == "LONG LONG INT" || kvpType->strValueUpper == "SIGNED LONG LONG" || kvpType->strValueUpper == "SIGNED LONG LONG INT" || kvpType->strValueUpper == "INT64" || kvpType->strValueUpper == "INT64_T") {
		  bSigned = true;
		  iComponentSize = 64;
	  } else if (kvpType->strValueUpper == "ULONGLONG" || kvpType->strValueUpper == "UNSIGNED LONG LONG" || kvpType->strValueUpper == "UNSIGNED LONG LONG INT" || kvpType->strValueUpper == "UINT64" || kvpType->strValueUpper == "UINT64_T") {
		  bSigned = true;
		  iComponentSize = 64;
	  } else if (kvpType->strValueUpper == "FLOAT") {
		  bSigned = true;
		  iComponentSize = 32;
	  } else if (kvpType->strValueUpper == "DOUBLE") {
		  bSigned = true;
		  iComponentSize = 64;
	  } else {
      pMasterController->DebugOut()->Error("NRRDConverter::Convert","Unsupported \"type\" in file %s", strSourceFilename.c_str());
	    return false;
    }
  }

  KeyValPair* kvpDim = parser.GetData("DIMENSION");
  if (kvpDim == NULL) {
    pMasterController->DebugOut()->Error("NRRDConverter::Convert","Could not open find token \"dimension\" in file %s", strSourceFilename.c_str());
	  return false;
  } else {
    if (kvpDim->iValue != 3)  {
      pMasterController->DebugOut()->Error("NRRDConverter::Convert","Only 3D NRRDs are supported at the moment");
	    return false;
     }
  }

  KeyValPair* kvpSizes = parser.GetData("SIZES");
  if (kvpSizes == NULL) {
    pMasterController->DebugOut()->Error("NRRDConverter::Convert","Could not open find token \"sizes\" in file %s", strSourceFilename.c_str());
	  return false;
  } else {
    vVolumeSize = kvpSizes->vuiValue;
  }

  UINT64 iHeaderSkip;
  if (bDetachedHeader) {
    KeyValPair* kvpDataFile = parser.GetData("DATA FILE");
    if (kvpDataFile == NULL) {
      pMasterController->DebugOut()->Error("NRRDConverter::Convert","Could not open find token \"data file\" in file %s", strSourceFilename.c_str());
	    return false;
    } else {
      strRAWFile = SysTools::GetPath(strSourceFilename) + kvpDataFile->strValue;
      iHeaderSkip = 0;
    }
  } else {
    iHeaderSkip = UINT64(parser.GetStopPos());
    strRAWFile = strSourceFilename;
  }

  KeyValPair* kvpSpacings = parser.GetData("SPACINGS");
  if (kvpSpacings != NULL) {
    vVolumeAspect = kvpSpacings->vfValue;
  }

  KeyValPair* kvpEndian = parser.GetData("ENDIAN");
  if (kvpEndian != NULL && kvpEndian->strValueUpper == "BIG") bBigEndian = true;

  KeyValPair* kvpEncoding = parser.GetData("ENCODING");
  if (kvpEncoding == NULL) {
    pMasterController->DebugOut()->Error("NRRDConverter::Convert","Could not find token \"encoding\" in file %s", strSourceFilename.c_str());
	  return false;
  } else {
    if (kvpEncoding->strValueUpper == "RAW")  {
      pMasterController->DebugOut()->Message("NRRDConverter::Convert","NRRD data is in RAW format!");

      return ConvertRAWDataset(strRAWFile, strTargetFilename, strTempDir, pMasterController, iHeaderSkip, iComponentSize, iComponentCount, bSigned, bBigEndian != EndianConvert::IsBigEndian(),
                               vVolumeSize, vVolumeAspect, "NRRD data", SysTools::GetFilename(strSourceFilename));
    } else
    if (kvpEncoding->strValueUpper == "TXT" || kvpEncoding->strValueUpper == "TEXT" || kvpEncoding->strValueUpper == "ASCII")  {
      pMasterController->DebugOut()->Error("NRRDConverter::Convert","NRRD data is in text format which is not supported at the moment.");
    } else
    if (kvpEncoding->strValueUpper == "HEX")  {
      pMasterController->DebugOut()->Error("NRRDConverter::Convert","NRRD data is in haxdecimal text format which is not supported at the moment.");
    } else
    if (kvpEncoding->strValueUpper == "GZ" || kvpEncoding->strValueUpper == "GZIP")  {
      pMasterController->DebugOut()->Message("NRRDConverter::Convert","NRRD data is GZIP compressed RAW format.");

      return ConvertGZIPDataset(strRAWFile, strTargetFilename, strTempDir, pMasterController, iHeaderSkip, iComponentSize, iComponentCount, bSigned, bBigEndian != EndianConvert::IsBigEndian(),
                               vVolumeSize, vVolumeAspect, "NRRD data", SysTools::GetFilename(strSourceFilename));

    } else
    if (kvpEncoding->strValueUpper == "BZ" || kvpEncoding->strValueUpper == "BZIP2")  {
      pMasterController->DebugOut()->Message("NRRDConverter::Convert","NRRD data is BZIP2 compressed RAW format.");

      return ConvertBZIP2Dataset(strRAWFile, strTargetFilename, strTempDir, pMasterController, iHeaderSkip, iComponentSize, iComponentCount, bSigned, bBigEndian != EndianConvert::IsBigEndian(),
                               vVolumeSize, vVolumeAspect, "NRRD data", SysTools::GetFilename(strSourceFilename));

    } else {
      pMasterController->DebugOut()->Error("NRRDConverter::Convert","NRRD data is in unknown \"%s\" format.");
    }
    return false;
  }
}
<|endoftext|>


<commit_before>/* Francois Faure, INRIA-UJF, 2006
 */
#include "Frame.h"
#include <iostream>
using std::cout;
using std::endl;

namespace Sofa
{
namespace Components
{
namespace Common
{

Frame::Frame (const Vec3 &origin, const Mat33& matrix )
    : origin_(origin)
    , basis_(matrix)
{}
Frame::Frame (const Vec3 &origin, const Quat &orientation, const Vec3& scale )
{
    setTransform( origin, orientation, scale );
}

Frame::Frame (const Vec3 &origin )
    : origin_(origin)
{
    basis_.identity();
}

Frame::Frame ()
{
    clear();
}

void Frame::clear()
{
    basis_.identity();
    origin_.clear();
}

//void clear() { origin_.clear(); basis__.clear(); scale_=Vec3(1,1,1); }

Frame::Vec3& Frame::getOrigin ()
{
    return origin_;
}
const Frame::Vec3& Frame::getOrigin () const
{
    return origin_;
}
void Frame::setOrigin( const Frame::Vec3& origin )
{
    origin_=origin;
}

Frame::Mat33& Frame::getBasis ()
{
    return basis_;
}
const Frame::Mat33& Frame::getBasis () const
{
    return basis_;
}
void Frame::setBasis( const Frame::Mat33& m )
{
    basis_=m;
}

void Frame::setTransform( const Frame::Vec3& origin, const Frame::Quat& orientation, const Frame::Vec3& scale )
{
    setOrigin(origin);
    orientation.toMatrix(basis_);
    for( int i=0; i<3; i++ )
    {
        basis_[i][0] *= scale[0];
        basis_[i][1] *= scale[1];
        basis_[i][2] *= scale[2];
    }
}

Frame Frame::identity()
{
    Frame c;
    c.clear();
    return c;
}

/// Apply a transformation defined in the child frame (mult. right)
void Frame::multRight( const Frame& c )
{
    origin_ += basis_ * c.getOrigin();
    basis_ = basis_ * c.getBasis();
}

/// compute the product with another frame on the right
Frame Frame::mult( const Frame& c ) const
{
    Frame r = (*this);
    r.multRight(c);
    return r;
}

/// Write the OpenGL transformation matrix
void Frame::writeOpenGlMatrix( float m[16] ) const
{
    m[0] = basis_[0][0];
    m[1] = basis_[1][0];
    m[2] = basis_[2][0];
    m[3] = 0;
    m[4] = basis_[0][1];
    m[5] = basis_[1][1];
    m[6] = basis_[2][1];
    m[7] = 0;
    m[8] = basis_[0][2];
    m[9] = basis_[1][2];
    m[10] = basis_[2][2];
    m[11] = 0;
    m[12] = origin_[0];
    m[13] = origin_[1];
    m[14] = origin_[2];
    m[15] = 1;
}

/// Compute the transformation from the parent to the child
Frame Frame::inversed() const
{
    Mat33 inv;
    bool invertible = inv.invert( basis_ );
    assert( invertible );
    return Frame( -(inv*origin_) , inv );
}

std::ostream& operator << (std::ostream& out, const Sofa::Components::Common::Frame& c )
{
    out<<"origin = "<<c.getOrigin()<<", basis matrix="<<endl;
    for( int i=0; i<3; i++ )
    {
        for( int j=0; j<3; j++ )
            out<<c.getBasis()[i][j]<<" ";
        out<<endl;
    }
    return out;
}

}//Common
}//Components
}//Sofa

<commit_msg>r348/sofa-dev : Remove more warnings<commit_after>/* Francois Faure, INRIA-UJF, 2006
 */
#include "Frame.h"
#include <iostream>
using std::cout;
using std::endl;

namespace Sofa
{
namespace Components
{
namespace Common
{

Frame::Frame (const Vec3 &origin, const Mat33& matrix )
    : origin_(origin)
    , basis_(matrix)
{}
Frame::Frame (const Vec3 &origin, const Quat &orientation, const Vec3& scale )
{
    setTransform( origin, orientation, scale );
}

Frame::Frame (const Vec3 &origin )
    : origin_(origin)
{
    basis_.identity();
}

Frame::Frame ()
{
    clear();
}

void Frame::clear()
{
    basis_.identity();
    origin_.clear();
}

//void clear() { origin_.clear(); basis__.clear(); scale_=Vec3(1,1,1); }

Frame::Vec3& Frame::getOrigin ()
{
    return origin_;
}
const Frame::Vec3& Frame::getOrigin () const
{
    return origin_;
}
void Frame::setOrigin( const Frame::Vec3& origin )
{
    origin_=origin;
}

Frame::Mat33& Frame::getBasis ()
{
    return basis_;
}
const Frame::Mat33& Frame::getBasis () const
{
    return basis_;
}
void Frame::setBasis( const Frame::Mat33& m )
{
    basis_=m;
}

void Frame::setTransform( const Frame::Vec3& origin, const Frame::Quat& orientation, const Frame::Vec3& scale )
{
    setOrigin(origin);
    orientation.toMatrix(basis_);
    for( int i=0; i<3; i++ )
    {
        basis_[i][0] *= scale[0];
        basis_[i][1] *= scale[1];
        basis_[i][2] *= scale[2];
    }
}

Frame Frame::identity()
{
    Frame c;
    c.clear();
    return c;
}

/// Apply a transformation defined in the child frame (mult. right)
void Frame::multRight( const Frame& c )
{
    origin_ += basis_ * c.getOrigin();
    basis_ = basis_ * c.getBasis();
}

/// compute the product with another frame on the right
Frame Frame::mult( const Frame& c ) const
{
    Frame r = (*this);
    r.multRight(c);
    return r;
}

/// Write the OpenGL transformation matrix
void Frame::writeOpenGlMatrix( float m[16] ) const
{
    m[0] = basis_[0][0];
    m[1] = basis_[1][0];
    m[2] = basis_[2][0];
    m[3] = 0;
    m[4] = basis_[0][1];
    m[5] = basis_[1][1];
    m[6] = basis_[2][1];
    m[7] = 0;
    m[8] = basis_[0][2];
    m[9] = basis_[1][2];
    m[10] = basis_[2][2];
    m[11] = 0;
    m[12] = origin_[0];
    m[13] = origin_[1];
    m[14] = origin_[2];
    m[15] = 1;
}

/// Compute the transformation from the parent to the child
Frame Frame::inversed() const
{
    Mat33 inv;
#ifdef NDEBUG
    inv.invert( basis_ );
#else
    bool invertible = inv.invert( basis_ );
    assert( invertible );
#endif
    return Frame( -(inv*origin_) , inv );
}

std::ostream& operator << (std::ostream& out, const Sofa::Components::Common::Frame& c )
{
    out<<"origin = "<<c.getOrigin()<<", basis matrix="<<endl;
    for( int i=0; i<3; i++ )
    {
        for( int j=0; j<3; j++ )
            out<<c.getBasis()[i][j]<<" ";
        out<<endl;
    }
    return out;
}

}//Common
}//Components
}//Sofa

<|endoftext|>


<commit_before><commit_msg>Change error message to avoid validation failure<commit_after><|endoftext|>


<commit_before>/*
Copyright 2017 Luis Hsu, Kevin Cyu

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.
*/
#include <Call40.h>

void Call::sysExit(Stack &coreStack){
	// Check value count
	if(coreStack.valueNum < 1){
		throw Exception("[sys_exit] No enough value in the stack.", coreStack);
	}
	// Pop operand
	Value *operand = (Value *)coreStack.pop().data;
	if(operand->type != i32){
		throw Exception("[sys_exit] Operand type is not i32.", coreStack);
	}
	// Sys_exit
	exit(operand->data.i32);
	// Clean
	delete operand;
}
void Call::sysKill(Stack &coreStack){
	// Check value count
	if(coreStack.valueNum < 2){
		throw Exception("[sys_kill] No enough value in the stack.", coreStack);
	}
	// Pop operand
	Value *sig = (Value *)coreStack.pop().data;
	if(sig->type != i32){
		throw Exception("[sys_kill] signal type is not i32.", coreStack);
	}
	Value *pid = (Value *)coreStack.pop().data;
	if(pid->type != i32){
		throw Exception("[sys_kill] pid type is not i32.", coreStack);
	}
	// Sys_kill
	std::int32_t ret = kill(pid->data.i32, sig->data.i32);
	coreStack.push(ret);
	// Clean
	delete sig;
	delete pid;
}
void Call::sysPause(Stack &coreStack){
	// Sys_pause
	std::int32_t ret = pause();
	coreStack.push(ret);
}
void Call::sysGetpid(Stack &coreStack){
	// Sys_getpid
	std::int32_t ret = getpid();
	coreStack.push(ret);
}
void Call::sysExecve(Store &store, Stack &coreStack){
	// Check value count
	if(coreStack.valueNum < 3){
		throw Exception("[sys_execve] No enough value in the stack.", coreStack);
	}
	// Pop operand
	Value *envAddr = (Value *)coreStack.pop().data;
	Value *argvAddr = (Value *)coreStack.pop().data;
	Value *fileNameAddr = (Value *)coreStack.pop().data;
	if(envAddr->type != i32 || argvAddr->type != i32 || fileNameAddr->type != i32){
		throw Exception("[sys_execve] value types are not i32.", coreStack);
	}
	// Get memory address
	char *memoryData = store.mems.at(0)->data.data();
	char *fileNamePtr = memoryData += fileNameAddr->data.i32;
	char *argvPtr = memoryData += argvAddr->data.i32;
	char *envPtr = memoryData += envAddr->data.i32;
	// Get argv
	std::vector<char *> argv;
	do{
		argv.push_back(argvPtr);
		argvPtr += strlen(argvPtr) + 1;
	}while(*(std::int32_t *)argvPtr);
	argv.push_back(NULL);
	// Get env
	std::vector<char *> env;
	do{
		env.push_back(envPtr);
		envPtr += strlen(envPtr) + 1;
	}while(*(std::int32_t *)envPtr);
	env.push_back(NULL);
	// Sys_execve
	std::int32_t ret = execve(fileNamePtr, (char**)argv.data(), (char**)env.data());
	if(errno){
		perror("Error:");
	}
	coreStack.push(ret);
	// Clean
	delete envAddr;
	delete argvAddr;
	delete fileNameAddr;
}<commit_msg>Add exception while errno set<commit_after>/*
Copyright 2017 Luis Hsu, Kevin Cyu

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.
*/
#include <Call40.h>

void Call::sysExit(Stack &coreStack){
	// Check value count
	if(coreStack.valueNum < 1){
		throw Exception("[sys_exit] No enough value in the stack.", coreStack);
	}
	// Pop operand
	Value *operand = (Value *)coreStack.pop().data;
	if(operand->type != i32){
		throw Exception("[sys_exit] Operand type is not i32.", coreStack);
	}
	// Sys_exit
	exit(operand->data.i32);
	// Clean
	delete operand;
}
void Call::sysKill(Stack &coreStack){
	// Check value count
	if(coreStack.valueNum < 2){
		throw Exception("[sys_kill] No enough value in the stack.", coreStack);
	}
	// Pop operand
	Value *sig = (Value *)coreStack.pop().data;
	if(sig->type != i32){
		throw Exception("[sys_kill] signal type is not i32.", coreStack);
	}
	Value *pid = (Value *)coreStack.pop().data;
	if(pid->type != i32){
		throw Exception("[sys_kill] pid type is not i32.", coreStack);
	}
	// Sys_kill
	std::int32_t ret = kill(pid->data.i32, sig->data.i32);
	if(errno){
		throw Exception(std::string("[sys_kill] ") + strerror(errno), coreStack);
	}
	coreStack.push(ret);
	// Clean
	delete sig;
	delete pid;
}
void Call::sysPause(Stack &coreStack){
	// Sys_pause
	std::int32_t ret = pause();
	if(errno){
		throw Exception(std::string("[sys_pause] ") + strerror(errno), coreStack);
	}
	coreStack.push(ret);
}
void Call::sysGetpid(Stack &coreStack){
	// Sys_getpid
	std::int32_t ret = getpid();
	coreStack.push(ret);
}
void Call::sysExecve(Store &store, Stack &coreStack){
	// Check value count
	if(coreStack.valueNum < 3){
		throw Exception("[sys_execve] No enough value in the stack.", coreStack);
	}
	// Pop operand
	Value *envAddr = (Value *)coreStack.pop().data;
	Value *argvAddr = (Value *)coreStack.pop().data;
	Value *fileNameAddr = (Value *)coreStack.pop().data;
	if(envAddr->type != i32 || argvAddr->type != i32 || fileNameAddr->type != i32){
		throw Exception("[sys_execve] value types are not i32.", coreStack);
	}
	// Get memory address
	char *memoryData = store.mems.at(0)->data.data();
	char *fileNamePtr = memoryData += fileNameAddr->data.i32;
	char *argvPtr = memoryData += argvAddr->data.i32;
	char *envPtr = memoryData += envAddr->data.i32;
	// Get argv
	std::vector<char *> argv;
	do{
		argv.push_back(argvPtr);
		argvPtr += strlen(argvPtr) + 1;
	}while(*(std::int32_t *)argvPtr);
	argv.push_back(NULL);
	// Get env
	std::vector<char *> env;
	do{
		env.push_back(envPtr);
		envPtr += strlen(envPtr) + 1;
	}while(*(std::int32_t *)envPtr);
	env.push_back(NULL);
	// Sys_execve
	std::int32_t ret = execve(fileNamePtr, (char**)argv.data(), (char**)env.data());
	if(errno){
		throw Exception(std::string("[sys_execve] ") + strerror(errno), coreStack);
	}
	coreStack.push(ret);
	// Clean
	delete envAddr;
	delete argvAddr;
	delete fileNameAddr;
}<|endoftext|>


<commit_before>#include "GUIMenu.hpp"

using namespace MPACK;
using namespace MPACK::Core;
using namespace MPACK::Math;
using namespace MPACK::Graphics;

GUIMenu::GUIMenu()
	: action(0), m_sprite(NULL)
{
	m_pMMInputController=new MMInputController();

	m_pMMInputController->Link_FDOWN(Param2PtrCallbackStruct(GUIMenu::DOWNEvent,this));
	m_pMMInputController->Link_FUP(Param2PtrCallbackStruct(GUIMenu::UPEvent,this));
}

GUIMenu::~GUIMenu()
{
	for(vector<GUIMenuButton*>::iterator it=m_button.begin();it!=m_button.end();++it)
	{
		delete (*it);
	}

	delete m_pMMInputController;
}

int GUIMenu::Update(GLfloat timeStep)
{
	m_pMMInputController->Update(timeStep);

	for(vector<GUIMenuButton*>::iterator it=m_button.begin();it!=m_button.end();++it)
	{
		if((*it)->m_pFinger)
		{
			(*it)->m_pos.x=(*it)->m_fixedPos.x+((*it)->m_pFinger->m_pos.x-(*it)->m_fingerStartPos.x);
		}
	}

	if(action)
	{
		LOGE("action = %d",action);
	}

	int i = action;
	action = 0;
	return i;
}

void GUIMenu::Render()
{
	GLfloat width=m_sprite->GetWidth()*0.5;
	GLfloat height=m_sprite->GetHeight()*0.5;
	GLfloat DX[4];
	DX[0]=-width;
	DX[1]=+width;
	DX[2]=+width;
	DX[3]=-width;
	GLfloat DY[4];
	DY[0]=-height;
	DY[1]=-height;
	DY[2]=+height;
	DY[3]=+height;

	for(vector<GUIMenuButton*>::iterator it=m_button.begin();it!=m_button.end();++it)
	{
		m_sprite->m_position=(*it)->m_pos;
		for(register int i=0;i<4;++i)
		{
			Vector2f pos=m_sprite->m_position;
			pos.x+=DX[i];
			pos.y+=DY[i];

			Vector3f color;

			AABB1Df mid((*it)->m_fixedPos.x-m_sprite->GetWidth()*0.5,(*it)->m_fixedPos.x+m_sprite->GetWidth()*0.5);

			if(mid.Contain(pos.x))
			{
				color=Vector3f(1.0f,1.0f,1.0f);
			}
			else
			{
				GLfloat factor;
				if(pos.x<mid.m_xmin)
				{
					factor=mid.m_xmin-pos.x;
				}
				else
				{
					factor=pos.x-mid.m_xmax;
				}
				factor/=mid.m_xmin;

				Vector3f lrColor(173.0f/255.0f,113.0f/255.0f,52.0f/255.0f);
				Vector3f midColor(1.0f,1.0f,1.0f);
				factor=1.0f-factor;
				//factor=factor*factor;
				color=midColor*factor+lrColor*(1.0f-factor);
			}

			m_sprite->m_color[i].x=min(1.0f,color.x);
			m_sprite->m_color[i].y=min(1.0f,color.y);
			m_sprite->m_color[i].z=min(1.0f,color.z);
		}
		m_sprite->Render();
	}

	for(vector<GUIMenuButton*>::iterator it=m_button.begin();it!=m_button.end();++it)
	{
		Vector2f &pos=(*it)->m_pos;
		Global::pFont->SendString((*it)->m_text,pos.x,pos.y,TextureMappedFont::ALIGN_CENTER);
	}
}

void GUIMenu::AddButton(string text, int id)
{
	GUIMenuButton* pButton=new GUIMenuButton;
	pButton->m_text=text;
	pButton->m_id=id;

	m_button.push_back(pButton);
}

void GUIMenu::BuildLayout()
{
	const GLfloat TOP_PIXELS=75.0f;
	const GLfloat BOTTOM_PIXELS=20.0f;
	const GLfloat SPACING_PIXELS=20.0f;

	GLfloat buttons=m_button.size();
	GLfloat buttonWidth=0.40*Render::GetScreenWidth();
	GLfloat buttonHeight=(Render::GetScreenHeight()-TOP_PIXELS-BOTTOM_PIXELS-(buttons-1.0f)*SPACING_PIXELS)/buttons;

	m_sprite->SetSize(buttonWidth,buttonHeight);

	GLfloat indexButton=1.0f;
	for(vector<GUIMenuButton*>::iterator it=m_button.begin();it!=m_button.end();++it)
	{
		GLfloat x=Render::GetScreenWidth()*0.5f;
		GLfloat y=TOP_PIXELS+buttonHeight*(indexButton-0.5)+SPACING_PIXELS*(indexButton-1.0f);
		//y=Render::GetScreenHeight()-y;
		(*it)->m_fixedPos=(*it)->m_pos=Vector2f(x,y);
		indexButton+=1.0f;
	}
}

void GUIMenu::DOWNEvent(void *pointer1, void *pointer2)
{
	GUIMenu *pGUI=(GUIMenu*)(pointer1);
	MPACK::Input::Finger *pFinger=(MPACK::Input::Finger*)(pointer2);
	for(vector<GUIMenuButton*>::iterator it=pGUI->m_button.begin();it!=pGUI->m_button.end();++it)
	{
		if((*it)->m_pFinger)
		{
			continue;
		}

		Vector2f &pos=(*it)->m_pos;
		AABB2Df A;
		GLfloat width=pGUI->m_sprite->GetWidth()*0.5f;
		GLfloat height=pGUI->m_sprite->GetHeight()*0.5f;
		A.m_xmin=pos.x-width;
		A.m_xmax=pos.x+width;
		A.m_ymin=pos.y-height;
		A.m_ymax=pos.y+height;
		if(A.Contain(pFinger->m_pos))
		{
			(*it)->m_pFinger=pFinger;
			(*it)->m_fingerStartPos=pFinger->m_pos;
			break;
		}
	}
}

void GUIMenu::UPEvent(void *pointer1, void *pointer2)
{
	const GLfloat ACTION_THRESHOLD=0.1f;
	GLfloat leftThreshold=Render::GetScreenWidth()*ACTION_THRESHOLD;
	GLfloat rightThreshold=Render::GetScreenWidth()*(1.0f-ACTION_THRESHOLD);

	GUIMenu *pGUI=(GUIMenu*)(pointer1);
	MPACK::Input::Finger *pFinger=(MPACK::Input::Finger*)(pointer2);
	for(vector<GUIMenuButton*>::iterator it=pGUI->m_button.begin();it!=pGUI->m_button.end();++it)
	{
		if((*it)->m_pFinger==pFinger)
		{
			(*it)->m_pFinger=NULL;

			if((*it)->m_pos.x<leftThreshold || (*it)->m_pos.x>rightThreshold)
			{
				pGUI->action=(*it)->m_id;
			}
			(*it)->m_pos=(*it)->m_fixedPos;
		}
	}
}
<commit_msg>Remove obsolete register specifier<commit_after>#include "GUIMenu.hpp"

using namespace MPACK;
using namespace MPACK::Core;
using namespace MPACK::Math;
using namespace MPACK::Graphics;

GUIMenu::GUIMenu()
	: action(0), m_sprite(NULL)
{
	m_pMMInputController=new MMInputController();

	m_pMMInputController->Link_FDOWN(Param2PtrCallbackStruct(GUIMenu::DOWNEvent,this));
	m_pMMInputController->Link_FUP(Param2PtrCallbackStruct(GUIMenu::UPEvent,this));
}

GUIMenu::~GUIMenu()
{
	for(vector<GUIMenuButton*>::iterator it=m_button.begin();it!=m_button.end();++it)
	{
		delete (*it);
	}

	delete m_pMMInputController;
}

int GUIMenu::Update(GLfloat timeStep)
{
	m_pMMInputController->Update(timeStep);

	for(vector<GUIMenuButton*>::iterator it=m_button.begin();it!=m_button.end();++it)
	{
		if((*it)->m_pFinger)
		{
			(*it)->m_pos.x=(*it)->m_fixedPos.x+((*it)->m_pFinger->m_pos.x-(*it)->m_fingerStartPos.x);
		}
	}

	if(action)
	{
		LOGE("action = %d",action);
	}

	int i = action;
	action = 0;
	return i;
}

void GUIMenu::Render()
{
	GLfloat width=m_sprite->GetWidth()*0.5;
	GLfloat height=m_sprite->GetHeight()*0.5;
	GLfloat DX[4];
	DX[0]=-width;
	DX[1]=+width;
	DX[2]=+width;
	DX[3]=-width;
	GLfloat DY[4];
	DY[0]=-height;
	DY[1]=-height;
	DY[2]=+height;
	DY[3]=+height;

	for(vector<GUIMenuButton*>::iterator it=m_button.begin();it!=m_button.end();++it)
	{
		m_sprite->m_position=(*it)->m_pos;
		for(int i=0;i<4;++i)
		{
			Vector2f pos=m_sprite->m_position;
			pos.x+=DX[i];
			pos.y+=DY[i];

			Vector3f color;

			AABB1Df mid((*it)->m_fixedPos.x-m_sprite->GetWidth()*0.5,(*it)->m_fixedPos.x+m_sprite->GetWidth()*0.5);

			if(mid.Contain(pos.x))
			{
				color=Vector3f(1.0f,1.0f,1.0f);
			}
			else
			{
				GLfloat factor;
				if(pos.x<mid.m_xmin)
				{
					factor=mid.m_xmin-pos.x;
				}
				else
				{
					factor=pos.x-mid.m_xmax;
				}
				factor/=mid.m_xmin;

				Vector3f lrColor(173.0f/255.0f,113.0f/255.0f,52.0f/255.0f);
				Vector3f midColor(1.0f,1.0f,1.0f);
				factor=1.0f-factor;
				//factor=factor*factor;
				color=midColor*factor+lrColor*(1.0f-factor);
			}

			m_sprite->m_color[i].x=min(1.0f,color.x);
			m_sprite->m_color[i].y=min(1.0f,color.y);
			m_sprite->m_color[i].z=min(1.0f,color.z);
		}
		m_sprite->Render();
	}

	for(vector<GUIMenuButton*>::iterator it=m_button.begin();it!=m_button.end();++it)
	{
		Vector2f &pos=(*it)->m_pos;
		Global::pFont->SendString((*it)->m_text,pos.x,pos.y,TextureMappedFont::ALIGN_CENTER);
	}
}

void GUIMenu::AddButton(string text, int id)
{
	GUIMenuButton* pButton=new GUIMenuButton;
	pButton->m_text=text;
	pButton->m_id=id;

	m_button.push_back(pButton);
}

void GUIMenu::BuildLayout()
{
	const GLfloat TOP_PIXELS=75.0f;
	const GLfloat BOTTOM_PIXELS=20.0f;
	const GLfloat SPACING_PIXELS=20.0f;

	GLfloat buttons=m_button.size();
	GLfloat buttonWidth=0.40*Render::GetScreenWidth();
	GLfloat buttonHeight=(Render::GetScreenHeight()-TOP_PIXELS-BOTTOM_PIXELS-(buttons-1.0f)*SPACING_PIXELS)/buttons;

	m_sprite->SetSize(buttonWidth,buttonHeight);

	GLfloat indexButton=1.0f;
	for(vector<GUIMenuButton*>::iterator it=m_button.begin();it!=m_button.end();++it)
	{
		GLfloat x=Render::GetScreenWidth()*0.5f;
		GLfloat y=TOP_PIXELS+buttonHeight*(indexButton-0.5)+SPACING_PIXELS*(indexButton-1.0f);
		//y=Render::GetScreenHeight()-y;
		(*it)->m_fixedPos=(*it)->m_pos=Vector2f(x,y);
		indexButton+=1.0f;
	}
}

void GUIMenu::DOWNEvent(void *pointer1, void *pointer2)
{
	GUIMenu *pGUI=(GUIMenu*)(pointer1);
	MPACK::Input::Finger *pFinger=(MPACK::Input::Finger*)(pointer2);
	for(vector<GUIMenuButton*>::iterator it=pGUI->m_button.begin();it!=pGUI->m_button.end();++it)
	{
		if((*it)->m_pFinger)
		{
			continue;
		}

		Vector2f &pos=(*it)->m_pos;
		AABB2Df A;
		GLfloat width=pGUI->m_sprite->GetWidth()*0.5f;
		GLfloat height=pGUI->m_sprite->GetHeight()*0.5f;
		A.m_xmin=pos.x-width;
		A.m_xmax=pos.x+width;
		A.m_ymin=pos.y-height;
		A.m_ymax=pos.y+height;
		if(A.Contain(pFinger->m_pos))
		{
			(*it)->m_pFinger=pFinger;
			(*it)->m_fingerStartPos=pFinger->m_pos;
			break;
		}
	}
}

void GUIMenu::UPEvent(void *pointer1, void *pointer2)
{
	const GLfloat ACTION_THRESHOLD=0.1f;
	GLfloat leftThreshold=Render::GetScreenWidth()*ACTION_THRESHOLD;
	GLfloat rightThreshold=Render::GetScreenWidth()*(1.0f-ACTION_THRESHOLD);

	GUIMenu *pGUI=(GUIMenu*)(pointer1);
	MPACK::Input::Finger *pFinger=(MPACK::Input::Finger*)(pointer2);
	for(vector<GUIMenuButton*>::iterator it=pGUI->m_button.begin();it!=pGUI->m_button.end();++it)
	{
		if((*it)->m_pFinger==pFinger)
		{
			(*it)->m_pFinger=NULL;

			if((*it)->m_pos.x<leftThreshold || (*it)->m_pos.x>rightThreshold)
			{
				pGUI->action=(*it)->m_id;
			}
			(*it)->m_pos=(*it)->m_fixedPos;
		}
	}
}
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (people-users@projects.maemo.org)
**
** This file is part of contactsd.
**
** If you have questions regarding the use of this file, please contact
** Nokia at people-users@projects.maemo.org.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "contactsdaemon.h"

// contactd
#include "contactsdpluginloader.h"
// Qt
#include <QSettings>

/*!
  \class ContactsDaemon

  \brief Main daemon class which managers remote contact plug-ins.

  \section y  Populating the contact list with remote contacts
  Remote contacts are the user's buddies from various online sources, like social networks, and IM accounts set up on the device. We have
  written a daemon process which gathers remote contacts from various sources and synchronizes them
  with tracker. And these contacts can be accessed using the QtMobility contacts API. Apart from
  this, the daemon also provides real-time updates of the remote contacts, and this can also be
  monitored using the mobility contacts API.

  \section x Setting up remote contact fetching.

  Start m-sb-session and start up mission-control and the contactsd. After that run contacts
  application. enter your gtalk id and password
  in the login dialog in the first page of the contacts application. Then after few seconds you
  should see your remote contacts
  in the contact list.

  The contacts daemon is located in /usr/bin/contactsd and normally it needs to be manually started
  inside scratchbox.

*/

/*!
  \fn ContactsDaemon::loadAllPlugins (const QStringList &loadPlugins)

  instructs the daemon to load all plugins, and after loading, daemon will also execute the plugins.
  \param loadPlugins - constraints loading to load and init only those plugins with metadata->("name") in loadPlugins list.

  \sa initPlugin(const QString&), initPlugins(), PersonCollectorInterface::init()
*/

/*!
  \fn ContactsDaemon::initPlugins()

  runs all the already loaded plugins by executing
  \l{ContacsdPluginInterface::init()}{initializes the plugin}.

  \sa initPlugin(const QString&)
*/

/*!

  \fn QStringList ContactsDaemon::validPlugins() const

  \return The list of valid plugins handled by the current daemon session.
*/

class ContactsDaemon::Private
{
public:
    Private():settings(0), loader(0) {}
    ~Private()
    {
        delete settings;
        delete loader;
    }
    QSettings * settings;
    ContactsdPluginLoader *loader;
    QStringList banList;
};

ContactsDaemon::ContactsDaemon(QObject* parent): QObject(parent),
        d(new Private)
{
    d->settings = new QSettings(QSettings::IniFormat, QSettings::UserScope, "Nokia","ContactsDaemon");
}

ContactsDaemon::~ContactsDaemon()
{
    delete d;
}

void ContactsDaemon::loadAllPlugins(const QStringList &loadPlugins)
{
    if( !d->loader ) {
        d->loader = new ContactsdPluginLoader(loadPlugins, d->banList);
        connect(d->loader, SIGNAL(pluginsLoaded()), this, SIGNAL(pluginsLoaded()));
    }
}

QStringList ContactsDaemon::validPlugins() const
{
    if (d->loader != 0) {
        return d->loader->validPlugins();
    }
}
<commit_msg>Changes: Fixing warning for missing return value from non void method<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (people-users@projects.maemo.org)
**
** This file is part of contactsd.
**
** If you have questions regarding the use of this file, please contact
** Nokia at people-users@projects.maemo.org.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "contactsdaemon.h"

// contactd
#include "contactsdpluginloader.h"
// Qt
#include <QSettings>

/*!
  \class ContactsDaemon

  \brief Main daemon class which managers remote contact plug-ins.

  \section y  Populating the contact list with remote contacts
  Remote contacts are the user's buddies from various online sources, like social networks, and IM accounts set up on the device. We have
  written a daemon process which gathers remote contacts from various sources and synchronizes them
  with tracker. And these contacts can be accessed using the QtMobility contacts API. Apart from
  this, the daemon also provides real-time updates of the remote contacts, and this can also be
  monitored using the mobility contacts API.

  \section x Setting up remote contact fetching.

  Start m-sb-session and start up mission-control and the contactsd. After that run contacts
  application. enter your gtalk id and password
  in the login dialog in the first page of the contacts application. Then after few seconds you
  should see your remote contacts
  in the contact list.

  The contacts daemon is located in /usr/bin/contactsd and normally it needs to be manually started
  inside scratchbox.

*/

/*!
  \fn ContactsDaemon::loadAllPlugins (const QStringList &loadPlugins)

  instructs the daemon to load all plugins, and after loading, daemon will also execute the plugins.
  \param loadPlugins - constraints loading to load and init only those plugins with metadata->("name") in loadPlugins list.

  \sa initPlugin(const QString&), initPlugins(), PersonCollectorInterface::init()
*/

/*!
  \fn ContactsDaemon::initPlugins()

  runs all the already loaded plugins by executing
  \l{ContacsdPluginInterface::init()}{initializes the plugin}.

  \sa initPlugin(const QString&)
*/

/*!

  \fn QStringList ContactsDaemon::validPlugins() const

  \return The list of valid plugins handled by the current daemon session.
*/

class ContactsDaemon::Private
{
public:
    Private():settings(0), loader(0) {}
    ~Private()
    {
        delete settings;
        delete loader;
    }
    QSettings * settings;
    ContactsdPluginLoader *loader;
    QStringList banList;
};

ContactsDaemon::ContactsDaemon(QObject* parent): QObject(parent),
        d(new Private)
{
    d->settings = new QSettings(QSettings::IniFormat, QSettings::UserScope, "Nokia","ContactsDaemon");
}

ContactsDaemon::~ContactsDaemon()
{
    delete d;
}

void ContactsDaemon::loadAllPlugins(const QStringList &loadPlugins)
{
    if( !d->loader ) {
        d->loader = new ContactsdPluginLoader(loadPlugins, d->banList);
        connect(d->loader, SIGNAL(pluginsLoaded()), this, SIGNAL(pluginsLoaded()));
    }
}

QStringList ContactsDaemon::validPlugins() const
{
    if (d->loader != 0) {
        return d->loader->validPlugins();
    }
    return QStringList();
}
<|endoftext|>