<commit_before>#ifdef _WIN32
#include <windows.h>
#pragma comment(lib,"user32.lib")
#endif
#ifdef unix
#include <iostream>
#include <stdlib.h> /* putenv */
#include <string.h> /* strdup */
#include <unistd.h> /* execvp */
#include <errno.h> /* errno */
#endif
#include <sstream>
#include <RefeusProcess.h>

/** constructor
 */
RefeusProcess::RefeusProcess() {
  parametersvector.push_back("startup.ini");
  #ifdef _WIN32
  executable = "refeus.exe";
  #endif
  #ifdef unix
  executable = "refeus.sh";
  #endif
}
/**
 * get the next argument from a vector that is split by blanks
 * @return string
 * @param arguments_separated_by_blank (unmodifyable vector, passed by reference for performance)
 * @param start_iterater reference to move iterator for the argParser
 * --last "noblank"
 * --last "with blank"
 * --last "with many blanks"
 */
std::string RefeusProcess::argParserNext(const std::vector<std::string> &arguments_separated_by_blank, std::vector<std::string>::iterator &start_iterator){
  std::string next_arg = "";
  next_arg = (*start_iterator);
  for ( it = start_iterator
      ; it != arguments_separated_by_blank.end()
      ; it++
      ){
    if ( (*it).at(0) == "\""
      && !(*it).at((*it).size()-1) == "\""
      ){
      next_arg = (*it).substr(1,(*it).size()-2);
      in_quotes = true;
    }
    if ( (*it).at(0) == "\""
      && (*it).at((*it).size()-1) == "\""
      ){
      next_arg = (*it).substr(1,(*it).size()-3);
      break;
    }
    if ( in_quotes && (*it).at((*it).size()-1) == "\"" ){
      next_arg+= (*it).substr(0,(*it).size()-2);
      break;
    }
    if ( in_quotes ){
      next_arg+= " " + next_arg;
      continue;
    }
    break;
  }
  start_iterator = it;
  return next_arg;
}
/** Argument Parser parses takes as parameter the command line then parses
  *  all the arguments that are separated from each other with a single blank
  *  --help outputs all possible arguments
  *  --new opens a 'save file as' dialog window
  *  --open "C:/works with/spaces too.txt" but path name must be inside " "
  *  --refeus sets to refeus.ini
  *  --plus sets to plus.ini
  *  --cloud-enabled sets CLOUD_ENABLED to true
  */
bool RefeusProcess::argParser(std::string command_line) {
  std::vector<std::string> per_blank_vector,per_quotes_vector;
  //splitting command line per single blanks
  split(command_line, " ", per_blank_vector);
  std::vector<std::string>::iterator it;
  for ( it = per_blank_vector.begin()
      ; it < per_blank_vector.end()
      ; ++it
      ) {
           std::string hello = *it;
           printf("the per blank vector is %s \n",hello.c_str());
    if ( *it == "--help"
       ||*it == "/?"
       ) {
      usage();
      return false;
    }
    if ( *it == "--new" ) {
      configureNewRefeusDocument();
    } else if ( *it == "--open" ) {
      //splitting command line per double quotes
      // THIS is invalid: split takes character as parameter, you give string
      split(command_line, "\"\"", per_quotes_vector);
      //per_quotes_vector.erase(per_quotes_vector.begin());
      if ( per_quotes_vector.size() > 1 ) {
        //TODO: use refeus_database_autostart
        configureOpenRefeusDocument(per_quotes_vector.at(1));
      } else {
        configureNewRefeusDocument();
      }
    } else if ( *it == "--plus" ) {
      parametersvector.clear();
      parametersvector.push_back("plus.ini");
    } else if ( *it == "--refeus" ) {
      parametersvector.clear();
      parametersvector.push_back("refeus.ini");
    } else if ( *it == "--cloud-enabled" ) {
      configureCloudSetting();
    } else if ( *it == "--debug" ) {
      configureDebug();
    } else if ( *it == "--language" ) {
      configureLanguageFromIsoString(argParserNext(per_blank_vector, it));
    } else if ( *it == "--auto-backup" ) {
      //TODO: set AUTO_BACKUP=YES
    } else if ( *it == "--no-auto-backup" ) {
      //TODO: set AUTO_BACKUP=NO
    } else if ( *it == "--skip-maintenance" ) {
      //TODO: set SKIP_MAINTENANCE=YES
    } else if ( *it == "--startup-activity" ) {
      //TODO: set STARTUP_ACTIVITY=next parameter (eg manage::overview)
    }
    /**
     * REFEUS_SETTINGS_LOCATION=[when set: ini-file for portable]
     * REFEUS_DOCUMENTS_LOCATION=path/to/documents
     * REFEUS_PICTURES_LOCATION=path/to/pictures
     */
  }
  return true;
}
void RefeusProcess::configureCloudSetting() {
   environmentmap["CLOUD_ENABLED"] = "true";
}
void RefeusProcess::configureDebug() {
  #ifdef _WIN32
  executable = "code.exe"; /** start a commandline window to output debug messages*/
  #endif
  environmentmap["WKE_DEBUG"] = "YES";
  environmentmap["WKE_DEBUG_CONSOLE"] = "YES";
}
void RefeusProcess::configureNewRefeusDocument() {
   environmentmap["open_refeus_database"] = "true";
}

void RefeusProcess::configureLanguageFromIsoString(std::string iso_language) {
  if ( iso_language == "en" ){
    langcheck(0); //default
  } else if (iso_language == "de") {
    langcheck(1031);
  } else if (iso_language == "fr") {
    langcheck(1036);
  } else if (iso_language == "pl") {
    langcheck(1045);
  }
}
void RefeusProcess::configureOpenRefeusDocument(std::string path_name) {
   environmentmap["refeus_database"] = path_name;
}
/**
  * Function langCheck takes as parameter the Language ID of the system
  * Checks if it is German->French->Polish->English
  * Then sets the appropriate Envir-Variables to the language that got
  * matched first
  * \param api_language_code - windows-api language code
  */
void RefeusProcess::langCheck(int api_language_code) {
  switch ( api_language_code ) {
    case 1031:  //German
      environmentmap["DSC_Language"] = "German";
      environmentmap["Language"] = "German";
      break;
    case 1036:  //French
      environmentmap["DSC_Language"] = "French";
      environmentmap["Language"] = "French";
      break;
    case 1045:  //Polish
      environmentmap["DSC_Language"] = "Polish";
      environmentmap["Language"] = "Polish";
      break;
    default:  //English
      environmentmap["DSC_Language"] = "English";
      environmentmap["Language"] = "English";
      break;
  }
}
void RefeusProcess::setEnvironment(std::string env_name, std::string env_value) {
  environmentmap[env_name] = env_value;
}
/** \brief Split String into Vector using a delimter
  * \param string_to_split - some string to be split by a specific character
  * \param delimiter_character - character for splitting
  * \param element_vector - reference vector for storing the split result
  */
std::vector<std::string> &RefeusProcess::split(const std::string &string_to_split, char* delimiter_character, std::vector<std::string> &element_vector) {
  std::stringstream sstream(string_to_split);
  std::string item;
  while (std::getline(sstream, item, *delimiter_character)) {
    element_vector.push_back(item);
  }
  return element_vector;
}
/** Function start takes no arguments
  *  sets all environment variables that are saved in environmenenmap
  *  prepares the full_executable path with the pre-configured ini file
  *  then creates the process with the appropriate env. variables and ini file
  */
int RefeusProcess:: start() {
  std::string executable_with_parameter = executable;
  std::vector<std::string>::iterator parameter_iterator;
  std::map<std::string, std::string>::iterator map_iterator;

  #ifdef _WIN32
  STARTUPINFO StartupInfo;                        //This is an [in] parameter
  PROCESS_INFORMATION ProcessInfo; //This is what we get as an [out] parameter
  #endif
  for ( map_iterator = environmentmap.begin(); map_iterator != environmentmap.end(); ++map_iterator) {
    std::string env = map_iterator->first + "=" + map_iterator->second;
    char * env_cstr = new char[env.size() + 1];
    std::copy(env.begin(), env.end(), env_cstr);
    env_cstr[env.size()] = '\0';
    putenv(env_cstr);
  }

  #ifdef _WIN32
  /**
   * win32 implementation only
   */
  for ( parameter_iterator = parametersvector.begin()
      ; parameter_iterator < parametersvector.end()
      ; ++parameter_iterator
      ) {
    executable_with_parameter = executable_with_parameter + " " + *parameter_iterator;
  }
  ZeroMemory(&StartupInfo, sizeof(StartupInfo));
  ZeroMemory(&ProcessInfo, sizeof(ProcessInfo));
  StartupInfo.cb = sizeof(StartupInfo) ;            //Only compulsory field
  //Formatting exe to const char* and full_exe to char* for CreateProcess

  char* executable_with_parameter_cstr = new char [executable_with_parameter.size() + 1];
  const char* executable_cstr = strdup(executable.c_str());
  std::copy(executable_with_parameter.begin(), executable_with_parameter.end(), executable_with_parameter_cstr);
  executable_with_parameter_cstr[executable_with_parameter.size()] = '\0';
  bool process_started = CreateProcess( executable_cstr
                                   , executable_with_parameter_cstr              //exe + ini names
                                   , 0
                                   , 0
                                   , FALSE
                                   , CREATE_DEFAULT_ERROR_MODE
                                   , 0
                                   , 0
                                   , &StartupInfo
                                   , &ProcessInfo);
    if ( process_started ){
    WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
    CloseHandle(ProcessInfo.hThread);
    CloseHandle(ProcessInfo.hProcess);
  } else {
     MessageBox(NULL, "The process could not be started... \n" , "Process Failed!", MB_OK);
     return 1;
  }
  #endif
  #ifdef unix
  /**
   * unix implementation only
   */
  char **exec_argv = static_cast<char**>(malloc(sizeof(char*) * (parametersvector.size() + 1) ));
  int parameter_iterator_index = 0;
  for ( parameter_iterator = parametersvector.begin()
      ; parameter_iterator < parametersvector.end()
      ; ++parameter_iterator
      ) {
    exec_argv[parameter_iterator_index] = strdup((*parameter_iterator).c_str());
    parameter_iterator_index++;
  }
  exec_argv[parameter_iterator_index] = NULL;
  if ( execvp(executable.c_str(),exec_argv) == -1 ){
    std::cerr << strerror(errno);
  }
  #endif
  return 0;
}
void RefeusProcess::usage() {
  const char* help_string = "--help displays all possible arguments\n"
       "--new opens a 'save as' dialog window\n"
       "--open \"C:/file_name\" starts refeus with specific file\n"
       "--plus sets the ini file to plus.ini\n"
       "--refeus sets the ini file to refeus.ini\n"
       "--debug sets the application to debug-mode (allows shift+ctrl+i)\n"
       "--cloud-enabled sets CLOUD_ENABLED to true\n"
       "TODO: add more parameters"
       ;
  #ifdef _WIN32
  MessageBox(NULL, help_string, "Help!", MB_OK);
  #endif
  #ifdef unix
  std::cout << help_string << std::endl;
  #endif
}
<commit_msg>make sure refeus autostarts when a filename is provided, use open-dialog otherwise<commit_after>#ifdef _WIN32
#include <windows.h>
#pragma comment(lib,"user32.lib")
#endif
#ifdef unix
#include <iostream>
#include <stdlib.h> /* putenv */
#include <string.h> /* strdup */
#include <unistd.h> /* execvp */
#include <errno.h> /* errno */
#endif
#include <sstream>
#include <RefeusProcess.h>

/** constructor
 */
