<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief V8 line editor
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2011-2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "v8-line-editor.h"

#include <readline/readline.h>
#include <readline/history.h>

#include "BasicsC/strings.h"

#if RL_READLINE_VERSION >= 0x0500
#define completion_matches rl_completion_matches
#endif

using namespace std;

// -----------------------------------------------------------------------------
// --SECTION--                                                class V8LineEditor
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                                 private variables
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup V8Shell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief word break characters
////////////////////////////////////////////////////////////////////////////////

static char WordBreakCharacters[] = {
    ' ', '\t', '\n', '"', '\\', '\'', '`', '@',
    '<', '>', '=', ';', '|', '&', '{', '}', '(', ')',
    '\0'
};

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                 private functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup V8LineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief completion generator
////////////////////////////////////////////////////////////////////////////////

static char* CompletionGenerator (char const* text, int state) {
  static size_t currentIndex;
  static vector<string> result;
  char* prefix;

  // compute the possible completion
  if (state == 0) {
    if (! v8::Context::InContext()) {
      return 0;
    }

    // locate global object or sub-object
    v8::Handle<v8::Object> current = v8::Context::GetCurrent()->Global();
    string path;

    if (*text != '\0') {
      TRI_vector_string_t splitted = TRI_SplitString(text, '.');

      if (1 < splitted._length) {
        for (size_t i = 0;  i < splitted._length - 1;  ++i) {
          v8::Handle<v8::String> name = v8::String::New(splitted._buffer[i]);

          if (! current->Has(name)) {
            TRI_DestroyVectorString(&splitted);
            return 0;
          }

          v8::Handle<v8::Value> val = current->Get(name);

          if (! val->IsObject()) {
            TRI_DestroyVectorString(&splitted);
            return 0;
          }

          current = val->ToObject();
          path = path + splitted._buffer[i] + ".";
        }

        prefix = TRI_DuplicateString(splitted._buffer[splitted._length - 1]);
      }
      else {
        prefix = TRI_DuplicateString(text);
      }

      TRI_DestroyVectorString(&splitted);
    }
    else {
      prefix = TRI_DuplicateString(text);
    }

    // compute all possible completions
    v8::Handle<v8::Array> properties;
    v8::Handle<v8::String> cpl = v8::String::New("_COMPLETIONS");

    if (current->HasOwnProperty(cpl)) {
      v8::Handle<v8::Value> funcVal = current->Get(cpl);

      if (funcVal->IsFunction()) {
        v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(funcVal);
        v8::Handle<v8::Value> args;
        v8::Handle<v8::Value> cpls = func->Call(current, 0, &args);

        if (cpls->IsArray()) {
          properties = v8::Handle<v8::Array>::Cast(cpls);
        }
      }
    }
    else {
      properties = current->GetPropertyNames();
    }

    // locate
    if (! properties.IsEmpty()) {
      size_t n = properties->Length();

      for (size_t i = 0;  i < n;  ++i) {
        v8::Handle<v8::Value> v = properties->Get(i);

        v8::String::Utf8Value str(v);
        char const* s = *str;

        if (s != 0) {
          string suffix = (current->Get(v)->IsFunction()) ? "()" : "";
          string name = path + s + suffix;

          if (*prefix == '\0' || TRI_IsPrefixString(s, prefix)) {
            result.push_back(name);
          }
        }
      }
    }

    currentIndex = 0;

    TRI_FreeString(prefix);
  }

  if (currentIndex < result.size()) {
    return TRI_DuplicateString(result[currentIndex++].c_str());
  }
  else {
    result.clear();
    return 0;
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief attempted completion
////////////////////////////////////////////////////////////////////////////////

static char** AttemptedCompletion (char const* text, int start, int end) {
  char** result;

  result = completion_matches(text, CompletionGenerator);
  rl_attempted_completion_over = true;

  if (result != 0 && result[0] != 0 && result[1] == 0) {
    size_t n = strlen(result[0]);

    if (result[0][n-1] == ')') {
      result[0][n-1] = '\0';

#if RL_READLINE_VERSION < 0x0500
      rl_completion_suppress_append = 1;
#endif
    }
  }

  return result;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief checks if javascript is missing a closing bracket
////////////////////////////////////////////////////////////////////////////////

static bool CheckJavaScript (string const& source) {
  char const* ptr;
  char const* end;
  int openParen;
  int openBrackets;
  int openBraces;

  enum {
    NORMAL,             // start
    NORMAL_1,           // from NORMAL: seen a single /
    DOUBLE_QUOTE,       // from NORMAL: seen a single "
    DOUBLE_QUOTE_ESC,   // from DOUBLE_QUOTE: seen a backslash
    SINGLE_QUOTE,       // from NORMAL: seen a single '
    SINGLE_QUOTE_ESC,   // from SINGLE_QUOTE: seen a backslash
    MULTI_COMMENT,      // from NORMAL_1: seen a *
    MULTI_COMMENT_1,    // from MULTI_COMMENT, seen a *
    SINGLE_COMMENT      // from NORMAL_1; seen a /
  }
  state;

  openParen = 0;
  openBrackets = 0;
  openBraces = 0;

  ptr = source.c_str();
  end = ptr + source.length();
  state = NORMAL;

  while (ptr < end) {
    if (state == DOUBLE_QUOTE) {
      if (*ptr == '\\') {
        state = DOUBLE_QUOTE_ESC;
      }
      else if (*ptr == '"') {
        state = NORMAL;
      }

      ++ptr;
    }
    else if (state == DOUBLE_QUOTE_ESC) {
      state = DOUBLE_QUOTE;
      ptr++;
    }
    else if (state == SINGLE_QUOTE) {
      if (*ptr == '\\') {
        state = SINGLE_QUOTE_ESC;
      }
      else if (*ptr == '\'') {
        state = NORMAL;
      }

      ++ptr;
    }
    else if (state == SINGLE_QUOTE_ESC) {
      state = SINGLE_QUOTE;
      ptr++;
    }
    else if (state == MULTI_COMMENT) {
      if (*ptr == '*') {
        state = MULTI_COMMENT_1;
      }

      ++ptr;
    }
    else if (state == MULTI_COMMENT_1) {
      if (*ptr == '/') {
        state = NORMAL;
      }

      ++ptr;
    }
    else if (state == SINGLE_COMMENT) {
      ++ptr;

      if (ptr == end) {
        state = NORMAL;
      }
    }
    else if (state == NORMAL_1) {
      switch (*ptr) {
        case '/':
          state = SINGLE_COMMENT;
          ++ptr;
          break;

        case '*':
          state = MULTI_COMMENT;
          ++ptr;
          break;

        default:
          state = NORMAL; // try again, do not change ptr
          break;
      }
    }
    else {
      switch (*ptr) {
        case '"':
          state = DOUBLE_QUOTE;
          break;

        case '\'':
          state = SINGLE_QUOTE;
          break;

        case '/':
          state = NORMAL_1;
          break;

        case '(':
          ++openParen;
          break;

        case ')':
          --openParen;
          break;

        case '[':
          ++openBrackets;
          break;

        case ']':
          --openBrackets;
          break;

        case '{':
          ++openBraces;
          break;

        case '}':
          --openBraces;
          break;
      }

      ++ptr;
    }
  }

  return openParen <= 0 && openBrackets <= 0 && openBraces <= 0;
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup V8LineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief constructs a new editor
////////////////////////////////////////////////////////////////////////////////

V8LineEditor::V8LineEditor (v8::Handle<v8::Context> context, string const& history)
  : _current(), _historyFilename(history), _context(context) {
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                    public methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup V8LineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief line editor open
////////////////////////////////////////////////////////////////////////////////

bool V8LineEditor::open (const bool autoComplete) {
  rl_initialize();

  if (autoComplete) {
    rl_attempted_completion_function = AttemptedCompletion;
    rl_completer_word_break_characters = WordBreakCharacters;

    rl_bind_key('\t', rl_complete);
  }

  using_history();
  stifle_history(MAX_HISTORY_ENTRIES);

  return read_history(getHistoryPath().c_str()) == 0;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief line editor shutdown
////////////////////////////////////////////////////////////////////////////////

bool V8LineEditor::close () {
  bool result = write_history(getHistoryPath().c_str());

  return result;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief get the history file path
////////////////////////////////////////////////////////////////////////////////

string V8LineEditor::getHistoryPath () {
  string path;

  if (getenv("HOME")) {
    path.append(getenv("HOME"));
    path += '/';
  }

  path.append(_historyFilename);

  return path;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief line editor prompt
////////////////////////////////////////////////////////////////////////////////

char* V8LineEditor::prompt (char const* prompt) {
  string dotdot;
  char const* p = prompt;
  size_t len1 = strlen(prompt);
  size_t len2 = len1;

  if (len1 < 3) {
    dotdot = "> ";
    len2 = 2;
  }
  else {
    dotdot = string(len1 - 2, '.') + "> ";
  }

  char const* sep = "";
  char* originalLine = 0;

  while (true) {
    char* result = readline(p);
    originalLine = result;
    p = dotdot.c_str();

    if (result == 0) {
      // give up, if the user pressed control-D on the top-most level
      if (_current.empty()) {
        return 0;
      }

      // otherwise clear current content
      _current.clear();
      break;
    }

    _current += sep;
    sep = "\n";

    bool c1 = strncmp(result, prompt, len1) == 0;
    bool c2 = strncmp(result, dotdot.c_str(), len2) == 0;

    while (c1 || c2) {
      if (c1) {
        result += len1;
      }
      else if (c2) {
        result += len2;
      }

      c1 = strncmp(result, prompt, len1) == 0;
      c2 = strncmp(result, dotdot.c_str(), len2) == 0;
    }

    _current += result;
    bool ok = CheckJavaScript(_current);

    if (ok) {
      break;
    }
    TRI_Free(originalLine);
  }

  char* line = TRI_DuplicateString(_current.c_str());
  _current.clear();

  // avoid memleaks
  if (originalLine != 0) {
    TRI_Free(originalLine);
  }

  return line;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief add to history
////////////////////////////////////////////////////////////////////////////////

void V8LineEditor::addHistory (char const* str) {
  if (*str == '\0') {
    return;
  }

  history_set_pos(history_length-1);

  if (current_history()) {
    do {
      if (strcmp(current_history()->line, str) == 0) {
        remove_history(where_history());
        break;
      }
    }
    while (previous_history());
  }

  add_history(str);
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:
<commit_msg>MacOS old readline<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief V8 line editor
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2011-2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "v8-line-editor.h"

#include <readline/readline.h>
#include <readline/history.h>

#include "BasicsC/strings.h"

#if RL_READLINE_VERSION >= 0x0500
#define completion_matches rl_completion_matches
#endif

using namespace std;

// -----------------------------------------------------------------------------
// --SECTION--                                                class V8LineEditor
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                                 private variables
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup V8Shell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief word break characters
////////////////////////////////////////////////////////////////////////////////

static char WordBreakCharacters[] = {
    ' ', '\t', '\n', '"', '\\', '\'', '`', '@',
    '<', '>', '=', ';', '|', '&', '{', '}', '(', ')',
    '\0'
};

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                 private functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup V8LineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief completion generator
////////////////////////////////////////////////////////////////////////////////

static char* CompletionGenerator (char const* text, int state) {
  static size_t currentIndex;
  static vector<string> result;
  char* prefix;

  // compute the possible completion
  if (state == 0) {
    if (! v8::Context::InContext()) {
      return 0;
    }

    // locate global object or sub-object
    v8::Handle<v8::Object> current = v8::Context::GetCurrent()->Global();
    string path;

    if (*text != '\0') {
      TRI_vector_string_t splitted = TRI_SplitString(text, '.');

      if (1 < splitted._length) {
        for (size_t i = 0;  i < splitted._length - 1;  ++i) {
          v8::Handle<v8::String> name = v8::String::New(splitted._buffer[i]);

          if (! current->Has(name)) {
            TRI_DestroyVectorString(&splitted);
            return 0;
          }

          v8::Handle<v8::Value> val = current->Get(name);

          if (! val->IsObject()) {
            TRI_DestroyVectorString(&splitted);
            return 0;
          }

          current = val->ToObject();
          path = path + splitted._buffer[i] + ".";
        }

        prefix = TRI_DuplicateString(splitted._buffer[splitted._length - 1]);
      }
      else {
        prefix = TRI_DuplicateString(text);
      }

      TRI_DestroyVectorString(&splitted);
    }
    else {
      prefix = TRI_DuplicateString(text);
    }

    // compute all possible completions
    v8::Handle<v8::Array> properties;
    v8::Handle<v8::String> cpl = v8::String::New("_COMPLETIONS");

    if (current->HasOwnProperty(cpl)) {
      v8::Handle<v8::Value> funcVal = current->Get(cpl);

      if (funcVal->IsFunction()) {
        v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(funcVal);
        v8::Handle<v8::Value> args;
        v8::Handle<v8::Value> cpls = func->Call(current, 0, &args);

        if (cpls->IsArray()) {
          properties = v8::Handle<v8::Array>::Cast(cpls);
        }
      }
    }
    else {
      properties = current->GetPropertyNames();
    }

    // locate
    if (! properties.IsEmpty()) {
      size_t n = properties->Length();

      for (size_t i = 0;  i < n;  ++i) {
        v8::Handle<v8::Value> v = properties->Get(i);

        v8::String::Utf8Value str(v);
        char const* s = *str;

        if (s != 0) {
          string suffix = (current->Get(v)->IsFunction()) ? "()" : "";
          string name = path + s + suffix;

          if (*prefix == '\0' || TRI_IsPrefixString(s, prefix)) {
            result.push_back(name);
          }
        }
      }
    }

    currentIndex = 0;

    TRI_FreeString(prefix);
  }

  if (currentIndex < result.size()) {
    return TRI_DuplicateString(result[currentIndex++].c_str());
  }
  else {
    result.clear();
    return 0;
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief attempted completion
////////////////////////////////////////////////////////////////////////////////

static char** AttemptedCompletion (char const* text, int start, int end) {
  char** result;

  result = completion_matches(text, CompletionGenerator);
  rl_attempted_completion_over = true;

  if (result != 0 && result[0] != 0 && result[1] == 0) {
    size_t n = strlen(result[0]);

    if (result[0][n-1] == ')') {
      result[0][n-1] = '\0';

#if RL_READLINE_VERSION >= 0x0500
      rl_completion_suppress_append = 1;
#endif
    }
  }

  return result;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief checks if javascript is missing a closing bracket
////////////////////////////////////////////////////////////////////////////////

static bool CheckJavaScript (string const& source) {
  char const* ptr;
  char const* end;
  int openParen;
  int openBrackets;
  int openBraces;

  enum {
    NORMAL,             // start
    NORMAL_1,           // from NORMAL: seen a single /
    DOUBLE_QUOTE,       // from NORMAL: seen a single "
    DOUBLE_QUOTE_ESC,   // from DOUBLE_QUOTE: seen a backslash
    SINGLE_QUOTE,       // from NORMAL: seen a single '
    SINGLE_QUOTE_ESC,   // from SINGLE_QUOTE: seen a backslash
    MULTI_COMMENT,      // from NORMAL_1: seen a *
    MULTI_COMMENT_1,    // from MULTI_COMMENT, seen a *
    SINGLE_COMMENT      // from NORMAL_1; seen a /
  }
  state;

  openParen = 0;
  openBrackets = 0;
  openBraces = 0;

  ptr = source.c_str();
  end = ptr + source.length();
  state = NORMAL;

  while (ptr < end) {
    if (state == DOUBLE_QUOTE) {
      if (*ptr == '\\') {
        state = DOUBLE_QUOTE_ESC;
      }
      else if (*ptr == '"') {
        state = NORMAL;
      }

      ++ptr;
    }
    else if (state == DOUBLE_QUOTE_ESC) {
      state = DOUBLE_QUOTE;
      ptr++;
    }
    else if (state == SINGLE_QUOTE) {
      if (*ptr == '\\') {
        state = SINGLE_QUOTE_ESC;
      }
      else if (*ptr == '\'') {
        state = NORMAL;
      }

      ++ptr;
    }
    else if (state == SINGLE_QUOTE_ESC) {
      state = SINGLE_QUOTE;
      ptr++;
    }
    else if (state == MULTI_COMMENT) {
      if (*ptr == '*') {
        state = MULTI_COMMENT_1;
      }

      ++ptr;
    }
    else if (state == MULTI_COMMENT_1) {
      if (*ptr == '/') {
        state = NORMAL;
      }

      ++ptr;
    }
    else if (state == SINGLE_COMMENT) {
      ++ptr;

      if (ptr == end) {
        state = NORMAL;
      }
    }
    else if (state == NORMAL_1) {
      switch (*ptr) {
        case '/':
          state = SINGLE_COMMENT;
          ++ptr;
          break;

        case '*':
          state = MULTI_COMMENT;
          ++ptr;
          break;

        default:
          state = NORMAL; // try again, do not change ptr
          break;
      }
    }
    else {
      switch (*ptr) {
        case '"':
          state = DOUBLE_QUOTE;
          break;

        case '\'':
          state = SINGLE_QUOTE;
          break;

        case '/':
          state = NORMAL_1;
          break;

        case '(':
          ++openParen;
          break;

        case ')':
          --openParen;
          break;

        case '[':
          ++openBrackets;
          break;

        case ']':
          --openBrackets;
          break;

        case '{':
          ++openBraces;
          break;

        case '}':
          --openBraces;
          break;
      }

      ++ptr;
    }
  }

  return openParen <= 0 && openBrackets <= 0 && openBraces <= 0;
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup V8LineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief constructs a new editor
////////////////////////////////////////////////////////////////////////////////

V8LineEditor::V8LineEditor (v8::Handle<v8::Context> context, string const& history)
  : _current(), _historyFilename(history), _context(context) {
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                    public methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup V8LineEditor
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief line editor open
////////////////////////////////////////////////////////////////////////////////

bool V8LineEditor::open (const bool autoComplete) {
  rl_initialize();

  if (autoComplete) {
    rl_attempted_completion_function = AttemptedCompletion;
    rl_completer_word_break_characters = WordBreakCharacters;

    rl_bind_key('\t', rl_complete);
  }

  using_history();
  stifle_history(MAX_HISTORY_ENTRIES);

  return read_history(getHistoryPath().c_str()) == 0;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief line editor shutdown
////////////////////////////////////////////////////////////////////////////////

bool V8LineEditor::close () {
  bool result = write_history(getHistoryPath().c_str());

  return result;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief get the history file path
////////////////////////////////////////////////////////////////////////////////

string V8LineEditor::getHistoryPath () {
  string path;

  if (getenv("HOME")) {
    path.append(getenv("HOME"));
    path += '/';
  }

  path.append(_historyFilename);

  return path;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief line editor prompt
////////////////////////////////////////////////////////////////////////////////

char* V8LineEditor::prompt (char const* prompt) {
  string dotdot;
  char const* p = prompt;
  size_t len1 = strlen(prompt);
  size_t len2 = len1;

  if (len1 < 3) {
    dotdot = "> ";
    len2 = 2;
  }
  else {
    dotdot = string(len1 - 2, '.') + "> ";
  }

  char const* sep = "";
  char* originalLine = 0;

  while (true) {
    char* result = readline(p);
    originalLine = result;
    p = dotdot.c_str();

    if (result == 0) {
      // give up, if the user pressed control-D on the top-most level
      if (_current.empty()) {
        return 0;
      }

      // otherwise clear current content
      _current.clear();
      break;
    }

    _current += sep;
    sep = "\n";

    bool c1 = strncmp(result, prompt, len1) == 0;
    bool c2 = strncmp(result, dotdot.c_str(), len2) == 0;

    while (c1 || c2) {
      if (c1) {
        result += len1;
      }
      else if (c2) {
        result += len2;
      }

      c1 = strncmp(result, prompt, len1) == 0;
      c2 = strncmp(result, dotdot.c_str(), len2) == 0;
    }

    _current += result;
    bool ok = CheckJavaScript(_current);

    if (ok) {
      break;
    }
    TRI_Free(originalLine);
  }

  char* line = TRI_DuplicateString(_current.c_str());
  _current.clear();

  // avoid memleaks
  if (originalLine != 0) {
    TRI_Free(originalLine);
  }

  return line;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief add to history
////////////////////////////////////////////////////////////////////////////////

void V8LineEditor::addHistory (char const* str) {
  if (*str == '\0') {
    return;
  }

  history_set_pos(history_length-1);

  if (current_history()) {
    do {
      if (strcmp(current_history()->line, str) == 0) {
        remove_history(where_history());
        break;
      }
    }
    while (previous_history());
  }

  add_history(str);
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:
<|endoftext|>


<commit_before>//=============================================================================
// test
// *** AddTaskFemto.C ***
//
// This macro initialize a complete AnalysisTask object for femtoscopy.
//
//=============================================================================

AliAnalysisTaskFemto *AddTaskFemto(const char *configMacroName="ConfigFemtoAnalysis.C", const char *configMacroParameters="" )
{
// Creates a proton analysis task and adds it to the analysis manager.

  // A. Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskFemto", "No analysis manager to connect to.");
    return NULL;
  }

  // B. Check the analysis type using the event handlers connected to the analysis
  //    manager. The availability of MC handler cann also be checked here.
  //==============================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskFemto", "This task requires an input event handler");
    return NULL;
  }
  TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
  cout << "Found " <<type << " event handler" << endl;

  // C. Create the task, add it to manager.
  //===========================================================================
//  gSystem->SetIncludePath("-I$ROOTSYS/include  -I./PWG2AOD/AOD -I./PWG2femtoscopy/FEMTOSCOPY/AliFemto -I./PWG2femtoscopyUser/FEMTOSCOPY/AliFemtoUser -I$ALICE_ROOT/include");

  if (TProofMgr::GetListOfManagers()->GetEntries()) {
//     if (dynamic_cast<TProofLite *> gProof) {
//       char *macrocommand[10000];
//       sprintf(macrocommand, ".L %s", configMacroName);
//       gProof->Exec(macrocommand);
//     }
//     else
    gProof->Load(configMacroName);
  }
  //  gROOT->LoadMacro("ConfigFemtoAnalysis.C++");

  AliAnalysisTaskFemto *taskfemto = new AliAnalysisTaskFemto("TaskFemto",configMacroName,configMacroParameters);
  mgr->AddTask(taskfemto);

  // D. Configure the analysis task. Extra parameters can be used via optional
  // arguments of the AddTaskXXX() function.
  //===========================================================================

  // E. Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
  TString outputfile = AliAnalysisManager::GetCommonFileName();
  outputfile += ":PWG2FEMTO";
  AliAnalysisDataContainer *cout_femto  = mgr->CreateContainer("femtolist",  TList::Class(),
  							       AliAnalysisManager::kOutputContainer,outputfile);

   mgr->ConnectInput(taskfemto, 0, mgr->GetCommonInputContainer());
   mgr->ConnectOutput(taskfemto, 0, cout_femto);

   // Return task pointer at the end
   return taskfemto;
}
<commit_msg>AliFemto: removal of unwanted file<commit_after><|endoftext|>


<commit_before>#ifndef __CINT__
#include <AliRsnCutTrackQuality.h>
#endif
Int_t AddRsnDaughterCutsPhiNsigma(AliPID::EParticleType type1,AliPID::EParticleType type2,TString opt,AliRsnInputHandler *rsnIH=0,AliAnalysisTaskSE *task=0)
{

   if (!rsnIH) return 0;

   Bool_t valid = kTRUE;
//   Int_t collisionType = AliRsnTrainManager::GetGlobalInt("IsCollisionType",valid);
   Int_t useCommonQualityCut = AliRsnTrainManager::GetGlobalInt("RsnCommonQualityCut",valid);
   TString rsnQualityCut = AliRsnTrainManager::GetGlobalStr("RsnQualityCut",valid);
   Int_t isMC = AliRsnTrainManager::GetGlobalInt("IsMC",valid);
   Int_t isRsnMini = AliRsnTrainManager::GetGlobalInt("IsRsnMini",valid);
   Int_t isMixing = AliRsnTrainManager::GetGlobalInt("IsMixing",valid);

   // experts only (don't touch)
   Int_t isRsnDev = AliAnalysisManager::GetGlobalInt("rsnUseRSNParDev",valid);

   // === USER HAS TO SET CORRECT NUMBER OF CUTS SETS =====
   Int_t numberOfCuts = 1;

   //---------------------------------------------
   //  Define single cuts
   //---------------------------------------------

   Printf("AliRsnCutPIDNSigma Option : %s",opt.Data());

   Double_t nSigmaTPC=3.0;
   Double_t nSigmaTOF=3.0;
   Double_t etaRange=0.8;
   Double_t trackPtMin=0.;
   Double_t trackPtMax=1.e10;
   Int_t NclTPC=70;
   Char_t DCAxyFormula[100]="0.0182+0.035/pt^1.01";

   Bool_t useTPC_K=kFALSE;
   Bool_t useTOF_K=kFALSE;
   Bool_t useTrackPtCut=kFALSE;

   if (opt.Contains("qualityonly")) {
      useTPC_K=kFALSE;
      useTOF_K=kFALSE;
   } else if (!opt.Contains("nsig")) {
      useTPC_K=kTRUE;
      useTOF_K=kTRUE;
   }

   if (opt.Contains("KTPCnsig"))  useTPC_K=kTRUE;
   if (opt.Contains("KTOFnsig"))  useTOF_K=kTRUE;

   if (opt.Contains("KTPCnsig05")) nSigmaTPC = 0.5;
   if (opt.Contains("KTPCnsig08")) nSigmaTPC = 0.8;
   if (opt.Contains("KTPCnsig10")) nSigmaTPC = 1.0;
   if (opt.Contains("KTPCnsig15")) nSigmaTPC = 1.5;
   if (opt.Contains("KTPCnsig20")) nSigmaTPC = 2.0;
   if (opt.Contains("KTPCnsig25")) nSigmaTPC = 2.5;
   if (opt.Contains("KTPCnsig30")) nSigmaTPC = 3.0;
   if (opt.Contains("KTPCnsig40")) nSigmaTPC = 4.0;
   if (opt.Contains("KTPCnsig50")) nSigmaTPC = 5.0;
   if (opt.Contains("KTPCnsig1000")) nSigmaTPC = 100.0;

   if (opt.Contains("KTOFnsig10")) nSigmaTOF = 1.0;
   if (opt.Contains("KTOFnsig15")) nSigmaTOF = 1.5;
   if (opt.Contains("KTOFnsig20")) nSigmaTOF = 2.0;
   if (opt.Contains("KTOFnsig25")) nSigmaTOF = 2.5;
   if (opt.Contains("KTOFnsig30")) nSigmaTOF = 3.0;
   if (opt.Contains("KTOFnsig1000")) nSigmaTOF = 100.0;

   if (opt.Contains("trackPt")) {
      useTrackPtCut = kTRUE;
      if (opt.Contains("trackPtMin015")) trackPtMin = 0.15;
      if (opt.Contains("trackPtMin02")) trackPtMin = 0.2;
      if (opt.Contains("trackPtMin05")) trackPtMin = 0.5;
      if (opt.Contains("trackPtMin06")) trackPtMin = 0.6;

      if (opt.Contains("trackPtMax18")) trackPtMax = 1.8;
      if (opt.Contains("trackPtMax20")) trackPtMax = 2.0;
      if (opt.Contains("trackPtMax25")) trackPtMax = 2.5;
   }

   Bool_t usePDG=kFALSE;
   if (opt.Contains("pdg")) {
      Printf("Using PDG");
      usePDG = kTRUE;
   }

   Bool_t useEta = kFALSE;
   if (opt.Contains("eta")) {
      if(opt.Contains("eta09")) etaRange=0.9;
      if(opt.Contains("eta08")) etaRange=0.8;
      if(opt.Contains("eta07")) etaRange=0.7;
      if(opt.Contains("eta06")) etaRange=0.6;
      Printf("Using ETA range (%.2f,%.2f)",-etaRange,etaRange);
      useEta = kTRUE;
   }

   Bool_t useNclTPC = kFALSE;
   if (opt.Contains("NclTPC")) {
      if (opt.Contains("NclTPC70")) NclTPC=70;
      if (opt.Contains("NclTPC75")) NclTPC=75;
      if (opt.Contains("NclTPC80")) NclTPC=80;
      if (opt.Contains("NclTPC85")) NclTPC=85;
      if (opt.Contains("NclTPC90")) NclTPC=90;
      useNclTPC = kTRUE;
   }

   Bool_t useDCAxy = kFALSE;
   if (opt.Contains("DCAxy")) {
      if (opt.Contains("DCAxyFormula7s")) sprintf(DCAxyFormula,"0.0182+0.035/pt^1.01");
      if (opt.Contains("DCAxyFormula6s")) sprintf(DCAxyFormula,"0.0156+0.03/pt^1.01");
      if (opt.Contains("DCAxyFormula5s")) sprintf(DCAxyFormula,"0.013+0.025/pt^1.01");
      useDCAxy = kTRUE;
   }

//---------------------------------------------
//  Combine cuts
//---------------------------------------------

   TString cutname = "K_Phi";
   if (!opt.IsNull()) cutname += Form("_%s",opt.Data());
   AliRsnCutSet *cuts = new AliRsnCutSet(cutname.Data(), AliRsnTarget::kDaughter);

   TString scheme="";
   AliRsnCutTrackQuality *qualityCut = new AliRsnCutTrackQuality("cutQualityK");
   if (!rsnQualityCut.IsNull()) {
      AliESDtrackCuts *esdTK = RsnQualityCut(rsnQualityCut.Data());
      if(useDCAxy) esdTK->SetMaxDCAToVertexXYPtDep(DCAxyFormula);
      qualityCut->SetESDtrackCuts(esdTK);
   } else {
      if (useCommonQualityCut>=0) {
         qualityCut->SetAODTestFilterBit(useCommonQualityCut);
         if(useDCAxy) {qualityCut->SetCheckOnlyFilterBit(kFALSE); qualityCut->SetDCARPtFormula(DCAxyFormula);}
      } else {
         qualityCut->SetDefaults2010();
         if(useDCAxy) qualityCut->SetDCARPtFormula(DCAxyFormula);
      }
   }

   cuts->AddCut(qualityCut);
   if (!scheme.IsNull()) scheme += "&";
   scheme += qualityCut->GetName();

   if (useTPC_K) {
      AliRsnCutPIDNSigma *cutKTPC = new AliRsnCutPIDNSigma("cutPIDNSigmaTPCK",AliPID::kKaon,AliRsnCutPIDNSigma::kTPC);
      cutKTPC->SinglePIDRange(nSigmaTPC);
      cuts->AddCut(cutKTPC);
      if (!scheme.IsNull()) scheme += "&";
      scheme += cutKTPC->GetName();
   }

   if (useTOF_K) {
      AliRsnCutPIDNSigma *cutKTOF = new AliRsnCutPIDNSigma("cutPIDNSigmaTOFK",AliPID::kKaon,AliRsnCutPIDNSigma::kTOF);
      cutKTOF->SinglePIDRange(nSigmaTOF);
      cuts->AddCut(cutKTOF);
      if (!scheme.IsNull()) scheme += "&";
      scheme += cutKTOF->GetName();
   }

   if (useEta) {
      Printf("Adding ETA ...");
      AliRsnValueDaughter *valEta = new AliRsnValueDaughter(Form("val%sETA%s",AliPID::ParticleName(type1),opt.Data()),AliRsnValueDaughter::kEta);
      AliRsnCutValue *cutEta = new AliRsnCutValue(Form("cut%sETA%s",AliPID::ParticleName(type1),opt.Data()),-etaRange,etaRange);
      cutEta->SetTargetType(AliRsnTarget::kDaughter);
      cutEta->SetValueObj(valEta);
      cuts->AddCut(cutEta);
      if (!scheme.IsNull()) scheme += "&";
      scheme += cutEta->GetName();
   }

   if (useTrackPtCut) {
      Printf("Adding Pt min=%.3f max=%.3f ...",trackPtMin,trackPtMax);
      AliRsnValueDaughter *valTrackPt = new AliRsnValueDaughter(Form("val%sTrackPt%s",AliPID::ParticleName(type1),opt.Data()),AliRsnValueDaughter::kPt);

      AliRsnCutValue *cutTrackPt = new AliRsnCutValue(Form("cut%sTrackPt%s",AliPID::ParticleName(type1),opt.Data()),trackPtMin,trackPtMax);
      cutTrackPt->SetTargetType(AliRsnTarget::kDaughter);
      cutTrackPt->SetValueObj(valTrackPt);
      cuts->AddCut(cutTrackPt);
      if (!scheme.IsNull()) scheme += "&";
      scheme += cutTrackPt->GetName();
   }

   if (useNclTPC) {
      Printf("Adding NclTPC >= %i",NclTPC);
      AliRsnValueDaughter *valNclTPC = new AliRsnValueDaughter(Form("val%sNclTPC%s",AliPID::ParticleName(type1),opt.Data()),AliRsnValueDaughter::kNTPCclusters);
      AliRsnCutValue *cutNclTPC = new AliRsnCutValue(Form("cut%sNclTPC%s",AliPID::ParticleName(type1),opt.Data()),NclTPC-0.1,1000.);
      cutNclTPC->SetTargetType(AliRsnTarget::kDaughter);
      cutNclTPC->SetValueObj(valNclTPC);
      cuts->AddCut(cutNclTPC);
      if (!scheme.IsNull()) scheme += "&";
      scheme += cutNclTPC->GetName();
   }

   if (usePDG) {
      Printf("Adding PDG ...");
      AliRsnCutPID *cutPDG = new AliRsnCutPID(Form("cut%sPDG%s",AliPID::ParticleName(type1),opt.Data()),type1,0.0,kTRUE);
      cuts->AddCut(cutPDG);
      if (!scheme.IsNull()) scheme += "&";
      scheme += cutPDG->GetName();
   }

   Printf ("CUT Scheme is '%s'",scheme.Data());
   cuts->SetCutScheme(scheme.Data());

   if (opt.Contains("mon")) {
      AddMonitorOutput(cuts->GetMonitorOutput(),opt);
   }
   if (isRsnMini) {
      AliRsnMiniAnalysisTask *taskRsnMini = (AliRsnMiniAnalysisTask *)task;
      if (taskRsnMini) {
         taskRsnMini->AddTrackCuts(cuts);
      }
   } else {
      AliRsnDaughterSelector *sel = rsnIH->GetSelector();
//       sel->SetLabelCheck(kFALSE);
      sel->Add(cuts, kTRUE);
      if (isRsnDev>=0 && opt.Contains("pairPID")) {
         AliRsnActPostDaughterSelection *pairPID = new AliRsnActPostDaughterSelection();
         pairPID->SetID(0);

         const char *fn="rsnRange.txt";
         if (!gSystem->AccessPathName(fn)) {
            TString minStr = gSystem->GetFromPipe(TString::Format("head -n 1 %s").Data());
            TString maxStr = gSystem->GetFromPipe(TString::Format("tail -n 1 %s").Data());
            pairPID->SetMass(minStr.Atof(),maxStr.Atof());
         } else {
            //       pairPID->SetMass(1.01,1.03);
            pairPID->SetMass(1.015,1.025);
            pairPID->SetMass(1.019,1.021);
            pairPID->SetMass(1.0195,1.0205);
            pairPID->SetMass(1.1000,1.1005);
            //       pairPID->SetMass(1.1005,1.1010);
         }
         sel->AddAction(pairPID);
      }

   }
   return numberOfCuts;

}

<commit_msg>Modified macros for phi analysis: improved pseudorapidity cut flexibility (A.Knospe)<commit_after>#ifndef __CINT__
#include <AliRsnCutTrackQuality.h>
#endif
Int_t AddRsnDaughterCutsPhiNsigma(AliPID::EParticleType type1,AliPID::EParticleType type2,TString opt,AliRsnInputHandler *rsnIH=0,AliAnalysisTaskSE *task=0)
{

  if (!rsnIH) return 0;

  Bool_t valid = kTRUE;
  //   Int_t collisionType = AliRsnTrainManager::GetGlobalInt("IsCollisionType",valid);
  Int_t useCommonQualityCut = AliRsnTrainManager::GetGlobalInt("RsnCommonQualityCut",valid);
  TString rsnQualityCut = AliRsnTrainManager::GetGlobalStr("RsnQualityCut",valid);
  Int_t isMC = AliRsnTrainManager::GetGlobalInt("IsMC",valid);
  Int_t isRsnMini = AliRsnTrainManager::GetGlobalInt("IsRsnMini",valid);
  Int_t isMixing = AliRsnTrainManager::GetGlobalInt("IsMixing",valid);

  // experts only (don't touch)
  Int_t isRsnDev = AliAnalysisManager::GetGlobalInt("rsnUseRSNParDev",valid);

  // === USER HAS TO SET CORRECT NUMBER OF CUTS SETS =====
  Int_t numberOfCuts = 1;

  //---------------------------------------------
  //  Define single cuts
  //---------------------------------------------

  Printf("AliRsnCutPIDNSigma Option : %s",opt.Data());

  Double_t nSigmaTPC=3.0;
  Double_t nSigmaTOF=3.0;
  Double_t etaMin=-0.8;
  Double_t etaMax=0.8;
  Double_t trackPtMin=0.;
  Double_t trackPtMax=1.e10;
  Int_t NclTPC=70;
  Char_t DCAxyFormula[100]="0.0182+0.035/pt^1.01";

  Bool_t useTPC_K=kFALSE;
  Bool_t useTOF_K=kFALSE;
  Bool_t useTrackPtCut=kFALSE;

  if (opt.Contains("qualityonly")) {
    useTPC_K=kFALSE;
    useTOF_K=kFALSE;
  } else if (!opt.Contains("nsig")) {
    useTPC_K=kTRUE;
    useTOF_K=kTRUE;
  }

  if (opt.Contains("KTPCnsig"))  useTPC_K=kTRUE;
  if (opt.Contains("KTOFnsig"))  useTOF_K=kTRUE;

  if (opt.Contains("KTPCnsig05")) nSigmaTPC = 0.5;
  if (opt.Contains("KTPCnsig08")) nSigmaTPC = 0.8;
  if (opt.Contains("KTPCnsig10")) nSigmaTPC = 1.0;
  if (opt.Contains("KTPCnsig15")) nSigmaTPC = 1.5;
  if (opt.Contains("KTPCnsig20")) nSigmaTPC = 2.0;
  if (opt.Contains("KTPCnsig25")) nSigmaTPC = 2.5;
  if (opt.Contains("KTPCnsig30")) nSigmaTPC = 3.0;
  if (opt.Contains("KTPCnsig40")) nSigmaTPC = 4.0;
  if (opt.Contains("KTPCnsig50")) nSigmaTPC = 5.0;
  if (opt.Contains("KTPCnsig1000")) nSigmaTPC = 100.0;

  if (opt.Contains("KTOFnsig10")) nSigmaTOF = 1.0;
  if (opt.Contains("KTOFnsig15")) nSigmaTOF = 1.5;
  if (opt.Contains("KTOFnsig20")) nSigmaTOF = 2.0;
  if (opt.Contains("KTOFnsig25")) nSigmaTOF = 2.5;
  if (opt.Contains("KTOFnsig30")) nSigmaTOF = 3.0;
  if (opt.Contains("KTOFnsig1000")) nSigmaTOF = 100.0;

  if (opt.Contains("trackPt")) {
    useTrackPtCut = kTRUE;
    if (opt.Contains("trackPtMin015")) trackPtMin = 0.15;
    if (opt.Contains("trackPtMin02")) trackPtMin = 0.2;
    if (opt.Contains("trackPtMin05")) trackPtMin = 0.5;
    if (opt.Contains("trackPtMin06")) trackPtMin = 0.6;

    if (opt.Contains("trackPtMax18")) trackPtMax = 1.8;
    if (opt.Contains("trackPtMax20")) trackPtMax = 2.0;
    if (opt.Contains("trackPtMax25")) trackPtMax = 2.5;
  }

  Bool_t usePDG=kFALSE;
  if (opt.Contains("pdg")) {
    Printf("Using PDG");
    usePDG = kTRUE;
  }

  Bool_t useEta = kFALSE;
  if (opt.Contains("eta")) {
    for(int j=1;j<=9;j++) if(opt.Contains(Form("eta0%i",j))){etaMin=-0.1*j; etaMax=0.1*j;}

    for(int j=1;j<=9;j++) if(opt.Contains(Form("etaMinMinus0%i",j))) etaMin=-0.1*j;
    if(opt.Contains("etaMin00")) etaMin=0.;
    for(int j=1;j<=9;j++) if(opt.Contains(Form("etaMinPlus0%i",j))) etaMin=0.1*j;

    for(int j=1;j<=9;j++) if(opt.Contains(Form("etaMaxMinus0%i",j))) etaMax=-0.1*j;
    if(opt.Contains("etaMax00")) etaMax=0.;
    for(int j=1;j<=9;j++) if(opt.Contains(Form("etaMaxPlus0%i",j))) etaMax=0.1*j;

    Printf("Using ETA range (%.2f,%.2f)",etaMin,etaMax);
    useEta = kTRUE;
  }

  Bool_t useNclTPC = kFALSE;
  if (opt.Contains("NclTPC")) {
    if (opt.Contains("NclTPC70")) NclTPC=70;
    if (opt.Contains("NclTPC75")) NclTPC=75;
    if (opt.Contains("NclTPC80")) NclTPC=80;
    if (opt.Contains("NclTPC85")) NclTPC=85;
    if (opt.Contains("NclTPC90")) NclTPC=90;
    useNclTPC = kTRUE;
  }

  Bool_t useDCAxy = kFALSE;
  if (opt.Contains("DCAxy")) {
    if (opt.Contains("DCAxyFormula7s")) sprintf(DCAxyFormula,"0.0182+0.035/pt^1.01");
    if (opt.Contains("DCAxyFormula6s")) sprintf(DCAxyFormula,"0.0156+0.03/pt^1.01");
    if (opt.Contains("DCAxyFormula5s")) sprintf(DCAxyFormula,"0.013+0.025/pt^1.01");
    useDCAxy = kTRUE;
  }

  //---------------------------------------------
  //  Combine cuts
  //---------------------------------------------

  TString cutname = "K_Phi";
  if (!opt.IsNull()) cutname += Form("_%s",opt.Data());
  AliRsnCutSet *cuts = new AliRsnCutSet(cutname.Data(), AliRsnTarget::kDaughter);

  TString scheme="";
  AliRsnCutTrackQuality *qualityCut = new AliRsnCutTrackQuality("cutQualityK");
  if (!rsnQualityCut.IsNull()) {
    AliESDtrackCuts *esdTK = RsnQualityCut(rsnQualityCut.Data());
    if(useDCAxy) esdTK->SetMaxDCAToVertexXYPtDep(DCAxyFormula);
    qualityCut->SetESDtrackCuts(esdTK);
  } else {
    if (useCommonQualityCut>=0) {
      qualityCut->SetAODTestFilterBit(useCommonQualityCut);
      if(useDCAxy) {qualityCut->SetCheckOnlyFilterBit(kFALSE); qualityCut->SetDCARPtFormula(DCAxyFormula);}
    } else {
      qualityCut->SetDefaults2010();
      if(useDCAxy) qualityCut->SetDCARPtFormula(DCAxyFormula);
    }
  }

  cuts->AddCut(qualityCut);
  if (!scheme.IsNull()) scheme += "&";
  scheme += qualityCut->GetName();

  if (useTPC_K) {
    AliRsnCutPIDNSigma *cutKTPC = new AliRsnCutPIDNSigma("cutPIDNSigmaTPCK",AliPID::kKaon,AliRsnCutPIDNSigma::kTPC);
    cutKTPC->SinglePIDRange(nSigmaTPC);
    cuts->AddCut(cutKTPC);
    if (!scheme.IsNull()) scheme += "&";
    scheme += cutKTPC->GetName();
  }

  if (useTOF_K) {
    AliRsnCutPIDNSigma *cutKTOF = new AliRsnCutPIDNSigma("cutPIDNSigmaTOFK",AliPID::kKaon,AliRsnCutPIDNSigma::kTOF);
    cutKTOF->SinglePIDRange(nSigmaTOF);
    cuts->AddCut(cutKTOF);
    if (!scheme.IsNull()) scheme += "&";
    scheme += cutKTOF->GetName();
  }

  if (useEta) {
    Printf("Adding ETA ...");
    AliRsnValueDaughter *valEta = new AliRsnValueDaughter(Form("val%sETA%s",AliPID::ParticleName(type1),opt.Data()),AliRsnValueDaughter::kEta);
    AliRsnCutValue *cutEta = new AliRsnCutValue(Form("cut%sETA%s",AliPID::ParticleName(type1),opt.Data()),etaMin,etaMax);
    cutEta->SetTargetType(AliRsnTarget::kDaughter);
    cutEta->SetValueObj(valEta);
    cuts->AddCut(cutEta);
    if (!scheme.IsNull()) scheme += "&";
    scheme += cutEta->GetName();
  }

  if (useTrackPtCut) {
    Printf("Adding Pt min=%.3f max=%.3f ...",trackPtMin,trackPtMax);
    AliRsnValueDaughter *valTrackPt = new AliRsnValueDaughter(Form("val%sTrackPt%s",AliPID::ParticleName(type1),opt.Data()),AliRsnValueDaughter::kPt);

    AliRsnCutValue *cutTrackPt = new AliRsnCutValue(Form("cut%sTrackPt%s",AliPID::ParticleName(type1),opt.Data()),trackPtMin,trackPtMax);
    cutTrackPt->SetTargetType(AliRsnTarget::kDaughter);
    cutTrackPt->SetValueObj(valTrackPt);
    cuts->AddCut(cutTrackPt);
    if (!scheme.IsNull()) scheme += "&";
    scheme += cutTrackPt->GetName();
  }

  if (useNclTPC) {
    Printf("Adding NclTPC >= %i",NclTPC);
    AliRsnValueDaughter *valNclTPC = new AliRsnValueDaughter(Form("val%sNclTPC%s",AliPID::ParticleName(type1),opt.Data()),AliRsnValueDaughter::kNTPCclusters);
    AliRsnCutValue *cutNclTPC = new AliRsnCutValue(Form("cut%sNclTPC%s",AliPID::ParticleName(type1),opt.Data()),NclTPC-0.1,1000.);
    cutNclTPC->SetTargetType(AliRsnTarget::kDaughter);
    cutNclTPC->SetValueObj(valNclTPC);
    cuts->AddCut(cutNclTPC);
    if (!scheme.IsNull()) scheme += "&";
    scheme += cutNclTPC->GetName();
  }

  if (usePDG) {
    Printf("Adding PDG ...");
    AliRsnCutPID *cutPDG = new AliRsnCutPID(Form("cut%sPDG%s",AliPID::ParticleName(type1),opt.Data()),type1,0.0,kTRUE);
    cuts->AddCut(cutPDG);
    if (!scheme.IsNull()) scheme += "&";
    scheme += cutPDG->GetName();
  }

  Printf ("CUT Scheme is '%s'",scheme.Data());
  cuts->SetCutScheme(scheme.Data());

  if (opt.Contains("mon")) {
    AddMonitorOutput(cuts->GetMonitorOutput(),opt);
  }
  if (isRsnMini) {
    AliRsnMiniAnalysisTask *taskRsnMini = (AliRsnMiniAnalysisTask *)task;
    if (taskRsnMini) {
      taskRsnMini->AddTrackCuts(cuts);
    }
  } else {
    AliRsnDaughterSelector *sel = rsnIH->GetSelector();
    //       sel->SetLabelCheck(kFALSE);
    sel->Add(cuts, kTRUE);
    if (isRsnDev>=0 && opt.Contains("pairPID")) {
      AliRsnActPostDaughterSelection *pairPID = new AliRsnActPostDaughterSelection();
      pairPID->SetID(0);

      const char *fn="rsnRange.txt";
      if (!gSystem->AccessPathName(fn)) {
	TString minStr = gSystem->GetFromPipe(TString::Format("head -n 1 %s").Data());
	TString maxStr = gSystem->GetFromPipe(TString::Format("tail -n 1 %s").Data());
	pairPID->SetMass(minStr.Atof(),maxStr.Atof());
      } else {
	//       pairPID->SetMass(1.01,1.03);
	pairPID->SetMass(1.015,1.025);
	pairPID->SetMass(1.019,1.021);
	pairPID->SetMass(1.0195,1.0205);
	pairPID->SetMass(1.1000,1.1005);
	//       pairPID->SetMass(1.1005,1.1010);
      }
      sel->AddAction(pairPID);
    }

  }
  return numberOfCuts;

}
<|endoftext|>


<commit_before>//
// Created by Administrator on 2017/1/3.
//

#include "AudioRefreshController.h"

#define LOG_NDEBUG 0
#define TAG "YTX-AudioRefreshController-JNI"
#include "ALog-priv.h"
#include "ffmsg.h"
#include <map>
#include <unistd.h>

//static std::map<SLAndroidSimpleBufferQueueItf,AudioRefreshController*>   audioEnMap;
static AudioRefreshController* mAudioRefreshController;
AudioRefreshController::AudioRefreshController(VideoStateInfo* mVideoStateInfo)
{
    ALOGI("AudioRefreshController()\n");
    this->mVideoStateInfo = mVideoStateInfo;
    mAudioEngine = new AudioEngine();
    mAudioRefreshController = this;
}

AudioRefreshController::~AudioRefreshController(){
    ALOGI("~AudioRefreshController\n");
    delete mAudioEngine;

}

void AudioRefreshController::handleRun(void* ptr){
    if(!prepare())
    {
        ALOGI("Couldn't prepare AudioRefreshController\n");
        return;
    }
    //sleep(1);
    refresh();
}

bool AudioRefreshController::prepare() {
    mAudioEngine->createEngine();
    mAudioEngine->createBufferQueueAudioPlayer(mVideoStateInfo->streamAudio->dec_ctx->sample_rate,960,mVideoStateInfo->out_channel_nb);
    ALOGI("AudioRefreshController::prepare pthread_self:%lu,bqPlayerBufferQueue=%#x\n", (long)pthread_self(), mAudioEngine->bqPlayerBufferQueue);
   // audioEnMap.insert(std::pair<SLAndroidSimpleBufferQueueItf,AudioRefreshController*>(mAudioEngine->bqPlayerBufferQueue, this));
    mAudioEngine->RegisterCallback(bqPlayerCallback);
    return true;
}

bool AudioRefreshController::process(AVMessage *msg) {

    ALOGI("AudioRefreshController::process in");
    bool ret = true;
    if(msg->what == FFP_MSG_CANCEL){
        ret = false;
    }

    switch (msg->what){
        case FFP_MSG_AUDIO_FIRST_FRAME:
            (*mAudioEngine->bqPlayerBufferQueue)->Clear(mAudioEngine->bqPlayerBufferQueue);
            audioFrameProcess();
            break;
        case FFP_MSG_COMPLETED:
            (*mAudioEngine->bqPlayerBufferQueue)->Clear(mAudioEngine->bqPlayerBufferQueue);
            mVideoStateInfo->frameQueueAudio->frameQueueReset();
            break;
    }
    ALOGI("AudioRefreshController::process out");
    return ret;

}

void AudioRefreshController::refresh() {
    AVMessage msg;
    while(mRunning){
        if(mVideoStateInfo->messageQueueAudio->get(&msg,true) < 0){
            mRunning = false;
        }else{
            if(!process(&msg))
            {
                mRunning = false;
            }
        }
    }
}

void AudioRefreshController::stop() {

    int ret = -1;
    (*mAudioEngine->bqPlayerBufferQueue)->Clear(mAudioEngine->bqPlayerBufferQueue);
    mVideoStateInfo->messageQueueAudio->abort();
    mRunning = false;
    if((ret = wait()) != 0) {
        ALOGI("Couldn't cancel IDecoder: %i\n", ret);
        return;
    }
}

void AudioRefreshController::bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void *context)
{
//    AudioRefreshController* sAudioRefreshController = NULL;
//
//  //  ALOGI("AudioRefreshController::bqPlayerCallback pthread_self:%lu,bqPlayerBufferQueue=%#x\n", (long)pthread_self(), bq);
//  //  ALOGI("AudioRefreshController::bqPlayerCallback pthread_self:%lu,getpid:%lu,gettid:%lu\n", (long)pthread_self(), (long)getpid(),(long)gettid());
//    std::map<SLAndroidSimpleBufferQueueItf,AudioRefreshController*>::iterator l_it;
//    l_it = audioEnMap.find(bq);
//    if(l_it == audioEnMap.end()){
//      //  ALOGI("AudioRefreshController::bqPlayerCallback we do not find");
//
//    } else {
//      //  ALOGI("AudioRefreshController::bqPlayerCallback we find");
//        sAudioRefreshController = l_it->second;
//    }

    assert(bq == mAudioRefreshController->mAudioEngine->bqPlayerBufferQueue);
    assert(NULL == context);

    mAudioRefreshController->audioFrameProcess();
    if(*mAudioRefreshController->mVideoStateInfo->mCurrentState == MEDIA_PLAYER_PAUSED){
        mAudioRefreshController->mVideoStateInfo->waitOnNotify(MEDIA_PLAYER_PAUSED);

    }

}

int AudioRefreshController::audioFrameProcess() {
    int ret = 0;
    Frame *af;
    double audio_clock;
    SLuint32 size_buff = 0;
    mAudioEngine->mLock.lock();
    int64_t audio_callback_time = av_gettime_relative();
    af = audioDecodeFrame();
    ALOGI("AudioRefreshController::process yuhaotest out_buffer_audio=%#x",af->out_buffer_audio);
//    /* update the audio clock with the pts */
//    if (!isnan(af->pts))
//        audio_clock = af->pts + (double) af->frame->nb_samples / af->frame->sample_rate;
//    else
//        audio_clock = NAN;

//    swr_convert(mVideoStateInfo->swrCtx, &(mVideoStateInfo->out_buffer_audio), MAX_AUDIO_FRAME_SIZE,
//                (const uint8_t **) af->frame->data, af->frame->nb_samples);
//    //获取sample的size
//    int out_buffer_size = av_samples_get_buffer_size(NULL, mVideoStateInfo->out_channel_nb,
//                                                     af->frame->nb_samples, mVideoStateInfo->out_sample_fmt,
//                                                     1);
    size_buff = (SLuint32) af->out_buffer_audio_size;
    fwrite(af->out_buffer_audio,1,size_buff,mVideoStateInfo->fp_pcm1);
    (*mAudioEngine->bqPlayerBufferQueue)->Enqueue(mAudioEngine->bqPlayerBufferQueue,
                                                  af->out_buffer_audio,
                                                  size_buff);
    mAudioEngine->mLock.unlock();

    if (!isnan(audio_clock)) {

        mVideoStateInfo->setClockAt(mVideoStateInfo->audClk, af->pts, af->serial,audio_callback_time/1000000.0);
        mVideoStateInfo->syncClock2Slave(mVideoStateInfo->extClk, mVideoStateInfo->audClk);
    }

    return ret;
}

Frame *AudioRefreshController::audioDecodeFrame() {

    Frame *af;
    do {

        do {
            af = mVideoStateInfo->frameQueueAudio->frameQueuePeekReadable();
            mVideoStateInfo->frameQueueAudio->frameQueueNext();
        } while (af == NULL);

    } while (af->serial != mVideoStateInfo->pkt_serial_audio);

    return af;

}

void AudioRefreshController::enqueue(AVMessage *msg) {
    mVideoStateInfo->messageQueueAudio->put(msg);
}<commit_msg>取消静态音频刷新类<commit_after>//
// Created by Administrator on 2017/1/3.
//

#include "AudioRefreshController.h"

#define LOG_NDEBUG 0
#define TAG "YTX-AudioRefreshController-JNI"
#include "ALog-priv.h"
#include "ffmsg.h"
#include <map>
#include <unistd.h>

static std::map<SLAndroidSimpleBufferQueueItf,AudioRefreshController*>   audioEnMap;
//static AudioRefreshController* mAudioRefreshController;
AudioRefreshController::AudioRefreshController(VideoStateInfo* mVideoStateInfo)
{
    ALOGI("AudioRefreshController()\n");
    this->mVideoStateInfo = mVideoStateInfo;
    mAudioEngine = new AudioEngine();
  //  mAudioRefreshController = this;
}

AudioRefreshController::~AudioRefreshController(){
    ALOGI("~AudioRefreshController\n");
    delete mAudioEngine;

}

void AudioRefreshController::handleRun(void* ptr){
    if(!prepare())
    {
        ALOGI("Couldn't prepare AudioRefreshController\n");
        return;
    }
    //sleep(1);
    refresh();
}

bool AudioRefreshController::prepare() {
    mAudioEngine->createEngine();
    mAudioEngine->createBufferQueueAudioPlayer(mVideoStateInfo->streamAudio->dec_ctx->sample_rate,960,mVideoStateInfo->out_channel_nb);
    ALOGI("AudioRefreshController::prepare pthread_self:%lu,bqPlayerBufferQueue=%#x\n", (long)pthread_self(), mAudioEngine->bqPlayerBufferQueue);
    audioEnMap.insert(std::pair<SLAndroidSimpleBufferQueueItf,AudioRefreshController*>(mAudioEngine->bqPlayerBufferQueue, this));
    mAudioEngine->RegisterCallback(bqPlayerCallback);
    return true;
}

bool AudioRefreshController::process(AVMessage *msg) {

    ALOGI("AudioRefreshController::process in");
    bool ret = true;
    if(msg->what == FFP_MSG_CANCEL){
        ret = false;
    }

    switch (msg->what){
        case FFP_MSG_AUDIO_FIRST_FRAME:
            (*mAudioEngine->bqPlayerBufferQueue)->Clear(mAudioEngine->bqPlayerBufferQueue);
            audioFrameProcess();
            break;
        case FFP_MSG_COMPLETED:
            (*mAudioEngine->bqPlayerBufferQueue)->Clear(mAudioEngine->bqPlayerBufferQueue);
            mVideoStateInfo->frameQueueAudio->frameQueueReset();
            break;
    }
    ALOGI("AudioRefreshController::process out");
    return ret;

}

void AudioRefreshController::refresh() {
    AVMessage msg;
    while(mRunning){
        if(mVideoStateInfo->messageQueueAudio->get(&msg,true) < 0){
            mRunning = false;
        }else{
            if(!process(&msg))
            {
                mRunning = false;
            }
        }
    }
}

void AudioRefreshController::stop() {

    int ret = -1;
    (*mAudioEngine->bqPlayerBufferQueue)->Clear(mAudioEngine->bqPlayerBufferQueue);
    mVideoStateInfo->messageQueueAudio->abort();
    mRunning = false;
    if((ret = wait()) != 0) {
        ALOGI("Couldn't cancel IDecoder: %i\n", ret);
        return;
    }
}

void AudioRefreshController::bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void *context)
{
    AudioRefreshController* sAudioRefreshController = NULL;

  //  ALOGI("AudioRefreshController::bqPlayerCallback pthread_self:%lu,bqPlayerBufferQueue=%#x\n", (long)pthread_self(), bq);
  //  ALOGI("AudioRefreshController::bqPlayerCallback pthread_self:%lu,getpid:%lu,gettid:%lu\n", (long)pthread_self(), (long)getpid(),(long)gettid());
    std::map<SLAndroidSimpleBufferQueueItf,AudioRefreshController*>::iterator l_it;
    l_it = audioEnMap.find(bq);
    if(l_it == audioEnMap.end()){
        ALOGI("AudioRefreshController::bqPlayerCallback we do not find");

    } else {
      //  ALOGI("AudioRefreshController::bqPlayerCallback we find");
        sAudioRefreshController = l_it->second;
    }

    assert(bq == sAudioRefreshController->mAudioEngine->bqPlayerBufferQueue);
    assert(NULL == context);

    sAudioRefreshController->audioFrameProcess();
    if(*sAudioRefreshController->mVideoStateInfo->mCurrentState == MEDIA_PLAYER_PAUSED){
        sAudioRefreshController->mVideoStateInfo->waitOnNotify(MEDIA_PLAYER_PAUSED);

    }

}

int AudioRefreshController::audioFrameProcess() {
    int ret = 0;
    Frame *af;
    double audio_clock;
    SLuint32 size_buff = 0;
    mAudioEngine->mLock.lock();
    int64_t audio_callback_time = av_gettime_relative();
    af = audioDecodeFrame();
    ALOGI("AudioRefreshController::process yuhaotest out_buffer_audio=%#x",af->out_buffer_audio);
//    /* update the audio clock with the pts */
//    if (!isnan(af->pts))
//        audio_clock = af->pts + (double) af->frame->nb_samples / af->frame->sample_rate;
//    else
//        audio_clock = NAN;

//    swr_convert(mVideoStateInfo->swrCtx, &(mVideoStateInfo->out_buffer_audio), MAX_AUDIO_FRAME_SIZE,
//                (const uint8_t **) af->frame->data, af->frame->nb_samples);
//    //获取sample的size
//    int out_buffer_size = av_samples_get_buffer_size(NULL, mVideoStateInfo->out_channel_nb,
//                                                     af->frame->nb_samples, mVideoStateInfo->out_sample_fmt,
//                                                     1);
    size_buff = (SLuint32) af->out_buffer_audio_size;
    fwrite(af->out_buffer_audio,1,size_buff,mVideoStateInfo->fp_pcm1);
    (*mAudioEngine->bqPlayerBufferQueue)->Enqueue(mAudioEngine->bqPlayerBufferQueue,
                                                  af->out_buffer_audio,
                                                  size_buff);
    mAudioEngine->mLock.unlock();

    if (!isnan(audio_clock)) {

        mVideoStateInfo->setClockAt(mVideoStateInfo->audClk, af->pts, af->serial,audio_callback_time/1000000.0);
        mVideoStateInfo->syncClock2Slave(mVideoStateInfo->extClk, mVideoStateInfo->audClk);
    }

    return ret;
}

Frame *AudioRefreshController::audioDecodeFrame() {

    Frame *af;
    do {

        do {
            af = mVideoStateInfo->frameQueueAudio->frameQueuePeekReadable();
            mVideoStateInfo->frameQueueAudio->frameQueueNext();
        } while (af == NULL);

    } while (af->serial != mVideoStateInfo->pkt_serial_audio);

    return af;

}

void AudioRefreshController::enqueue(AVMessage *msg) {
    mVideoStateInfo->messageQueueAudio->put(msg);
}<|endoftext|>


<commit_before>#include <string>
#include <cmath>
#include <memory>

#include <itkSpatialObjectReader.h>
#include <itkSpatialObjectWriter.h>

#include <vtkPolyData.h>
#include <vtkPointData.h>
#include <vtkPolyDataReader.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkPolyDataWriter.h>
#include <vtkXMLPolyDataWriter.h>
#include <vtkSmartPointer.h>
#include <vtkCell.h>
#include <vtkFloatArray.h>

#include "fiberio.h"

// hide function to this compilation unit
namespace
{
inline double SQ2(double x)
{
  return x * x;
}

};

void writeFiberFile(const std::string & filename, GroupType::Pointer fibergroup, bool saveProperties)
{
  // Make sure origins are updated
  fibergroup->ComputeObjectToWorldTransform();

  // ITK Spatial Object
  if( filename.rfind(".fib") != std::string::npos )
    {
    typedef itk::SpatialObjectWriter<3> WriterType;
    WriterType::Pointer writer  = WriterType::New();
    writer->SetInput(fibergroup);
    writer->SetFileName(filename);
    writer->Update();
    }
  // VTK Poly Data
  else if( filename.rfind(".vt") != std::string::npos )
    {
    // Build VTK data structure
    vtkSmartPointer<vtkPolyData>   polydata(vtkPolyData::New() );
    vtkSmartPointer<vtkFloatArray> tensorsdata(vtkFloatArray::New() );
    vtkSmartPointer<vtkIdList>     ids(vtkIdList::New() );
    vtkSmartPointer<vtkPoints>     pts(vtkPoints::New() );

    tensorsdata->SetNumberOfComponents(9);
    polydata->SetPoints(pts);

    ids->SetNumberOfIds(0);
    pts->SetNumberOfPoints(0);
    polydata->Allocate();
    vtkFloatArray *scalarFA = vtkFloatArray::New();
    vtkFloatArray *scalarMD = vtkFloatArray::New();
    vtkFloatArray *scalarRD = vtkFloatArray::New();
    vtkFloatArray *scalarAD = vtkFloatArray::New();
    scalarFA->SetNumberOfComponents(1);
    scalarFA->SetName("FA");
    scalarMD->SetNumberOfComponents(1);
    scalarMD->SetName("MD");
    scalarAD->SetNumberOfComponents(1);
    scalarAD->SetName("AD");
    scalarRD->SetNumberOfComponents(1);
    scalarRD->SetName("RD");

    std::auto_ptr<ChildrenListType> children(fibergroup->GetChildren(0) );
    typedef ChildrenListType::const_iterator IteratorType;
    for( IteratorType it = children->begin(); it != children->end(); it++ )
      {
      itk::SpatialObject<3>*        tmp = (*it).GetPointer();
      itk::DTITubeSpatialObject<3>* tube = dynamic_cast<itk::DTITubeSpatialObject<3> *>(tmp);
      unsigned int                  nPointsOnFiber = tube->GetNumberOfPoints();
      vtkIdType                     currentId = ids->GetNumberOfIds();
      for( unsigned int k = 0; k < nPointsOnFiber; k++ )
        {
        itk::Point<double, 3>  v(tube->GetPoint(k)->GetPosition() );
        itk::Vector<double, 3> spacing(tube->GetSpacing() );
        itk::Vector<double, 3> origin(tube->GetObjectToWorldTransform()->GetOffset() );

        // convert origin from LPS -> RAS
        origin[0] = -origin[0];
        origin[1] = -origin[1];

        vtkIdType id;
        // Need to multiply v by spacing and origin
        // Also negate the first to convert from LPS -> RAS
        // for slicer 3
        id = pts->InsertNextPoint(-v[0] * spacing[0] + origin[0],
                                  -v[1] * spacing[1] + origin[1],
                                  v[2] * spacing[2] + origin[2]);

        ids->InsertNextId(id);

        itk::DTITubeSpatialObjectPoint<3>* sopt = dynamic_cast<itk::DTITubeSpatialObjectPoint<3> *>(tube->GetPoint(k) );
        float                              vtktensor[9];
        vtktensor[0] = sopt->GetTensorMatrix()[0];
        vtktensor[1] = sopt->GetTensorMatrix()[1];
        vtktensor[2] = sopt->GetTensorMatrix()[2];
        vtktensor[3] = sopt->GetTensorMatrix()[1];
        vtktensor[4] = sopt->GetTensorMatrix()[3];
        vtktensor[5] = sopt->GetTensorMatrix()[4];
        vtktensor[6] = sopt->GetTensorMatrix()[2];
        vtktensor[7] = sopt->GetTensorMatrix()[4];
        vtktensor[8] = sopt->GetTensorMatrix()[5];

	//std::cout << "MD = " << sopt->GetField("md") << ", " ;

        scalarFA->InsertNextValue(sopt->GetField("fa"));
        scalarMD->InsertNextValue(sopt->GetField("md"));
        scalarAD->InsertNextValue(sopt->GetField("ad"));
        scalarRD->InsertNextValue(sopt->GetField("rd"));

        tensorsdata->InsertNextTupleValue(vtktensor);

        }
      polydata->InsertNextCell(VTK_POLY_LINE, nPointsOnFiber, ids->GetPointer(currentId) );
      }

    polydata->GetPointData()->SetTensors(tensorsdata);
    if (saveProperties)
      {
	polydata->GetPointData()->AddArray(scalarFA);
	polydata->GetPointData()->AddArray(scalarMD);
	polydata->GetPointData()->AddArray(scalarAD);
	polydata->GetPointData()->AddArray(scalarRD);
      }

    // Legacy
    if( filename.rfind(".vtk") != std::string::npos )
      {
      vtkSmartPointer<vtkPolyDataWriter> fiberwriter = vtkPolyDataWriter::New();
      fiberwriter->SetFileTypeToBinary();
      fiberwriter->SetFileName(filename.c_str() );
#if (VTK_MAJOR_VERSION < 6)
      fiberwriter->SetInput(polydata);
#else
      fiberwriter->SetInputData(polydata);
#endif
      fiberwriter->Update();
      }
    // XML
    else if( filename.rfind(".vtp") != std::string::npos )
      {
      vtkSmartPointer<vtkXMLPolyDataWriter> fiberwriter = vtkXMLPolyDataWriter::New();
      fiberwriter->SetFileName(filename.c_str() );
#if (VTK_MAJOR_VERSION < 6)
      fiberwriter->SetInput(polydata);
#else
      fiberwriter->SetInputData(polydata);
#endif
      fiberwriter->Update();
      }
    else
      {
      throw itk::ExceptionObject("Unknown file format for fibers");
      }
    }
  else
    {
    throw itk::ExceptionObject("Unknown file format for fibers");
    }
}

GroupType::Pointer readFiberFile(const std::string & filename)
{

  // ITK Spatial Object
  if( filename.rfind(".fib") != std::string::npos )
    {
    typedef itk::SpatialObjectReader<3, unsigned char> SpatialObjectReaderType;

    // Reading spatial object
    SpatialObjectReaderType::Pointer soreader = SpatialObjectReaderType::New();

    soreader->SetFileName(filename);
    soreader->Update();

    return soreader->GetGroup();
    }
  // VTK Poly Data
  else if( filename.rfind(".vt") != std::string::npos )
    {
    // Build up the principal data structure for fiber tracts
    GroupType::Pointer fibergroup = GroupType::New();

    vtkSmartPointer<vtkPolyData> fibdata(NULL);

    // Legacy
    if( filename.rfind(".vtk") != std::string::npos )
      {
      vtkSmartPointer<vtkPolyDataReader> reader(vtkPolyDataReader::New() );
      reader->SetFileName(filename.c_str() );
      reader->Update();
      fibdata = reader->GetOutput();

      }
    else if( filename.rfind(".vtp") != std::string::npos )
      {
      vtkSmartPointer<vtkXMLPolyDataReader> reader(vtkXMLPolyDataReader::New() );
      reader->SetFileName(filename.c_str() );
      reader->Update();
      fibdata = reader->GetOutput();
      }
    else
      {
      throw itk::ExceptionObject("Unknown file format for fibers");
      }

    typedef  itk::SymmetricSecondRankTensor<double, 3> ITKTensorType;
    typedef  ITKTensorType::EigenValuesArrayType       LambdaArrayType;

    // Iterate over VTK data
    const int nfib = fibdata->GetNumberOfCells();
    int       pindex = -1;
    for( int i = 0; i < nfib; ++i )
      {
      itk::DTITubeSpatialObject<3>::Pointer dtiTube = itk::DTITubeSpatialObject<3>::New();
      vtkSmartPointer<vtkCell>              fib = fibdata->GetCell(i);

      vtkSmartPointer<vtkPoints> points = fib->GetPoints();

      typedef itk::DTITubeSpatialObjectPoint<3> DTIPointType;
      std::vector<DTIPointType> pointsToAdd;

      vtkSmartPointer<vtkDataArray> fibtensordata = fibdata->GetPointData()->GetTensors();
      for( int j = 0; j < points->GetNumberOfPoints(); ++j )
        {
        ++pindex;

        vtkFloatingPointType* coordinates = points->GetPoint(j);
        DTIPointType          pt;
        // Convert from RAS to LPS for vtk
        pt.SetPosition(-coordinates[0], -coordinates[1], coordinates[2]);
        pt.SetRadius(0.5);
        pt.SetColor(0.0, 1.0, 0.0);

        vtkFloatingPointType* vtktensor = fibtensordata->GetTuple9(pindex);
        float                 floattensor[6];
        ITKTensorType         itktensor;

        floattensor[0] = itktensor[0] = vtktensor[0];
        floattensor[1] = itktensor[1] = vtktensor[1];
        floattensor[2] = itktensor[2] = vtktensor[2];
        floattensor[3] = itktensor[3] = vtktensor[4];
        floattensor[4] = itktensor[4] = vtktensor[5];
        floattensor[5] = itktensor[5] = vtktensor[8];

        pt.SetTensorMatrix(floattensor);

        LambdaArrayType lambdas;

        // Need to do do eigenanalysis of the tensor
        itktensor.ComputeEigenValues(lambdas);

        // FIXME: We should not be repeating this code here.  The code
        // for all these computations should be re-factored into a
        // common library.

        float md = (lambdas[0] + lambdas[1] + lambdas[2]) / 3;
        float fa = sqrt(1.5) * sqrt( (lambdas[0] - md) * (lambdas[0] - md)
                                     + (lambdas[1] - md) * (lambdas[1] - md)
                                     + (lambdas[2] - md) * (lambdas[2] - md) )
          / sqrt(lambdas[0] * lambdas[0] + lambdas[1] * lambdas[1] + lambdas[2] * lambdas[2]);

        float logavg = (log(lambdas[0]) + log(lambdas[1]) + log(lambdas[2]) ) / 3;

        float ga =  sqrt( SQ2(log(lambdas[0]) - logavg) \
                          + SQ2(log(lambdas[1]) - logavg) \
                          + SQ2(log(lambdas[2]) - logavg) );

	float rd = (lambdas[1] + lambdas[0])/2;

        pt.AddField("fa", fa);
        pt.AddField("ga", ga);
        pt.AddField("md", md);
        pt.AddField("l1", lambdas[2]);
        pt.AddField("l2", lambdas[1]);
        pt.AddField("l3", lambdas[0]);
        pt.AddField("rd", rd);

        pointsToAdd.push_back(pt);
        }

      dtiTube->SetPoints(pointsToAdd);
      fibergroup->AddSpatialObject(dtiTube);
      }
    return fibergroup;
    } // end process .vtk .vtp
  else
    {
    throw itk::ExceptionObject("Unknown fiber file");
    }
}
<commit_msg>COMP: vtk6 changes<commit_after>#include <string>
#include <cmath>
#include <memory>

#include <itkSpatialObjectReader.h>
#include <itkSpatialObjectWriter.h>
#include <vtkVersionMacros.h>
#include <vtkPolyData.h>
#include <vtkPointData.h>
#include <vtkPolyDataReader.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkPolyDataWriter.h>
#include <vtkXMLPolyDataWriter.h>
#include <vtkSmartPointer.h>
#include <vtkCell.h>
#include <vtkFloatArray.h>

#include "fiberio.h"

// hide function to this compilation unit
namespace
{
inline double SQ2(double x)
{
  return x * x;
}

};

void writeFiberFile(const std::string & filename, GroupType::Pointer fibergroup, bool saveProperties)
{
  // Make sure origins are updated
  fibergroup->ComputeObjectToWorldTransform();

  // ITK Spatial Object
  if( filename.rfind(".fib") != std::string::npos )
    {
    typedef itk::SpatialObjectWriter<3> WriterType;
    WriterType::Pointer writer  = WriterType::New();
    writer->SetInput(fibergroup);
    writer->SetFileName(filename);
    writer->Update();
    }
  // VTK Poly Data
  else if( filename.rfind(".vt") != std::string::npos )
    {
    // Build VTK data structure
    vtkSmartPointer<vtkPolyData>   polydata(vtkPolyData::New() );
    vtkSmartPointer<vtkFloatArray> tensorsdata(vtkFloatArray::New() );
    vtkSmartPointer<vtkIdList>     ids(vtkIdList::New() );
    vtkSmartPointer<vtkPoints>     pts(vtkPoints::New() );

    tensorsdata->SetNumberOfComponents(9);
    polydata->SetPoints(pts);

    ids->SetNumberOfIds(0);
    pts->SetNumberOfPoints(0);
    polydata->Allocate();
    vtkFloatArray *scalarFA = vtkFloatArray::New();
    vtkFloatArray *scalarMD = vtkFloatArray::New();
    vtkFloatArray *scalarRD = vtkFloatArray::New();
    vtkFloatArray *scalarAD = vtkFloatArray::New();
    scalarFA->SetNumberOfComponents(1);
    scalarFA->SetName("FA");
    scalarMD->SetNumberOfComponents(1);
    scalarMD->SetName("MD");
    scalarAD->SetNumberOfComponents(1);
    scalarAD->SetName("AD");
    scalarRD->SetNumberOfComponents(1);
    scalarRD->SetName("RD");

    std::auto_ptr<ChildrenListType> children(fibergroup->GetChildren(0) );
    typedef ChildrenListType::const_iterator IteratorType;
    for( IteratorType it = children->begin(); it != children->end(); it++ )
      {
      itk::SpatialObject<3>*        tmp = (*it).GetPointer();
      itk::DTITubeSpatialObject<3>* tube = dynamic_cast<itk::DTITubeSpatialObject<3> *>(tmp);
      unsigned int                  nPointsOnFiber = tube->GetNumberOfPoints();
      vtkIdType                     currentId = ids->GetNumberOfIds();
      for( unsigned int k = 0; k < nPointsOnFiber; k++ )
        {
        itk::Point<double, 3>  v(tube->GetPoint(k)->GetPosition() );
        itk::Vector<double, 3> spacing(tube->GetSpacing() );
        itk::Vector<double, 3> origin(tube->GetObjectToWorldTransform()->GetOffset() );

        // convert origin from LPS -> RAS
        origin[0] = -origin[0];
        origin[1] = -origin[1];

        vtkIdType id;
        // Need to multiply v by spacing and origin
        // Also negate the first to convert from LPS -> RAS
        // for slicer 3
        id = pts->InsertNextPoint(-v[0] * spacing[0] + origin[0],
                                  -v[1] * spacing[1] + origin[1],
                                  v[2] * spacing[2] + origin[2]);

        ids->InsertNextId(id);

        itk::DTITubeSpatialObjectPoint<3>* sopt = dynamic_cast<itk::DTITubeSpatialObjectPoint<3> *>(tube->GetPoint(k) );
        float                              vtktensor[9];
        vtktensor[0] = sopt->GetTensorMatrix()[0];
        vtktensor[1] = sopt->GetTensorMatrix()[1];
        vtktensor[2] = sopt->GetTensorMatrix()[2];
        vtktensor[3] = sopt->GetTensorMatrix()[1];
        vtktensor[4] = sopt->GetTensorMatrix()[3];
        vtktensor[5] = sopt->GetTensorMatrix()[4];
        vtktensor[6] = sopt->GetTensorMatrix()[2];
        vtktensor[7] = sopt->GetTensorMatrix()[4];
        vtktensor[8] = sopt->GetTensorMatrix()[5];

	//std::cout << "MD = " << sopt->GetField("md") << ", " ;

        scalarFA->InsertNextValue(sopt->GetField("fa"));
        scalarMD->InsertNextValue(sopt->GetField("md"));
        scalarAD->InsertNextValue(sopt->GetField("ad"));
        scalarRD->InsertNextValue(sopt->GetField("rd"));

        tensorsdata->InsertNextTupleValue(vtktensor);

        }
      polydata->InsertNextCell(VTK_POLY_LINE, nPointsOnFiber, ids->GetPointer(currentId) );
      }

    polydata->GetPointData()->SetTensors(tensorsdata);
    if (saveProperties)
      {
	polydata->GetPointData()->AddArray(scalarFA);
	polydata->GetPointData()->AddArray(scalarMD);
	polydata->GetPointData()->AddArray(scalarAD);
	polydata->GetPointData()->AddArray(scalarRD);
      }

    // Legacy
    if( filename.rfind(".vtk") != std::string::npos )
      {
      vtkSmartPointer<vtkPolyDataWriter> fiberwriter = vtkPolyDataWriter::New();
      fiberwriter->SetFileTypeToBinary();
      fiberwriter->SetFileName(filename.c_str() );
#if (VTK_MAJOR_VERSION < 6)
      fiberwriter->SetInput(polydata);
#else
      fiberwriter->SetInputData(polydata);
#endif
      fiberwriter->Update();
      }
    // XML
    else if( filename.rfind(".vtp") != std::string::npos )
      {
      vtkSmartPointer<vtkXMLPolyDataWriter> fiberwriter = vtkXMLPolyDataWriter::New();
      fiberwriter->SetFileName(filename.c_str() );
#if (VTK_MAJOR_VERSION < 6)
      fiberwriter->SetInput(polydata);
#else
      fiberwriter->SetInputData(polydata);
#endif
      fiberwriter->Update();
      }
    else
      {
      throw itk::ExceptionObject("Unknown file format for fibers");
      }
    }
  else
    {
    throw itk::ExceptionObject("Unknown file format for fibers");
    }
}

GroupType::Pointer readFiberFile(const std::string & filename)
{

  // ITK Spatial Object
  if( filename.rfind(".fib") != std::string::npos )
    {
    typedef itk::SpatialObjectReader<3, unsigned char> SpatialObjectReaderType;

    // Reading spatial object
    SpatialObjectReaderType::Pointer soreader = SpatialObjectReaderType::New();

    soreader->SetFileName(filename);
    soreader->Update();

    return soreader->GetGroup();
    }
  // VTK Poly Data
  else if( filename.rfind(".vt") != std::string::npos )
    {
    // Build up the principal data structure for fiber tracts
    GroupType::Pointer fibergroup = GroupType::New();

    vtkSmartPointer<vtkPolyData> fibdata(NULL);

    // Legacy
    if( filename.rfind(".vtk") != std::string::npos )
      {
      vtkSmartPointer<vtkPolyDataReader> reader(vtkPolyDataReader::New() );
      reader->SetFileName(filename.c_str() );
      reader->Update();
      fibdata = reader->GetOutput();

      }
    else if( filename.rfind(".vtp") != std::string::npos )
      {
      vtkSmartPointer<vtkXMLPolyDataReader> reader(vtkXMLPolyDataReader::New() );
      reader->SetFileName(filename.c_str() );
      reader->Update();
      fibdata = reader->GetOutput();
      }
    else
      {
      throw itk::ExceptionObject("Unknown file format for fibers");
      }

    typedef  itk::SymmetricSecondRankTensor<double, 3> ITKTensorType;
    typedef  ITKTensorType::EigenValuesArrayType       LambdaArrayType;

    // Iterate over VTK data
    const int nfib = fibdata->GetNumberOfCells();
    int       pindex = -1;
    for( int i = 0; i < nfib; ++i )
      {
      itk::DTITubeSpatialObject<3>::Pointer dtiTube = itk::DTITubeSpatialObject<3>::New();
      vtkSmartPointer<vtkCell>              fib = fibdata->GetCell(i);

      vtkSmartPointer<vtkPoints> points = fib->GetPoints();

      typedef itk::DTITubeSpatialObjectPoint<3> DTIPointType;
      std::vector<DTIPointType> pointsToAdd;

      vtkSmartPointer<vtkDataArray> fibtensordata = fibdata->GetPointData()->GetTensors();
      for( int j = 0; j < points->GetNumberOfPoints(); ++j )
        {
        ++pindex;

        double * coordinates = points->GetPoint(j);
        DTIPointType          pt;
        // Convert from RAS to LPS for vtk
        pt.SetPosition(-coordinates[0], -coordinates[1], coordinates[2]);
        pt.SetRadius(0.5);
        pt.SetColor(0.0, 1.0, 0.0);

        double * vtktensor = fibtensordata->GetTuple9(pindex);
        float                 floattensor[6];
        ITKTensorType         itktensor;

        floattensor[0] = itktensor[0] = vtktensor[0];
        floattensor[1] = itktensor[1] = vtktensor[1];
        floattensor[2] = itktensor[2] = vtktensor[2];
        floattensor[3] = itktensor[3] = vtktensor[4];
        floattensor[4] = itktensor[4] = vtktensor[5];
        floattensor[5] = itktensor[5] = vtktensor[8];

        pt.SetTensorMatrix(floattensor);

        LambdaArrayType lambdas;

        // Need to do do eigenanalysis of the tensor
        itktensor.ComputeEigenValues(lambdas);

        // FIXME: We should not be repeating this code here.  The code
        // for all these computations should be re-factored into a
        // common library.

        float md = (lambdas[0] + lambdas[1] + lambdas[2]) / 3;
        float fa = sqrt(1.5) * sqrt( (lambdas[0] - md) * (lambdas[0] - md)
                                     + (lambdas[1] - md) * (lambdas[1] - md)
                                     + (lambdas[2] - md) * (lambdas[2] - md) )
          / sqrt(lambdas[0] * lambdas[0] + lambdas[1] * lambdas[1] + lambdas[2] * lambdas[2]);

        float logavg = (log(lambdas[0]) + log(lambdas[1]) + log(lambdas[2]) ) / 3;

        float ga =  sqrt( SQ2(log(lambdas[0]) - logavg) \
                          + SQ2(log(lambdas[1]) - logavg) \
                          + SQ2(log(lambdas[2]) - logavg) );

	float rd = (lambdas[1] + lambdas[0])/2;

        pt.AddField("fa", fa);
        pt.AddField("ga", ga);
        pt.AddField("md", md);
        pt.AddField("l1", lambdas[2]);
        pt.AddField("l2", lambdas[1]);
        pt.AddField("l3", lambdas[0]);
        pt.AddField("rd", rd);

        pointsToAdd.push_back(pt);
        }

      dtiTube->SetPoints(pointsToAdd);
      fibergroup->AddSpatialObject(dtiTube);
      }
    return fibergroup;
    } // end process .vtk .vtp
  else
    {
    throw itk::ExceptionObject("Unknown fiber file");
    }
}
<|endoftext|>


<commit_before>#include "Card.hpp"
#include <iostream>

using std::ostream;
using std::string;

Card::Card ( ) : suit (CLUB), rank (TWO), value (0) {
	createCardName ( );
}

Card::Card (int n) : suit (CLUB), rank (TWO), value (n) {
	if (value < 0 || value > 51) {
		value = 0;
	}
	createCardName ( );
}

Card::Card (Suits s, Ranks r) : suit (s), rank (r), value (13 * s + r + 1) {
	createCardName();
}

Card::Card (Suits s, Ranks r, int v) : suit (s), rank (r), value (v) {
	createCardName ( );
}

Card::Suits Card::getSuit ( ) const {
	return suit;
}

Card::Ranks Card::getRank ( ) const {
	return rank;
}

int Card::getValue ( ) const {
	return value;
}

// Returns a negative value when the calling object's SUIT is smaller
// 0 when both SUITS are equal. Positive number when it's SUIT is larger.
int Card::compareBySuit (const Card& other) const {
	return  static_cast<int>(suit) - static_cast<int>(other.suit);
}

// Returns a negative value when the calling object's RANK is smaller.
// 0 when both RANKS are equal. Positive number when it's RANK is larger.
int Card::compareByRank (const Card& other) const {
	return static_cast<int>(rank) - static_cast<int>(other.rank);
}

int Card::compareByValue (const Card& other) const {
	return value - other.value;
}

void Card::createCardName ( ) {
	switch (rank) {
		case TWO:
			cardName += "Two";
			break;
		case THREE:
			cardName += "Three";
			break;
		case FOUR:
			cardName += "Four";
			break;
		case FIVE:
			cardName += "Five";
			break;
		case SIX:
			cardName += "Six";
			break;
		case SEVEN:
			cardName += "Seven";
			break;
		case EIGHT:
			cardName += "Eight";
			break;
		case NINE:
			cardName += "Nine";
			break;
		case TEN:
			cardName += "Ten";
			break;
		case JACK:
			cardName += "Jack";
			break;
		case QUEEN:
			cardName += "Queen";
			break;
		case KING:
			cardName += "King";
			break;
		case ACE:
			cardName += "Ace";
			break;
		default:
			cardName += "Joker";
			break;
	}
	cardName += " of ";
	switch (suit) {
		case CLUB:
			cardName += "Clubs";
			break;
		case DIAMOND:
			cardName += "Diamonds";
			break;
		case HEART:
			cardName += "Hearts";
			break;
		case SPADE:
			cardName += "Spades";
			break;
		default:
			cardName = "Jokers";
			break;
	}
}

ostream& operator<<(ostream& output, const Card& currentCard) {
	return output << currentCard.cardName;
}<commit_msg>Modifies the way cards are displayed by using ASCII symbols<commit_after>#include "Card.hpp"
#include <iostream>

using std::ostream;
using std::string;

Card::Card ( ) : suit (CLUB), rank (TWO), value (0) {
	createCardName ( );
}

Card::Card (int n) : suit (CLUB), rank (TWO), value (n) {
	if (value < 0 || value > 51) {
		value = 0;
	}
	createCardName ( );
}

Card::Card (Suits s, Ranks r) : suit (s), rank (r), value (13 * s + r + 1) {
	createCardName();
}

Card::Card (Suits s, Ranks r, int v) : suit (s), rank (r), value (v) {
	createCardName ( );
}

Card::Suits Card::getSuit ( ) const {
	return suit;
}

Card::Ranks Card::getRank ( ) const {
	return rank;
}

int Card::getValue ( ) const {
	return value;
}

// Returns a negative value when the calling object's SUIT is smaller
// 0 when both SUITS are equal. Positive number when it's SUIT is larger.
int Card::compareBySuit (const Card& other) const {
	return  static_cast<int>(suit) - static_cast<int>(other.suit);
}

// Returns a negative value when the calling object's RANK is smaller.
// 0 when both RANKS are equal. Positive number when it's RANK is larger.
int Card::compareByRank (const Card& other) const {
	return static_cast<int>(rank) - static_cast<int>(other.rank);
}

int Card::compareByValue (const Card& other) const {
	return value - other.value;
}

void Card::createCardName ( ) {
	switch (rank) {
		case TWO:
			cardName += "2";
			break;
		case THREE:
			cardName += "3";
			break;
		case FOUR:
			cardName += "4";
			break;
		case FIVE:
			cardName += "5";
			break;
		case SIX:
			cardName += "6";
			break;
		case SEVEN:
			cardName += "7";
			break;
		case EIGHT:
			cardName += "8";
			break;
		case NINE:
			cardName += "9";
			break;
		case TEN:
			cardName += "10";
			break;
		case JACK:
			cardName += "Jack";
			break;
		case QUEEN:
			cardName += "Queen";
			break;
		case KING:
			cardName += "King";
			break;
		case ACE:
			cardName += "Ace";
			break;
		default:
			cardName += "Joker";
			break;
	}
	cardName += " ";
	switch (suit) {
		case CLUB:
			cardName += '\6';
			break;
		case DIAMOND:
			cardName += '\4';
			break;
		case HEART:
			cardName += '\3';
			break;
		case SPADE:
			cardName += '\5';
			break;
		default:
			cardName = "?";
			break;
	}
}

ostream& operator<<(ostream& output, const Card& currentCard) {
	return output << currentCard.cardName;
}<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkBinaryImageToShapeLabelMapFilterTest1.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

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

#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkSimpleFilterWatcher.h"

#include "itkLabelObject.h"
#include "itkLabelMap.h"
#include "itkBinaryImageToShapeLabelMapFilter.h"
#include "itkLabelMapToLabelImageFilter.h"

#include "itkTestingMacros.h"

int itkBinaryImageToShapeLabelMapFilterTest1(int argc, char * argv[])
{

  if( argc != 6 )
    {
    std::cerr << "Usage: " << argv[0];
    std::cerr << " inputBinaryImage outputShapeLabelMap";
    std::cerr << " fullyConnected(0/1) foregroundValue backgroundValue";
    std::cerr << std::endl;
    return EXIT_FAILURE;
    }

  const unsigned int dim = 2;

  typedef itk::Image< unsigned char, dim > ImageType;

  typedef itk::ShapeLabelObject< unsigned char, dim > LabelObjectType;
  typedef itk::LabelMap< LabelObjectType >            LabelMapType;

  typedef itk::ImageFileReader< ImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );

  typedef itk::BinaryImageToShapeLabelMapFilter< ImageType, LabelMapType> I2LType;
  I2LType::Pointer i2l = I2LType::New();
  i2l->SetInput( reader->GetOutput() );
  i2l->SetFullyConnected( true );

  i2l->SetFullyConnected( atoi(argv[3]) );
  i2l->SetInputForegroundValue( atoi(argv[4]) );
  i2l->SetOutputBackgroundValue( atoi(argv[5]) );

  typedef itk::LabelMapToLabelImageFilter< LabelMapType, ImageType> L2IType;
  L2IType::Pointer l2i = L2IType::New();
  l2i->SetInput( i2l->GetOutput() );

  typedef itk::ImageFileWriter< ImageType > WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetInput( l2i->GetOutput() );
  writer->SetFileName( argv[2] );
  writer->UseCompressionOn();

  TRY_EXPECT_NO_EXCEPTION( writer->Update() );

  return EXIT_SUCCESS;
}
<commit_msg>ENH: Added additional code coverage for Set/Get and Boolean macros. itkTypeMacro test coverage is incomplete.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkBinaryImageToShapeLabelMapFilterTest1.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

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

#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkSimpleFilterWatcher.h"

#include "itkLabelObject.h"
#include "itkLabelMap.h"
#include "itkBinaryImageToShapeLabelMapFilter.h"
#include "itkLabelMapToLabelImageFilter.h"

#include "itkTestingMacros.h"

int itkBinaryImageToShapeLabelMapFilterTest1(int argc, char * argv[])
{

  if( argc != 6 )
    {
    std::cerr << "Usage: " << argv[0];
    std::cerr << " inputBinaryImage outputShapeLabelMap";
    std::cerr << " fullyConnected(0/1) foregroundValue backgroundValue";
    std::cerr << std::endl;
    return EXIT_FAILURE;
    }

  const unsigned int dim = 2;

  typedef itk::Image< unsigned char, dim > ImageType;

  typedef itk::ShapeLabelObject< unsigned char, dim > LabelObjectType;
  typedef itk::LabelMap< LabelObjectType >            LabelMapType;

  //reading image to file
  typedef itk::ImageFileReader< ImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );

  //converting binary image to shape label map
  typedef itk::BinaryImageToShapeLabelMapFilter< ImageType, LabelMapType> I2LType;
  I2LType::Pointer i2l = I2LType::New();
  i2l->SetInput( reader->GetOutput() );

  //testing get/set FullyConnected macro
  bool fullyConnected =  atoi(argv[3]);
  i2l->SetFullyConnected( fullyConnected );
  TEST_SET_GET_VALUE( fullyConnected, i2l->GetFullyConnected() );

  //testing boolean FullyConnected macro
  i2l->FullyConnectedOff();
  TEST_SET_GET_VALUE( false, i2l->GetFullyConnected() );

  i2l->FullyConnectedOn();
  TEST_SET_GET_VALUE( true, i2l->GetFullyConnected() );

  //testing get/set InputForegroundValue macro
  int inputForegroundValue = ( atoi(argv[4]) );
  i2l->SetInputForegroundValue( inputForegroundValue );
  TEST_SET_GET_VALUE( inputForegroundValue, i2l->GetInputForegroundValue() );

  //testing get/set OutputBackgroundValue macro
  int outputBackgroundValue = ( atoi(argv[5]) );
  i2l->SetOutputBackgroundValue( outputBackgroundValue );
  TEST_SET_GET_VALUE( outputBackgroundValue, i2l->GetOutputBackgroundValue() );

  //testing get/set ComputeFeretDiameter macro
  bool computeFeretDiameter =  atoi(argv[6]);
  i2l->SetComputeFeretDiameter( computeFeretDiameter );
  TEST_SET_GET_VALUE( computeFeretDiameter, i2l->GetComputeFeretDiameter() );

  //testing boolean ComputeFeretDiameter macro
  i2l->ComputeFeretDiameterOff();
  TEST_SET_GET_VALUE( false, i2l->GetComputeFeretDiameter() );

  i2l->ComputeFeretDiameterOn();
  TEST_SET_GET_VALUE( true, i2l->GetComputeFeretDiameter() );

  //testing get/set ComputePerimeter macro
  bool computePerimeter =  atoi(argv[6]);
  i2l->SetComputePerimeter( computePerimeter );
  TEST_SET_GET_VALUE( computePerimeter, i2l->GetComputePerimeter() );

  //testing boolean ComputePerimeter macro
  i2l->ComputePerimeterOff();
  TEST_SET_GET_VALUE( false, i2l->GetComputePerimeter() );

  i2l->ComputePerimeterOn();
  TEST_SET_GET_VALUE( true, i2l->GetComputePerimeter() );

  typedef itk::LabelMapToLabelImageFilter< LabelMapType, ImageType> L2IType;
  L2IType::Pointer l2i = L2IType::New();
  l2i->SetInput( i2l->GetOutput() );

  typedef itk::ImageFileWriter< ImageType > WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetInput( l2i->GetOutput() );
  writer->SetFileName( argv[2] );
  writer->UseCompressionOn();

  TRY_EXPECT_NO_EXCEPTION( writer->Update() );

  return EXIT_SUCCESS;
}
<|endoftext|>