<commit_before>#include <assert.h>
#include <math.h>
#include <time.h>

#include <cstdlib>
#include <cstdio>
#include <string>

#include "../UCT.h"

const std::string patternsFile = "patterns.pat";

UCTNode *root;

// http://www.ai-junkie.com/ga/intro/gat2.html
const float mutationChance = 0.7f;
const float percentSurvivors = 0.05f;
const unsigned int populationSize = 100;
const unsigned int numGenerations = 200000;

// int is fitness
std::vector<std::pair<Patterns, int>> patternPopulation;
Patterns originalPatterns;

void selectSurvivors() {
  unsigned int numSurvivors = (int)(populationSize * percentSurvivors);
  if (numSurvivors < 1)
    ++numSurvivors;

  int newLineAmount = sqrt(populationSize);
  int count = 0;
  for (auto x : patternPopulation) {
    count++;
    printf("%d ", x.second);
    if (count == newLineAmount) {
      printf("\n");
      count = 0;
    }
  }
  printf("\n");

  std::vector<std::pair<Patterns, int>> survivors;
  for (unsigned int i = 0; i < numSurvivors; ++i) {
    auto best = patternPopulation[0];
    for (auto member : patternPopulation) {
      if (member.second > best.second) {
        bool found = false;
        for (auto survivor : survivors) {
          if (survivor.first == member.first) {
            found = true;
            break;
          }
        }
        if (!found)
          best = member;
      }
    }
    survivors.push_back(best);
  }

  // repopulate
  patternPopulation.clear();
  for (unsigned int i = 0; i < populationSize; ++i) {
    unsigned long int choice = rand() % survivors.size();

    Patterns chosen = survivors[choice].first;
    if (rand() % 100 > mutationChance * 100)
      chosen.mutate();

    patternPopulation.push_back(std::make_pair(chosen, 0));
  }
}

void determineFitness() {
  auto count = 0;
  for (auto& member : patternPopulation) {
    for (auto i = 0; i < 100; ++i) {
      Board b;
      b.init();

      GameResult r;
      auto turn = &member.first;
      Player turnColor = Black;
      while (!b.isGameOver(&r)) {
        b.makeMove(*turn->getMove(&b));
        turn = turnColor == Black ? &originalPatterns : &member.first;
        turnColor = turnColor == Black ? White : Black;
      }
      if ((Player)r == Black)
        ++member.second;
      else
        --member.second;
    }
    printf("%d score: %d\n", count, member.second);
    ++count;
  }
}

int main(void) {
  printf("PatternEvolution\n");

  srand((unsigned int)time(NULL));
  int randNumber = rand();
  char fileName[256];
  snprintf(fileName, sizeof(fileName), "savedPatterns/patterns%d.pat", randNumber);

  originalPatterns.init("patterns.pat");

  for (unsigned int i = 0; i < populationSize; ++i)
    patternPopulation.push_back(std::make_pair(originalPatterns, 0));

  selectSurvivors();
  auto best = patternPopulation[0];

  for (unsigned int i = 0; i < numGenerations; ++i) {
    std::cout << "Generation " << i << std::endl;
    determineFitness();
    if (i % 1 == 0) {
      best = patternPopulation[0];
      for (auto member : patternPopulation)
        if (member.second > best.second)
          best = member;
      best.first.save(fileName);
    }
    selectSurvivors();
  }

  determineFitness();
  best = patternPopulation[0];
  for (auto member : patternPopulation)
    if (member.second > best.second)
      best = member;
  best.first.save(fileName);

  return 0;
}
<commit_msg>Changed the likelihood of mutation for a Pattern to be proportional to the amount of the times that Pattern was seen<commit_after>#include <assert.h>
#include <math.h>
#include <time.h>

#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <string>

#include "../UCT.h"

const std::string patternsFile = "patterns.pat";

UCTNode *root;

// http://www.ai-junkie.com/ga/intro/gat2.html
const float mutationChance = 0.7f;
const float percentSurvivors = 0.1f;
const unsigned int populationSize = 9;
const unsigned int numGenerations = 200000;

// int is fitness
std::vector<std::pair<Patterns, int>> patternPopulation;
Patterns originalPatterns;

// int is numEncountered
std::vector<std::string> patternsEncountered;

void selectSurvivors() {
  unsigned int numSurvivors = (int)(populationSize * percentSurvivors);
  if (numSurvivors < 1)
    ++numSurvivors;

  int newLineAmount = sqrt(populationSize);
  int count = 0;
  float totalScore = 0;
  for (auto x : patternPopulation) {
    count++;
    printf("%d ", x.second);
    if (count == newLineAmount) {
      printf("\n");
      count = 0;
    }
    totalScore += (float)x.second;
  }
  printf("\nAverageScore: %f\n", totalScore / (float)patternPopulation.size());

  std::vector<std::pair<Patterns, int>> survivors;
  for (unsigned int i = 0; i < numSurvivors; ++i) {
    auto best = patternPopulation[0];
    for (auto member : patternPopulation) {
      if (member.second > best.second) {
        bool found = false;
        for (auto survivor : survivors) {
          if (survivor.first == member.first) {
            found = true;
            break;
          }
        }
        if (!found)
          best = member;
      }
    }
    survivors.push_back(best);
  }

  // repopulate
  patternPopulation.clear();
  for (unsigned int i = 0; i < populationSize; ++i) {
    unsigned long int choice = rand() % survivors.size();

    Patterns chosen = survivors[choice].first;
    if (rand() % 100 > mutationChance * 100) {
      if (patternsEncountered.size() > 0) {
        choice = rand() % patternsEncountered.size();
        chosen.mutatePattern(patternsEncountered[choice]);

        /*std::cout << choice << std::endl;
        std::cout << std::count(patternsEncountered.begin(), patternsEncountered.end(), patternsEncountered[choice])
          << " " << patternsEncountered.size() << std::endl;
        std::cout << (float)std::count(patternsEncountered.begin(), patternsEncountered.end(), patternsEncountered[choice])
          / (float)patternsEncountered.size() << std::endl;
        std::cout << patternsEncountered[choice] << std::endl;
        */
      }
    }

    patternPopulation.push_back(std::make_pair(chosen, 0));
  }
  // std::cout << patternsEncountered.size() << std::endl;
  patternsEncountered.clear();
}

void determineFitness() {
  auto count = 0;
  for (auto& member : patternPopulation) {
    for (auto i = 0; i < 10000; ++i) {
      Board b;
      b.init();

      GameResult r;
      auto turn = &member.first;
      Player turnColor = Black;
      while (!b.isGameOver(&r)) {
        b.makeMove(*turn->getMove(&b));
        turn = turnColor == Black ? &originalPatterns : &member.first;
        turnColor = turnColor == Black ? White : Black;

        Pattern lastMove(b.lastMove);
        if (lastMove.isLegalPattern())
          patternsEncountered.push_back(lastMove.hash);
      }
      if ((Player)r == Black)
        ++member.second;
      else
        --member.second;
    }
    ++count;
  }
}

int main(void) {
  printf("PatternEvolution\n");

  srand((unsigned int)time(NULL));
  int randNumber = rand();
  char fileName[256];
  snprintf(fileName, sizeof(fileName), "savedPatterns/patterns%d.pat", randNumber);

  originalPatterns.init("patterns.pat");

  for (unsigned int i = 0; i < populationSize; ++i)
    patternPopulation.push_back(std::make_pair(originalPatterns, 0));

  selectSurvivors();
  auto best = patternPopulation[0];

  for (unsigned int i = 0; i < numGenerations; ++i) {
    std::cout << "Generation " << i << std::endl;
    determineFitness();
    if (i % 1 == 0) {
      best = patternPopulation[0];
      for (auto member : patternPopulation)
        if (member.second > best.second)
          best = member;
      best.first.save(fileName);
    }
    selectSurvivors();
  }

  determineFitness();
  best = patternPopulation[0];
  for (auto member : patternPopulation)
    if (member.second > best.second)
      best = member;
  best.first.save(fileName);

  return 0;
}
<|endoftext|>


<commit_before>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.

// Copyright (c) 2012, 2013, 2014, 2015 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/sfm/sfm_data.hpp"
#include "openMVG/sfm/sfm_data_io.hpp"
#include "openMVG/stl/stlMap.hpp"

#include "software/SfM/tools_precisionEvaluationToGt.hpp"
#include "software/SfM/SfMPlyHelper.hpp"

#include "software/SfM/import/io_readGTInterface.hpp"
#include "software/SfM/import/io_readGTStrecha.hpp"

#include "third_party/cmdLine/cmdLine.h"
#include "third_party/htmlDoc/htmlDoc.hpp"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"

#include <cstdlib>

using namespace openMVG;
using namespace openMVG::sfm;
using namespace openMVG::cameras;