RefeusProcess::RefeusProcess() {
  parametersvector.push_back("startup.ini");
  #ifdef _WIN32
  executable = "refeus.exe";
  #endif
  #ifdef unix
  executable = "refeus.sh";
  #endif
}
/**
 * get the next argument from a vector that is split by blanks
 * @return string
 * @param arguments_separated_by_blank (unmodifyable vector, passed by reference for performance)
 * @param start_iterater reference to move iterator for the argParser
 * --last "noblank"
 * --last "with blank"
 * --last "with many blanks"
 */
std::string RefeusProcess::argParserNext(const std::vector<std::string> &arguments_separated_by_blank, std::vector<std::string>::iterator &start_iterator){
  std::string next_arg = "";
  next_arg = (*start_iterator);
  for ( it = start_iterator
      ; it != arguments_separated_by_blank.end()
      ; it++
      ){
    if ( (*it).at(0) == "\""
      && !(*it).at((*it).size()-1) == "\""
      ){
      next_arg = (*it).substr(1,(*it).size()-2);
      in_quotes = true;
    }
    if ( (*it).at(0) == "\""
      && (*it).at((*it).size()-1) == "\""
      ){
      next_arg = (*it).substr(1,(*it).size()-3);
      break;
    }
    if ( in_quotes && (*it).at((*it).size()-1) == "\"" ){
      next_arg+= (*it).substr(0,(*it).size()-2);
      break;
    }
    if ( in_quotes ){
      next_arg+= " " + next_arg;
      continue;
    }
    break;
  }
  start_iterator = it;
  return next_arg;
}
/** Argument Parser parses takes as parameter the command line then parses
  *  all the arguments that are separated from each other with a single blank
  *  --help outputs all possible arguments
  *  --new opens a 'save file as' dialog window
  *  --open "C:/works with/spaces too.txt" but path name must be inside " "
  *  --refeus sets to refeus.ini
  *  --plus sets to plus.ini
  *  --cloud-enabled sets CLOUD_ENABLED to true
  */
bool RefeusProcess::argParser(std::string command_line) {
  std::vector<std::string> per_blank_vector,per_quotes_vector;
  //splitting command line per single blanks
  split(command_line, " ", per_blank_vector);
  std::vector<std::string>::iterator it;
  for ( it = per_blank_vector.begin()
      ; it < per_blank_vector.end()
      ; ++it
      ) {
           std::string hello = *it;
           printf("the per blank vector is %s \n",hello.c_str());
    if ( *it == "--help"
       ||*it == "/?"
       ) {
      usage();
      return false;
    }
    if ( *it == "--new" ) {
      configureNewRefeusDocument();
    } else if ( *it == "--open" ) {
      //splitting command line per double quotes
      // THIS is invalid: split takes character as parameter, you give string
      split(command_line, "\"\"", per_quotes_vector);
      //per_quotes_vector.erase(per_quotes_vector.begin());
      if ( per_quotes_vector.size() > 1 ) {
        //TODO: use refeus_database_autostart
        configureOpenRefeusDocument(per_quotes_vector.at(1));
      } else {
        configureNewRefeusDocument();
      }
    } else if ( *it == "--plus" ) {
      parametersvector.clear();
      parametersvector.push_back("plus.ini");
    } else if ( *it == "--refeus" ) {
      parametersvector.clear();
      parametersvector.push_back("refeus.ini");
    } else if ( *it == "--cloud-enabled" ) {
      configureCloudSetting();
    } else if ( *it == "--debug" ) {
      configureDebug();
    } else if ( *it == "--language" ) {
      configureLanguageFromIsoString(argParserNext(per_blank_vector, it));
    } else if ( *it == "--auto-backup" ) {
      //TODO: set AUTO_BACKUP=YES
    } else if ( *it == "--no-auto-backup" ) {
      //TODO: set AUTO_BACKUP=NO
    } else if ( *it == "--skip-maintenance" ) {
      //TODO: set SKIP_MAINTENANCE=YES
    } else if ( *it == "--startup-activity" ) {
      //TODO: set STARTUP_ACTIVITY=next parameter (eg manage::overview)
    }
    /**
     * REFEUS_SETTINGS_LOCATION=[when set: ini-file for portable]
     * REFEUS_DOCUMENTS_LOCATION=path/to/documents
     * REFEUS_PICTURES_LOCATION=path/to/pictures
     */
  }
  return true;
}
void RefeusProcess::configureCloudSetting() {
   environmentmap["CLOUD_ENABLED"] = "true";
}
void RefeusProcess::configureDebug() {
  #ifdef _WIN32
  executable = "code.exe"; /** start a commandline window to output debug messages*/
  #endif
  environmentmap["WKE_DEBUG"] = "YES";
  environmentmap["WKE_DEBUG_CONSOLE"] = "YES";
}
void RefeusProcess::configureNewRefeusDocument() {
   environmentmap["open_refeus_database"] = "true";
}

void RefeusProcess::configureLanguageFromIsoString(std::string iso_language) {
  if ( iso_language == "en" ){
    langcheck(0); //default
  } else if (iso_language == "de") {
    langcheck(1031);
  } else if (iso_language == "fr") {
    langcheck(1036);
  } else if (iso_language == "pl") {
    langcheck(1045);
  }
}
void RefeusProcess::configureOpenRefeusDocument(std::string path_name) {
   environmentmap["refeus_database"] = path_name;
   environmentmap["refeus_database_autostart"] = "true";
}
/**
  * Function langCheck takes as parameter the Language ID of the system
  * Checks if it is German->French->Polish->English
  * Then sets the appropriate Envir-Variables to the language that got
  * matched first
  * \param api_language_code - windows-api language code
  */
void RefeusProcess::langCheck(int api_language_code) {
  switch ( api_language_code ) {
    case 1031:  //German
      environmentmap["DSC_Language"] = "German";
      environmentmap["Language"] = "German";
      break;
    case 1036:  //French
      environmentmap["DSC_Language"] = "French";
      environmentmap["Language"] = "French";
      break;
    case 1045:  //Polish
      environmentmap["DSC_Language"] = "Polish";
      environmentmap["Language"] = "Polish";
      break;
    default:  //English
      environmentmap["DSC_Language"] = "English";
      environmentmap["Language"] = "English";
      break;
  }
}
void RefeusProcess::setEnvironment(std::string env_name, std::string env_value) {
  environmentmap[env_name] = env_value;
}
/** \brief Split String into Vector using a delimter
  * \param string_to_split - some string to be split by a specific character
  * \param delimiter_character - character for splitting
  * \param element_vector - reference vector for storing the split result
  */
std::vector<std::string> &RefeusProcess::split(const std::string &string_to_split, char* delimiter_character, std::vector<std::string> &element_vector) {
  std::stringstream sstream(string_to_split);
  std::string item;
  while (std::getline(sstream, item, *delimiter_character)) {
    element_vector.push_back(item);
  }
  return element_vector;
}
/** Function start takes no arguments
  *  sets all environment variables that are saved in environmenenmap
  *  prepares the full_executable path with the pre-configured ini file
  *  then creates the process with the appropriate env. variables and ini file
  */
int RefeusProcess:: start() {
  std::string executable_with_parameter = executable;
  std::vector<std::string>::iterator parameter_iterator;
  std::map<std::string, std::string>::iterator map_iterator;

  #ifdef _WIN32
  STARTUPINFO StartupInfo;                        //This is an [in] parameter
  PROCESS_INFORMATION ProcessInfo; //This is what we get as an [out] parameter
  #endif
  for ( map_iterator = environmentmap.begin(); map_iterator != environmentmap.end(); ++map_iterator) {
    std::string env = map_iterator->first + "=" + map_iterator->second;
    char * env_cstr = new char[env.size() + 1];
    std::copy(env.begin(), env.end(), env_cstr);
    env_cstr[env.size()] = '\0';
    putenv(env_cstr);
  }

  #ifdef _WIN32
  /**
   * win32 implementation only
   */
  for ( parameter_iterator = parametersvector.begin()
      ; parameter_iterator < parametersvector.end()
      ; ++parameter_iterator
      ) {
    executable_with_parameter = executable_with_parameter + " " + *parameter_iterator;
  }
  ZeroMemory(&StartupInfo, sizeof(StartupInfo));
  ZeroMemory(&ProcessInfo, sizeof(ProcessInfo));
  StartupInfo.cb = sizeof(StartupInfo) ;            //Only compulsory field
  //Formatting exe to const char* and full_exe to char* for CreateProcess

  char* executable_with_parameter_cstr = new char [executable_with_parameter.size() + 1];
  const char* executable_cstr = strdup(executable.c_str());
  std::copy(executable_with_parameter.begin(), executable_with_parameter.end(), executable_with_parameter_cstr);
  executable_with_parameter_cstr[executable_with_parameter.size()] = '\0';
  bool process_started = CreateProcess( executable_cstr
                                   , executable_with_parameter_cstr              //exe + ini names
                                   , 0
                                   , 0
                                   , FALSE
                                   , CREATE_DEFAULT_ERROR_MODE
                                   , 0
                                   , 0
                                   , &StartupInfo
                                   , &ProcessInfo);
    if ( process_started ){
    WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
    CloseHandle(ProcessInfo.hThread);
    CloseHandle(ProcessInfo.hProcess);
  } else {
     MessageBox(NULL, "The process could not be started... \n" , "Process Failed!", MB_OK);
     return 1;
  }
  #endif
  #ifdef unix
  /**
   * unix implementation only
   */
  char **exec_argv = static_cast<char**>(malloc(sizeof(char*) * (parametersvector.size() + 1) ));
  int parameter_iterator_index = 0;
  for ( parameter_iterator = parametersvector.begin()
      ; parameter_iterator < parametersvector.end()
      ; ++parameter_iterator
      ) {
    exec_argv[parameter_iterator_index] = strdup((*parameter_iterator).c_str());
    parameter_iterator_index++;
  }
  exec_argv[parameter_iterator_index] = NULL;
  if ( execvp(executable.c_str(),exec_argv) == -1 ){
    std::cerr << strerror(errno);
  }
  #endif
  return 0;
}
void RefeusProcess::usage() {
  const char* help_string = "--help displays all possible arguments\n"
       "--new opens a 'save as' dialog window\n"
       "--open \"C:/file_name\" starts refeus with specific file\n"
       "--plus sets the ini file to plus.ini\n"
       "--refeus sets the ini file to refeus.ini\n"
       "--debug sets the application to debug-mode (allows shift+ctrl+i)\n"
       "--cloud-enabled sets CLOUD_ENABLED to true\n"
       "TODO: add more parameters"
       ;
  #ifdef _WIN32
  MessageBox(NULL, help_string, "Help!", MB_OK);
  #endif
  #ifdef unix
  std::cout << help_string << std::endl;
  #endif
}
<|endoftext|>


<commit_before>#include "../src/RobotLocation.hpp"

#include <WPILib.h>
#include <iostream>

RobotLocation::RobotLocation() : gyro(2, 3)
{
	std::cout << "Hello World" << std::endl;
}

void RobotLocation::update()
{
	std::cout << "Hello World" << std::endl;
}
<commit_msg>Update location<commit_after>#include <WPILib.h>
#include "RobotLocation.hpp"
#include <iostream>
#include <cmath>

bool tolerance(float val1, float val2, float tolVal)
{
	if(fabs(val1 - val2) < tolVal)
	{
		return true;
	}
}

RobotLocation::RobotLocation()
	: gyro(1)
	, left(0,1)
	, right(0, 1)
{
	std::cout << "Hello World" << std::endl;
}

void RobotLocation::update()
{
	direction == gyro.GetAngle()*180/M_PI;
	if(tolerance(left.GetDistance(), right.GetDistance(), 5e-5) == true)
	{
		float x = left.GetDistance()/cos(direction);
		float y = right.GetDistance()/sin(direction);
		pos.first += x;
		pos.second += y;

	}

}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "src/trace_processor/importers/systrace/systrace_parser.h"

#include "perfetto/ext/base/optional.h"
#include "src/trace_processor/event_tracker.h"
#include "src/trace_processor/process_tracker.h"
#include "src/trace_processor/slice_tracker.h"
#include "src/trace_processor/track_tracker.h"

namespace perfetto {
namespace trace_processor {

SystraceParser::SystraceParser(TraceProcessorContext* ctx)
    : context_(ctx), lmk_id_(ctx->storage->InternString("mem.lmk")) {}

SystraceParser::~SystraceParser() = default;

void SystraceParser::ParsePrintEvent(int64_t ts,
                                     uint32_t pid,
                                     base::StringView event) {
  systrace_utils::SystraceTracePoint point{};
  switch (ParseSystraceTracePoint(event, &point)) {
    case systrace_utils::SystraceParseResult::kSuccess:
      ParseSystracePoint(ts, pid, point);
      break;
    case systrace_utils::SystraceParseResult::kFailure:
      context_->storage->IncrementStats(stats::systrace_parse_failure);
      break;
    case systrace_utils::SystraceParseResult::kUnsupported:
      // Silently ignore unsupported results.
      break;
  }
}

void SystraceParser::ParseZeroEvent(int64_t ts,
                                    uint32_t pid,
                                    int32_t flag,
                                    base::StringView name,
                                    uint32_t tgid,
                                    int64_t value) {
  systrace_utils::SystraceTracePoint point{};
  point.name = name;
  point.tgid = tgid;
  point.value = value;

  // The value of these constants can be found in the msm-google kernel.
  constexpr int32_t kSystraceEventBegin = 1 << 0;
  constexpr int32_t kSystraceEventEnd = 1 << 1;
  constexpr int32_t kSystraceEventInt64 = 1 << 2;

  if ((flag & kSystraceEventBegin) != 0) {
    point.phase = 'B';
  } else if ((flag & kSystraceEventEnd) != 0) {
    point.phase = 'E';
  } else if ((flag & kSystraceEventInt64) != 0) {
    point.phase = 'C';
  } else {
    context_->storage->IncrementStats(stats::systrace_parse_failure);
    return;
  }
  ParseSystracePoint(ts, pid, point);
}

void SystraceParser::ParseSdeTracingMarkWrite(int64_t ts,
                                              uint32_t pid,
                                              char trace_type,
                                              bool trace_begin,
                                              base::StringView trace_name,
                                              uint32_t tgid,
                                              int64_t value) {
  systrace_utils::SystraceTracePoint point{};
  point.name = trace_name;
  point.tgid = tgid;
  point.value = value;

  if (trace_type == 0) {
    point.phase = trace_begin ? 'B' : 'E';
  } else if (trace_type == 'B' && trace_type == 'E' && trace_type == 'C') {
    point.phase = trace_type;
  } else {
    context_->storage->IncrementStats(stats::systrace_parse_failure);
    return;
  }

  ParseSystracePoint(ts, pid, point);
}

void SystraceParser::ParseSystracePoint(
    int64_t ts,
    uint32_t pid,
    systrace_utils::SystraceTracePoint point) {
  switch (point.phase) {
    case 'B': {
      StringId name_id = context_->storage->InternString(point.name);
      UniqueTid utid = context_->process_tracker->UpdateThread(pid, point.tgid);
      TrackId track_id = context_->track_tracker->InternThreadTrack(utid);
      context_->slice_tracker->Begin(ts, track_id, kNullStringId /* cat */,
                                     name_id);
      break;
    }

    case 'E': {
      // |point.tgid| can be 0 in older android versions where the end event
      // would not contain the value.
      UniqueTid utid;
      if (point.tgid == 0) {
        // If we haven't seen this thread before, there can't have been a Begin
        // event for it so just ignore the event.
        auto opt_utid = context_->process_tracker->GetThreadOrNull(pid);
        if (!opt_utid)
          break;
        utid = *opt_utid;
      } else {
        utid = context_->process_tracker->UpdateThread(pid, point.tgid);
      }
      TrackId track_id = context_->track_tracker->InternThreadTrack(utid);
      context_->slice_tracker->End(ts, track_id);
      break;
    }

    case 'S':
    case 'F': {
      StringId name_id = context_->storage->InternString(point.name);
      int64_t cookie = static_cast<int64_t>(point.value);
      UniquePid upid =
          context_->process_tracker->GetOrCreateProcess(point.tgid);

      TrackId track_id = context_->track_tracker->InternAndroidAsyncTrack(
          name_id, upid, cookie);
      if (point.phase == 'S') {
        context_->slice_tracker->Begin(ts, track_id, kNullStringId, name_id);
      } else {
        context_->slice_tracker->End(ts, track_id);
      }
      break;
    }

    case 'C': {
      // LMK events from userspace are hacked as counter events with the "value"
      // of the counter representing the pid of the killed process which is
      // reset to 0 once the kill is complete.
      // Homogenise this with kernel LMK events as an instant event, ignoring
      // the resets to 0.
      if (point.name == "kill_one_process") {
        auto killed_pid = static_cast<uint32_t>(point.value);
        if (killed_pid != 0) {
          UniquePid killed_upid =
              context_->process_tracker->GetOrCreateProcess(killed_pid);
          context_->event_tracker->PushInstant(ts, lmk_id_, killed_upid,
                                               RefType::kRefUpid);
        }
        // TODO(lalitm): we should not add LMK events to the counters table
        // once the UI has support for displaying instants.
      }
      // This is per upid on purpose. Some counters are pushed from arbitrary
      // threads but are really per process.
      UniquePid upid =
          context_->process_tracker->GetOrCreateProcess(point.tgid);
      StringId name_id = context_->storage->InternString(point.name);
      TrackId track =
          context_->track_tracker->InternProcessCounterTrack(name_id, upid);
      context_->event_tracker->PushCounter(ts, point.value, track);
    }
  }
}

}  // namespace trace_processor
}  // namespace perfetto
<commit_msg>trace_processor: Fix SDE parsing bug<commit_after>/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "src/trace_processor/importers/systrace/systrace_parser.h"

#include "perfetto/ext/base/optional.h"
#include "src/trace_processor/event_tracker.h"
#include "src/trace_processor/process_tracker.h"
#include "src/trace_processor/slice_tracker.h"
#include "src/trace_processor/track_tracker.h"

namespace perfetto {
namespace trace_processor {

SystraceParser::SystraceParser(TraceProcessorContext* ctx)
    : context_(ctx), lmk_id_(ctx->storage->InternString("mem.lmk")) {}

SystraceParser::~SystraceParser() = default;

void SystraceParser::ParsePrintEvent(int64_t ts,
                                     uint32_t pid,
                                     base::StringView event) {
  systrace_utils::SystraceTracePoint point{};
  switch (ParseSystraceTracePoint(event, &point)) {
    case systrace_utils::SystraceParseResult::kSuccess:
      ParseSystracePoint(ts, pid, point);
      break;
    case systrace_utils::SystraceParseResult::kFailure:
      context_->storage->IncrementStats(stats::systrace_parse_failure);
      break;
    case systrace_utils::SystraceParseResult::kUnsupported:
      // Silently ignore unsupported results.
      break;
  }
}

void SystraceParser::ParseZeroEvent(int64_t ts,
                                    uint32_t pid,
                                    int32_t flag,
                                    base::StringView name,
                                    uint32_t tgid,
                                    int64_t value) {
  systrace_utils::SystraceTracePoint point{};
  point.name = name;
  point.tgid = tgid;
  point.value = value;

  // The value of these constants can be found in the msm-google kernel.
  constexpr int32_t kSystraceEventBegin = 1 << 0;
  constexpr int32_t kSystraceEventEnd = 1 << 1;
  constexpr int32_t kSystraceEventInt64 = 1 << 2;

  if ((flag & kSystraceEventBegin) != 0) {
    point.phase = 'B';
  } else if ((flag & kSystraceEventEnd) != 0) {
    point.phase = 'E';
  } else if ((flag & kSystraceEventInt64) != 0) {
    point.phase = 'C';
  } else {
    context_->storage->IncrementStats(stats::systrace_parse_failure);
    return;
  }
  ParseSystracePoint(ts, pid, point);
}

void SystraceParser::ParseSdeTracingMarkWrite(int64_t ts,
                                              uint32_t pid,
                                              char trace_type,
                                              bool trace_begin,
                                              base::StringView trace_name,
                                              uint32_t tgid,
                                              int64_t value) {
  systrace_utils::SystraceTracePoint point{};
  point.name = trace_name;
  point.tgid = tgid;
  point.value = value;
  // Some versions of this trace point fill trace_type with one of (B/E/C),
  // others use the trace_begin boolean and only support begin/end events:
  if (trace_type == 0) {
    point.phase = trace_begin ? 'B' : 'E';
  } else if (trace_type == 'B' || trace_type == 'E' || trace_type == 'C') {
    point.phase = trace_type;
  } else {
    context_->storage->IncrementStats(stats::systrace_parse_failure);
    return;
  }

  ParseSystracePoint(ts, pid, point);
}

void SystraceParser::ParseSystracePoint(
    int64_t ts,
    uint32_t pid,
    systrace_utils::SystraceTracePoint point) {
  switch (point.phase) {
    case 'B': {
      StringId name_id = context_->storage->InternString(point.name);
      UniqueTid utid = context_->process_tracker->UpdateThread(pid, point.tgid);
      TrackId track_id = context_->track_tracker->InternThreadTrack(utid);
      context_->slice_tracker->Begin(ts, track_id, kNullStringId /* cat */,
                                     name_id);
      break;
    }

    case 'E': {
      // |point.tgid| can be 0 in older android versions where the end event
      // would not contain the value.
      UniqueTid utid;
      if (point.tgid == 0) {
        // If we haven't seen this thread before, there can't have been a Begin
        // event for it so just ignore the event.
        auto opt_utid = context_->process_tracker->GetThreadOrNull(pid);
        if (!opt_utid)
          break;
        utid = *opt_utid;
      } else {
        utid = context_->process_tracker->UpdateThread(pid, point.tgid);
      }
      TrackId track_id = context_->track_tracker->InternThreadTrack(utid);
      context_->slice_tracker->End(ts, track_id);
      break;
    }

    case 'S':
    case 'F': {
      StringId name_id = context_->storage->InternString(point.name);
      int64_t cookie = static_cast<int64_t>(point.value);
      UniquePid upid =
          context_->process_tracker->GetOrCreateProcess(point.tgid);

      TrackId track_id = context_->track_tracker->InternAndroidAsyncTrack(
          name_id, upid, cookie);
      if (point.phase == 'S') {
        context_->slice_tracker->Begin(ts, track_id, kNullStringId, name_id);
      } else {
        context_->slice_tracker->End(ts, track_id);
      }
      break;
    }

    case 'C': {
      // LMK events from userspace are hacked as counter events with the "value"
      // of the counter representing the pid of the killed process which is
      // reset to 0 once the kill is complete.
      // Homogenise this with kernel LMK events as an instant event, ignoring
      // the resets to 0.
      if (point.name == "kill_one_process") {
        auto killed_pid = static_cast<uint32_t>(point.value);
        if (killed_pid != 0) {
          UniquePid killed_upid =
              context_->process_tracker->GetOrCreateProcess(killed_pid);
          context_->event_tracker->PushInstant(ts, lmk_id_, killed_upid,
                                               RefType::kRefUpid);
        }
        // TODO(lalitm): we should not add LMK events to the counters table
        // once the UI has support for displaying instants.
      }
      // This is per upid on purpose. Some counters are pushed from arbitrary
      // threads but are really per process.
      UniquePid upid =
          context_->process_tracker->GetOrCreateProcess(point.tgid);
      StringId name_id = context_->storage->InternString(point.name);
      TrackId track =
          context_->track_tracker->InternProcessCounterTrack(name_id, upid);
      context_->event_tracker->PushCounter(ts, point.value, track);
    }
  }
}

}  // namespace trace_processor
}  // namespace perfetto
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <fstream>
#include <set>
#include <sstream>
#include <string>