int main(int argc, char **argv)
{
  using namespace std;

  CmdLine cmd;

  std::string
    sGTDirectory,
    sComputedDirectory,
    sOutDir = "";

  cmd.add( make_option('i', sGTDirectory, "gt") );
  cmd.add( make_option('c', sComputedDirectory, "computed") );
  cmd.add( make_option('o', sOutDir, "outdir") );

  try {
    if (argc == 1) throw std::string("Invalid command line parameter.");
    cmd.process(argc, argv);
  } catch (const std::string& s) {
    std::cerr << "Usage: " << argv[0] << '\n'
      << "[-i|--gt] path (where the ground truth dataset is saved).\n"
      << "[-c|--computed] path to the sfm_data file to compare.\n"
      << "[-o|--output] path (where the registration statistics will be saved).\n"
      << std::endl;

    std::cerr << s << std::endl;
    return EXIT_FAILURE;
  }

  if (sOutDir.empty())  {
    std::cerr << "\nIt is an invalid output directory" << std::endl;
    return EXIT_FAILURE;
  }

  if (!stlplus::folder_exists(sOutDir))
    stlplus::folder_create(sOutDir);

  //---------------------------------------
  // Quality evaluation
  //---------------------------------------

  // 1. Initialize the GT:
  //
  std::shared_ptr<SfM_Data_GT_Loader_Interface> sfm_data_gt_loader =
      std::make_shared<SfM_Data_GT_Loader_Strecha>();

  // Load the gt data
  if (!sfm_data_gt_loader->run(
        stlplus::folder_append_separator(sGTDirectory) + "gt_dense_cameras",
        stlplus::folder_append_separator(sGTDirectory) + "images"))
  {
    std::cerr << "Cannot initialize the GT dataset." << std::endl;
    return EXIT_FAILURE;
  }
  const SfM_Data sfm_data_gt = sfm_data_gt_loader->GetSfMData();

  // 2. Load the scene to compare
  //
  SfM_Data sfm_data_to_compare;
  if (!Load(sfm_data_to_compare, sComputedDirectory, ESfM_Data(VIEWS|INTRINSICS|EXTRINSICS))) {
    std::cerr << std::endl
      << "The input SfM_Data file \""<< sComputedDirectory << "\" cannot be read." << std::endl;
    return EXIT_FAILURE;
  }
  // Assert that GT and loaded scene have the same camera count
  if (sfm_data_gt.GetPoses().size() != sfm_data_to_compare.GetPoses().size())
  {
    std::cerr << std::endl
      << "Dataset poses count does not match." << "\n"
      << "#GT poses: " << sfm_data_gt.GetPoses().size() << "\n"
      << "#Scene poses: " << sfm_data_to_compare.GetPoses().size() << std::endl;
    return EXIT_FAILURE;
  }

  // Assert that the sfm_data files have the same camera's id_pose.
  {
    // Collect GT pose_ids.
    std::set<IndexT> pose_id_gt;
    std::transform(
      sfm_data_gt.GetPoses().cbegin(),
      sfm_data_gt.GetPoses().cend(),
      std::inserter(pose_id_gt, pose_id_gt.begin()),
      stl::RetrieveKey());

    // Collect the sfm_data to compare pose_ids.
    std::set<IndexT> pose_id_to_compare;
    std::transform(
      sfm_data_to_compare.GetPoses().cbegin(),
      sfm_data_to_compare.GetPoses().cend(),
      std::inserter(pose_id_to_compare, pose_id_to_compare.begin()),
      stl::RetrieveKey());

    // Check if the pose_id intersect or not
    std::vector<IndexT> pose_id_intersection;
    std::set_intersection(pose_id_gt.cbegin(), pose_id_gt.cend(),
                          pose_id_to_compare.cbegin(), pose_id_to_compare.cend(),
                          std::back_inserter(pose_id_intersection));

    if (pose_id_gt.empty() || pose_id_to_compare.empty()
        || pose_id_intersection.size() != sfm_data_gt.GetPoses().size())
    {
      std::cerr << "Invalid data input. "
       << "The dataset does not have corresponding camera Ids." << std::endl;
      return EXIT_FAILURE;
    }
  }

  // 3. Find corresponding camera pose data:
  //
  std::vector<Vec3> camera_pos_gt, camera_pos_to_compare;
  std::vector<Mat3> camera_rot_gt, camera_rot_to_compare;

  for (const auto & pose_gt_it : sfm_data_gt.GetPoses())
  {
    const IndexT pose_id = pose_gt_it.first;
    //sfm_data_gt.GetPoses().count(pose_id)
    const auto & pose_to_compare_it = sfm_data_gt.GetPoses().at(pose_id);

    camera_pos_gt.push_back(pose_gt_it.second.center());
    camera_rot_gt.push_back(pose_gt_it.second.rotation());

    camera_pos_to_compare.push_back(pose_to_compare_it.center());
    camera_rot_to_compare.push_back(pose_to_compare_it.rotation());
  }

  // Visual output of the camera location
  plyHelper::exportToPly(camera_pos_gt, string(stlplus::folder_append_separator(sOutDir) + "camGT.ply").c_str());
  plyHelper::exportToPly(camera_pos_to_compare, string(stlplus::folder_append_separator(sOutDir) + "camComputed.ply").c_str());

  // Evaluation
  htmlDocument::htmlDocumentStream _htmlDocStream("openMVG Quality evaluation.");
  EvaluteToGT(camera_pos_gt, camera_pos_to_compare,
    camera_rot_gt, camera_rot_to_compare,
    sOutDir, &_htmlDocStream);

  ofstream htmlFileStream( string(stlplus::folder_append_separator(sOutDir) +
    "ExternalCalib_Report.html").c_str());
  htmlFileStream << _htmlDocStream.getDoc();

  return EXIT_SUCCESS;
}
<commit_msg>[Software] Fix main_evalQuality Ground tuth was comparing against itself<commit_after>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.

// Copyright (c) 2012, 2013, 2014, 2015 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/sfm/sfm_data.hpp"
#include "openMVG/sfm/sfm_data_io.hpp"
#include "openMVG/stl/stlMap.hpp"

#include "software/SfM/tools_precisionEvaluationToGt.hpp"
#include "software/SfM/SfMPlyHelper.hpp"

#include "software/SfM/import/io_readGTInterface.hpp"
#include "software/SfM/import/io_readGTStrecha.hpp"

#include "third_party/cmdLine/cmdLine.h"
#include "third_party/htmlDoc/htmlDoc.hpp"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"

#include <cstdlib>

using namespace openMVG;
using namespace openMVG::sfm;
using namespace openMVG::cameras;

int main(int argc, char **argv)
{
  using namespace std;

  CmdLine cmd;

  std::string
    sGTDirectory,
    sComputedDirectory,
    sOutDir = "";

  cmd.add( make_option('i', sGTDirectory, "gt") );
  cmd.add( make_option('c', sComputedDirectory, "computed") );
  cmd.add( make_option('o', sOutDir, "outdir") );

  try {
    if (argc == 1) throw std::string("Invalid command line parameter.");
    cmd.process(argc, argv);
  } catch (const std::string& s) {
    std::cerr << "Usage: " << argv[0] << '\n'
      << "[-i|--gt] path (where the ground truth dataset is saved).\n"
      << "[-c|--computed] path to the sfm_data file to compare.\n"
      << "[-o|--output] path (where the registration statistics will be saved).\n"
      << std::endl;

    std::cerr << s << std::endl;
    return EXIT_FAILURE;
  }

  if (sOutDir.empty())  {
    std::cerr << "\nIt is an invalid output directory" << std::endl;
    return EXIT_FAILURE;
  }

  if (!stlplus::folder_exists(sOutDir))
    stlplus::folder_create(sOutDir);

  //---------------------------------------
  // Quality evaluation
  //---------------------------------------

  // 1. Initialize the GT:
  //
  std::shared_ptr<SfM_Data_GT_Loader_Interface> sfm_data_gt_loader =
      std::make_shared<SfM_Data_GT_Loader_Strecha>();

  // Load the gt data
  if (!sfm_data_gt_loader->run(
        stlplus::folder_append_separator(sGTDirectory) + "gt_dense_cameras",
        stlplus::folder_append_separator(sGTDirectory) + "images"))
  {
    std::cerr << "Cannot initialize the GT dataset." << std::endl;
    return EXIT_FAILURE;
  }
  const SfM_Data sfm_data_gt = sfm_data_gt_loader->GetSfMData();

  // 2. Load the scene to compare
  //
  SfM_Data sfm_data_to_compare;
  if (!Load(sfm_data_to_compare, sComputedDirectory, ESfM_Data(VIEWS|INTRINSICS|EXTRINSICS))) {
    std::cerr << std::endl
      << "The input SfM_Data file \""<< sComputedDirectory << "\" cannot be read." << std::endl;
    return EXIT_FAILURE;
  }
  // Assert that GT and loaded scene have the same camera count
  if (sfm_data_gt.GetPoses().size() != sfm_data_to_compare.GetPoses().size())
  {
    std::cerr << std::endl
      << "Dataset poses count does not match." << "\n"
      << "#GT poses: " << sfm_data_gt.GetPoses().size() << "\n"
      << "#Scene poses: " << sfm_data_to_compare.GetPoses().size() << std::endl;
    return EXIT_FAILURE;
  }

  // Assert that the sfm_data files have the same camera's id_pose.
  {
    // Collect GT pose_ids.
    std::set<IndexT> pose_id_gt;
    std::transform(
      sfm_data_gt.GetPoses().cbegin(),
      sfm_data_gt.GetPoses().cend(),
      std::inserter(pose_id_gt, pose_id_gt.begin()),
      stl::RetrieveKey());

    // Collect the sfm_data to compare pose_ids.
    std::set<IndexT> pose_id_to_compare;
    std::transform(
      sfm_data_to_compare.GetPoses().cbegin(),
      sfm_data_to_compare.GetPoses().cend(),
      std::inserter(pose_id_to_compare, pose_id_to_compare.begin()),
      stl::RetrieveKey());

    // Check if the pose_id intersect or not
    std::vector<IndexT> pose_id_intersection;
    std::set_intersection(pose_id_gt.cbegin(), pose_id_gt.cend(),
                          pose_id_to_compare.cbegin(), pose_id_to_compare.cend(),
                          std::back_inserter(pose_id_intersection));

    if (pose_id_gt.empty() || pose_id_to_compare.empty()
        || pose_id_intersection.size() != sfm_data_gt.GetPoses().size())
    {
      std::cerr << "Invalid data input. "
       << "The dataset does not have corresponding camera Ids." << std::endl;
      return EXIT_FAILURE;
    }
  }

  // 3. Find corresponding camera pose data:
  //
  std::vector<Vec3> camera_pos_gt, camera_pos_to_compare;
  std::vector<Mat3> camera_rot_gt, camera_rot_to_compare;

  for (const auto & pose_gt_it : sfm_data_gt.GetPoses())
  {
    const IndexT pose_id = pose_gt_it.first;
    //sfm_data_gt.GetPoses().count(pose_id)
    const auto & pose_to_compare_it = sfm_data_to_compare.GetPoses().at(pose_id);

    camera_pos_gt.push_back(pose_gt_it.second.center());
    camera_rot_gt.push_back(pose_gt_it.second.rotation());

    camera_pos_to_compare.push_back(pose_to_compare_it.center());
    camera_rot_to_compare.push_back(pose_to_compare_it.rotation());
  }

  // Visual output of the camera location
  plyHelper::exportToPly(camera_pos_gt, string(stlplus::folder_append_separator(sOutDir) + "camGT.ply").c_str());
  plyHelper::exportToPly(camera_pos_to_compare, string(stlplus::folder_append_separator(sOutDir) + "camComputed.ply").c_str());

  // Evaluation
  htmlDocument::htmlDocumentStream _htmlDocStream("openMVG Quality evaluation.");
  EvaluteToGT(camera_pos_gt, camera_pos_to_compare,
    camera_rot_gt, camera_rot_to_compare,
    sOutDir, &_htmlDocStream);

  ofstream htmlFileStream( string(stlplus::folder_append_separator(sOutDir) +
    "ExternalCalib_Report.html").c_str());
  htmlFileStream << _htmlDocStream.getDoc();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelsoundsettingsapplet.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "alerttone.h"
#include "trackerconnection.h"

#ifdef HAVE_LIBPROFILE
#include <profiled/libprofile.h>
#endif

#undef DEBUG
#define WARNING
#include "../debug.h"

/*!
 * The constructor of the class sets the key that can't be changed later.
 */
AlertTone::AlertTone(
        const QString &key):
	QProfileValue(key, true)
{
    SYS_DEBUG ("*** key = %s", SYS_STR(key));
    /*
     * TrackerConnection might send a signal about the tracker answer when it is
     * available.
     */
    connect (TrackerConnection::instance (),
             SIGNAL (dataReady (QString,QString,QString)),
             SLOT (dataReceived (QString,QString,QString)));
}

/*!
 * A method for getting AlertTone objects for all
 * available settings (ringing, voip, email, sms, im)
 *
 * \return AlertTone instances...
 */
QList<AlertTone *>
AlertTone::alertTones ()
{
    QList<AlertTone *> v;

#ifdef HAVE_LIBPROFILE
    QList<QString> keys;

    profileval_t *vals = profile_get_values(NULL);
    if (vals)
    {
        for (int profile = 0 ; vals[profile].pv_key != NULL ; profile++)
        {
            QStringList split_key =
                QString (vals[profile].pv_key).split ('.');

            if (split_key.size() == 3)
            {
                if (split_key[0] != "clock" &&
                    split_key[1] == "alert" &&
                    split_key[2] == "tone")
                    keys.push_back (vals[profile].pv_key);
            }
        }
        profile_free_values (vals);
    }

    QList<QString> list;
    list << "ringing.alert.tone"
          << "voip.alert.tone"
          << "email.alert.tone"
          << "sms.alert.tone"
          << "im.alert.tone"
          << "calendar.alert.tone";

    for (int i = 0 ; i < list.size() ; i++)
    {
        if  (keys.contains(list.at(i)))
        {
            keys.removeOne(list.at(i));
            v << new AlertTone(QString(list.at(i)) + "@general");
        }
    }

    for (int i = 0 ; i < keys.size() ; i++ )
        v << new AlertTone(QString(keys.at(i)));
#endif

    return v;
}

/*!
 * \returns The human readable name of the sound file.
 *
 * For the sound files under the /home directory this method will return the
 * sound file title provided by the tracker subsystem by reading the sound file
 * itself. For files under a different diretory the method will create the nice
 * name from the filename, because tracker will not provide file information for
 * these files. In this case the nice name is created from the basename of the
 * file by removing the file extension and changing underscore ('-') characters
 * to spaces (' ').
 */
QString
AlertTone::niceName()
{
    maybeUpdate();
    return m_niceName;
}

/*!
 * \returns the tracker-id of the sound file when it is available.
 */
QString
AlertTone::trackerId()
{
    maybeUpdate();
    return m_trackerId;
}

void
AlertTone::maybeUpdate()
{
    if (m_val.isNull()) {
        SYS_DEBUG ("m_val is NULL...");
        m_niceName =  "";
        m_trackerId = "";
        fetchFromBackend();
    } else if (m_niceName.isEmpty()) {
        m_niceName = TrackerConnection::instance()->niceNameFromFileName (
        m_val.toString());
    }
}

void
AlertTone::realSetValue(
        const QVariant &newValue)
{
    if (m_val != newValue) {
        m_niceName.clear();
        m_trackerId.clear();
        QProfileValue::realSetValue(newValue);
    }
}

void
AlertTone::fetchFromBackend()
{
    QProfileValue::fetchFromBackend();
    m_niceName = TrackerConnection::instance()->niceNameFromFileName (
            m_val.toString());
}

/*!
 * \returns The full path of the currently set sound file.
 */
QString
AlertTone::fileName()
{
    QProfileValue::fetchFromBackend();

    if (!m_val.isNull())
        return m_val.toString();

    return QString("");
}

void
AlertTone::dataReceived (
            const QString   &filename,
            const QString   &title,
            const QString   &trackerId)
{
    if (!m_val.isNull() && m_val.toString() == filename) {
        SYS_DEBUG ("Got an answer...");
        m_niceName = title;
        m_trackerId = trackerId;
        emit refreshed();
    }
}

<commit_msg>Changes: SoundSettingsApplet: small speed enhancements in AlertTone class<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelsoundsettingsapplet.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "alerttone.h"
#include "trackerconnection.h"

#include <QList>
#include <QVector>
#include <QString>

#ifdef HAVE_LIBPROFILE
#include <profiled/libprofile.h>
#endif

/*
 * This causes small slow-down, but ensures whether all the
 * profile keys are exists (lets disable it for now...)
 */
#undef WANT_PROFILED_CHECKS

#undef DEBUG
#define WARNING
#include "../debug.h"

/*!
 * The constructor of the class sets the key that can't be changed later.
 */
AlertTone::AlertTone(
        const QString &key):
	QProfileValue(key, true)
{
    SYS_DEBUG ("*** key = %s", SYS_STR(key));
    /*
     * TrackerConnection might send a signal about the tracker answer when it is
     * available.
     */
    connect (TrackerConnection::instance (),
             SIGNAL (dataReady (QString,QString,QString)),
             SLOT (dataReceived (QString,QString,QString)));
}

/*!
 * A method for getting AlertTone objects for all
 * available settings (ringing, voip, email, sms, im)
 *
 * \return AlertTone instances...
 */
QList<AlertTone *>
AlertTone::alertTones ()
{
    QList<AlertTone *> v;

#ifdef HAVE_LIBPROFILE
#ifdef WANT_PROFILED_CHECKS
    QList<QString> keys;

    profileval_t *vals = profile_get_values(NULL);
    if (vals)
    {
        for (int profile = 0 ; vals[profile].pv_key != NULL ; profile++)
        {
            QStringList split_key =
                QString (vals[profile].pv_key).split ('.');

            if (split_key.size() == 3)
            {
                if (split_key[0] != "clock" &&
                    split_key[1] == "alert" &&
                    split_key[2] == "tone")
                    keys.push_back (vals[profile].pv_key);
            }
        }
        profile_free_values (vals);
    }

    QVector<QString> toneKeys (0);
    toneKeys << "ringing.alert.tone"
             << "voip.alert.tone"
             << "email.alert.tone"
             << "sms.alert.tone"
             << "im.alert.tone"
             << "calendar.alert.tone";

    for (int i = 0 ; i < toneKeys.size() ; i++)
    {
        if (keys.contains (toneKeys.at (i)))
        {
            keys.removeOne (toneKeys.at (i));
            v << new AlertTone (QString (toneKeys.at (i)) + "@general");
        }
    }
#else // do not WANT_PROFILED_CHECKS
    QVector<QString> toneKeys (0);
    toneKeys << "ringing.alert.tone@general"
             << "voip.alert.tone@general"
             << "email.alert.tone@general"
             << "sms.alert.tone@general"
             << "im.alert.tone@general"
             << "calendar.alert.tone@general";

    for (int i = 0; i < toneKeys.size (); i++)
    {
        v << new AlertTone (toneKeys.at (i));
    }
#endif
#endif // HAVE_LIBPROFILE

    return v;
}

/*!
 * \returns The human readable name of the sound file.
 *
 * For the sound files under the /home directory this method will return the
 * sound file title provided by the tracker subsystem by reading the sound file
 * itself. For files under a different diretory the method will create the nice
 * name from the filename, because tracker will not provide file information for
 * these files. In this case the nice name is created from the basename of the
 * file by removing the file extension and changing underscore ('-') characters
 * to spaces (' ').
 */
QString
AlertTone::niceName()
{
    maybeUpdate();
    return m_niceName;
}

/*!
 * \returns the tracker-id of the sound file when it is available.
 */
QString
AlertTone::trackerId()
{
    maybeUpdate();
    return m_trackerId;
}

void
AlertTone::maybeUpdate()
{
    if (m_val.isNull()) {
        SYS_DEBUG ("m_val is NULL...");
        m_niceName =  "";
        m_trackerId = "";
        fetchFromBackend();
    } else if (m_niceName.isEmpty()) {
        m_niceName = TrackerConnection::instance()->niceNameFromFileName (
        m_val.toString());
    }
}

void
AlertTone::realSetValue(
        const QVariant &newValue)
{
    if (m_val != newValue) {
        m_niceName.clear();
        m_trackerId.clear();
        QProfileValue::realSetValue(newValue);
    }
}

void
AlertTone::fetchFromBackend()
{
    QProfileValue::fetchFromBackend();
    m_niceName = TrackerConnection::instance()->niceNameFromFileName (
            m_val.toString());
}

/*!
 * \returns The full path of the currently set sound file.
 */
QString
AlertTone::fileName()
{
    if (m_val.isNull ())
        QProfileValue::fetchFromBackend ();

    if (!m_val.isNull ())
        return m_val.toString ();

    return QString ("");
}

void
AlertTone::dataReceived (
            const QString   &filename,
            const QString   &title,
            const QString   &trackerId)
{
    if (!m_val.isNull() && m_val.toString() == filename) {
        SYS_DEBUG ("Got an answer...");
        m_niceName = title;
        m_trackerId = trackerId;
        emit refreshed();
    }
}

<|endoftext|>


<commit_before>
#include "Mutex.h"

int g_lockdep = 0;

#ifdef LOCKDEP

#include "include/types.h"
#include "Clock.h"
#include "BackTrace.h"

#include <hash_map>

#include "config.h"

#define  dout(l)    if (l<=g_conf.debug_lockdep) *_dout << g_clock.now() << " " << pthread_self() << " lockdep: "
#define  derr(l)    if (l<=g_conf.debug_lockdep) *_derr << g_clock.now() << " " << pthread_self() << " lockdep: "

pthread_mutex_t lockdep_mutex = PTHREAD_MUTEX_INITIALIZER;

hash_map<pthread_t, map<const char *, BackTrace *> > held;
hash_map<const char *, map<const char *, BackTrace *> > follows;       // <left item> follows <right items>
hash_map<const char *, map<const char *, BackTrace *> > follows_ever;

#define BACKTRACE_SKIP 3

// does a follow b?
bool does_follow(const char *a, const char *b)
{
  if (!follows.count(a))
    return false;

  map<const char *, BackTrace *> &s = follows[a];
  if (s.count(b)) {
    dout(0) << "------------------------------------" << std::endl;
    dout(0) << a << " <- " << b << " at: " << std::endl;
    s[b]->print(*_dout);
    *_dout << std::endl;
    return true;
  }

  for (map<const char *, BackTrace *>::iterator p = s.begin(); p != s.end(); p++)
    if (does_follow(p->first, b)) {
      dout(0) << a << " <- " << p->first << " at: " << std::endl;
      p->second->print(*_dout);
      *_dout << std::endl;
      return true;
    }

  return false;
}

void Mutex::_will_lock()
{
  pthread_t p = pthread_self();

  dout(20) << name << " _will_lock" << std::endl;

  pthread_mutex_lock(&lockdep_mutex);

  // check dependency graph
  map<const char *, BackTrace *> &m = held[p];
  for (map<const char *, BackTrace *>::iterator p = m.begin();
       p != m.end();
       p++) {
    if (!follows[name].count(p->first)) {
      // new dependency

      // did we just create a cycle?
      BackTrace *bt = new BackTrace(BACKTRACE_SKIP);
      if (does_follow(p->first, name)) {
	dout(0) << "new dependency " << name << " <- " << p->first
		<< " creates a cycle at"
		<< std::endl;
	bt->print(*_dout);
	*_dout << std::endl;
	*_dout << std::endl;
	*_dout << std::endl;

	// don't add this dependency, or we'll get aMutex. cycle in the graph, and
	// does_follow() won't terminate.
      } else {
	follows[name][p->first] = bt;
	dout(10) << name << " <- " << p->first << " at" << std::endl;
	//bt->print(*_dout);
      }
    }
  }

  pthread_mutex_unlock(&lockdep_mutex);
}

void Mutex::_locked()
{
  BackTrace *bt = new BackTrace(BACKTRACE_SKIP);
  pthread_t p = pthread_self();

  dout(20) << name << " _locked" << std::endl;

  pthread_mutex_lock(&lockdep_mutex);
  held[p][name] = bt;
  pthread_mutex_unlock(&lockdep_mutex);
}

void Mutex::_unlocked()
{
  pthread_t p = pthread_self();

  dout(20) << name << " _unlocked" << std::endl;
  pthread_mutex_lock(&lockdep_mutex);
  assert(held.count(p));
  assert(held[p].count(name));
  delete held[p][name];
  held[p].erase(name);
  pthread_mutex_unlock(&lockdep_mutex);
}

#endif
<commit_msg>lockdep: fix include<commit_after>
#include "Mutex.h"

int g_lockdep = 0;

#ifdef LOCKDEP

#include "include/types.h"
#include "Clock.h"
#include "BackTrace.h"

#include <ext/hash_map>

#include "config.h"

#define  dout(l)    if (l<=g_conf.debug_lockdep) *_dout << g_clock.now() << " " << pthread_self() << " lockdep: "
#define  derr(l)    if (l<=g_conf.debug_lockdep) *_derr << g_clock.now() << " " << pthread_self() << " lockdep: "

pthread_mutex_t lockdep_mutex = PTHREAD_MUTEX_INITIALIZER;

hash_map<pthread_t, map<const char *, BackTrace *> > held;
hash_map<const char *, map<const char *, BackTrace *> > follows;       // <left item> follows <right items>
hash_map<const char *, map<const char *, BackTrace *> > follows_ever;

#define BACKTRACE_SKIP 3

// does a follow b?
bool does_follow(const char *a, const char *b)
{
  if (!follows.count(a))
    return false;

  map<const char *, BackTrace *> &s = follows[a];
  if (s.count(b)) {
    dout(0) << "------------------------------------" << std::endl;
    dout(0) << a << " <- " << b << " at: " << std::endl;
    s[b]->print(*_dout);
    *_dout << std::endl;
    return true;
  }

  for (map<const char *, BackTrace *>::iterator p = s.begin(); p != s.end(); p++)
    if (does_follow(p->first, b)) {
      dout(0) << a << " <- " << p->first << " at: " << std::endl;
      p->second->print(*_dout);
      *_dout << std::endl;
      return true;
    }

  return false;
}

void Mutex::_will_lock()
{
  pthread_t p = pthread_self();

  dout(20) << name << " _will_lock" << std::endl;

  pthread_mutex_lock(&lockdep_mutex);

  // check dependency graph
  map<const char *, BackTrace *> &m = held[p];
  for (map<const char *, BackTrace *>::iterator p = m.begin();
       p != m.end();
       p++) {
    if (!follows[name].count(p->first)) {
      // new dependency

      // did we just create a cycle?
      BackTrace *bt = new BackTrace(BACKTRACE_SKIP);
      if (does_follow(p->first, name)) {
	dout(0) << "new dependency " << name << " <- " << p->first
		<< " creates a cycle at"
		<< std::endl;
	bt->print(*_dout);
	*_dout << std::endl;
	*_dout << std::endl;
	*_dout << std::endl;

	// don't add this dependency, or we'll get aMutex. cycle in the graph, and
	// does_follow() won't terminate.
      } else {
	follows[name][p->first] = bt;
	dout(10) << name << " <- " << p->first << " at" << std::endl;
	//bt->print(*_dout);
      }
    }
  }

  pthread_mutex_unlock(&lockdep_mutex);
}

void Mutex::_locked()
{
  BackTrace *bt = new BackTrace(BACKTRACE_SKIP);
  pthread_t p = pthread_self();

  dout(20) << name << " _locked" << std::endl;

  pthread_mutex_lock(&lockdep_mutex);
  held[p][name] = bt;
  pthread_mutex_unlock(&lockdep_mutex);
}

void Mutex::_unlocked()
{
  pthread_t p = pthread_self();

  dout(20) << name << " _unlocked" << std::endl;
  pthread_mutex_lock(&lockdep_mutex);
  assert(held.count(p));
  assert(held[p].count(name));
  delete held[p][name];
  held[p].erase(name);
  pthread_mutex_unlock(&lockdep_mutex);
}

#endif
<|endoftext|>


<commit_before>#include "Server.hpp"
#include "FileHandler.hpp"
#include "CommandHandler.hpp"

#include <memory>

//Define constants
const int Server::BUFFER_SIZE = 16384;

//Define static
std::mutex Server::m;
std::string Server::thePath = "";

//Constructor
Server::Server(int s) : sock(s) { RUN_ONCE
	sstr s2; s2 << "Child server has started.";
	FileHandler::log(s2);
	start();
}

//Destructor
Server::~Server() {
	sstr s2; s2 << "Client disconnected from server.";
	FileHandler::userQuit(me());
	FileHandler::log(s2);
}

//Get the current path
std::string Server::getPath() {
	std::lock_guard<std::mutex> m2(m);
	auto ret = thePath; return ret;
}

//Change the path, if it changed, log it
void Server::setPath(const std::string& s) {
	std::lock_guard<std::mutex> m2(m);
	if (s != thePath) {
		sstr s2; s2 << "Path changed to \"" << s << "\"";
		FileHandler::log(s2); thePath = s;
	}
}

//Log and send a string
inline void respond(int sock, std::string&& s) {
	FileHandler::log(s);
	Assert(send( sock, s.data(), s.size(), 0) == s.size(), "send() failed.");
}

//The function that runs the server
void Server::start() { RUN_ONCE

	//Create a buffer
	char buf[BUFFER_SIZE+1]; buf[BUFFER_SIZE] = 0;

	//Loop and recieve data from the client
	for(int n; (n = (int)recv( sock, buf, BUFFER_SIZE, 0 ) ); ) {

		//Check for errors or disconnects
		if (n < 0) Err("recv() failed");
		else if (!n) return;
		else buf[n] = 0;

		//Ignore prepended whitespace
		int i; for(i = 0; i < n; i++)
			if (buf[i] && !isspace(buf[i])) break;

		//If an empty string was recieved, note so then continue
		if (i == n) {
			respond( sock, "Empty string recieved\n" );
			//TODO
			continue;
		}

		//Find the command
		int k; for(k = i + 1; k < n; k++)
			if (!buf[k] || isspace(buf[k])) break;

		if (k == n) {
			respond( sock, "Incomplete command recieved\n" );
			//TODO
			continue;
		}

		//Create needed strings string of arguments
		std::string args(&buf[k+1], n-(k+1));
		std::string cmd(&buf[i], k-i);

		//Log the command, or at least part of it
		sstr s2; s2 << "Running command: " << cmd << '\n';
		respond(sock, s2.str());
		FileHandler::log(s2);

		//TODO: change, thread
		//Run the command and send the result
		std::string output = CommandHandler::runCmd( std::move(cmd),
													 std::move(args), false );

		//If there is output
		if (output.size()) {

			//Log it
			sstr s; s << "Server sent: " << output;
			FileHandler::log(s);

			//Reply to the client
			Assert( send(sock, output.data(), output.size(), 0) == output.size(),
			        "send() failed." );
		}
	}
}
<commit_msg>Threading enabled<commit_after>#include "Server.hpp"
#include "FileHandler.hpp"
#include "CommandHandler.hpp"

#include <memory>

//Define constants
const int Server::BUFFER_SIZE = 16384;

//Define static
std::mutex Server::m;
std::string Server::thePath = "";

//Constructor
Server::Server(int s) : sock(s) { RUN_ONCE
	sstr s2; s2 << "Child server has started.";
	FileHandler::log(s2);
	start();
}

//Destructor
Server::~Server() {
	sstr s2; s2 << "Client disconnected from server.";
	FileHandler::userQuit(me());
	FileHandler::log(s2);
}

//Get the current path
std::string Server::getPath() {
	std::lock_guard<std::mutex> m2(m);
	auto ret = thePath; return ret;
}

//Change the path, if it changed, log it
void Server::setPath(const std::string& s) {
	std::lock_guard<std::mutex> m2(m);
	if (s != thePath) {
		sstr s2; s2 << "Path changed to \"" << s << "\"";
		FileHandler::log(s2); thePath = s;
	}
}

//Log and send a string
inline void respond(int sock, std::string&& s) {
	FileHandler::log(s);
	Assert(send( sock, s.data(), s.size(), 0) == s.size(), "send() failed.");
}

//The function that runs the server
void Server::start() { RUN_ONCE

	//Local variables
	bool newThread;
	int i, k;

	//Create a buffer
	char buf[BUFFER_SIZE+1]; buf[BUFFER_SIZE] = 0;

	//Loop and recieve data from the client
	for(int n; (n = (int)recv( sock, buf, BUFFER_SIZE, 0 ) ); ) {

		//Check for errors or disconnects
		if (n < 0) Err("recv() failed");
		else if (!n) return;
		else buf[n] = 0;

		//Check if threading should be done
		i = 0; if (buf[0] == '&') i++;
		newThread = i;

		//Ignore prepended whitespace
		for(; i < n; i++) if (buf[i] && !isspace(buf[i])) break;

		//If an empty string was recieved, note so then continue
		if (i == n) {
			respond( sock, "Empty string recieved\n" );
			//TODO
			continue;
		}

		//Find the command
		for(k = i + 1; k < n; k++) if (!buf[k] || isspace(buf[k])) break;

		if (k == n) {
			respond( sock, "Incomplete command recieved\n" );
			//TODO
			continue;
		}

		//Create needed strings string of arguments
		std::string args(&buf[k+1], n-(k+1));
		std::string cmd(&buf[i], k-i);

		//Log the command, or at least part of it
		sstr s2; s2 << "Running command: " << cmd << '\n';
		respond(sock, s2.str());
		FileHandler::log(s2);

		//TODO: change, thread
		//Run the command and send the result
		std::string output = CommandHandler::runCmd( std::move(cmd),
													 std::move(args), newThread );

		//If there is output
		if (output.size()) {

			//Log it
			sstr s; s << "Server sent: " << output;
			FileHandler::log(s);

			//Reply to the client
			Assert( send(sock, output.data(), output.size(), 0) == output.size(),
			        "send() failed." );
		}
	}
}
<|endoftext|>


<commit_before>#include <AnnotatorLib/Commands/NewAnnotation.h>
#include <AnnotatorLib/Commands/UpdateAnnotation.h>
#include <QMenu>
#include <QObject>

#include "annotationgraphicsitem.h"
#include "plugins/pluginloader.h"
#include "gui/newobjectdialog.h"

AnnotatorLib::Annotation *AnnotationGraphicsItem::getAnnotation() {
  return annotation;
}

AnnotationGraphicsItem::AnnotationGraphicsItem(
    AnnotatorLib::Annotation *annotation)
    : QGraphicsItem::QGraphicsItem(nullptr) {
  assert(annotation);
  this->annotation = annotation;

  if (annotation->getObject() == nullptr)
    borderColor = idToColor(annotation->getId());
  else
    borderColor = idToColor(annotation->getObject()->getId());

  setPos(annotation->getX(), annotation->getY());
  initCorners();
  initIdText();

  rectX = 0;
  rectY = 0;
  width = annotation->getWidth();
  height = annotation->getHeight();
  cornerXPos = 0;
  cornerYPos = 0;
  cornerWidth = width, cornerHeight = height,

  originColor = borderColor;
}

AnnotationGraphicsItem::~AnnotationGraphicsItem() {
  for (int i = 0; i < 4; ++i) {
    delete corners[i];
  }
}

static double r_ = (1 + sqrt(5)) / 2;
static double g_ = (3 + sqrt(7)) / 2;
static double b_ = (11 + sqrt(13)) / 2;

QColor AnnotationGraphicsItem::idToColor(long id) {
  double r = id * r_ - floor(id * r_);
  double g = id * g_ - floor(id * g_);
  double b = id * b_ - floor(id * b_);
  return QColor(r * 255, g * 255, b * 255);
}

void AnnotationGraphicsItem::setPlayer(Player *player) {
  this->player = player;
}

void AnnotationGraphicsItem::initCorners() {
  for (int i = 0; i < 4; ++i) {
    corners[i] = new Corner(this, i);
    corners[i]->hide();
    // corners[i]->installSceneEventFilter(this);
  }
  setCornerPositions();
}

void AnnotationGraphicsItem::initIdText() {
  if (annotation) {
    idText.setParentItem(this);
    idText.setDefaultTextColor(borderColor);
    idText.setPlainText(QString::number(annotation->getId()));

    idText.setPos(rectX, rectY - 20);
    idText.hide();
  }
}

void AnnotationGraphicsItem::mouseDoubleClickEvent(
    QGraphicsSceneMouseEvent *event) {
  QGraphicsItem::mouseDoubleClickEvent(event);
  if (this->player != nullptr && this->annotation != nullptr &&
      this->annotation->getObject() != nullptr) {
    this->player->selectObject(annotation->getObject());
  }
}

/**
 * Will be triggered when a
 *
*/
void AnnotationGraphicsItem::contextMenuEvent(
    QGraphicsSceneContextMenuEvent *event) {
  //    QMenu menu;
  //    menu.addAction("Edit");
  //    menu.addAction("Remove");
  //    QAction *a = menu.exec(event->screenPos());

  // this->player->pause();
  showContextMenu(event->screenPos());
}

void AnnotationGraphicsItem::showContextMenu(const QPoint &pos) {
  QMenu contextMenu("Context menu");

  QAction action_del(QString("Remove"), (QObject *)this->parentObject());
  QAction action_edit(QString("Edit"), (QObject *)this->parentObject());

  QObject::connect(&action_del, SIGNAL(triggered()), this,
                   SLOT(removeAnnotation()));
  QObject::connect(&action_edit, SIGNAL(triggered()), this,
                   SLOT(editAnnotation()));

  contextMenu.addAction(&action_del);
  contextMenu.addAction(&action_edit);
  contextMenu.exec(pos);
}

void AnnotationGraphicsItem::removeAnnotation()
{
    //TODO: remove rect permanently
    AnnotatorLib::Commands::RemoveAnnotation * cmd = new AnnotatorLib::Commands::RemoveAnnotation(player->getSession(), annotation);
    player->getSession()->execute(cmd);
}

void AnnotationGraphicsItem::editAnnotation()
{
    //TODO: emit signal to show popup
}

/////////////////////////////////////////////////////////////
/**
 * change item setting: if mouse on hover
*/
void AnnotationGraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent *) {
  corners[0] = new Corner(this, 0);
  corners[1] = new Corner(this, 1);
  corners[2] = new Corner(this, 2);
  corners[3] = new Corner(this, 3);

  corners[0]->installSceneEventFilter(this);
  corners[1]->installSceneEventFilter(this);
  corners[2]->installSceneEventFilter(this);
  corners[3]->installSceneEventFilter(this);

  setCornerPositions();

  borderColor = Qt::green;

  QLinearGradient gradient;
  gradient.setStart(cornerXPos, cornerYPos);
  gradient.setFinalStop(cornerWidth, cornerYPos);

  QColor grey1(150, 150, 150, 125);
  QColor grey2(225, 225, 225, 125);

  gradient.setColorAt((qreal)0, grey1);
  gradient.setColorAt((qreal)1, grey2);

  brush = gradient;
  idText.show();

  update();
}