#include "perfetto/ext/base/file_utils.h"
#include "src/traced/probes/ftrace/ftrace_controller.h"
#include "src/traced/probes/ftrace/ftrace_procfs.h"
#include "test/gtest_and_gmock.h"

using testing::Contains;
using testing::HasSubstr;
using testing::IsEmpty;
using testing::Not;
using testing::UnorderedElementsAre;

namespace perfetto {
namespace {

std::string GetFtracePath() {
  size_t i = 0;
  while (!FtraceProcfs::Create(FtraceController::kTracingPaths[i])) {
    i++;
  }
  return std::string(FtraceController::kTracingPaths[i]);
}

void ResetFtrace(FtraceProcfs* ftrace) {
  ftrace->DisableAllEvents();
  ftrace->ClearTrace();
  ftrace->EnableTracing();
}

std::string ReadFile(const std::string& name) {
  std::string result;
  PERFETTO_CHECK(base::ReadFile(GetFtracePath() + name, &result));
  return result;
}

std::string GetTraceOutput() {
  std::string output = ReadFile("trace");
  if (output.empty()) {
    ADD_FAILURE() << "Could not read trace output";
  }
  return output;
}

}  // namespace

// TODO(lalitm): reenable these tests (see b/72306171).
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_CreateWithGoodPath CreateWithGoodPath
#else
#define MAYBE_CreateWithGoodPath DISABLED_CreateWithGoodPath
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_CreateWithGoodPath) {
  EXPECT_TRUE(FtraceProcfs::Create(GetFtracePath()));
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_CreateWithBadPath CreateWithBadPath
#else
#define MAYBE_CreateWithBadPath DISABLED_CreateWithBadath
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_CreateWithBadPath) {
  EXPECT_FALSE(FtraceProcfs::Create(GetFtracePath() + std::string("bad_path")));
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_ClearTrace ClearTrace
#else
#define MAYBE_ClearTrace DISABLED_ClearTrace
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_ClearTrace) {
  FtraceProcfs ftrace(GetFtracePath());
  ResetFtrace(&ftrace);
  ftrace.WriteTraceMarker("Hello, World!");
  ftrace.ClearTrace();
  EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("Hello, World!")));
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_TraceMarker TraceMarker
#else
#define MAYBE_TraceMarker DISABLED_TraceMarker
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_TraceMarker) {
  FtraceProcfs ftrace(GetFtracePath());
  ResetFtrace(&ftrace);
  ftrace.WriteTraceMarker("Hello, World!");
  EXPECT_THAT(GetTraceOutput(), HasSubstr("Hello, World!"));
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_EnableDisableEvent EnableDisableEvent
#else
#define MAYBE_EnableDisableEvent DISABLED_EnableDisableEvent
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_EnableDisableEvent) {
  FtraceProcfs ftrace(GetFtracePath());
  ResetFtrace(&ftrace);
  ftrace.EnableEvent("sched", "sched_switch");
  sleep(1);
  EXPECT_THAT(GetTraceOutput(), HasSubstr("sched_switch"));

  ftrace.DisableEvent("sched", "sched_switch");
  ftrace.ClearTrace();
  sleep(1);
  EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("sched_switch")));
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_EnableDisableTracing EnableDisableTracing
#else
#define MAYBE_EnableDisableTracing DISABLED_EnableDisableTracing
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_EnableDisableTracing) {
  FtraceProcfs ftrace(GetFtracePath());
  ResetFtrace(&ftrace);
  EXPECT_TRUE(ftrace.IsTracingEnabled());
  ftrace.WriteTraceMarker("Before");
  ftrace.DisableTracing();
  EXPECT_FALSE(ftrace.IsTracingEnabled());
  ftrace.WriteTraceMarker("During");
  ftrace.EnableTracing();
  EXPECT_TRUE(ftrace.IsTracingEnabled());
  ftrace.WriteTraceMarker("After");
  EXPECT_THAT(GetTraceOutput(), HasSubstr("Before"));
  EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("During")));
  EXPECT_THAT(GetTraceOutput(), HasSubstr("After"));
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_ReadFormatFile ReadFormatFile
#else
#define MAYBE_ReadFormatFile DISABLED_ReadFormatFile
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_ReadFormatFile) {
  FtraceProcfs ftrace(GetFtracePath());
  std::string format = ftrace.ReadEventFormat("ftrace", "print");
  EXPECT_THAT(format, HasSubstr("name: print"));
  EXPECT_THAT(format, HasSubstr("field:char buf"));
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_CanOpenTracePipeRaw CanOpenTracePipeRaw
#else
#define MAYBE_CanOpenTracePipeRaw DISABLED_CanOpenTracePipeRaw
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_CanOpenTracePipeRaw) {
  FtraceProcfs ftrace(GetFtracePath());
  EXPECT_TRUE(ftrace.OpenPipeForCpu(0));
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_Clock Clock
#else
#define MAYBE_Clock DISABLED_Clock
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_Clock) {
  FtraceProcfs ftrace(GetFtracePath());
  std::set<std::string> clocks = ftrace.AvailableClocks();
  EXPECT_THAT(clocks, Contains("local"));
  EXPECT_THAT(clocks, Contains("global"));

  EXPECT_TRUE(ftrace.SetClock("global"));
  EXPECT_EQ(ftrace.GetClock(), "global");
  EXPECT_TRUE(ftrace.SetClock("local"));
  EXPECT_EQ(ftrace.GetClock(), "local");
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_CanSetBufferSize CanSetBufferSize
#else
#define MAYBE_CanSetBufferSize DISABLED_CanSetBufferSize
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_CanSetBufferSize) {
  FtraceProcfs ftrace(GetFtracePath());
  EXPECT_TRUE(ftrace.SetCpuBufferSizeInPages(4ul));
  EXPECT_EQ(ReadFile("buffer_size_kb"), "16\n");  // (4096 * 4) / 1024
  EXPECT_TRUE(ftrace.SetCpuBufferSizeInPages(5ul));
  EXPECT_EQ(ReadFile("buffer_size_kb"), "20\n");  // (4096 * 5) / 1024
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_FtraceControllerHardReset FtraceControllerHardReset
#else
#define MAYBE_FtraceControllerHardReset DISABLED_FtraceControllerHardReset
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_FtraceControllerHardReset) {
  FtraceProcfs ftrace(GetFtracePath());
  ResetFtrace(&ftrace);

  ftrace.SetCpuBufferSizeInPages(4ul);
  ftrace.EnableTracing();
  ftrace.EnableEvent("sched", "sched_switch");
  ftrace.WriteTraceMarker("Hello, World!");

  EXPECT_EQ(ReadFile("buffer_size_kb"), "16\n");
  EXPECT_EQ(ReadFile("tracing_on"), "1\n");
  EXPECT_EQ(ReadFile("events/enable"), "X\n");
  EXPECT_THAT(GetTraceOutput(), HasSubstr("Hello"));

  HardResetFtraceState();

  EXPECT_EQ(ReadFile("buffer_size_kb"), "4\n");
  EXPECT_EQ(ReadFile("tracing_on"), "0\n");
  EXPECT_EQ(ReadFile("events/enable"), "0\n");
  EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("Hello")));
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_ReadEnabledEvents ReadEnabledEvents
#else
#define MAYBE_ReadEnabledEvents DISABLED_ReadEnabledEvents
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_ReadEnabledEvents) {
  FtraceProcfs ftrace(GetFtracePath());
  ResetFtrace(&ftrace);

  EXPECT_THAT(ftrace.ReadEnabledEvents(), IsEmpty());

  ftrace.EnableEvent("sched", "sched_switch");
  ftrace.EnableEvent("kmem", "kmalloc");

  EXPECT_THAT(ftrace.ReadEnabledEvents(),
              UnorderedElementsAre("sched/sched_switch", "kmem/kmalloc"));

  ftrace.DisableEvent("sched", "sched_switch");
  ftrace.DisableEvent("kmem", "kmalloc");

  EXPECT_THAT(ftrace.ReadEnabledEvents(), IsEmpty());
}

}  // namespace perfetto
<commit_msg>Test: Improve FtraceProcfsIntegrationTest, skip if systrace is on am: 16b67309ba am: f9e65127ad am: 21be68b9b7 am: 032c2dc613 am: 7dd9748f5a<commit_after>/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <fstream>
#include <set>
#include <sstream>
#include <string>

#include "perfetto/ext/base/file_utils.h"
#include "src/traced/probes/ftrace/ftrace_controller.h"
#include "src/traced/probes/ftrace/ftrace_procfs.h"
#include "test/gtest_and_gmock.h"

using testing::Contains;
using testing::HasSubstr;
using testing::IsEmpty;
using testing::Not;
using testing::UnorderedElementsAre;

// These tests run only on Android because on linux they require access to
// ftrace, which would be problematic in the CI when multiple tests run
// concurrently on the same machine. Android instead uses one emulator instance
// for each worker.
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define ANDROID_ONLY_TEST(x) x
#else
#define ANDROID_ONLY_TEST(x) DISABLED_##x
#endif

namespace perfetto {
namespace {

std::string GetFtracePath() {
  size_t i = 0;
  while (!FtraceProcfs::Create(FtraceController::kTracingPaths[i])) {
    i++;
  }
  return std::string(FtraceController::kTracingPaths[i]);
}

std::string ReadFile(const std::string& name) {
  std::string result;
  PERFETTO_CHECK(base::ReadFile(GetFtracePath() + name, &result));
  return result;
}

std::string GetTraceOutput() {
  std::string output = ReadFile("trace");
  if (output.empty()) {
    ADD_FAILURE() << "Could not read trace output";
  }
  return output;
}

class FtraceProcfsIntegrationTest : public testing::Test {
 public:
  void SetUp() override;
  void TearDown() override;