/**
 * set corner position
*/
void AnnotationGraphicsItem::setCornerPositions() {
  corners[0]->setPos(cornerXPos, cornerYPos);
  corners[1]->setPos(cornerXPos + cornerWidth - corners[0]->getWidth(),
                     cornerYPos);
  corners[2]->setPos(cornerXPos + cornerWidth - corners[0]->getWidth(),
                     cornerYPos + cornerHeight - corners[0]->getHeight());
  corners[3]->setPos(cornerXPos,
                     cornerYPos + cornerHeight - corners[0]->getHeight());
}

/**
 * reset item setting: if mouse leave hover
*/
void AnnotationGraphicsItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *) {
  corners[0]->setParentItem(NULL);
  corners[1]->setParentItem(NULL);
  corners[2]->setParentItem(NULL);
  corners[3]->setParentItem(NULL);

  delete corners[0];
  delete corners[1];
  delete corners[2];
  delete corners[3];

  borderColor = originColor;

  brush = Qt::NoBrush;
  idText.hide();
  update();
}

/**
 * set new size to the item
*/
void AnnotationGraphicsItem::setSize(int x, int y) {
  width += x;
  height += y;

  cornerWidth = width;
  cornerHeight = height;
}

/**
 * filter event: to get mouse press, move and release from parent graphicsScene
*/
bool AnnotationGraphicsItem::sceneEventFilter(QGraphicsItem *watched,
                                              QEvent *event) {
  Corner *corner = dynamic_cast<Corner *>(watched);
  if (corner == NULL)
    return false;

  QGraphicsSceneMouseEvent *own_event =
      dynamic_cast<QGraphicsSceneMouseEvent *>(event);
  if (own_event == NULL) {
    return false;
  }

  switch (event->type()) {
  // if the mouse pressed, save the (x,y) coordinates inside the corner object
  case QEvent::GraphicsSceneMousePress: {
    corner->setMouseState(Corner::MouseDown);
    corner->mouseDownX = own_event->pos().x();
    corner->mouseDownY = own_event->pos().y();
    this->setSelected(true);
  } break;

  case QEvent::GraphicsSceneMouseRelease: {
    corner->setMouseState(Corner::MouseReleased);
    changeAnnotationSize((int)this->x(), (int)this->y(), (int)this->width,
                         (int)this->height);
  } break;

  case QEvent::GraphicsSceneMouseMove: {
    corner->setMouseState(Corner::MouseMoving);
  } break;

  default:
    return false;
    break;
  }

  if (corner->getMouseState() == Corner::MouseMoving) {
    qreal x = own_event->pos().x();
    qreal y = own_event->pos().y();

    // XSign and YSign to add add or substract size of Item

    int XSign = 0;
    int YSign = 0;
    switch (corner->getCorner()) {
    case 0: {
      XSign = +1;
      YSign = +1;
    } break;

    case 1: {
      XSign = -1;
      YSign = +1;
    } break;

    case 2: {
      XSign = -1;
      YSign = -1;
    } break;

    case 3: {
      XSign = +1;
      YSign = -1;
    } break;
    }

    // Set the new size of Item, whene the the corner position is changed.
    int XPos = corner->mouseDownX - x;
    int YPos = corner->mouseDownY - y;

    // set min width and min height to 10 px.
    int newWidth = width + (XSign * XPos);
    if (newWidth < 10)
      newWidth = 10;

    int newHeight = height + (YSign * YPos);
    if (newHeight < 10)
      newHeight = 10;

    int deltaWidth = newWidth - width;
    int deltaHeight = newHeight - height;

    // set the new size to item.
    setSize(deltaWidth, deltaHeight);

    deltaWidth *= (-1);
    deltaHeight *= (-1);

    switch (corner->getCorner()) {
    case 0: {
      int newXPos = this->pos().x() + deltaWidth;
      int newYpos = this->pos().y() + deltaHeight;
      this->setPos(newXPos, newYpos);
    } break;

    case 1: {
      int newYpos = this->pos().y() + deltaHeight;
      this->setPos(this->pos().x(), newYpos);
    } break;

    case 2: {
      this->setPos(this->pos().x(), this->pos().y());
    } break;

    case 3: {
      int newXPos = this->pos().x() + deltaWidth;
      this->setPos(newXPos, this->pos().y());
    } break;
    }

    setCornerPositions();

    this->update();
  }

  return true;
}

void AnnotationGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
  QGraphicsItem::mousePressEvent(event);

  if (event->button() == Qt::LeftButton) {
    deltax = this->x();
    deltay = this->y();
  }
}

void AnnotationGraphicsItem::mouseReleaseEvent(
    QGraphicsSceneMouseEvent *event) {
  QGraphicsItem::mouseReleaseEvent(event);

  if (event->button() == Qt::LeftButton) {
    deltax = this->x() - deltax;
    deltay = this->y() - deltay;

    changeAnnotationPosition(this->x(), this->y());
    setCornerPositions();
    this->update();
  }
}

void AnnotationGraphicsItem::setAnnotationSize(int x, int y) {
  annotation->setPosition(annotation->getX(), annotation->getY(), x, y);
}

void AnnotationGraphicsItem::changeAnnotationPosition(int x, int y) {
  if (annotation->isInterpolated()) {
    annotation->setInterpolated(false);
    AnnotatorLib::Commands::NewAnnotation *nA =
        new AnnotatorLib::Commands::NewAnnotation(
            annotation->getObject(), annotation->getFrame(), x, y,
            annotation->getWidth(), annotation->getHeight(),
            annotation->getNext(), annotation->getPrevious(),
            player->getSession(), true);
    player->getSession()->execute(nA);
  } else {
    AnnotatorLib::Commands::UpdateAnnotation *uA =
        new AnnotatorLib::Commands::UpdateAnnotation(
            annotation, x, y, annotation->getWidth(), annotation->getHeight());
    player->getSession()->execute(uA);
  }

  // update position of last annotation in automation plugin
  Annotator::Plugin *plugin =
      Annotator::PluginLoader::getInstance().getCurrent();
  if (plugin) {
    plugin->setObject(annotation->getObject());
    plugin->setLastAnnotation(annotation);
  }
}

void AnnotationGraphicsItem::changeAnnotationSize(int x, int y, int w, int h) {
  if (annotation->isInterpolated()) {
    annotation->setInterpolated(false);
    AnnotatorLib::Commands::NewAnnotation *nA =
        new AnnotatorLib::Commands::NewAnnotation(
            annotation->getObject(), annotation->getFrame(), x, y, w, h,
            annotation->getNext(), annotation->getPrevious(),
            player->getSession(), true);
    player->getSession()->execute(nA);
  } else {
    AnnotatorLib::Commands::UpdateAnnotation *uA =
        new AnnotatorLib::Commands::UpdateAnnotation(annotation, x, y, w, h);
    player->getSession()->execute(uA);
  }

  // update position of last annotation in automation plugin
  Annotator::Plugin *plugin =
      Annotator::PluginLoader::getInstance().getCurrent();
  if (plugin) {
    plugin->setObject(annotation->getObject());
    plugin->setLastAnnotation(annotation);
  }
}
<commit_msg>remove annotation via command-controller<commit_after>#include <AnnotatorLib/Commands/NewAnnotation.h>
#include <AnnotatorLib/Commands/UpdateAnnotation.h>
#include <AnnotatorLib/Commands/RemoveAnnotation.h>
#include <QMenu>
#include <QObject>

#include "annotationgraphicsitem.h"
#include "plugins/pluginloader.h"
#include "gui/newobjectdialog.h"
#include "controller/commandcontroller.h"

AnnotatorLib::Annotation *AnnotationGraphicsItem::getAnnotation() {
  return annotation;
}