  std::unique_ptr<FtraceProcfs> ftrace_;
};

void FtraceProcfsIntegrationTest::SetUp() {
  ftrace_ = FtraceProcfs::Create(GetFtracePath());
  ASSERT_TRUE(ftrace_);
  if (ftrace_->IsTracingEnabled()) {
    GTEST_SKIP() << "Something else is using ftrace, skipping";
  }

  ftrace_->DisableAllEvents();
  ftrace_->ClearTrace();
  ftrace_->EnableTracing();
}

void FtraceProcfsIntegrationTest::TearDown() {
  ftrace_->DisableAllEvents();
  ftrace_->ClearTrace();
  ftrace_->DisableTracing();
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(CreateWithBadPath)) {
  EXPECT_FALSE(FtraceProcfs::Create(GetFtracePath() + std::string("bad_path")));
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(ClearTrace)) {
  ftrace_->WriteTraceMarker("Hello, World!");
  ftrace_->ClearTrace();
  EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("Hello, World!")));
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(TraceMarker)) {
  ftrace_->WriteTraceMarker("Hello, World!");
  EXPECT_THAT(GetTraceOutput(), HasSubstr("Hello, World!"));
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(EnableDisableEvent)) {
  ftrace_->EnableEvent("sched", "sched_switch");
  sleep(1);
  EXPECT_THAT(GetTraceOutput(), HasSubstr("sched_switch"));

  ftrace_->DisableEvent("sched", "sched_switch");
  ftrace_->ClearTrace();
  sleep(1);
  EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("sched_switch")));
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(EnableDisableTracing)) {
  EXPECT_TRUE(ftrace_->IsTracingEnabled());
  ftrace_->WriteTraceMarker("Before");
  ftrace_->DisableTracing();
  EXPECT_FALSE(ftrace_->IsTracingEnabled());
  ftrace_->WriteTraceMarker("During");
  ftrace_->EnableTracing();
  EXPECT_TRUE(ftrace_->IsTracingEnabled());
  ftrace_->WriteTraceMarker("After");
  EXPECT_THAT(GetTraceOutput(), HasSubstr("Before"));
  EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("During")));
  EXPECT_THAT(GetTraceOutput(), HasSubstr("After"));
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(ReadFormatFile)) {
  std::string format = ftrace_->ReadEventFormat("ftrace", "print");
  EXPECT_THAT(format, HasSubstr("name: print"));
  EXPECT_THAT(format, HasSubstr("field:char buf"));
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(CanOpenTracePipeRaw)) {
  EXPECT_TRUE(ftrace_->OpenPipeForCpu(0));
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(Clock)) {
  std::set<std::string> clocks = ftrace_->AvailableClocks();
  EXPECT_THAT(clocks, Contains("local"));
  EXPECT_THAT(clocks, Contains("global"));

  EXPECT_TRUE(ftrace_->SetClock("global"));
  EXPECT_EQ(ftrace_->GetClock(), "global");
  EXPECT_TRUE(ftrace_->SetClock("local"));
  EXPECT_EQ(ftrace_->GetClock(), "local");
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(CanSetBufferSize)) {
  EXPECT_TRUE(ftrace_->SetCpuBufferSizeInPages(4ul));
  EXPECT_EQ(ReadFile("buffer_size_kb"), "16\n");  // (4096 * 4) / 1024
  EXPECT_TRUE(ftrace_->SetCpuBufferSizeInPages(5ul));
  EXPECT_EQ(ReadFile("buffer_size_kb"), "20\n");  // (4096 * 5) / 1024
}

TEST_F(FtraceProcfsIntegrationTest,
       ANDROID_ONLY_TEST(FtraceControllerHardReset)) {
  ftrace_->SetCpuBufferSizeInPages(4ul);
  ftrace_->EnableTracing();
  ftrace_->EnableEvent("sched", "sched_switch");
  ftrace_->WriteTraceMarker("Hello, World!");

  EXPECT_EQ(ReadFile("buffer_size_kb"), "16\n");
  EXPECT_EQ(ReadFile("tracing_on"), "1\n");
  EXPECT_EQ(ReadFile("events/enable"), "X\n");
  EXPECT_THAT(GetTraceOutput(), HasSubstr("Hello"));

  HardResetFtraceState();

  EXPECT_EQ(ReadFile("buffer_size_kb"), "4\n");
  EXPECT_EQ(ReadFile("tracing_on"), "0\n");
  EXPECT_EQ(ReadFile("events/enable"), "0\n");
  EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("Hello")));
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(ReadEnabledEvents)) {
  EXPECT_THAT(ftrace_->ReadEnabledEvents(), IsEmpty());

  ftrace_->EnableEvent("sched", "sched_switch");
  ftrace_->EnableEvent("kmem", "kmalloc");

  EXPECT_THAT(ftrace_->ReadEnabledEvents(),
              UnorderedElementsAre("sched/sched_switch", "kmem/kmalloc"));

  ftrace_->DisableEvent("sched", "sched_switch");
  ftrace_->DisableEvent("kmem", "kmalloc");

  EXPECT_THAT(ftrace_->ReadEnabledEvents(), IsEmpty());
}

}  // namespace
}  // namespace perfetto
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsgpainteditem.h"
#include <private/qsgpainteditem_p.h>
#include <private/qsgpainternode_p.h>

#include <private/qsgcontext_p.h>
#include <private/qsgadaptationlayer_p.h>
#include <qmath.h>

QT_BEGIN_NAMESPACE

/*!
    \class QSGPaintedItem
    \brief The QSGPaintedItem class provides a way to use the QPainter API in the
    QML Scene Graph.

    The QSGPaintedItem makes it possible to use the QPainter API with the QML Scene Graph.
    It sets up a textured rectangle in the Scene Graph and uses a QPainter to paint
    onto the texture. The render target can be either a QImage or a QGLFramebufferObject.
    When the render target is a QImage, QPainter first renders into the image then
    the content is uploaded to the texture.
    When a QGLFramebufferObject is used, QPainter paints directly onto the texture.
    Call update() to trigger a repaint.

    To enable QPainter to do anti-aliased rendering, use setAntialiasing().

    QSGPaintedItem is meant to make it easier to port old code that is using the
    QPainter API to the QML Scene Graph API and it should be used only for that purpose.

    To write your own painted item, you first create a subclass of QSGPaintedItem, and then
    start by implementing its only pure virtual public function: paint(), which implements
    the actual painting. To get the size of the area painted by the item, use
    contentsBoundingRect().
*/

/*!
    \enum QSGPaintedItem::RenderTarget

    This enum describes QSGPaintedItem's render targets. The render target is the
    surface QPainter paints onto before the item is rendered on screen.

    \value Image The default; QPainter paints into a QImage using the raster paint engine.
    The image's content needs to be uploaded to graphics memory afterward, this operation
    can potentially be slow if the item is large. This render target allows high quality
    anti-aliasing and fast item resizing.

    \value FramebufferObject QPainter paints into a QGLFramebufferObject using the GL
    paint engine. Painting can be faster as no texture upload is required, but anti-aliasing
    quality is not as good as if using an image. This render target allows faster rendering
    in some cases, but you should avoid using it if the item is resized often.

    \sa setRenderTarget()
*/

/*!
    \internal
*/
QSGPaintedItemPrivate::QSGPaintedItemPrivate()
    : QSGItemPrivate()
    , contentsScale(1.0)
    , fillColor(Qt::transparent)
    , renderTarget(QSGPaintedItem::Image)
    , geometryDirty(false)
    , contentsDirty(false)
    , opaquePainting(false)
    , antialiasing(false)
    , mipmap(false)
{
}

/*!
    Constructs a QSGPaintedItem with the given \a parent item.
 */
QSGPaintedItem::QSGPaintedItem(QSGItem *parent)
    : QSGItem(*(new QSGPaintedItemPrivate), parent)
{
    setFlag(ItemHasContents);
}

/*!
    \internal
*/
QSGPaintedItem::QSGPaintedItem(QSGPaintedItemPrivate &dd, QSGItem *parent)
    : QSGItem(dd, parent)
{
    setFlag(ItemHasContents);
}

/*!
    Destroys the QSGPaintedItem.
*/
QSGPaintedItem::~QSGPaintedItem()
{
}

/*!
    Schedules a redraw of the area covered by \a rect in this item. You can call this function
    whenever your item needs to be redrawn, such as if it changes appearance or size.

    This function does not cause an immediate paint; instead it schedules a paint request that
    is processed by the QML Scene Graph when the next frame is rendered. The item will only be
    redrawn if it is visible.

    Note that calling this function will trigger a repaint of the whole scene.

    \sa paint()
*/
void QSGPaintedItem::update(const QRect &rect)
{
    Q_D(QSGPaintedItem);
    d->contentsDirty = true;

    QRect srect(qCeil(rect.x()*d->contentsScale),
            qCeil(rect.y()*d->contentsScale),
            qCeil(rect.width()*d->contentsScale),
            qCeil(rect.height()*d->contentsScale));

    if (srect.isNull() && !d->dirtyRect.isNull())
        d->dirtyRect = contentsBoundingRect().toAlignedRect();
    else
        d->dirtyRect |= (contentsBoundingRect() & srect).toAlignedRect();
    QSGItem::update();
}

/*!
    Returns true if this item is opaque; otherwise, false is returned.

    By default, painted items are not opaque.

    \sa setOpaquePainting()
*/
bool QSGPaintedItem::opaquePainting() const
{
    Q_D(const QSGPaintedItem);
    return d->opaquePainting;
}

/*!
    If \a opaque is true, the item is opaque; otherwise, it is considered as translucent.

    Opaque items are not blended with the rest of the scene, you should set this to true
    if the content of the item is opaque to speed up rendering.

    By default, painted items are not opaque.

    \sa opaquePainting()
*/
void QSGPaintedItem::setOpaquePainting(bool opaque)
{
    Q_D(QSGPaintedItem);

    if (d->opaquePainting == opaque)
        return;

    d->opaquePainting = opaque;
    QSGItem::update();
}

/*!
    Returns true if antialiased painting is enabled; otherwise, false is returned.

    By default, antialiasing is not enabled.

    \sa setAntialiasing()
*/
bool QSGPaintedItem::antialiasing() const
{
    Q_D(const QSGPaintedItem);
    return d->antialiasing;
}

/*!
    If \a enable is true, antialiased painting is enabled.

    By default, antialiasing is not enabled.

    \sa antialiasing()
*/
void QSGPaintedItem::setAntialiasing(bool enable)
{
    Q_D(QSGPaintedItem);

    if (d->antialiasing == enable)
        return;

    d->antialiasing = enable;
    update();
}

/*!
    Returns true if mipmaps are enabled; otherwise, false is returned.

    By default, mipmapping is not enabled.

    \sa setMipmap()
*/
bool QSGPaintedItem::mipmap() const
{
    Q_D(const QSGPaintedItem);
    return d->mipmap;
}

/*!
    If \a enable is true, mipmapping is enabled on the associated texture.

    Mipmapping increases rendering speed and reduces aliasing artifacts when the item is
    scaled down.

    By default, mipmapping is not enabled.

    \sa mipmap()
*/
void QSGPaintedItem::setMipmap(bool enable)
{
    Q_D(QSGPaintedItem);

    if (d->mipmap == enable)
        return;

    d->mipmap = enable;
    update();
}

/*!
    This function returns the outer bounds of the item as a rectangle; all painting must be
    restricted to inside an item's bounding rect.

    If the contents size has not been set it reflects the size of the item; otherwise
    it reflects the contents size scaled by the contents scale.

    Use this function to know the area painted by the item.

    \sa QSGItem::width(), QSGItem::height(), contentsSize(), contentsScale()
*/
QRectF QSGPaintedItem::contentsBoundingRect() const
{
    Q_D(const QSGPaintedItem);

    qreal w = d->width;
    QSizeF sz = d->contentsSize * d->contentsScale;
    if (w < sz.width())
        w = sz.width();
    qreal h = d->height;
    if (h < sz.height())
        h = sz.height();

    return QRectF(0, 0, w, h);
}

/*!
    \property QSGPaintedItem::contentsSize
    \brief The size of the contents

    The contents size is the size of the item in regards to how it is painted
    using the paint() function.  This is distinct from the size of the
    item in regards to height() and width().
*/
QSize QSGPaintedItem::contentsSize() const
{
    Q_D(const QSGPaintedItem);
    return d->contentsSize;
}

void QSGPaintedItem::setContentsSize(const QSize &size)
{
    Q_D(QSGPaintedItem);

    if (d->contentsSize == size)
        return;

    d->contentsSize = size;
    update();
}

/*!
    This convenience function is equivalent to calling setContentsSize(QSize()).
*/
void QSGPaintedItem::resetContentsSize()
{
    setContentsSize(QSize());
}