AnnotationGraphicsItem::AnnotationGraphicsItem(
    AnnotatorLib::Annotation *annotation)
    : QGraphicsItem::QGraphicsItem(nullptr) {
  assert(annotation);
  this->annotation = annotation;

  if (annotation->getObject() == nullptr)
    borderColor = idToColor(annotation->getId());
  else
    borderColor = idToColor(annotation->getObject()->getId());

  setPos(annotation->getX(), annotation->getY());
  initCorners();
  initIdText();

  rectX = 0;
  rectY = 0;
  width = annotation->getWidth();
  height = annotation->getHeight();
  cornerXPos = 0;
  cornerYPos = 0;
  cornerWidth = width, cornerHeight = height,

  originColor = borderColor;
}

AnnotationGraphicsItem::~AnnotationGraphicsItem() {
  for (int i = 0; i < 4; ++i) {
    delete corners[i];
  }
}

static double r_ = (1 + sqrt(5)) / 2;
static double g_ = (3 + sqrt(7)) / 2;
static double b_ = (11 + sqrt(13)) / 2;

QColor AnnotationGraphicsItem::idToColor(long id) {
  double r = id * r_ - floor(id * r_);
  double g = id * g_ - floor(id * g_);
  double b = id * b_ - floor(id * b_);
  return QColor(r * 255, g * 255, b * 255);
}

void AnnotationGraphicsItem::setPlayer(Player *player) {
  this->player = player;
}

void AnnotationGraphicsItem::initCorners() {
  for (int i = 0; i < 4; ++i) {
    corners[i] = new Corner(this, i);
    corners[i]->hide();
    // corners[i]->installSceneEventFilter(this);
  }
  setCornerPositions();
}

void AnnotationGraphicsItem::initIdText() {
  if (annotation) {
    idText.setParentItem(this);
    idText.setDefaultTextColor(borderColor);
    idText.setPlainText(QString::number(annotation->getId()));

    idText.setPos(rectX, rectY - 20);
    idText.hide();
  }
}

void AnnotationGraphicsItem::mouseDoubleClickEvent(
    QGraphicsSceneMouseEvent *event) {
  QGraphicsItem::mouseDoubleClickEvent(event);
  if (this->player != nullptr && this->annotation != nullptr &&
      this->annotation->getObject() != nullptr) {
    this->player->selectObject(annotation->getObject());
  }
}

/**
 * Will be triggered when a
 *
*/
void AnnotationGraphicsItem::contextMenuEvent(
    QGraphicsSceneContextMenuEvent *event) {
  // this->player->pause();
  showContextMenu(event->screenPos());
}

void AnnotationGraphicsItem::showContextMenu(const QPoint &pos) {
  QMenu contextMenu("Context menu");

  QAction action_del(QString("Remove"), (QObject *)this->parentObject());
  QAction action_edit(QString("Edit"), (QObject *)this->parentObject());

  QObject::connect(&action_del, SIGNAL(triggered()), this,
                   SLOT(removeAnnotation()));
  QObject::connect(&action_edit, SIGNAL(triggered()), this,
                   SLOT(editAnnotation()));

  contextMenu.addAction(&action_del);
  contextMenu.addAction(&action_edit);
  contextMenu.exec(pos);
}

void AnnotationGraphicsItem::removeAnnotation()
{
    //TODO: remove rect permanently
    AnnotatorLib::Commands::RemoveAnnotation * cmd = new AnnotatorLib::Commands::RemoveAnnotation(player->getSession(), annotation);
    CommandController::instance()->execute(cmd);
}

void AnnotationGraphicsItem::editAnnotation()
{
    //TODO: emit signal to show popup
}

/////////////////////////////////////////////////////////////
/**
 * change item setting: if mouse on hover
*/
void AnnotationGraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent *) {
  corners[0] = new Corner(this, 0);
  corners[1] = new Corner(this, 1);
  corners[2] = new Corner(this, 2);
  corners[3] = new Corner(this, 3);

  corners[0]->installSceneEventFilter(this);
  corners[1]->installSceneEventFilter(this);
  corners[2]->installSceneEventFilter(this);
  corners[3]->installSceneEventFilter(this);

  setCornerPositions();

  borderColor = Qt::green;

  QLinearGradient gradient;
  gradient.setStart(cornerXPos, cornerYPos);
  gradient.setFinalStop(cornerWidth, cornerYPos);

  QColor grey1(150, 150, 150, 125);
  QColor grey2(225, 225, 225, 125);

  gradient.setColorAt((qreal)0, grey1);
  gradient.setColorAt((qreal)1, grey2);

  brush = gradient;
  idText.show();

  update();
}

/**
 * set corner position
*/
void AnnotationGraphicsItem::setCornerPositions() {
  corners[0]->setPos(cornerXPos, cornerYPos);
  corners[1]->setPos(cornerXPos + cornerWidth - corners[0]->getWidth(),
                     cornerYPos);
  corners[2]->setPos(cornerXPos + cornerWidth - corners[0]->getWidth(),
                     cornerYPos + cornerHeight - corners[0]->getHeight());
  corners[3]->setPos(cornerXPos,
                     cornerYPos + cornerHeight - corners[0]->getHeight());
}

/**
 * reset item setting: if mouse leave hover
*/
void AnnotationGraphicsItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *) {
  corners[0]->setParentItem(NULL);
  corners[1]->setParentItem(NULL);
  corners[2]->setParentItem(NULL);
  corners[3]->setParentItem(NULL);

  delete corners[0];
  delete corners[1];
  delete corners[2];
  delete corners[3];

  borderColor = originColor;

  brush = Qt::NoBrush;
  idText.hide();
  update();
}

/**
 * set new size to the item
*/
void AnnotationGraphicsItem::setSize(int x, int y) {
  width += x;
  height += y;

  cornerWidth = width;
  cornerHeight = height;
}

/**
 * filter event: to get mouse press, move and release from parent graphicsScene
*/
bool AnnotationGraphicsItem::sceneEventFilter(QGraphicsItem *watched,
                                              QEvent *event) {
  Corner *corner = dynamic_cast<Corner *>(watched);
  if (corner == NULL)
    return false;

  QGraphicsSceneMouseEvent *own_event =
      dynamic_cast<QGraphicsSceneMouseEvent *>(event);
  if (own_event == NULL) {
    return false;
  }

  switch (event->type()) {
  // if the mouse pressed, save the (x,y) coordinates inside the corner object
  case QEvent::GraphicsSceneMousePress: {
    corner->setMouseState(Corner::MouseDown);
    corner->mouseDownX = own_event->pos().x();
    corner->mouseDownY = own_event->pos().y();
    this->setSelected(true);
  } break;

  case QEvent::GraphicsSceneMouseRelease: {
    corner->setMouseState(Corner::MouseReleased);
    changeAnnotationSize((int)this->x(), (int)this->y(), (int)this->width,
                         (int)this->height);
  } break;

  case QEvent::GraphicsSceneMouseMove: {
    corner->setMouseState(Corner::MouseMoving);
  } break;

  default:
    return false;
    break;
  }

  if (corner->getMouseState() == Corner::MouseMoving) {
    qreal x = own_event->pos().x();
    qreal y = own_event->pos().y();

    // XSign and YSign to add add or substract size of Item

    int XSign = 0;
    int YSign = 0;
    switch (corner->getCorner()) {
    case 0: {
      XSign = +1;
      YSign = +1;
    } break;

    case 1: {
      XSign = -1;
      YSign = +1;
    } break;

    case 2: {
      XSign = -1;
      YSign = -1;
    } break;

    case 3: {
      XSign = +1;
      YSign = -1;
    } break;
    }

    // Set the new size of Item, whene the the corner position is changed.
    int XPos = corner->mouseDownX - x;
    int YPos = corner->mouseDownY - y;

    // set min width and min height to 10 px.
    int newWidth = width + (XSign * XPos);
    if (newWidth < 10)
      newWidth = 10;

    int newHeight = height + (YSign * YPos);
    if (newHeight < 10)
      newHeight = 10;

    int deltaWidth = newWidth - width;
    int deltaHeight = newHeight - height;

    // set the new size to item.
    setSize(deltaWidth, deltaHeight);

    deltaWidth *= (-1);
    deltaHeight *= (-1);

    switch (corner->getCorner()) {
    case 0: {
      int newXPos = this->pos().x() + deltaWidth;
      int newYpos = this->pos().y() + deltaHeight;
      this->setPos(newXPos, newYpos);
    } break;

    case 1: {
      int newYpos = this->pos().y() + deltaHeight;
      this->setPos(this->pos().x(), newYpos);
    } break;

    case 2: {
      this->setPos(this->pos().x(), this->pos().y());
    } break;

    case 3: {
      int newXPos = this->pos().x() + deltaWidth;
      this->setPos(newXPos, this->pos().y());
    } break;
    }

    setCornerPositions();

    this->update();
  }

  return true;
}

void AnnotationGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *event) {
  QGraphicsItem::mousePressEvent(event);

  if (event->button() == Qt::LeftButton) {
    deltax = this->x();
    deltay = this->y();
  }
}

void AnnotationGraphicsItem::mouseReleaseEvent(
    QGraphicsSceneMouseEvent *event) {
  QGraphicsItem::mouseReleaseEvent(event);

  if (event->button() == Qt::LeftButton) {
    deltax = this->x() - deltax;
    deltay = this->y() - deltay;

    changeAnnotationPosition(this->x(), this->y());
    setCornerPositions();
    this->update();
  }
}

void AnnotationGraphicsItem::setAnnotationSize(int x, int y) {
  annotation->setPosition(annotation->getX(), annotation->getY(), x, y);
}

void AnnotationGraphicsItem::changeAnnotationPosition(int x, int y) {
  if (annotation->isInterpolated()) {
    annotation->setInterpolated(false);
    AnnotatorLib::Commands::NewAnnotation *nA =
        new AnnotatorLib::Commands::NewAnnotation(
            annotation->getObject(), annotation->getFrame(), x, y,
            annotation->getWidth(), annotation->getHeight(),
            annotation->getNext(), annotation->getPrevious(),
            player->getSession(), true);
    player->getSession()->execute(nA);
  } else {
    AnnotatorLib::Commands::UpdateAnnotation *uA =
        new AnnotatorLib::Commands::UpdateAnnotation(
            annotation, x, y, annotation->getWidth(), annotation->getHeight());
    player->getSession()->execute(uA);
  }

  // update position of last annotation in automation plugin
  Annotator::Plugin *plugin =
      Annotator::PluginLoader::getInstance().getCurrent();
  if (plugin) {
    plugin->setObject(annotation->getObject());
    plugin->setLastAnnotation(annotation);
  }
}

void AnnotationGraphicsItem::changeAnnotationSize(int x, int y, int w, int h) {
  if (annotation->isInterpolated()) {
    annotation->setInterpolated(false);
    AnnotatorLib::Commands::NewAnnotation *nA =
        new AnnotatorLib::Commands::NewAnnotation(
            annotation->getObject(), annotation->getFrame(), x, y, w, h,
            annotation->getNext(), annotation->getPrevious(),
            player->getSession(), true);
    player->getSession()->execute(nA);
  } else {
    AnnotatorLib::Commands::UpdateAnnotation *uA =
        new AnnotatorLib::Commands::UpdateAnnotation(annotation, x, y, w, h);
    player->getSession()->execute(uA);
  }

  // update position of last annotation in automation plugin
  Annotator::Plugin *plugin =
      Annotator::PluginLoader::getInstance().getCurrent();
  if (plugin) {
    plugin->setObject(annotation->getObject());
    plugin->setLastAnnotation(annotation);
  }
}
<|endoftext|>