/*!
    \property QSGPaintedItem::contentsScale
    \brief The scale of the contents

    All painting happening in paint() is scaled by the contents scale. This is distinct
    from the scale of the item in regards to scale().

    The default value is 1.
*/
qreal QSGPaintedItem::contentsScale() const
{
    Q_D(const QSGPaintedItem);
    return d->contentsScale;
}

void QSGPaintedItem::setContentsScale(qreal scale)
{
    Q_D(QSGPaintedItem);

    if (d->contentsScale == scale)
        return;

    d->contentsScale = scale;
    update();
}

/*!
    \property QSGPaintedItem::fillColor
    \brief The item's background fill color.

    By default, the fill color is set to Qt::transparent.
*/
QColor QSGPaintedItem::fillColor() const
{
    Q_D(const QSGPaintedItem);
    return d->fillColor;
}

void QSGPaintedItem::setFillColor(const QColor &c)
{
    Q_D(QSGPaintedItem);

    if (d->fillColor == c)
        return;

    d->fillColor = c;
    update();

    emit fillColorChanged();
}

/*!
    \property QSGPaintedItem::renderTarget
    \brief The item's render target.

    This property defines which render target the QPainter renders into, it can be either
    QSGPaintedItem::Image or QSGPaintedItem::FramebufferObject. Both have certains benefits,
    typically performance versus quality. Using a framebuffer object avoids a costly upload
    of the image contents to the texture in graphics memory, while using an image enables
    high quality anti-aliasing.

    \warning Resizing a framebuffer object is a costly operation, avoid using
    the QSGPaintedItem::FramebufferObject render target if the item gets resized often.

    By default, the render target is QSGPaintedItem::Image.
*/
QSGPaintedItem::RenderTarget QSGPaintedItem::renderTarget() const
{
    Q_D(const QSGPaintedItem);
    return d->renderTarget;
}

void QSGPaintedItem::setRenderTarget(RenderTarget target)
{
    Q_D(QSGPaintedItem);

    if (d->renderTarget == target)
        return;

    d->renderTarget = target;
    update();

    emit renderTargetChanged();
}

/*!
    \fn virtual void QSGPaintedItem::paint(QPainter *painter) = 0

    This function, which is usually called by the QML Scene Graph, paints the
    contents of an item in local coordinates.

    The function is called after the item has been filled with the fillColor.

    Reimplement this function in a QSGPaintedItem subclass to provide the
    item's painting implementation, using \a painter.
*/

/*!
    This function is called after the item's geometry has changed.
*/
void QSGPaintedItem::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
    Q_D(QSGPaintedItem);
    d->geometryDirty = true;
    QSGItem::geometryChanged(newGeometry, oldGeometry);
}

/*!
    This function is called when the Scene Graph node associated to the item needs to
    be updated.
*/
QSGNode *QSGPaintedItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data)
{
    Q_UNUSED(data);
    Q_D(QSGPaintedItem);

    if (width() <= 0 || height() <= 0) {
        delete oldNode;
        return 0;
    }

    QSGPainterNode *node = static_cast<QSGPainterNode *>(oldNode);
    if (!node)
        node = new QSGPainterNode(this);

    QRectF br = contentsBoundingRect();

    node->setPreferredRenderTarget(d->renderTarget);
    node->setSize(QSize(qRound(br.width()), qRound(br.height())));
    node->setSmoothPainting(d->antialiasing);
    node->setLinearFiltering(d->smooth);
    node->setMipmapping(d->mipmap);
    node->setOpaquePainting(d->opaquePainting);
    node->setFillColor(d->fillColor);
    node->setContentsScale(d->contentsScale);
    node->setDirty(d->contentsDirty || d->geometryDirty, d->dirtyRect);
    node->update();

    d->contentsDirty = false;
    d->geometryDirty = false;
    d->dirtyRect = QRect();

    return node;
}

QT_END_NAMESPACE
<commit_msg>Documented which thread gets the QSGPaintedItem::paint() call.<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsgpainteditem.h"
#include <private/qsgpainteditem_p.h>
#include <private/qsgpainternode_p.h>

#include <private/qsgcontext_p.h>
#include <private/qsgadaptationlayer_p.h>
#include <qmath.h>

QT_BEGIN_NAMESPACE

/*!
    \class QSGPaintedItem
    \brief The QSGPaintedItem class provides a way to use the QPainter API in the
    QML Scene Graph.

    The QSGPaintedItem makes it possible to use the QPainter API with the QML Scene Graph.
    It sets up a textured rectangle in the Scene Graph and uses a QPainter to paint
    onto the texture. The render target can be either a QImage or a QGLFramebufferObject.
    When the render target is a QImage, QPainter first renders into the image then
    the content is uploaded to the texture.
    When a QGLFramebufferObject is used, QPainter paints directly onto the texture.
    Call update() to trigger a repaint.

    To enable QPainter to do anti-aliased rendering, use setAntialiasing().

    QSGPaintedItem is meant to make it easier to port old code that is using the
    QPainter API to the QML Scene Graph API and it should be used only for that purpose.

    To write your own painted item, you first create a subclass of QSGPaintedItem, and then
    start by implementing its only pure virtual public function: paint(), which implements
    the actual painting. To get the size of the area painted by the item, use
    contentsBoundingRect().
*/

/*!
    \enum QSGPaintedItem::RenderTarget

    This enum describes QSGPaintedItem's render targets. The render target is the
    surface QPainter paints onto before the item is rendered on screen.

    \value Image The default; QPainter paints into a QImage using the raster paint engine.
    The image's content needs to be uploaded to graphics memory afterward, this operation
    can potentially be slow if the item is large. This render target allows high quality
    anti-aliasing and fast item resizing.

    \value FramebufferObject QPainter paints into a QGLFramebufferObject using the GL
    paint engine. Painting can be faster as no texture upload is required, but anti-aliasing
    quality is not as good as if using an image. This render target allows faster rendering
    in some cases, but you should avoid using it if the item is resized often.

    \sa setRenderTarget()
*/

/*!
    \internal
*/
QSGPaintedItemPrivate::QSGPaintedItemPrivate()
    : QSGItemPrivate()
    , contentsScale(1.0)
    , fillColor(Qt::transparent)
    , renderTarget(QSGPaintedItem::Image)
    , geometryDirty(false)
    , contentsDirty(false)
    , opaquePainting(false)
    , antialiasing(false)
    , mipmap(false)
{
}

/*!
    Constructs a QSGPaintedItem with the given \a parent item.
 */
QSGPaintedItem::QSGPaintedItem(QSGItem *parent)
    : QSGItem(*(new QSGPaintedItemPrivate), parent)
{
    setFlag(ItemHasContents);
}

/*!
    \internal
*/
QSGPaintedItem::QSGPaintedItem(QSGPaintedItemPrivate &dd, QSGItem *parent)
    : QSGItem(dd, parent)
{
    setFlag(ItemHasContents);
}

/*!
    Destroys the QSGPaintedItem.
*/
QSGPaintedItem::~QSGPaintedItem()
{
}

/*!
    Schedules a redraw of the area covered by \a rect in this item. You can call this function
    whenever your item needs to be redrawn, such as if it changes appearance or size.

    This function does not cause an immediate paint; instead it schedules a paint request that
    is processed by the QML Scene Graph when the next frame is rendered. The item will only be
    redrawn if it is visible.

    Note that calling this function will trigger a repaint of the whole scene.

    \sa paint()
*/
void QSGPaintedItem::update(const QRect &rect)
{
    Q_D(QSGPaintedItem);
    d->contentsDirty = true;

    QRect srect(qCeil(rect.x()*d->contentsScale),
            qCeil(rect.y()*d->contentsScale),
            qCeil(rect.width()*d->contentsScale),
            qCeil(rect.height()*d->contentsScale));

    if (srect.isNull() && !d->dirtyRect.isNull())
        d->dirtyRect = contentsBoundingRect().toAlignedRect();
    else
        d->dirtyRect |= (contentsBoundingRect() & srect).toAlignedRect();
    QSGItem::update();
}

/*!
    Returns true if this item is opaque; otherwise, false is returned.

    By default, painted items are not opaque.

    \sa setOpaquePainting()
*/
bool QSGPaintedItem::opaquePainting() const
{
    Q_D(const QSGPaintedItem);
    return d->opaquePainting;
}

/*!
    If \a opaque is true, the item is opaque; otherwise, it is considered as translucent.

    Opaque items are not blended with the rest of the scene, you should set this to true
    if the content of the item is opaque to speed up rendering.

    By default, painted items are not opaque.

    \sa opaquePainting()
*/
void QSGPaintedItem::setOpaquePainting(bool opaque)
{
    Q_D(QSGPaintedItem);

    if (d->opaquePainting == opaque)
        return;

    d->opaquePainting = opaque;
    QSGItem::update();
}

/*!
    Returns true if antialiased painting is enabled; otherwise, false is returned.

    By default, antialiasing is not enabled.

    \sa setAntialiasing()
*/
bool QSGPaintedItem::antialiasing() const
{
    Q_D(const QSGPaintedItem);
    return d->antialiasing;
}

/*!
    If \a enable is true, antialiased painting is enabled.

    By default, antialiasing is not enabled.

    \sa antialiasing()
*/
void QSGPaintedItem::setAntialiasing(bool enable)
{
    Q_D(QSGPaintedItem);

    if (d->antialiasing == enable)
        return;

    d->antialiasing = enable;
    update();
}

/*!
    Returns true if mipmaps are enabled; otherwise, false is returned.

    By default, mipmapping is not enabled.

    \sa setMipmap()
*/
bool QSGPaintedItem::mipmap() const
{
    Q_D(const QSGPaintedItem);
    return d->mipmap;
}

/*!
    If \a enable is true, mipmapping is enabled on the associated texture.

    Mipmapping increases rendering speed and reduces aliasing artifacts when the item is
    scaled down.

    By default, mipmapping is not enabled.

    \sa mipmap()
*/
void QSGPaintedItem::setMipmap(bool enable)
{
    Q_D(QSGPaintedItem);

    if (d->mipmap == enable)
        return;

    d->mipmap = enable;
    update();
}

/*!
    This function returns the outer bounds of the item as a rectangle; all painting must be
    restricted to inside an item's bounding rect.

    If the contents size has not been set it reflects the size of the item; otherwise
    it reflects the contents size scaled by the contents scale.

    Use this function to know the area painted by the item.

    \sa QSGItem::width(), QSGItem::height(), contentsSize(), contentsScale()
*/
QRectF QSGPaintedItem::contentsBoundingRect() const
{
    Q_D(const QSGPaintedItem);

    qreal w = d->width;
    QSizeF sz = d->contentsSize * d->contentsScale;
    if (w < sz.width())
        w = sz.width();
    qreal h = d->height;
    if (h < sz.height())
        h = sz.height();

    return QRectF(0, 0, w, h);
}

/*!
    \property QSGPaintedItem::contentsSize
    \brief The size of the contents

    The contents size is the size of the item in regards to how it is painted
    using the paint() function.  This is distinct from the size of the
    item in regards to height() and width().
*/
QSize QSGPaintedItem::contentsSize() const
{
    Q_D(const QSGPaintedItem);
    return d->contentsSize;
}

void QSGPaintedItem::setContentsSize(const QSize &size)
{
    Q_D(QSGPaintedItem);

    if (d->contentsSize == size)
        return;

    d->contentsSize = size;
    update();
}

/*!
    This convenience function is equivalent to calling setContentsSize(QSize()).
*/
void QSGPaintedItem::resetContentsSize()
{
    setContentsSize(QSize());
}