<commit_before>#include <tightdb/util/file.hpp>

#include "test_path.hpp"

using namespace std;
using namespace tightdb::util;
using namespace tightdb::test_util::unit_test;

namespace {

bool keep_files = false;

string path_prefix;
string resource_path;

} // anonymous namespace

namespace tightdb {
namespace test_util {

void keep_test_files()
{
    keep_files = true;
}

string get_test_path(const TestDetails& test_details, const char* suffix)
{
    string path = path_prefix;
    path += test_details.test_name;
    path += suffix;
    return path;
}

void set_test_path_prefix(const string& prefix)
{
    path_prefix = prefix;
}

string get_test_path_prefix()
{
    return path_prefix;
}

string get_test_resource_path()
{
    return resource_path;
}

void set_test_resource_path(const string& path)
{
    resource_path = path;
}

TestPathGuard::TestPathGuard(const string& path):
    m_path(path)
{
    File::try_remove(m_path);
}

TestPathGuard::~TestPathGuard() TIGHTDB_NOEXCEPT
{
    if (keep_files)
        return;
    try {
        File::try_remove(m_path);
    }
    catch (...) {
        // Exception deliberately ignored
    }
}

SharedGroupTestPathGuard::SharedGroupTestPathGuard(const string& path):
    TestPathGuard(path)
{
    File::try_remove(get_lock_path());
}

SharedGroupTestPathGuard::~SharedGroupTestPathGuard()
{
    File::try_remove(get_lock_path());
}

} // namespace test_util
} // namespace tightdb
<commit_msg>removing .log_a and .log_b files after test<commit_after>#include <tightdb/util/file.hpp>

#include "test_path.hpp"

using namespace std;
using namespace tightdb::util;
using namespace tightdb::test_util::unit_test;

namespace {

bool keep_files = false;

string path_prefix;
string resource_path;

} // anonymous namespace

namespace tightdb {
namespace test_util {

void keep_test_files()
{
    keep_files = true;
}

string get_test_path(const TestDetails& test_details, const char* suffix)
{
    string path = path_prefix;
    path += test_details.test_name;
    path += suffix;
    return path;
}

void set_test_path_prefix(const string& prefix)
{
    path_prefix = prefix;
}

string get_test_path_prefix()
{
    return path_prefix;
}

string get_test_resource_path()
{
    return resource_path;
}

void set_test_resource_path(const string& path)
{
    resource_path = path;
}

TestPathGuard::TestPathGuard(const string& path):
    m_path(path)
{
    File::try_remove(m_path);
}

TestPathGuard::~TestPathGuard() TIGHTDB_NOEXCEPT
{
    if (keep_files)
        return;
    try {
        File::try_remove(m_path);
    }
    catch (...) {
        // Exception deliberately ignored
    }
}

SharedGroupTestPathGuard::SharedGroupTestPathGuard(const string& path):
    TestPathGuard(path)
{
    File::try_remove(get_lock_path());
    File::try_remove(m_path + ".log_a");
    File::try_remove(m_path + ".log_b");
}

SharedGroupTestPathGuard::~SharedGroupTestPathGuard()
{
    File::try_remove(get_lock_path());
    File::try_remove(m_path + ".log_a");
    File::try_remove(m_path + ".log_b");
}

} // namespace test_util
} // namespace tightdb
<|endoftext|>


<commit_before>#include "Text_Editor_Shader.h"
#include"Application.h"

Editor_Text_Shader::Editor_Text_Shader()
{
}

Editor_Text_Shader::~Editor_Text_Shader()
{
}

void Editor_Text_Shader::Enable_Text_Editor(bool visible, const char* path_shader)
{

	if (visible) {

		ImGui::Begin("Editor Shader", &App->gui->show_editor_shaders);

		if (first_time_edit && path_shader == nullptr) {
			editor_text_shader.InsertText("//This is meant to be an editor of shaders");
			editor_text_shader.InsertText("\n");
			first_time_edit = false;
		}
		else if (first_time_edit ==true && path_shader != nullptr) {

			//In a close future will need to load the text of the shader
			std::string str_temp = "";
			editor_text_shader.SetText(str_temp);
			char* buffer = nullptr;
			int size_file = App->fs_e->LoadFile(path_shader, &buffer);
			actual_path = path_shader;
			if (buffer != nullptr) {
				buffer[size_file] = '\0';
				std::string str_shader = buffer;
				editor_text_shader.InsertText(str_shader);
				first_time_edit = false;
			}

		}

		if (ImGui::Button("Compile"))
		{
			//See if compile
		}
		ImGui::SameLine();
		if (ImGui::Button("Save"))
		{
			//char* text_str_buffer = editor_text_shader.GetText().c_str();
			App->fs_e->SaveFile(actual_path.c_str(), (char*)editor_text_shader.GetText().c_str(), editor_text_shader.GetText().size());
			//Modify txt
		}

		if (App->input->GetKey(SDL_SCANCODE_RETURN) == KEY_DOWN) {
			editor_text_shader.InsertText("\n");
		}

		if (App->input->GetKey(SDL_SCANCODE_LCTRL) == KEY_REPEAT ){
			if (App->input->GetKey(SDL_SCANCODE_C) == KEY_DOWN) {
				text_selected = editor_text_shader.GetSelectedText();
			}
		}

		if (App->input->GetKey(SDL_SCANCODE_LCTRL) == KEY_REPEAT){
			if (App->input->GetKey(SDL_SCANCODE_V) == KEY_DOWN) {
				editor_text_shader.InsertText(text_selected);
			}
		}

		if (App->input->GetKey(SDL_SCANCODE_LCTRL) == KEY_REPEAT) {
			if (App->input->GetKey(SDL_SCANCODE_Z) == KEY_DOWN) {
				editor_text_shader.Undo();
			}
		}

		if (App->input->GetKey(SDL_SCANCODE_LCTRL) == KEY_REPEAT) {
			if (App->input->GetKey(SDL_SCANCODE_Y) == KEY_DOWN) {
				editor_text_shader.Redo();
			}
		}

		editor_text_shader.Render("Test_shader_editor");

		ImGui::End();
	}
	else {
		first_time_edit = true;
	}

}
<commit_msg>Delete a useless button<commit_after>#include "Text_Editor_Shader.h"
#include"Application.h"

Editor_Text_Shader::Editor_Text_Shader()
{
}

Editor_Text_Shader::~Editor_Text_Shader()
{
}

void Editor_Text_Shader::Enable_Text_Editor(bool visible, const char* path_shader)
{

	if (visible) {

		ImGui::Begin("Editor Shader", &App->gui->show_editor_shaders);

		if (first_time_edit && path_shader == nullptr) {
			editor_text_shader.InsertText("//This is meant to be an editor of shaders");
			editor_text_shader.InsertText("\n");
			first_time_edit = false;
		}
		else if (first_time_edit ==true && path_shader != nullptr) {

			//In a close future will need to load the text of the shader
			std::string str_temp = "";
			editor_text_shader.SetText(str_temp);
			char* buffer = nullptr;
			int size_file = App->fs_e->LoadFile(path_shader, &buffer);
			actual_path = path_shader;
			if (buffer != nullptr) {
				buffer[size_file] = '\0';
				std::string str_shader = buffer;
				editor_text_shader.InsertText(str_shader);
				first_time_edit = false;
			}

		}

		if (ImGui::Button("Save"))
		{
			//char* text_str_buffer = editor_text_shader.GetText().c_str();
			App->fs_e->SaveFile(actual_path.c_str(), (char*)editor_text_shader.GetText().c_str(), editor_text_shader.GetText().size());
			//Modify txt
		}

		if (App->input->GetKey(SDL_SCANCODE_RETURN) == KEY_DOWN) {
			editor_text_shader.InsertText("\n");
		}

		if (App->input->GetKey(SDL_SCANCODE_LCTRL) == KEY_REPEAT ){
			if (App->input->GetKey(SDL_SCANCODE_C) == KEY_DOWN) {
				text_selected = editor_text_shader.GetSelectedText();
			}
		}

		if (App->input->GetKey(SDL_SCANCODE_LCTRL) == KEY_REPEAT){
			if (App->input->GetKey(SDL_SCANCODE_V) == KEY_DOWN) {
				editor_text_shader.InsertText(text_selected);
			}
		}

		if (App->input->GetKey(SDL_SCANCODE_LCTRL) == KEY_REPEAT) {
			if (App->input->GetKey(SDL_SCANCODE_Z) == KEY_DOWN) {
				editor_text_shader.Undo();
			}
		}

		if (App->input->GetKey(SDL_SCANCODE_LCTRL) == KEY_REPEAT) {
			if (App->input->GetKey(SDL_SCANCODE_Y) == KEY_DOWN) {
				editor_text_shader.Redo();
			}
		}

		editor_text_shader.Render("Test_shader_editor");

		ImGui::End();
	}
	else {
		first_time_edit = true;
	}

}
<|endoftext|>


<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <limits.h>

#include "base/files/file_path.h"
#include "base/files/memory_mapped_file.h"
#include "base/logging.h"
#include "base/strings/string_piece.h"
#include "ipc/ipc_message.h"
#include "tools/ipc_fuzzer/message_lib/message_cracker.h"
#include "tools/ipc_fuzzer/message_lib/message_file.h"
#include "tools/ipc_fuzzer/message_lib/message_file_format.h"
#include "tools/ipc_fuzzer/message_lib/message_names.h"

namespace ipc_fuzzer {

namespace {

// Helper class to read IPC message file into a MessageVector and
// fix message types.
class Reader {
 public:
  Reader(const base::FilePath& path);
  bool Read(MessageVector* messages);

 private:
  template <typename T>
  bool CutObject(const T** object);

  // Reads the header, checks magic and version.
  bool ReadHeader();

  bool MapFile();
  bool ReadMessages();

  // Last part of the file is a string table for message names.
  bool ReadStringTable();

  // Reads type <-> name mapping into name_map_. References string table.
  bool ReadNameTable();

  // Removes obsolete messages from the vector.
  bool RemoveUnknownMessages();

  // Does type -> name -> correct_type fixup.
  void FixMessageTypes();

  // Raw data.
  base::FilePath path_;
  base::MemoryMappedFile mapped_file_;
  base::StringPiece file_data_;
  base::StringPiece string_table_;

  // Parsed data.
  const FileHeader* header_;
  MessageVector* messages_;
  MessageNames name_map_;