/*!
    \property QSGPaintedItem::contentsScale
    \brief The scale of the contents

    All painting happening in paint() is scaled by the contents scale. This is distinct
    from the scale of the item in regards to scale().

    The default value is 1.
*/
qreal QSGPaintedItem::contentsScale() const
{
    Q_D(const QSGPaintedItem);
    return d->contentsScale;
}

void QSGPaintedItem::setContentsScale(qreal scale)
{
    Q_D(QSGPaintedItem);

    if (d->contentsScale == scale)
        return;

    d->contentsScale = scale;
    update();
}

/*!
    \property QSGPaintedItem::fillColor
    \brief The item's background fill color.

    By default, the fill color is set to Qt::transparent.
*/
QColor QSGPaintedItem::fillColor() const
{
    Q_D(const QSGPaintedItem);
    return d->fillColor;
}

void QSGPaintedItem::setFillColor(const QColor &c)
{
    Q_D(QSGPaintedItem);

    if (d->fillColor == c)
        return;

    d->fillColor = c;
    update();

    emit fillColorChanged();
}

/*!
    \property QSGPaintedItem::renderTarget
    \brief The item's render target.

    This property defines which render target the QPainter renders into, it can be either
    QSGPaintedItem::Image or QSGPaintedItem::FramebufferObject. Both have certains benefits,
    typically performance versus quality. Using a framebuffer object avoids a costly upload
    of the image contents to the texture in graphics memory, while using an image enables
    high quality anti-aliasing.

    \warning Resizing a framebuffer object is a costly operation, avoid using
    the QSGPaintedItem::FramebufferObject render target if the item gets resized often.

    By default, the render target is QSGPaintedItem::Image.
*/
QSGPaintedItem::RenderTarget QSGPaintedItem::renderTarget() const
{
    Q_D(const QSGPaintedItem);
    return d->renderTarget;
}

void QSGPaintedItem::setRenderTarget(RenderTarget target)
{
    Q_D(QSGPaintedItem);

    if (d->renderTarget == target)
        return;

    d->renderTarget = target;
    update();

    emit renderTargetChanged();
}

/*!
    \fn virtual void QSGPaintedItem::paint(QPainter *painter) = 0

    This function, which is usually called by the QML Scene Graph, paints the
    contents of an item in local coordinates.

    The function is called after the item has been filled with the fillColor.

    Reimplement this function in a QSGPaintedItem subclass to provide the
    item's painting implementation, using \a painter.

    \note The QML Scene Graph uses two separate threads, the main thread does things such as
    processing events or updating animations while a second thread does the actual OpenGL rendering.
    As a consequence, paint() is not called from the main GUI thread but from the GL enabled
    renderer thread.
*/

/*!
    This function is called after the item's geometry has changed.
*/
void QSGPaintedItem::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
    Q_D(QSGPaintedItem);
    d->geometryDirty = true;
    QSGItem::geometryChanged(newGeometry, oldGeometry);
}

/*!
    This function is called when the Scene Graph node associated to the item needs to
    be updated.
*/
QSGNode *QSGPaintedItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data)
{
    Q_UNUSED(data);
    Q_D(QSGPaintedItem);

    if (width() <= 0 || height() <= 0) {
        delete oldNode;
        return 0;
    }

    QSGPainterNode *node = static_cast<QSGPainterNode *>(oldNode);
    if (!node)
        node = new QSGPainterNode(this);

    QRectF br = contentsBoundingRect();

    node->setPreferredRenderTarget(d->renderTarget);
    node->setSize(QSize(qRound(br.width()), qRound(br.height())));
    node->setSmoothPainting(d->antialiasing);
    node->setLinearFiltering(d->smooth);
    node->setMipmapping(d->mipmap);
    node->setOpaquePainting(d->opaquePainting);
    node->setFillColor(d->fillColor);
    node->setContentsScale(d->contentsScale);
    node->setDirty(d->contentsDirty || d->geometryDirty, d->dirtyRect);
    node->update();

    d->contentsDirty = false;
    d->geometryDirty = false;
    d->dirtyRect = QRect();

    return node;
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>/*
 * Copyright © 2012, United States Government, as represented by the
 * Administrator of the National Aeronautics and Space Administration.
 * All rights reserved.
 *
 * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is 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.
*/

/**
 * @file tgPrismaticInfo.cpp
 * @brief Contains the definition of members of the class tgPrismatic. A prismatic actuator builder.
 * @author Alexander Xydes
 * @copyright Copyright (C) 2014 NASA Ames Research Center
 * $Id$
 */

#include "tgPrismaticInfo.h"

tgPrismaticInfo::tgPrismaticInfo(const tgPrismatic::Config& config) :
    m_config(config),
    tgConnectorInfo()
{
}

tgPrismaticInfo::tgPrismaticInfo(const tgPrismatic::Config& config, tgTags tags) :
    m_config(config),
    tgConnectorInfo(tags)
{}

tgPrismaticInfo::tgPrismaticInfo(const tgPrismatic::Config& config, const tgPair& pair) :
    m_config(config),
    tgConnectorInfo(pair)
{}

tgConnectorInfo* tgPrismaticInfo::createConnectorInfo(const tgPair& pair)
{
    return new tgPrismaticInfo(m_config, pair);
}

void tgPrismaticInfo::initConnector(tgWorld& world)
{
    // Anything to do here?
}

tgModel* tgPrismaticInfo::createModel(tgWorld& world)
{
    tgNode startNode = this->getFrom();
    tgNode endNode = this->getTo();

    btVector3 buildVec = (endNode - startNode);
    double m_startLength = buildVec.length();

    tgNode midNode = tgNode(startNode + (buildVec / 2.0),"mid");

    m_config.m_minTotalLength = m_startLength;

    tgPrismatic* prism = new tgPrismatic(getTags(), m_config);
    buildModel(world, prism);
    return prism;
}

const int tgPrismaticInfo::getSegments() const
{
    //@todo: make configurable
    return 2;
}

double tgPrismaticInfo::getMass()
{
    // @todo: add up the rigid bodies
    return 0;
}

void tgPrismaticInfo::buildModel(tgWorld& world, tgModel* prismatic)
{
    // get global from _ to - still need these is both places I think.
    tgNode startNode = this->getFrom();
    tgNode endNode = this->getTo();

    // Calculate the size of the rods
    double rodSize = m_config.m_minTotalLength / 2.0;

    btVector3 buildVec = (endNode - startNode);
    btVector3 offset = btVector3(0.1,0.1,0.1);
    tgNode midNode = tgNode((buildVec / 2.0),"mid");
    tgNode midNode1 = tgNode(midNode - offset,"mid1");
    tgNode midNode2 = tgNode(midNode + offset,"mid2");

    //super structure to the prismatic actuator's two rods
    tgStructure prism;

    tgStructure rod;
    rod.addNode(0,0,0); //Bottom
    rod.addNode(midNode1);
    rod.addPair(0,1,"a rod");

    tgStructure* rod1 = new tgStructure(rod);
    rod1->addTags("rod v1");
    rod1->move(startNode + offset);
    prism.addChild(rod1);

    tgStructure* rod2 = new tgStructure(rod);
    rod2->addTags("rod v2");
    rod2->move(startNode + midNode2);
    prism.addChild(rod2);

    std::vector<tgStructure*> children = prism.getChildren();
    tgNodes n1 = children[0]->getNodes();
    tgNodes n2 = children[1]->getNodes();
    prism.addPair(n1[1], n2[0], "muscle seg");

    tgBuildSpec spec;
    spec.addBuilder("rod", new tgRodInfo(m_config.m_rod1Config));
    spec.addBuilder("muscle", new tgLinearStringInfo(m_stringConfig));

    // Create your structureInfo
    tgStructureInfo structureInfo(prism, spec);

    std::cout << "tgPrismaticInfo::buildModel() 7" << std::endl;
    // Use the structureInfo to build our model
    structureInfo.buildInto(*prismatic, world);

    /* Now that the sub-structure has been created, attach it
    * to the super-structure via hard links?
    * Very manual from here, since this is the only place we have all
    * of the necessary pointers
    */
    // We have to delete these
    std::vector<tgPair*> linkerPairs;

    // "From" side:
    linkerPairs.push_back(new tgPair(startNode, n1[0], tgString("anchor seg",1)));
    // "To" side:
    linkerPairs.push_back(new tgPair(n2[1], endNode, tgString("anchor seg",2)));

    // Perhaps overkill...
    // These pointers will be deleted by tgStructure
    std::vector <tgRigidInfo*> allRigids(structureInfo.getAllRigids());
    std::cout << "tgPrismaticInfo num rigids: " << allRigids.size() << std::endl;
    allRigids.push_back(getToRigidInfo());
    allRigids.push_back(getFromRigidInfo());

    // We have to delete these
//    std::vector <tgConnectorInfo* > linkerInfo;

    // Can this part be done in a loop easily?
//    linkerInfo.push_back(new tgLinearStringInfo(m_stringConfig, *linkerPairs[0]));
//    linkerInfo.push_back(new tgLinearStringInfo(m_stringConfig, *linkerPairs[1]));

    for (std::size_t i = 0; i < linkerInfo.size(); i++)
    {
        linkerInfo[i]->chooseRigids(allRigids);
        linkerInfo[i]->initConnector(world);

        tgModel* m = linkerInfo[i]->createModel(world);
        m->setTags(linkerInfo[i]->getTags());
        if(m != 0) {
            prismatic->addChild(m);
        }
    }

    // Clean up - see if there's a way to do this with references instead?
    for (std::size_t i = 0; i < linkerInfo.size(); i++)
    {
        delete linkerInfo[i];
    }
    linkerInfo.clear();

    for (std::size_t i = 0; i < linkerPairs.size(); i++)
    {
        delete linkerPairs[i];
    }
    linkerPairs.clear();

    /**
    double m_startLength = buildVec.length();
    btVector3 offset = buildVec.normalize();
    tgStructure rod;
    rod.addNode(0,0,0); //Bottom
    rod.addNode(midNode);
    rod.addPair(0,1,"a rod");

    //1st rod
    tgStructure* rod1 = new tgStructure(rod);

    //Move the first one into position
    rod1->addTags("rod v1");
    rod1->move(startNode);
    prism.addChild(rod1);

    //second rod
    tgStructure* rod2 = new tgStructure(rod);
    rod2->addTags("rod v2");
    rod2->move(startNode + midNode);
    prism.addChild(rod2);

    std::vector<tgStructure*> children = prism.getChildren();
    tgNodes n1 = children[0]->getNodes();
    tgNodes n2 = children[1]->getNodes();
    prism.addPair(n1[1], n2[0], "muscle seg");

    tgBuildSpec spec;
    spec.addBuilder("rod", new tgRodInfo(m_config.m_rod1Config));
//    spec.addBuilder("rod v1", new tgRodInfo(m_config.m_rod1Config));
//    spec.addBuilder("rod v2", new tgRodInfo(m_config.m_rod2Config));
    spec.addBuilder("muscle", new tgLinearStringInfo(m_stringConfig));

    // Create your structureInfo
    tgStructureInfo structureInfo(prism, spec);

    std::cout << "tgPrismaticInfo::buildModel() 7" << std::endl;
    // Use the structureInfo to build our model
    structureInfo.buildInto(*prismatic, world);

    /* Now that the sub-structure has been created, attach it
    * to the super-structure
    * Very manual from here, since this is the only place we have all
    * of the necessary pointers
    *
    // We have to delete these
    std::vector<tgPair*> linkerPairs;

    // "From" side:
    linkerPairs.push_back(new tgPair(startNode, n1[0], tgString("anchor seg",1)));
    // "To" side:
    linkerPairs.push_back(new tgPair(n2[1], endNode, tgString("anchor seg",2)));

    // Perhaps overkill...
    // These pointers will be deleted by tgStructure
    std::vector <tgRigidInfo*> allRigids(structureInfo.getAllRigids());
    std::cout << "tgPrismaticInfo num rigids: " << allRigids.size() << std::endl;
    allRigids.push_back(getToRigidInfo());
    allRigids.push_back(getFromRigidInfo());

    // We have to delete these
    std::vector <tgConnectorInfo* > linkerInfo;

    // Can this part be done in a loop easily?
    linkerInfo.push_back(new tgLinearStringInfo(m_stringConfig, *linkerPairs[0]));
    linkerInfo.push_back(new tgLinearStringInfo(m_stringConfig, *linkerPairs[1]));

    for (std::size_t i = 0; i < linkerInfo.size(); i++)
    {
        linkerInfo[i]->chooseRigids(allRigids);
        linkerInfo[i]->initConnector(world);

        tgModel* m = linkerInfo[i]->createModel(world);
        m->setTags(linkerInfo[i]->getTags());
        if(m != 0) {
            prismatic->addChild(m);
        }
    }

    // Clean up - see if there's a way to do this with references instead?
    for (std::size_t i = 0; i < linkerInfo.size(); i++)
    {
        delete linkerInfo[i];
    }
    linkerInfo.clear();

    for (std::size_t i = 0; i < linkerPairs.size(); i++)
    {
        delete linkerPairs[i];
    }
    linkerPairs.clear();
    /**/

    std::cout << "tgPrismaticInfo::buildModel() 8" << std::endl;
    //not needed?
//    prismatic->setup(world);

#if(0)
    // Debug printing
    std::cout << "StructureInfo:" << std::endl;
    std::cout << structureInfo << std::endl;

    std::cout << "Model: " << std::endl;
    std::cout << *prismatic << std::endl;
#endif
}
<commit_msg>Uncommenting accidentally commented line<commit_after>/*
 * Copyright © 2012, United States Government, as represented by the
 * Administrator of the National Aeronautics and Space Administration.
 * All rights reserved.
 *
 * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is 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.
*/

/**
 * @file tgPrismaticInfo.cpp
 * @brief Contains the definition of members of the class tgPrismatic. A prismatic actuator builder.
 * @author Alexander Xydes
 * @copyright Copyright (C) 2014 NASA Ames Research Center
 * $Id$
 */

#include "tgPrismaticInfo.h"

tgPrismaticInfo::tgPrismaticInfo(const tgPrismatic::Config& config) :
    m_config(config),
    tgConnectorInfo()
{
}

tgPrismaticInfo::tgPrismaticInfo(const tgPrismatic::Config& config, tgTags tags) :
    m_config(config),
    tgConnectorInfo(tags)
{}

tgPrismaticInfo::tgPrismaticInfo(const tgPrismatic::Config& config, const tgPair& pair) :
    m_config(config),
    tgConnectorInfo(pair)
{}

tgConnectorInfo* tgPrismaticInfo::createConnectorInfo(const tgPair& pair)
{
    return new tgPrismaticInfo(m_config, pair);
}

void tgPrismaticInfo::initConnector(tgWorld& world)
{
    // Anything to do here?
}

tgModel* tgPrismaticInfo::createModel(tgWorld& world)
{
    tgNode startNode = this->getFrom();
    tgNode endNode = this->getTo();

    btVector3 buildVec = (endNode - startNode);
    double m_startLength = buildVec.length();

    tgNode midNode = tgNode(startNode + (buildVec / 2.0),"mid");

    m_config.m_minTotalLength = m_startLength;

    tgPrismatic* prism = new tgPrismatic(getTags(), m_config);
    buildModel(world, prism);
    return prism;
}

const int tgPrismaticInfo::getSegments() const
{
    //@todo: make configurable
    return 2;
}

double tgPrismaticInfo::getMass()
{
    // @todo: add up the rigid bodies
    return 0;
}

void tgPrismaticInfo::buildModel(tgWorld& world, tgModel* prismatic)
{
    // get global from _ to - still need these is both places I think.
    tgNode startNode = this->getFrom();
    tgNode endNode = this->getTo();

    // Calculate the size of the rods
    double rodSize = m_config.m_minTotalLength / 2.0;

    btVector3 buildVec = (endNode - startNode);
    btVector3 offset = btVector3(0.1,0.1,0.1);
    tgNode midNode = tgNode((buildVec / 2.0),"mid");
    tgNode midNode1 = tgNode(midNode - offset,"mid1");
    tgNode midNode2 = tgNode(midNode + offset,"mid2");

    //super structure to the prismatic actuator's two rods
    tgStructure prism;

    tgStructure rod;
    rod.addNode(0,0,0); //Bottom
    rod.addNode(midNode1);
    rod.addPair(0,1,"a rod");

    tgStructure* rod1 = new tgStructure(rod);
    rod1->addTags("rod v1");
    rod1->move(startNode + offset);
    prism.addChild(rod1);

    tgStructure* rod2 = new tgStructure(rod);
    rod2->addTags("rod v2");
    rod2->move(startNode + midNode2);
    prism.addChild(rod2);

    std::vector<tgStructure*> children = prism.getChildren();
    tgNodes n1 = children[0]->getNodes();
    tgNodes n2 = children[1]->getNodes();
    prism.addPair(n1[1], n2[0], "muscle seg");

    tgBuildSpec spec;
    spec.addBuilder("rod", new tgRodInfo(m_config.m_rod1Config));
    spec.addBuilder("muscle", new tgLinearStringInfo(m_stringConfig));

    // Create your structureInfo
    tgStructureInfo structureInfo(prism, spec);

    std::cout << "tgPrismaticInfo::buildModel() 7" << std::endl;
    // Use the structureInfo to build our model
    structureInfo.buildInto(*prismatic, world);

    /* Now that the sub-structure has been created, attach it
    * to the super-structure via hard links?
    * Very manual from here, since this is the only place we have all
    * of the necessary pointers
    */
    // We have to delete these
    std::vector<tgPair*> linkerPairs;

    // "From" side:
    linkerPairs.push_back(new tgPair(startNode, n1[0], tgString("anchor seg",1)));
    // "To" side:
    linkerPairs.push_back(new tgPair(n2[1], endNode, tgString("anchor seg",2)));

    // Perhaps overkill...
    // These pointers will be deleted by tgStructure
    std::vector <tgRigidInfo*> allRigids(structureInfo.getAllRigids());
    std::cout << "tgPrismaticInfo num rigids: " << allRigids.size() << std::endl;
    allRigids.push_back(getToRigidInfo());
    allRigids.push_back(getFromRigidInfo());

    // We have to delete these
    std::vector <tgConnectorInfo* > linkerInfo;

    // Can this part be done in a loop easily?
//    linkerInfo.push_back(new tgLinearStringInfo(m_stringConfig, *linkerPairs[0]));
//    linkerInfo.push_back(new tgLinearStringInfo(m_stringConfig, *linkerPairs[1]));

    for (std::size_t i = 0; i < linkerInfo.size(); i++)
    {
        linkerInfo[i]->chooseRigids(allRigids);
        linkerInfo[i]->initConnector(world);

        tgModel* m = linkerInfo[i]->createModel(world);
        m->setTags(linkerInfo[i]->getTags());
        if(m != 0) {
            prismatic->addChild(m);
        }
    }

    // Clean up - see if there's a way to do this with references instead?
    for (std::size_t i = 0; i < linkerInfo.size(); i++)
    {
        delete linkerInfo[i];
    }
    linkerInfo.clear();

    for (std::size_t i = 0; i < linkerPairs.size(); i++)
    {
        delete linkerPairs[i];
    }
    linkerPairs.clear();

    /**
    double m_startLength = buildVec.length();
    btVector3 offset = buildVec.normalize();
    tgStructure rod;
    rod.addNode(0,0,0); //Bottom
    rod.addNode(midNode);
    rod.addPair(0,1,"a rod");

    //1st rod
    tgStructure* rod1 = new tgStructure(rod);

    //Move the first one into position
    rod1->addTags("rod v1");
    rod1->move(startNode);
    prism.addChild(rod1);

    //second rod
    tgStructure* rod2 = new tgStructure(rod);
    rod2->addTags("rod v2");
    rod2->move(startNode + midNode);
    prism.addChild(rod2);

    std::vector<tgStructure*> children = prism.getChildren();
    tgNodes n1 = children[0]->getNodes();
    tgNodes n2 = children[1]->getNodes();
    prism.addPair(n1[1], n2[0], "muscle seg");

    tgBuildSpec spec;
    spec.addBuilder("rod", new tgRodInfo(m_config.m_rod1Config));
//    spec.addBuilder("rod v1", new tgRodInfo(m_config.m_rod1Config));
//    spec.addBuilder("rod v2", new tgRodInfo(m_config.m_rod2Config));
    spec.addBuilder("muscle", new tgLinearStringInfo(m_stringConfig));

    // Create your structureInfo
    tgStructureInfo structureInfo(prism, spec);

    std::cout << "tgPrismaticInfo::buildModel() 7" << std::endl;
    // Use the structureInfo to build our model
    structureInfo.buildInto(*prismatic, world);

    /* Now that the sub-structure has been created, attach it
    * to the super-structure
    * Very manual from here, since this is the only place we have all
    * of the necessary pointers
    *
    // We have to delete these
    std::vector<tgPair*> linkerPairs;

    // "From" side:
    linkerPairs.push_back(new tgPair(startNode, n1[0], tgString("anchor seg",1)));
    // "To" side:
    linkerPairs.push_back(new tgPair(n2[1], endNode, tgString("anchor seg",2)));

    // Perhaps overkill...
    // These pointers will be deleted by tgStructure
    std::vector <tgRigidInfo*> allRigids(structureInfo.getAllRigids());
    std::cout << "tgPrismaticInfo num rigids: " << allRigids.size() << std::endl;
    allRigids.push_back(getToRigidInfo());
    allRigids.push_back(getFromRigidInfo());

    // We have to delete these
    std::vector <tgConnectorInfo* > linkerInfo;

    // Can this part be done in a loop easily?
    linkerInfo.push_back(new tgLinearStringInfo(m_stringConfig, *linkerPairs[0]));
    linkerInfo.push_back(new tgLinearStringInfo(m_stringConfig, *linkerPairs[1]));

    for (std::size_t i = 0; i < linkerInfo.size(); i++)
    {
        linkerInfo[i]->chooseRigids(allRigids);
        linkerInfo[i]->initConnector(world);

        tgModel* m = linkerInfo[i]->createModel(world);
        m->setTags(linkerInfo[i]->getTags());
        if(m != 0) {
            prismatic->addChild(m);
        }
    }

    // Clean up - see if there's a way to do this with references instead?
    for (std::size_t i = 0; i < linkerInfo.size(); i++)
    {
        delete linkerInfo[i];
    }
    linkerInfo.clear();

    for (std::size_t i = 0; i < linkerPairs.size(); i++)
    {
        delete linkerPairs[i];
    }
    linkerPairs.clear();
    /**/

    std::cout << "tgPrismaticInfo::buildModel() 8" << std::endl;
    //not needed?
//    prismatic->setup(world);

#if(0)
    // Debug printing
    std::cout << "StructureInfo:" << std::endl;
    std::cout << structureInfo << std::endl;

    std::cout << "Model: " << std::endl;
    std::cout << *prismatic << std::endl;
#endif
}
<|endoftext|>