  DISALLOW_COPY_AND_ASSIGN(Reader);
};

Reader::Reader(const base::FilePath& path)
    : path_(path),
      header_(NULL),
      messages_(NULL) {
}

template <typename T>
bool Reader::CutObject(const T** object) {
  if (file_data_.size() < sizeof(T)) {
    LOG(ERROR) << "Unexpected EOF.";
    return false;
  }
  *object = reinterpret_cast<const T*>(file_data_.data());
  file_data_.remove_prefix(sizeof(T));
  return true;
}

bool Reader::ReadHeader() {
  if (!CutObject<FileHeader>(&header_))
    return false;
  if (header_->magic != FileHeader::kMagicValue) {
    LOG(ERROR) << path_.value() << " is not an IPC message file.";
    return false;
  }
  if (header_->version != FileHeader::kCurrentVersion) {
    LOG(ERROR) << "Wrong version for message file " << path_.value() << ". "
               << "File version is " << header_->version << ", "
               << "current version is " << FileHeader::kCurrentVersion << ".";
    return false;
  }
  return true;
}

bool Reader::MapFile() {
  if (!mapped_file_.Initialize(path_)) {
    LOG(ERROR) << "Failed to map testcase: " << path_.value();
    return false;
  }
  const char* data = reinterpret_cast<const char*>(mapped_file_.data());
  file_data_.set(data, mapped_file_.length());
  return true;
}

bool Reader::ReadMessages() {
  for (size_t i = 0; i < header_->message_count; ++i) {
    const char* begin = file_data_.begin();
    const char* end = file_data_.end();
    IPC::Message::NextMessageInfo info = IPC::Message::FindNext(begin, end);
    if (!info.message_found) {
      LOG(ERROR) << "Failed to parse message.";
      return false;
    }

    CHECK_EQ(info.message_end, info.pickle_end);
    size_t msglen = info.message_end - begin;
    if (msglen > INT_MAX) {
      LOG(ERROR) << "Message too large.";
      return false;
    }

    // Copy is necessary to fix message type later.
    IPC::Message const_message(begin, msglen);
    IPC::Message* message = new IPC::Message(const_message);
    messages_->push_back(message);
    file_data_.remove_prefix(msglen);
  }
  return true;
}

bool Reader::ReadStringTable() {
  size_t name_count = header_->name_count;
  if (!name_count)
    return true;
  if (name_count > file_data_.size() / sizeof(NameTableEntry)) {
    LOG(ERROR) << "Invalid name table size: " << name_count;
    return false;
  }

  size_t string_table_offset = name_count * sizeof(NameTableEntry);
  string_table_ = file_data_.substr(string_table_offset);
  if (string_table_.empty()) {
    LOG(ERROR) << "Missing string table.";
    return false;
  }
  if (string_table_.end()[-1] != '\0') {
    LOG(ERROR) << "String table doesn't end with NUL.";
    return false;
  }
  return true;
}

bool Reader::ReadNameTable() {
  for (size_t i = 0; i < header_->name_count; ++i) {
    const NameTableEntry* entry;
    if (!CutObject<NameTableEntry>(&entry))
      return false;
    size_t offset = entry->string_table_offset;
    if (offset >= string_table_.size()) {
      LOG(ERROR) << "Invalid string table offset: " << offset;
      return false;
    }
    name_map_.Add(entry->type, std::string(string_table_.data() + offset));
  }
  return true;
}

bool Reader::RemoveUnknownMessages() {
  MessageVector::iterator it = messages_->begin();
  while (it != messages_->end()) {
    uint32 type = (*it)->type();
    if (!name_map_.TypeExists(type)) {
      LOG(ERROR) << "Missing name table entry for type " << type;
      return false;
    }
    const std::string& name = name_map_.TypeToName(type);
    if (!MessageNames::GetInstance()->NameExists(name)) {
      LOG(WARNING) << "Unknown message " << name;
      it = messages_->erase(it);
    } else {
      ++it;
    }
  }
  return true;
}

// Message types are based on line numbers, so a minor edit of *_messages.h
// changes the types of messages in that file. The types are fixed here to
// increase the lifetime of message files. This is only a partial fix because
// message arguments and structure layouts can change as well.
void Reader::FixMessageTypes() {
  for (MessageVector::iterator it = messages_->begin();
       it != messages_->end(); ++it) {
    uint32 type = (*it)->type();
    const std::string& name = name_map_.TypeToName(type);
    uint32 correct_type = MessageNames::GetInstance()->NameToType(name);
    if (type != correct_type)
      MessageCracker::SetMessageType(*it, correct_type);
  }
}

bool Reader::Read(MessageVector* messages) {
  messages_ = messages;

  if (!MapFile())
    return false;
  if (!ReadHeader())
    return false;
  if (!ReadMessages())
    return false;
  if (!ReadStringTable())
    return false;
  if (!ReadNameTable())
    return false;
  if (!RemoveUnknownMessages())
    return false;
  FixMessageTypes();

  return true;
}

}  // namespace

bool MessageFile::Read(const base::FilePath& path, MessageVector* messages) {
  Reader reader(path);
  return reader.Read(messages);
}

}  // namespace ipc_fuzzer
<commit_msg>Revert of IPC fuzzer: Update a call to IPC::Message::FindNext. (patchset #2 id:20001 of https://codereview.chromium.org/1312793005/ )<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <limits.h>

#include "base/files/file_path.h"
#include "base/files/memory_mapped_file.h"
#include "base/logging.h"
#include "base/strings/string_piece.h"
#include "ipc/ipc_message.h"
#include "tools/ipc_fuzzer/message_lib/message_cracker.h"
#include "tools/ipc_fuzzer/message_lib/message_file.h"
#include "tools/ipc_fuzzer/message_lib/message_file_format.h"
#include "tools/ipc_fuzzer/message_lib/message_names.h"

namespace ipc_fuzzer {

namespace {

// Helper class to read IPC message file into a MessageVector and
// fix message types.
class Reader {
 public:
  Reader(const base::FilePath& path);
  bool Read(MessageVector* messages);

 private:
  template <typename T>
  bool CutObject(const T** object);

  // Reads the header, checks magic and version.
  bool ReadHeader();

  bool MapFile();
  bool ReadMessages();

  // Last part of the file is a string table for message names.
  bool ReadStringTable();

  // Reads type <-> name mapping into name_map_. References string table.
  bool ReadNameTable();

  // Removes obsolete messages from the vector.
  bool RemoveUnknownMessages();

  // Does type -> name -> correct_type fixup.
  void FixMessageTypes();

  // Raw data.
  base::FilePath path_;
  base::MemoryMappedFile mapped_file_;
  base::StringPiece file_data_;
  base::StringPiece string_table_;

  // Parsed data.
  const FileHeader* header_;
  MessageVector* messages_;
  MessageNames name_map_;

  DISALLOW_COPY_AND_ASSIGN(Reader);
};

Reader::Reader(const base::FilePath& path)
    : path_(path),
      header_(NULL),
      messages_(NULL) {
}

template <typename T>
bool Reader::CutObject(const T** object) {
  if (file_data_.size() < sizeof(T)) {
    LOG(ERROR) << "Unexpected EOF.";
    return false;
  }
  *object = reinterpret_cast<const T*>(file_data_.data());
  file_data_.remove_prefix(sizeof(T));
  return true;
}

bool Reader::ReadHeader() {
  if (!CutObject<FileHeader>(&header_))
    return false;
  if (header_->magic != FileHeader::kMagicValue) {
    LOG(ERROR) << path_.value() << " is not an IPC message file.";
    return false;
  }
  if (header_->version != FileHeader::kCurrentVersion) {
    LOG(ERROR) << "Wrong version for message file " << path_.value() << ". "
               << "File version is " << header_->version << ", "
               << "current version is " << FileHeader::kCurrentVersion << ".";
    return false;
  }
  return true;
}

bool Reader::MapFile() {
  if (!mapped_file_.Initialize(path_)) {
    LOG(ERROR) << "Failed to map testcase: " << path_.value();
    return false;
  }
  const char* data = reinterpret_cast<const char*>(mapped_file_.data());
  file_data_.set(data, mapped_file_.length());
  return true;
}

bool Reader::ReadMessages() {
  for (size_t i = 0; i < header_->message_count; ++i) {
    const char* begin = file_data_.begin();
    const char* end = file_data_.end();
    const char* message_tail = IPC::Message::FindNext(begin, end);
    if (!message_tail) {
      LOG(ERROR) << "Failed to parse message.";
      return false;
    }

    size_t msglen = message_tail - begin;
    if (msglen > INT_MAX) {
      LOG(ERROR) << "Message too large.";
      return false;
    }

    // Copy is necessary to fix message type later.
    IPC::Message const_message(begin, msglen);
    IPC::Message* message = new IPC::Message(const_message);
    messages_->push_back(message);
    file_data_.remove_prefix(msglen);
  }
  return true;
}

bool Reader::ReadStringTable() {
  size_t name_count = header_->name_count;
  if (!name_count)
    return true;
  if (name_count > file_data_.size() / sizeof(NameTableEntry)) {
    LOG(ERROR) << "Invalid name table size: " << name_count;
    return false;
  }

  size_t string_table_offset = name_count * sizeof(NameTableEntry);
  string_table_ = file_data_.substr(string_table_offset);
  if (string_table_.empty()) {
    LOG(ERROR) << "Missing string table.";
    return false;
  }
  if (string_table_.end()[-1] != '\0') {
    LOG(ERROR) << "String table doesn't end with NUL.";
    return false;
  }
  return true;
}

bool Reader::ReadNameTable() {
  for (size_t i = 0; i < header_->name_count; ++i) {
    const NameTableEntry* entry;
    if (!CutObject<NameTableEntry>(&entry))
      return false;
    size_t offset = entry->string_table_offset;
    if (offset >= string_table_.size()) {
      LOG(ERROR) << "Invalid string table offset: " << offset;
      return false;
    }
    name_map_.Add(entry->type, std::string(string_table_.data() + offset));
  }
  return true;
}

bool Reader::RemoveUnknownMessages() {
  MessageVector::iterator it = messages_->begin();
  while (it != messages_->end()) {
    uint32 type = (*it)->type();
    if (!name_map_.TypeExists(type)) {
      LOG(ERROR) << "Missing name table entry for type " << type;
      return false;
    }
    const std::string& name = name_map_.TypeToName(type);
    if (!MessageNames::GetInstance()->NameExists(name)) {
      LOG(WARNING) << "Unknown message " << name;
      it = messages_->erase(it);
    } else {
      ++it;
    }
  }
  return true;
}

// Message types are based on line numbers, so a minor edit of *_messages.h
// changes the types of messages in that file. The types are fixed here to
// increase the lifetime of message files. This is only a partial fix because
// message arguments and structure layouts can change as well.
void Reader::FixMessageTypes() {
  for (MessageVector::iterator it = messages_->begin();
       it != messages_->end(); ++it) {
    uint32 type = (*it)->type();
    const std::string& name = name_map_.TypeToName(type);
    uint32 correct_type = MessageNames::GetInstance()->NameToType(name);
    if (type != correct_type)
      MessageCracker::SetMessageType(*it, correct_type);
  }
}

bool Reader::Read(MessageVector* messages) {
  messages_ = messages;

  if (!MapFile())
    return false;
  if (!ReadHeader())
    return false;
  if (!ReadMessages())
    return false;
  if (!ReadStringTable())
    return false;
  if (!ReadNameTable())
    return false;
  if (!RemoveUnknownMessages())
    return false;
  FixMessageTypes();

  return true;
}

}  // namespace

bool MessageFile::Read(const base::FilePath& path, MessageVector* messages) {
  Reader reader(path);
  return reader.Read(messages);
}

}  // namespace ipc_fuzzer
<|endoftext|>