<commit_before>#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;

// NURA [SCM-00000]

//function prototype
void displayout();

int main() {

	//variables declarations
	double CourseWork, FinalMark, Exam;
	string FName, LName;
	string grade;
	int PAssignment, Test;

	//Creating inFile and outFile
	ifstream inFile;
	ofstream outFile;

	//Openning inFile and outFile
	inFile.open("studentInfile.txt");
	outFile.open("studentOutfile.txt");

	//On screen headings for assessment report
	cout << "  Student Names " << "   " << " Test " << " " << " PAssignment " <<" Exam " << " " << " CourseWork " << "   " << " Final Mark " << "    " << " Grade " << endl;
	cout << " ----------------------------------------------------------------------------- " << endl;
	//Resultout.txt headings for assessment report
	outFile << " Student Names " << " " << " Test " << " " << " PAssignment " << " " << " Exam " << " " << " CourseWork " << " Final Mark " << "  " << " Grade " << endl;
	outFile << " ----------------------------------------------------------------------------------------------- " << endl;

	//while loop that repeat reading from file
	while (!inFile.eof())
	{
		//Q1: Reading from a File [studentinfile.txt]
		inFile >> FName >> LName >> Test >> PAssignment >> Exam;

		//Calculation of students assessment
		//int LabMark = Lab1 + Lab2 + Lab3 + Lab4;
		//int QuizMark = Quiz1 + Quiz2 + Quiz3;
		CourseWork = PAssignment * 0.15 + Test * 0.35;
		FinalMark = Exam * 0.50 + CourseWork;

		//for loop which count the number of students
		for (int i = 0; i <=0; i++)
		{
			//conditions that test the range of students marks
			if ((FinalMark >= 0) && (FinalMark <= 39))
			{
				grade = "F" " " "Fail";
			}
			else if ((FinalMark >= 40) && (FinalMark <= 44))
			{
				grade = "D" " " "Fail";
			}
			else if ((FinalMark >= 45) && (FinalMark <= 49))
			{
				grade = "C-" " " "Fail";
			}
			else if ((FinalMark >= 50) && (FinalMark <= 54))
			{
				grade = "C" " " "Pass";
			}
			else if ((FinalMark >= 55) && (FinalMark <= 59))
			{
				grade = "C+" " " "Credit";
			}
			else if ((FinalMark >= 60) && (FinalMark <= 64))
			{
				grade = "B-" " " "Credit";
			}
			else if ((FinalMark >= 65) && (FinalMark <= 69))
			{
				grade = "B" " " "Credit";
			}
			else if ((FinalMark >= 70) && (FinalMark <= 74))
			{
				grade = "B+" " " "Credit";
			}
			else if ((FinalMark >= 75) && (FinalMark <= 79))
			{
				grade = "A-" " " "Distinction";
			}
			else if ((FinalMark >= 80) && (FinalMark <= 100))
			{
				grade = "A" " " "Distinction";
			}

			//Q2: Displaying students report on screen
			cout << endl;
			cout << setw(2);
			cout << left << setw(10) << FName << setw(5) << LName
				<< right << setw(13) << Test << setw(14) << PAssignment << setw(14) << Exam << setw(14) << CourseWork << setw(12) << FinalMark << setw(18) << grade << endl;

			//Q2: Writing students report to a File[studentoutfile.txt]
			outFile << left << setw(10) << FName << setw(10)
				<< LName << right << setw(3) << Test << setw(14) << PAssignment << setw(14) << Exam << setw(10) << CourseWork << setw(10) << FinalMark << setw(20) << grade << endl;

		} //End for loop
	} //End while loop

	//Q3: Calling Function to display assessment on screen
	displayout();

	//Closing inFile and outFile
	inFile.close();
	outFile.close();

	system("pause");

	return 0;
}

//Function Implementation Syntax

void displayout()      //function name with no return type
{
	//Q3: Displaying information on screen
	cout << endl << endl;
	cout << "-----------------------------------------------" << endl;
	cout << endl << endl;
	cout << fixed << showpoint << setprecision(2);
	cout << " Status " << "    " << " Mark Distribution " << "    " << " NoOfStudent " << endl;
	cout << " ----------------------------------------------- " << endl;
	cout << "  F  " << "         " << "      0-39   " << "            " << " 7 " << endl << endl;
	cout << "  D  " << "         " << "      40-44  " << "          " << "   3 " << endl << endl;
	cout << "  C- " << "         " << "      45-49  " << "            " << " 1 " << endl << endl;
	cout << "  C  " << "         " << "      50-54  " << "            " << " 1 " << endl << endl;
	cout << "  C+ " << "         " << "      55-59  " << "            " << " 5 " << endl << endl;
	cout << "  B- " << "         " << "      60-64  " << "            " << " 4 " << endl << endl;
	cout << "  B  " << "         " << "      65-69  " << "            " << " 3 " << endl << endl;
	cout << "  B+ " << "         " << "      70-74  " << "            " << " 2 " << endl << endl;
	cout << "  A- " << "         " << "      75-79  " << "            " << " 1 " << endl << endl;
	cout << "  A  " << "         " << "      80-100 " << "            " << " 3 " << endl << endl;

	//Overall results statistics
	cout << endl;
	cout << " OVERALL STATISTICS" << endl;
	cout << " ------------------" << endl;
	cout << endl;
	cout << " Total Number of Students Processed : " << " 30 " << endl;
	cout << " Total Number of Distinction : " << " 4 " << endl;
	cout << " Total Number of Credit : " << " 9 " << endl;
	cout << " Total Number of Pass : " << " 6 " << endl;
	cout << " Total Number of Fail : " << " 11 " << endl;
	cout << " Average Mark : " << " 55.28 " << endl;
	cout << " Highest Mark : " << " 87.75 " << endl;
	cout << " Lowest Mark : " << " 21.35 " << endl;

} //End Function
<commit_msg>Update main.cpp<commit_after>#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;

// Author
Deen Adam

//function prototype
void displayout();

int main() {

	//variables declarations
	double CourseWork, FinalMark, Exam;
	string FName, LName;
	string grade;
	int PAssignment, Test;

	//Creating inFile and outFile
	ifstream inFile;
	ofstream outFile;

	//Openning inFile and outFile
	inFile.open("studentInfile.txt");
	outFile.open("studentOutfile.txt");

	//On screen headings for assessment report
	cout << "  Student Names " << "   " << " Test " << " " << " PAssignment " <<" Exam " << " " << " CourseWork " << "   " << " Final Mark " << "    " << " Grade " << endl;
	cout << " ----------------------------------------------------------------------------- " << endl;
	//Resultout.txt headings for assessment report
	outFile << " Student Names " << " " << " Test " << " " << " PAssignment " << " " << " Exam " << " " << " CourseWork " << " Final Mark " << "  " << " Grade " << endl;
	outFile << " ----------------------------------------------------------------------------------------------- " << endl;

	//while loop that repeat reading from file
	while (!inFile.eof())
	{
		//Q1: Reading from a File [studentinfile.txt]
		inFile >> FName >> LName >> Test >> PAssignment >> Exam;

		//Calculation of students assessment
		//int LabMark = Lab1 + Lab2 + Lab3 + Lab4;
		//int QuizMark = Quiz1 + Quiz2 + Quiz3;
		CourseWork = PAssignment * 0.15 + Test * 0.35;
		FinalMark = Exam * 0.50 + CourseWork;

		//for loop which count the number of students
		for (int i = 0; i <=0; i++)
		{
			//conditions that test the range of students marks
			if ((FinalMark >= 0) && (FinalMark <= 39))
			{
				grade = "F" " " "Fail";
			}
			else if ((FinalMark >= 40) && (FinalMark <= 44))
			{
				grade = "D" " " "Fail";
			}
			else if ((FinalMark >= 45) && (FinalMark <= 49))
			{
				grade = "C-" " " "Fail";
			}
			else if ((FinalMark >= 50) && (FinalMark <= 54))
			{
				grade = "C" " " "Pass";
			}
			else if ((FinalMark >= 55) && (FinalMark <= 59))
			{
				grade = "C+" " " "Credit";
			}
			else if ((FinalMark >= 60) && (FinalMark <= 64))
			{
				grade = "B-" " " "Credit";
			}
			else if ((FinalMark >= 65) && (FinalMark <= 69))
			{
				grade = "B" " " "Credit";
			}
			else if ((FinalMark >= 70) && (FinalMark <= 74))
			{
				grade = "B+" " " "Credit";
			}
			else if ((FinalMark >= 75) && (FinalMark <= 79))
			{
				grade = "A-" " " "Distinction";
			}
			else if ((FinalMark >= 80) && (FinalMark <= 100))
			{
				grade = "A" " " "Distinction";
			}

			//Q2: Displaying students report on screen
			cout << endl;
			cout << setw(2);
			cout << left << setw(10) << FName << setw(5) << LName
				<< right << setw(13) << Test << setw(14) << PAssignment << setw(14) << Exam << setw(14) << CourseWork << setw(12) << FinalMark << setw(18) << grade << endl;

			//Q2: Writing students report to a File[studentoutfile.txt]
			outFile << left << setw(10) << FName << setw(10)
				<< LName << right << setw(3) << Test << setw(14) << PAssignment << setw(14) << Exam << setw(10) << CourseWork << setw(10) << FinalMark << setw(20) << grade << endl;

		} //End for loop
	} //End while loop

	//Q3: Calling Function to display assessment on screen
	displayout();

	//Closing inFile and outFile
	inFile.close();
	outFile.close();

	system("pause");

	return 0;
}

//Function Implementation Syntax

void displayout()      //function name with no return type
{
	//Q3: Displaying information on screen
	cout << endl << endl;
	cout << "-----------------------------------------------" << endl;
	cout << endl << endl;
	cout << fixed << showpoint << setprecision(2);
	cout << " Status " << "    " << " Mark Distribution " << "    " << " NoOfStudent " << endl;
	cout << " ----------------------------------------------- " << endl;
	cout << "  F  " << "         " << "      0-39   " << "            " << " 7 " << endl << endl;
	cout << "  D  " << "         " << "      40-44  " << "          " << "   3 " << endl << endl;
	cout << "  C- " << "         " << "      45-49  " << "            " << " 1 " << endl << endl;
	cout << "  C  " << "         " << "      50-54  " << "            " << " 1 " << endl << endl;
	cout << "  C+ " << "         " << "      55-59  " << "            " << " 5 " << endl << endl;
	cout << "  B- " << "         " << "      60-64  " << "            " << " 4 " << endl << endl;
	cout << "  B  " << "         " << "      65-69  " << "            " << " 3 " << endl << endl;
	cout << "  B+ " << "         " << "      70-74  " << "            " << " 2 " << endl << endl;
	cout << "  A- " << "         " << "      75-79  " << "            " << " 1 " << endl << endl;
	cout << "  A  " << "         " << "      80-100 " << "            " << " 3 " << endl << endl;

	//Overall results statistics
	cout << endl;
	cout << " OVERALL STATISTICS" << endl;
	cout << " ------------------" << endl;
	cout << endl;
	cout << " Total Number of Students Processed : " << " 30 " << endl;
	cout << " Total Number of Distinction : " << " 4 " << endl;
	cout << " Total Number of Credit : " << " 9 " << endl;
	cout << " Total Number of Pass : " << " 6 " << endl;
	cout << " Total Number of Fail : " << " 11 " << endl;
	cout << " Average Mark : " << " 55.28 " << endl;
	cout << " Highest Mark : " << " 87.75 " << endl;
	cout << " Lowest Mark : " << " 21.35 " << endl;

} //End Function
<|endoftext|>


<commit_before>#include <cmath>

#include "checker.hpp"

bool Checker::checkStep(GameDesk& a, Move& move) {
    if (move.undo_action = true) {
        return true;
    }
    int rownumber = a.getRowNumber();
    int n1 = a.getDeskNumber(move.p1);
    int n2 = a.getDeskNumber(move.p2);
    return checkIndex(rownumber, move) && n1 == n2;
}

bool Checker::checkIndex(int max, Move& move) {
    int p1c = move.p1.col;
    int p2c = move.p2.col;
    int p1r = move.p1.row;
    int p2r = move.p2.row;
    if (checkRange(max, move)) {
        if ((p1c == p2c) && (std::abs((p1r - p2r)) == 1)) {
            return true;
        } else if ((p1r == p2r) && (std::abs(p1c - p2c) == 1)) {
            return true;
        }
        return false;
    }
    return false;
}

bool Checker::checkRange(int max, Move& move) {
    int p1c = move.p1.col;
    int p2c = move.p2.col;
    int p1r = move.p1.row;
    int p2r = move.p2.row;
    bool gt0 = p1r >= 0 && p1c >= 0 && p2r >= 0 && p2c >= 0;
    bool ltm = p1r < max && p1c < max && p2r < max && p2c < max;
    return gt0 && ltm;
}

<commit_msg>Corect mistake in Checker::checkStep<commit_after>#include <cmath>

#include "checker.hpp"

bool Checker::checkStep(GameDesk& a, Move& move) {
    if (move.undo_action == true) {
        return true;
    }
    int rownumber = a.getRowNumber();
    int n1 = a.getDeskNumber(move.p1);
    int n2 = a.getDeskNumber(move.p2);
    return checkIndex(rownumber, move) && n1 == n2;
}

bool Checker::checkIndex(int max, Move& move) {
    int p1c = move.p1.col;
    int p2c = move.p2.col;
    int p1r = move.p1.row;
    int p2r = move.p2.row;
    if (checkRange(max, move)) {
        if ((p1c == p2c) && (std::abs((p1r - p2r)) == 1)) {
            return true;
        } else if ((p1r == p2r) && (std::abs(p1c - p2c) == 1)) {
            return true;
        }
        return false;
    }
    return false;
}

bool Checker::checkRange(int max, Move& move) {
    int p1c = move.p1.col;
    int p2c = move.p2.col;
    int p1r = move.p1.row;
    int p2r = move.p2.row;
    bool gt0 = p1r >= 0 && p1c >= 0 && p2r >= 0 && p2c >= 0;
    bool ltm = p1r < max && p1c < max && p2r < max && p2c < max;
    return gt0 && ltm;
}

<|endoftext|>


<commit_before>/**************************************************************************\
 * camera.hpp - Defining a movable and scalable camera w viewport         *
 *                                               ___                      *
 *    /\/\   __ _  __ _ _ __  _   _ _ __ ___     /___\_ __  _   _ ___     *
 *   /    \ / _` |/ _` | '_ \| | | | '_ ` _ \   //  // '_ \| | | / __|    *
 *  / /\/\ \ (_| | (_| | | | | |_| | | | | | | / \_//| |_) | |_| \__ \    *
 *  \/    \/\__,_|\__, |_| |_|\__,_|_| |_| |_| \___/ | .__/ \__,_|___/    *
 *                |___/                              |_|                  *
 *                                                                        *
 * Copyright (c) 2015 Florian Oetke & Sebastian Schalow                   *
 *                                                                        *
 *  This file is part of MagnumOpus and distributed under the MIT License *
 *  See LICENSE file for details.                                         *
\**************************************************************************/

#pragma once

#include <glm/glm.hpp>

#include "../engine.hpp"

namespace mo {
namespace renderer {

	class Camera {

	public:

		// Constructors
		Camera(const Engine &engine, float world_scale=1.f,
		       const glm::vec2 position=glm::vec2(0.0f), float zoom=1.0f) noexcept;

		// Methods
		void position(glm::vec2 pos) noexcept {_pos = pos; _dirty = true;}
		void move(glm::vec2 offset) noexcept {_pos+=offset; _dirty = true;}
		void zoom(float z) noexcept {_zoom=z; _dirty=true;}
		void viewport(glm::vec4 viewport)noexcept;

		auto zoom() const noexcept { return _zoom; }
		auto position() const noexcept { return _pos; }
		auto viewport() const noexcept { return _viewport; }

		auto vp() const noexcept -> const glm::mat4&;

		auto screen_to_world(const glm::vec2 screen_pos) const noexcept -> glm::vec2;
		auto world_to_screen(const glm::vec2 world_pos) const noexcept -> glm::vec2;

	private:
		void recalc_vp()const noexcept;

		glm::vec4 _viewport; //< x,y,w,h
		glm::mat4 _projection;

		const float _world_scale;
		float _zoom;
		glm::vec2 _pos;
		mutable glm::mat4 _vp;
		mutable bool _dirty;

	};
}
}
<commit_msg>Animation Data<commit_after>/**************************************************************************\
 * camera.hpp - Defining a movable and scalable camera w viewport         *
 *                                               ___                      *
 *    /\/\   __ _  __ _ _ __  _   _ _ __ ___     /___\_ __  _   _ ___     *
 *   /    \ / _` |/ _` | '_ \| | | | '_ ` _ \   //  // '_ \| | | / __|    *
 *  / /\/\ \ (_| | (_| | | | | |_| | | | | | | / \_//| |_) | |_| \__ \    *
 *  \/    \/\__,_|\__, |_| |_|\__,_|_| |_| |_| \___/ | .__/ \__,_|___/    *
 *                |___/                              |_|                  *
 *                                                                        *
 * Copyright (c) 2015 Florian Oetke & Sebastian Schalow                   *
 *                                                                        *
 *  This file is part of MagnumOpus and distributed under the MIT License *
 *  See LICENSE file for details.                                         *
\**************************************************************************/

#pragma once

#include <glm/glm.hpp>

#include "../engine.hpp"

namespace mo {
namespace renderer {

	class Camera {

	public:

		// Constructors
		Camera(const Engine &engine, float world_scale=1.f,
		       const glm::vec2 position=glm::vec2(0.0f), float zoom=1.0f) noexcept;

		// Methods
		void position(glm::vec2 pos) noexcept {_pos = pos; _dirty = true;}
		void move(glm::vec2 offset) noexcept {_pos+=offset; _dirty = true;}
		void zoom(float z) noexcept {_zoom=z; _dirty=true;}
		void viewport(glm::vec4 viewport)noexcept;

		auto zoom() const noexcept { return _zoom; }
		auto position() const noexcept { return _pos; }
		auto viewport() const noexcept { return _viewport; }
        auto world_scale() const noexcept { return _world_scale; }

		auto vp() const noexcept -> const glm::mat4&;

		auto screen_to_world(const glm::vec2 screen_pos) const noexcept -> glm::vec2;
		auto world_to_screen(const glm::vec2 world_pos) const noexcept -> glm::vec2;

	private:
		void recalc_vp()const noexcept;

		glm::vec4 _viewport; //< x,y,w,h
		glm::mat4 _projection;

		const float _world_scale;
		float _zoom;
		glm::vec2 _pos;
		mutable glm::mat4 _vp;
		mutable bool _dirty;

	};
}
}
<|endoftext|>


<commit_before>#if !defined(BOOST_PP_IS_ITERATING) || !BOOST_PP_IS_ITERATING

#ifndef SHEAR__LALR__REDUCE_HPP
#define SHEAR__LALR__REDUCE_HPP

#include <boost/preprocessor/iteration/iterate.hpp>
#include <boost/preprocessor/iteration/local.hpp>
#include <boost/preprocessor/arithmetic/sub.hpp>
#include <boost/fusion/include/transform.hpp>
#include <boost/fusion/algorithm/transformation/remove.hpp>

#include <shear/compiletime/argument_type.hpp>
#include <shear/lalr/any_symbol.hpp>

namespace shear { namespace lalr {

namespace detail {

template<typename T, typename ArgVec>
typename boost::enable_if<
  typename mpl::equal_to<
    typename mpl::size<ArgVec>::type,
    mpl::size_t<0>
  >::type,
  T*
>::type new_expand_vector(const ArgVec& args) {
  return new T();
}

template<typename T, typename ArgVec>
typename boost::enable_if<
  typename mpl::equal_to<
    typename mpl::size<ArgVec>::type,
    mpl::size_t<1>
  >::type,
  T*
>::type new_expand_vector(const ArgVec& args) {
  return new T(fusion::at<mpl::size_t<0> >(args));
}

#define BOOST_PP_ITERATION_PARAMS_1 \
  (3, (2, SHEAR_PRODUCTION_LIMIT, "shear/lalr/reduce.hpp"))
#include BOOST_PP_ITERATE()

} // namespace detail

template<
  typename Grammar,
  typename Production,
  typename SymbolIndexType,
  typename Symbols
>
any_symbol<SymbolIndexType> reduce(const Symbols& symbols)
{
  typedef typename Production::argument_tags tags;
  typedef typename fusion::result_of::as_vector<tags>::type tags_vector_type;
  tags_vector_type tags_vector;
  typedef typename fusion::result_of::transform<
    const Symbols, tags_vector_type, compiletime::argument_type
  >::type transformed_symbols_type;
  transformed_symbols_type transformed_symbols(
      symbols, tags_vector, compiletime::argument_type()
    );
  typedef typename fusion::result_of::remove<
    transformed_symbols_type,
    void
  >::type filtered_symbols_type;
  filtered_symbols_type filtered_symbols(transformed_symbols);
  typedef typename Production::source result_type;
  boost::shared_ptr<result_type> result(
      detail::new_expand_vector<result_type>(
        fusion::as_vector(filtered_symbols)
      )
    );
  return any_symbol<SymbolIndexType>(
      result,
      mpl::at<typename Grammar::symbol_index_map, result_type>::type::value
    );
}

}}

#endif // SHEAR__LALR__REDUCE_HPP

#else // iterating

template<typename T, typename ArgVec>
typename boost::enable_if<
  typename mpl::equal_to<
    typename mpl::size<ArgVec>::type,
    mpl::size_t<BOOST_PP_ITERATION()>
  >::type,
  T*
>::type new_expand_vector(const ArgVec& args) {
  return new T(
#define BOOST_PP_LOCAL_MACRO(index) \
      fusion::at<mpl::size_t<index> >(args),
#define BOOST_PP_LOCAL_LIMITS (0, BOOST_PP_SUB(BOOST_PP_ITERATION(), 2))
#include BOOST_PP_LOCAL_ITERATE()
      fusion::at<mpl::size_t<BOOST_PP_ITERATION()-1> >(args)
    );
}

#endif

<commit_msg>Avoid unused argument warning<commit_after>#if !defined(BOOST_PP_IS_ITERATING) || !BOOST_PP_IS_ITERATING

#ifndef SHEAR__LALR__REDUCE_HPP
#define SHEAR__LALR__REDUCE_HPP

#include <boost/preprocessor/iteration/iterate.hpp>
#include <boost/preprocessor/iteration/local.hpp>
#include <boost/preprocessor/arithmetic/sub.hpp>
#include <boost/fusion/include/transform.hpp>
#include <boost/fusion/algorithm/transformation/remove.hpp>

#include <shear/compiletime/argument_type.hpp>
#include <shear/lalr/any_symbol.hpp>

namespace shear { namespace lalr {

namespace detail {

template<typename T, typename ArgVec>
typename boost::enable_if<
  typename mpl::equal_to<
    typename mpl::size<ArgVec>::type,
    mpl::size_t<0>
  >::type,
  T*
>::type new_expand_vector(const ArgVec&) {
  return new T();
}

template<typename T, typename ArgVec>
typename boost::enable_if<
  typename mpl::equal_to<
    typename mpl::size<ArgVec>::type,
    mpl::size_t<1>
  >::type,
  T*
>::type new_expand_vector(const ArgVec& args) {
  return new T(fusion::at<mpl::size_t<0> >(args));
}

#define BOOST_PP_ITERATION_PARAMS_1 \
  (3, (2, SHEAR_PRODUCTION_LIMIT, "shear/lalr/reduce.hpp"))
#include BOOST_PP_ITERATE()

} // namespace detail

template<
  typename Grammar,
  typename Production,
  typename SymbolIndexType,
  typename Symbols
>
any_symbol<SymbolIndexType> reduce(const Symbols& symbols)
{
  typedef typename Production::argument_tags tags;
  typedef typename fusion::result_of::as_vector<tags>::type tags_vector_type;
  tags_vector_type tags_vector;
  typedef typename fusion::result_of::transform<
    const Symbols, tags_vector_type, compiletime::argument_type
  >::type transformed_symbols_type;
  transformed_symbols_type transformed_symbols(
      symbols, tags_vector, compiletime::argument_type()
    );
  typedef typename fusion::result_of::remove<
    transformed_symbols_type,
    void
  >::type filtered_symbols_type;
  filtered_symbols_type filtered_symbols(transformed_symbols);
  typedef typename Production::source result_type;
  boost::shared_ptr<result_type> result(
      detail::new_expand_vector<result_type>(
        fusion::as_vector(filtered_symbols)
      )
    );
  return any_symbol<SymbolIndexType>(
      result,
      mpl::at<typename Grammar::symbol_index_map, result_type>::type::value
    );
}

}}

#endif // SHEAR__LALR__REDUCE_HPP

#else // iterating

template<typename T, typename ArgVec>
typename boost::enable_if<
  typename mpl::equal_to<
    typename mpl::size<ArgVec>::type,
    mpl::size_t<BOOST_PP_ITERATION()>
  >::type,
  T*
>::type new_expand_vector(const ArgVec& args) {
  return new T(
#define BOOST_PP_LOCAL_MACRO(index) \
      fusion::at<mpl::size_t<index> >(args),
#define BOOST_PP_LOCAL_LIMITS (0, BOOST_PP_SUB(BOOST_PP_ITERATION(), 2))
#include BOOST_PP_LOCAL_ITERATE()
      fusion::at<mpl::size_t<BOOST_PP_ITERATION()-1> >(args)
    );
}

#endif

<|endoftext|>


<commit_before>#include <QString>
#include <QDir>
#include <QtCore>
#include <iostream>

int main(int argc, char** argv)
{
    //QCoreApplication app(argc, argv);
    QDir dir;

    dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
    dir.setSorting(QDir::Size | QDir::Reversed);

    QString path = argv[1];

    dir.cd(path);

    QFileInfoList list = dir.entryInfoList();

    std::cout << "     Bytes Filename" << std::endl;

    for (int i = 0; i < list.size(); ++i)
    {
        QFileInfo fileInfo = list.at(i);

        std::cout << qPrintable(QString("%1 %2").arg(fileInfo.size(), 10).arg(fileInfo.fileName()));
        std::cout << std::endl;
    }

    return 0; //app.exec();
}

<commit_msg>Add QCoreApplication app. Replace return 0 on return app.exec().<commit_after>#include <QString>
#include <QDir>
#include <QtCore>
#include <iostream>

int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);
    QDir dir;

    dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
    dir.setSorting(QDir::Size | QDir::Reversed);

    QString path = argv[1];

    dir.cd(path);

    QFileInfoList list = dir.entryInfoList();

    std::cout << "     Bytes Filename" << std::endl;

    for (int i = 0; i < list.size(); ++i)
    {
        QFileInfo fileInfo = list.at(i);

        std::cout << qPrintable(QString("%1 %2").arg(fileInfo.size(), 10).arg(fileInfo.fileName()));
        std::cout << std::endl;
    }

    return app.exec();
}

<|endoftext|>


<commit_before>#include <CQMsgHandler.h>

#include <QApplication>

namespace CQMsgHandler {

bool
checkEnv(const char *name) {
  const char *p = getenv(name);
  if (! p) return false;

  QString s = p;

  return (s == "1" || s == "true" || s == "yes");
}

bool
isIgnoreMsg(const QString &msg)
{
  static QStringList ignoreMessages;

  if (ignoreMessages.empty()) {
    ignoreMessages.push_back("QBasicTimer can only be used with threads started with QThread");
  }

  for (const auto &imsg : ignoreMessages) {
    if (msg.indexOf(imsg) > 0)
      return true;
  }

  return false;
}

void
messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
  auto localMsg = msg.toLocal8Bit();

  if (isIgnoreMsg(localMsg))
    return;

  switch (type) {
    case QtDebugMsg: {
      fprintf(stderr, "Debug: %s (%s:%u, %s)\n",
              localMsg.constData(), context.file, context.line, context.function);
      break;
    }
    case QtInfoMsg: {
      fprintf(stderr, "Info: %s (%s:%u, %s)\n",
              localMsg.constData(), context.file, context.line, context.function);
      break;
    }
    case QtWarningMsg: {
      fprintf(stderr, "Warning: %s (%s:%u, %s)\n",
              localMsg.constData(), context.file, context.line, context.function);

      if (checkEnv("CQMSG_HANDLER_WARN_ASSERT"))
        abort();

      break;
    }
    case QtCriticalMsg: {
      fprintf(stderr, "Critical: %s (%s:%u, %s)\n",
              localMsg.constData(), context.file, context.line, context.function);
      abort();
      break;
    }
    case QtFatalMsg: {
      fprintf(stderr, "Fatal: %s (%s:%u, %s)\n",
              localMsg.constData(), context.file, context.line, context.function);
      abort();
      break;
    }
  }
}

}

namespace CQMsgHandler {

void
install()
{
  qInstallMessageHandler(messageOutput);
}

}
<commit_msg>new files<commit_after>#include <CQMsgHandler.h>

#include <QApplication>

namespace CQMsgHandler {

bool
checkEnv(const char *name) {
  const char *p = getenv(name);
  if (! p) return false;

  QString s = p;

  return (s == "1" || s == "true" || s == "yes");
}

bool
isIgnoreMsg(const QString &msg)
{
  static QStringList ignoreMessages;

  if (ignoreMessages.empty()) {
    ignoreMessages.push_back("QBasicTimer can only be used with threads started with QThread");
    ignoreMessages.push_back("Timers can only be used with threads started with QThread");
  }

  for (const auto &imsg : ignoreMessages) {
    if (msg.indexOf(imsg) > 0)
      return true;
  }

  return false;
}

void
messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
  auto localMsg = msg.toLocal8Bit();

  if (isIgnoreMsg(localMsg))
    return;

  switch (type) {
    case QtDebugMsg: {
      fprintf(stderr, "Debug: %s (%s:%u, %s)\n",
              localMsg.constData(), context.file, context.line, context.function);
      break;
    }
    case QtInfoMsg: {
      fprintf(stderr, "Info: %s (%s:%u, %s)\n",
              localMsg.constData(), context.file, context.line, context.function);
      break;
    }
    case QtWarningMsg: {
      fprintf(stderr, "Warning: %s (%s:%u, %s)\n",
              localMsg.constData(), context.file, context.line, context.function);

      if (checkEnv("CQMSG_HANDLER_WARN_ASSERT"))
        abort();

      break;
    }
    case QtCriticalMsg: {
      fprintf(stderr, "Critical: %s (%s:%u, %s)\n",
              localMsg.constData(), context.file, context.line, context.function);
      abort();
      break;
    }
    case QtFatalMsg: {
      fprintf(stderr, "Fatal: %s (%s:%u, %s)\n",
              localMsg.constData(), context.file, context.line, context.function);
      abort();
      break;
    }
  }
}

}

namespace CQMsgHandler {

void
install()
{
  qInstallMessageHandler(messageOutput);
}

}
<|endoftext|>


<commit_before>#include <assert.h>
#include <list>
#include <algorithm>
#include <portmidi.h>
#include "core.hpp"

using namespace rack;

static bool initialized = false;

void midiInit() {
	if (initialized)
		return;

	PmError err = Pm_Initialize();
	if (err) {
		printf("Failed to initialize PortMidi: %s\n", Pm_GetErrorText(err));
		return;
	}
	initialized = true;
}

struct MidiInterface : Module {
	enum ParamIds {
		NUM_PARAMS
	};
	enum InputIds {
		NUM_INPUTS
	};
	enum OutputIds {
		PITCH_OUTPUT,
		GATE_OUTPUT,
		MOD_OUTPUT,
		PITCHWHEEL_OUTPUT,
		NUM_OUTPUTS
	};

	int portId = -1;
	PortMidiStream *stream = NULL;
	std::list<int> notes;
	/** Filter MIDI channel
	-1 means all MIDI channels
	*/
	int channel = -1;
	bool pedal = false;
	int note = 60; // C4, most modules should use 261.626 Hz
	int mod = 0;
	int pitchWheel = 64;
	bool retrigger = false;
	bool retriggered = false;

	MidiInterface();
	~MidiInterface();
	void step();

	int getPortCount();
	std::string getPortName(int portId);
	// -1 will close the port
	void openPort(int portId);
	void pressNote(int note);
	void releaseNote(int note);
	void processMidi(long msg);
};

MidiInterface::MidiInterface() {
	params.resize(NUM_PARAMS);
	inputs.resize(NUM_INPUTS);
	outputs.resize(NUM_OUTPUTS);
	midiInit();

	printf("<<<%d>>>\n", getPortCount());
}

MidiInterface::~MidiInterface() {
	openPort(-1);
}

void MidiInterface::step() {
	if (stream) {
		// Read MIDI events
		PmEvent event;
		while (Pm_Read(stream, &event, 1) > 0) {
			processMidi(event.message);
		}
	}

	if (outputs[PITCH_OUTPUT]) {
		*outputs[PITCH_OUTPUT] = ((note - 64)) / 12.0;
	}
	if (outputs[GATE_OUTPUT]) {
		bool gate = pedal || !notes.empty();
		if (retrigger && retriggered) {
			gate = false;
			retriggered = false;
		}
		*outputs[GATE_OUTPUT] = gate ? 5.0 : 0.0;
	}
	if (outputs[MOD_OUTPUT]) {
		*outputs[MOD_OUTPUT] = mod;
	}
	if (outputs[PITCHWHEEL_OUTPUT]) {
		*outputs[PITCHWHEEL_OUTPUT] = (pitchWheel - 64) / 64.0 / 12.0;
	}
}

int MidiInterface::getPortCount() {
	return Pm_CountDevices();
}

std::string MidiInterface::getPortName(int portId) {
	const PmDeviceInfo *info = Pm_GetDeviceInfo(portId);
	if (!info)
		return "";
	return stringf("%s: %s (%s)", info->interf, info->name, info->input ? "input" : "output");
}

void MidiInterface::openPort(int portId) {
	PmError err;

	// Close existing port
	if (stream) {
		err = Pm_Close(stream);
		if (err) {
			printf("Failed to close MIDI port: %s\n", Pm_GetErrorText(err));
		}
		stream = NULL;
	}

	// Open new port
	if (portId >= 0) {
		err = Pm_OpenInput(&stream, portId, NULL, 128, NULL, NULL);
		if (err) {
			printf("Failed to open MIDI port: %s\n", Pm_GetErrorText(err));
			return;
		}
	}
	this->portId = portId;
}

void MidiInterface::pressNote(int note) {
	// Remove existing similar note
	auto it = std::find(notes.begin(), notes.end(), note);
	if (it != notes.end())
		notes.erase(it);
	// Push note
	notes.push_back(note);
	this->note = note;
	retriggered = true;
}

void MidiInterface::releaseNote(int note) {
	// Remove the note
	auto it = std::find(notes.begin(), notes.end(), note);
	if (it != notes.end())
		notes.erase(it);

	if (pedal) {
		// Don't release if pedal is held
	}
	else if (!notes.empty()) {
		// Play previous note
		auto it2 = notes.end();
		it2--;
		this->note = *it2;
		retriggered = true;
	}
}

void MidiInterface::processMidi(long msg) {
	int channel = msg & 0xf;
	int status = (msg >> 4) & 0xf;
	int data1 = (msg >> 8) & 0xff;
	int data2 = (msg >> 16) & 0xff;

	if (channel != 0)
		return;
	printf("channel %d status %d data1 %d data2 %d\n", channel, status, data1, data2);

	switch (status) {
		// note off
		case 0x8: {
			releaseNote(data1);
		} break;
		case 0x9: // note on
			if (data2 > 0) {
				pressNote(data1);
			}
			else {
				// For some reason, some keyboards send a "note on" event with a velocity of 0 to signal that the key has been released.
				releaseNote(data1);
			}
			break;
		case 0xb: // cc
			switch (data1) {
				case 0x40:
					pedal = (data2 >= 64);
					releaseNote(-1);
					break;
			}
			break;
		case 0xe: // pitch wheel
			this->pitchWheel = data2;
			break;
	}
}

struct MidiItem : MenuItem {
	MidiInterface *midiInterface;
	int portId;
	void onAction() {
		midiInterface->openPort(portId);
	}
};

struct MidiChoice : ChoiceButton {
	MidiInterface *midiInterface;
	void onAction() {
		Menu *menu = gScene->createMenu();
		menu->box.pos = getAbsolutePos().plus(Vec(0, box.size.y));
		menu->box.size.x = box.size.x;

		int portCount = midiInterface->getPortCount();
		{
			MidiItem *midiItem = new MidiItem();
			midiItem->midiInterface = midiInterface;
			midiItem->portId = -1;
			midiItem->text = "No device";
			menu->pushChild(midiItem);
		}
		for (int portId = 0; portId < portCount; portId++) {
			MidiItem *midiItem = new MidiItem();
			midiItem->midiInterface = midiInterface;
			midiItem->portId = portId;
			midiItem->text = midiInterface->getPortName(portId);
			menu->pushChild(midiItem);
		}
	}
	void step() {
		std::string name = midiInterface->getPortName(midiInterface->portId);
		text = name.empty() ? "(no device)" : ellipsize(name, 14);
	}
};

struct ChannelItem : MenuItem {
	MidiInterface *midiInterface;
	int channel;
	void onAction() {
		midiInterface->channel = channel;
	}
};

struct ChannelChoice : ChoiceButton {
	MidiInterface *midiInterface;
	void onAction() {
		Menu *menu = gScene->createMenu();
		menu->box.pos = getAbsolutePos().plus(Vec(0, box.size.y));
		menu->box.size.x = box.size.x;

		{
			ChannelItem *channelItem = new ChannelItem();
			channelItem->midiInterface = midiInterface;
			channelItem->channel = -1;
			channelItem->text = "All";
			menu->pushChild(channelItem);
		}
		for (int channel = 0; channel < 16; channel++) {
			ChannelItem *channelItem = new ChannelItem();
			channelItem->midiInterface = midiInterface;
			channelItem->channel = channel;
			channelItem->text = stringf("%d", channel + 1);
			menu->pushChild(channelItem);
		}
	}
	void step() {
		text = (midiInterface->channel >= 0) ? stringf("%d", midiInterface->channel + 1) : "All";
	}
};

MidiInterfaceWidget::MidiInterfaceWidget() {
	MidiInterface *module = new MidiInterface();
	setModule(module);
	box.size = Vec(15*8, 380);

	{
		Panel *panel = new LightPanel();
		panel->box.size = box.size;
		addChild(panel);
	}

	float margin = 5;
	float labelHeight = 15;
	float yPos = margin;

	{
		Label *label = new Label();
		label->box.pos = Vec(margin, yPos);
		label->text = "MIDI device";
		addChild(label);
		yPos += labelHeight + margin;

		MidiChoice *midiChoice = new MidiChoice();
		midiChoice->midiInterface = dynamic_cast<MidiInterface*>(module);
		midiChoice->box.pos = Vec(margin, yPos);
		midiChoice->box.size.x = box.size.x - 10;
		addChild(midiChoice);
		yPos += midiChoice->box.size.y + margin;
	}

	{
		Label *label = new Label();
		label->box.pos = Vec(margin, yPos);
		label->text = "MIDI channel";
		addChild(label);
		yPos += labelHeight + margin;

		ChannelChoice *channelChoice = new ChannelChoice();
		channelChoice->midiInterface = dynamic_cast<MidiInterface*>(module);
		channelChoice->box.pos = Vec(margin, yPos);
		channelChoice->box.size.x = box.size.x - 10;
		addChild(channelChoice);
		yPos += channelChoice->box.size.y + margin;
	}

	yPos += 5;
	addOutput(createOutput<PJ3410Port>(Vec(20, yPos), module, MidiInterface::PITCH_OUTPUT));
	yPos += 37 + margin;

	yPos += 5;
	addOutput(createOutput<PJ3410Port>(Vec(20, yPos), module, MidiInterface::GATE_OUTPUT));
	yPos += 37 + margin;

	yPos += 5;
	addOutput(createOutput<PJ3410Port>(Vec(20, yPos), module, MidiInterface::MOD_OUTPUT));
	yPos += 37 + margin;

	yPos += 5;
	addOutput(createOutput<PJ3410Port>(Vec(20, yPos), module, MidiInterface::PITCHWHEEL_OUTPUT));
	yPos += 37 + margin;
}
<commit_msg>Added mod wheel and MIDI channel functionality to MIDI Interface<commit_after>#include <assert.h>
#include <list>
#include <algorithm>
#include <portmidi.h>
#include "core.hpp"

using namespace rack;

static bool initialized = false;

void midiInit() {
	if (initialized)
		return;

	PmError err = Pm_Initialize();
	if (err) {
		printf("Failed to initialize PortMidi: %s\n", Pm_GetErrorText(err));
		return;
	}
	initialized = true;
}

struct MidiInterface : Module {
	enum ParamIds {
		NUM_PARAMS
	};
	enum InputIds {
		NUM_INPUTS
	};
	enum OutputIds {
		PITCH_OUTPUT,
		GATE_OUTPUT,
		MOD_OUTPUT,
		PITCHWHEEL_OUTPUT,
		NUM_OUTPUTS
	};

	int portId = -1;
	PortMidiStream *stream = NULL;
	std::list<int> notes;
	/** Filter MIDI channel
	-1 means all MIDI channels
	*/
	int channel = -1;
	bool pedal = false;
	int note = 60; // C4, most modules should use 261.626 Hz
	int mod = 0;
	int pitchWheel = 64;
	bool retrigger = false;
	bool retriggered = false;

	MidiInterface();
	~MidiInterface();
	void step();

	int getPortCount();
	std::string getPortName(int portId);
	// -1 will close the port
	void openPort(int portId);
	void pressNote(int note);
	void releaseNote(int note);
	void processMidi(long msg);
};

MidiInterface::MidiInterface() {
	params.resize(NUM_PARAMS);
	inputs.resize(NUM_INPUTS);
	outputs.resize(NUM_OUTPUTS);
	midiInit();
}

MidiInterface::~MidiInterface() {
	openPort(-1);
}

void MidiInterface::step() {
	if (stream) {
		// Read MIDI events
		PmEvent event;
		while (Pm_Read(stream, &event, 1) > 0) {
			processMidi(event.message);
		}
	}

	if (outputs[PITCH_OUTPUT]) {
		*outputs[PITCH_OUTPUT] = ((note - 64)) / 12.0;
	}
	if (outputs[GATE_OUTPUT]) {
		bool gate = pedal || !notes.empty();
		if (retrigger && retriggered) {
			gate = false;
			retriggered = false;
		}
		*outputs[GATE_OUTPUT] = gate ? 10.0 : 0.0;
	}
	if (outputs[MOD_OUTPUT]) {
		*outputs[MOD_OUTPUT] = mod / 127.0 * 10.0;
	}
	if (outputs[PITCHWHEEL_OUTPUT]) {
		*outputs[PITCHWHEEL_OUTPUT] = (pitchWheel - 64) / 64.0 * 10.0;
	}
}

int MidiInterface::getPortCount() {
	return Pm_CountDevices();
}

std::string MidiInterface::getPortName(int portId) {
	const PmDeviceInfo *info = Pm_GetDeviceInfo(portId);
	if (!info)
		return "";
	return stringf("%s: %s (%s)", info->interf, info->name, info->input ? "input" : "output");
}

void MidiInterface::openPort(int portId) {
	PmError err;

	// Close existing port
	if (stream) {
		err = Pm_Close(stream);
		if (err) {
			printf("Failed to close MIDI port: %s\n", Pm_GetErrorText(err));
		}
		stream = NULL;
	}
	this->portId = -1;

	// Open new port
	if (portId >= 0) {
		err = Pm_OpenInput(&stream, portId, NULL, 128, NULL, NULL);
		if (err) {
			printf("Failed to open MIDI port: %s\n", Pm_GetErrorText(err));
			return;
		}
	}
	this->portId = portId;
}

void MidiInterface::pressNote(int note) {
	// Remove existing similar note
	auto it = std::find(notes.begin(), notes.end(), note);
	if (it != notes.end())
		notes.erase(it);
	// Push note
	notes.push_back(note);
	this->note = note;
	retriggered = true;
}

void MidiInterface::releaseNote(int note) {
	// Remove the note
	auto it = std::find(notes.begin(), notes.end(), note);
	if (it != notes.end())
		notes.erase(it);

	if (pedal) {
		// Don't release if pedal is held
	}
	else if (!notes.empty()) {
		// Play previous note
		auto it2 = notes.end();
		it2--;
		this->note = *it2;
		retriggered = true;
	}
}

void MidiInterface::processMidi(long msg) {
	int channel = msg & 0xf;
	int status = (msg >> 4) & 0xf;
	int data1 = (msg >> 8) & 0xff;
	int data2 = (msg >> 16) & 0xff;
	printf("channel %d status %d data1 %d data2 %d\n", channel, status, data1, data2);

	// Filter channels
	if (this->channel >= 0 && this->channel != channel)
		return;

	switch (status) {
		// note off
		case 0x8: {
			releaseNote(data1);
		} break;
		case 0x9: // note on
			if (data2 > 0) {
				pressNote(data1);
			}
			else {
				// For some reason, some keyboards send a "note on" event with a velocity of 0 to signal that the key has been released.
				releaseNote(data1);
			}
			break;
		case 0xb: // cc
			switch (data1) {
				case 0x01: // mod
					this->mod = data2;
					break;
				case 0x40: // sustain
					pedal = (data2 >= 64);
					releaseNote(-1);
					break;
			}
			break;
		case 0xe: // pitch wheel
			this->pitchWheel = data2;
			break;
	}
}

struct MidiItem : MenuItem {
	MidiInterface *midiInterface;
	int portId;
	void onAction() {
		midiInterface->openPort(portId);
	}
};

struct MidiChoice : ChoiceButton {
	MidiInterface *midiInterface;
	void onAction() {
		Menu *menu = gScene->createMenu();
		menu->box.pos = getAbsolutePos().plus(Vec(0, box.size.y));
		menu->box.size.x = box.size.x;

		int portCount = midiInterface->getPortCount();
		{
			MidiItem *midiItem = new MidiItem();
			midiItem->midiInterface = midiInterface;
			midiItem->portId = -1;
			midiItem->text = "No device";
			menu->pushChild(midiItem);
		}
		for (int portId = 0; portId < portCount; portId++) {
			MidiItem *midiItem = new MidiItem();
			midiItem->midiInterface = midiInterface;
			midiItem->portId = portId;
			midiItem->text = midiInterface->getPortName(portId);
			menu->pushChild(midiItem);
		}
	}
	void step() {
		std::string name = midiInterface->getPortName(midiInterface->portId);
		text = name.empty() ? "(no device)" : ellipsize(name, 14);
	}
};

struct ChannelItem : MenuItem {
	MidiInterface *midiInterface;
	int channel;
	void onAction() {
		midiInterface->channel = channel;
	}
};

struct ChannelChoice : ChoiceButton {
	MidiInterface *midiInterface;
	void onAction() {
		Menu *menu = gScene->createMenu();
		menu->box.pos = getAbsolutePos().plus(Vec(0, box.size.y));
		menu->box.size.x = box.size.x;

		{
			ChannelItem *channelItem = new ChannelItem();
			channelItem->midiInterface = midiInterface;
			channelItem->channel = -1;
			channelItem->text = "All";
			menu->pushChild(channelItem);
		}
		for (int channel = 0; channel < 16; channel++) {
			ChannelItem *channelItem = new ChannelItem();
			channelItem->midiInterface = midiInterface;
			channelItem->channel = channel;
			channelItem->text = stringf("%d", channel + 1);
			menu->pushChild(channelItem);
		}
	}
	void step() {
		text = (midiInterface->channel >= 0) ? stringf("%d", midiInterface->channel + 1) : "All";
	}
};

MidiInterfaceWidget::MidiInterfaceWidget() {
	MidiInterface *module = new MidiInterface();
	setModule(module);
	box.size = Vec(15*8, 380);

	{
		Panel *panel = new LightPanel();
		panel->box.size = box.size;
		addChild(panel);
	}

	float margin = 5;
	float labelHeight = 15;
	float yPos = margin;

	{
		Label *label = new Label();
		label->box.pos = Vec(margin, yPos);
		label->text = "MIDI device";
		addChild(label);
		yPos += labelHeight + margin;

		MidiChoice *midiChoice = new MidiChoice();
		midiChoice->midiInterface = dynamic_cast<MidiInterface*>(module);
		midiChoice->box.pos = Vec(margin, yPos);
		midiChoice->box.size.x = box.size.x - 10;
		addChild(midiChoice);
		yPos += midiChoice->box.size.y + margin;
	}

	{
		Label *label = new Label();
		label->box.pos = Vec(margin, yPos);
		label->text = "MIDI channel";
		addChild(label);
		yPos += labelHeight + margin;

		ChannelChoice *channelChoice = new ChannelChoice();
		channelChoice->midiInterface = dynamic_cast<MidiInterface*>(module);
		channelChoice->box.pos = Vec(margin, yPos);
		channelChoice->box.size.x = box.size.x - 10;
		addChild(channelChoice);
		yPos += channelChoice->box.size.y + margin;
	}

	yPos += 5;
	addOutput(createOutput<PJ3410Port>(Vec(20, yPos), module, MidiInterface::PITCH_OUTPUT));
	yPos += 37 + margin;

	yPos += 5;
	addOutput(createOutput<PJ3410Port>(Vec(20, yPos), module, MidiInterface::GATE_OUTPUT));
	yPos += 37 + margin;

	yPos += 5;
	addOutput(createOutput<PJ3410Port>(Vec(20, yPos), module, MidiInterface::MOD_OUTPUT));
	yPos += 37 + margin;

	yPos += 5;
	addOutput(createOutput<PJ3410Port>(Vec(20, yPos), module, MidiInterface::PITCHWHEEL_OUTPUT));
	yPos += 37 + margin;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBitmapCache.h"
#include "SkImage.h"
#include "SkResourceCache.h"
#include "SkMipMap.h"
#include "SkPixelRef.h"
#include "SkRect.h"

/**
 *  Use this for bitmapcache and mipmapcache entries.
 */
uint64_t SkMakeResourceCacheSharedIDForBitmap(uint32_t bitmapGenID) {
    uint64_t sharedID = SkSetFourByteTag('b', 'm', 'a', 'p');
    return (sharedID << 32) | bitmapGenID;
}

void SkNotifyBitmapGenIDIsStale(uint32_t bitmapGenID) {
    SkResourceCache::PostPurgeSharedID(SkMakeResourceCacheSharedIDForBitmap(bitmapGenID));
}

///////////////////////////////////////////////////////////////////////////////////////////////////

SkBitmap::Allocator* SkBitmapCache::GetAllocator() {
    return SkResourceCache::GetAllocator();
}

/**
 This function finds the bounds of the bitmap *within its pixelRef*.
 If the bitmap lacks a pixelRef, it will return an empty rect, since
 that doesn't make sense.  This may be a useful enough function that
 it should be somewhere else (in SkBitmap?).
 */
static SkIRect get_bounds_from_bitmap(const SkBitmap& bm) {
    if (!(bm.pixelRef())) {
        return SkIRect::MakeEmpty();
    }
    SkIPoint origin = bm.pixelRefOrigin();
    return SkIRect::MakeXYWH(origin.fX, origin.fY, bm.width(), bm.height());
}

/**
 *  This function finds the bounds of the image. Today this is just the entire bounds,
 *  but in the future we may support subsets within an image, in which case this should
 *  return that subset (see get_bounds_from_bitmap).
 */
static SkIRect get_bounds_from_image(const SkImage* image) {
    return SkIRect::MakeWH(image->width(), image->height());
}

SkBitmapCacheDesc SkBitmapCacheDesc::Make(const SkBitmap& bm, int width, int height) {
    SkBitmapCacheDesc desc;
    desc.fImageID = bm.getGenerationID();
    desc.fWidth = width;
    desc.fHeight = height;
    desc.fBounds = get_bounds_from_bitmap(bm);
    return desc;
}

SkBitmapCacheDesc SkBitmapCacheDesc::Make(const SkBitmap& bm) {
    return Make(bm, bm.width(), bm.height());
}

SkBitmapCacheDesc SkBitmapCacheDesc::Make(const SkImage* image, int width, int height) {
    SkBitmapCacheDesc desc;
    desc.fImageID = image->uniqueID();
    desc.fWidth = width;
    desc.fHeight = height;
    desc.fBounds = get_bounds_from_image(image);
    return desc;
}

SkBitmapCacheDesc SkBitmapCacheDesc::Make(const SkImage* image) {
    return Make(image, image->width(), image->height());
}

namespace {
static unsigned gBitmapKeyNamespaceLabel;

struct BitmapKey : public SkResourceCache::Key {
public:
    BitmapKey(uint32_t genID, int width, int height, const SkIRect& bounds)
        : fGenID(genID)
        , fWidth(width)
        , fHeight(height)
        , fBounds(bounds)
    {
        this->init(&gBitmapKeyNamespaceLabel, SkMakeResourceCacheSharedIDForBitmap(fGenID),
                   sizeof(fGenID) + sizeof(fWidth) + sizeof(fHeight) + sizeof(fBounds));
    }

    BitmapKey(const SkBitmapCacheDesc& desc)
        : fGenID(desc.fImageID)
        , fWidth(desc.fWidth)
        , fHeight(desc.fHeight)
        , fBounds(desc.fBounds)
    {
        this->init(&gBitmapKeyNamespaceLabel, SkMakeResourceCacheSharedIDForBitmap(fGenID),
                   sizeof(fGenID) + sizeof(fWidth) + sizeof(fHeight) + sizeof(fBounds));
    }

    void dump() const {
        SkDebugf("-- add [%d %d] %d [%d %d %d %d]\n", fWidth, fHeight, fGenID,
                 fBounds.x(), fBounds.y(), fBounds.width(), fBounds.height());
    }

    const uint32_t  fGenID;
    const int       fWidth;
    const int       fHeight;
    const SkIRect   fBounds;
};

struct BitmapRec : public SkResourceCache::Rec {
    BitmapRec(uint32_t genID, int width, int height, const SkIRect& bounds,
              const SkBitmap& result)
        : fKey(genID, width, height, bounds)
        , fBitmap(result)
    {
#ifdef TRACE_NEW_BITMAP_CACHE_RECS
        fKey.dump();
#endif
    }

    BitmapRec(const SkBitmapCacheDesc& desc, const SkBitmap& result)
        : fKey(desc)
        , fBitmap(result)
    {
#ifdef TRACE_NEW_BITMAP_CACHE_RECS
        fKey.dump();
#endif
    }

    const Key& getKey() const override { return fKey; }
    size_t bytesUsed() const override { return sizeof(fKey) + fBitmap.getSize(); }

    const char* getCategory() const override { return "bitmap"; }
    SkDiscardableMemory* diagnostic_only_getDiscardable() const override {
        return fBitmap.pixelRef()->diagnostic_only_getDiscardable();
    }

    static bool Finder(const SkResourceCache::Rec& baseRec, void* contextBitmap) {
        const BitmapRec& rec = static_cast<const BitmapRec&>(baseRec);
        SkBitmap* result = (SkBitmap*)contextBitmap;

        *result = rec.fBitmap;
        result->lockPixels();
        return SkToBool(result->getPixels());
    }

private:
    BitmapKey   fKey;
    SkBitmap    fBitmap;
};
} // namespace

#define CHECK_LOCAL(localCache, localName, globalName, ...) \
    ((localCache) ? localCache->localName(__VA_ARGS__) : SkResourceCache::globalName(__VA_ARGS__))

bool SkBitmapCache::FindWH(const SkBitmapCacheDesc& desc, SkBitmap* result,
                           SkResourceCache* localCache) {
    if (0 == desc.fWidth || 0 == desc.fHeight) {
        // degenerate
        return false;
    }
    return CHECK_LOCAL(localCache, find, Find, BitmapKey(desc), BitmapRec::Finder, result);
}

bool SkBitmapCache::AddWH(const SkBitmapCacheDesc& desc, const SkBitmap& result,
                          SkResourceCache* localCache) {
    if (0 == desc.fWidth || 0 == desc.fHeight) {
        // degenerate, and the key we use for mipmaps
        return false;
    }
    SkASSERT(result.isImmutable());
    BitmapRec* rec = new BitmapRec(desc, result);
    CHECK_LOCAL(localCache, add, Add, rec);
    return true;
}

bool SkBitmapCache::Find(uint32_t genID, const SkIRect& subset, SkBitmap* result,
                         SkResourceCache* localCache) {
    BitmapKey key(genID, SK_Scalar1, SK_Scalar1, subset);

    return CHECK_LOCAL(localCache, find, Find, key, BitmapRec::Finder, result);
}

bool SkBitmapCache::Add(SkPixelRef* pr, const SkIRect& subset, const SkBitmap& result,
                        SkResourceCache* localCache) {
    SkASSERT(result.isImmutable());

    if (subset.isEmpty()
        || subset.top() < 0
        || subset.left() < 0
        || result.width() != subset.width()
        || result.height() != subset.height()) {
        return false;
    } else {
        BitmapRec* rec = new BitmapRec(pr->getGenerationID(), 1, 1, subset, result);

        CHECK_LOCAL(localCache, add, Add, rec);
        pr->notifyAddedToCache();
        return true;
    }
}

bool SkBitmapCache::Find(uint32_t genID, SkBitmap* result, SkResourceCache* localCache) {
    BitmapKey key(genID, SK_Scalar1, SK_Scalar1, SkIRect::MakeEmpty());

    return CHECK_LOCAL(localCache, find, Find, key, BitmapRec::Finder, result);
}

void SkBitmapCache::Add(uint32_t genID, const SkBitmap& result, SkResourceCache* localCache) {
    SkASSERT(result.isImmutable());

    BitmapRec* rec = new BitmapRec(genID, 1, 1, SkIRect::MakeEmpty(), result);

    CHECK_LOCAL(localCache, add, Add, rec);
}

//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////

namespace {
static unsigned gMipMapKeyNamespaceLabel;

struct MipMapKey : public SkResourceCache::Key {
public:
    MipMapKey(uint32_t genID, SkSourceGammaTreatment treatment, const SkIRect& bounds)
        : fGenID(genID), fSrcGammaTreatment(static_cast<uint32_t>(treatment)), fBounds(bounds)
    {
        this->init(&gMipMapKeyNamespaceLabel, SkMakeResourceCacheSharedIDForBitmap(genID),
                   sizeof(fGenID) + sizeof(fSrcGammaTreatment) + sizeof(fBounds));
    }

    uint32_t    fGenID;
    uint32_t    fSrcGammaTreatment;
    SkIRect     fBounds;
};

struct MipMapRec : public SkResourceCache::Rec {
    MipMapRec(const SkBitmap& src, SkSourceGammaTreatment treatment, const SkMipMap* result)
        : fKey(src.getGenerationID(), treatment, get_bounds_from_bitmap(src))
        , fMipMap(result)
    {
        fMipMap->attachToCacheAndRef();
    }

    virtual ~MipMapRec() {
        fMipMap->detachFromCacheAndUnref();
    }

    const Key& getKey() const override { return fKey; }
    size_t bytesUsed() const override { return sizeof(fKey) + fMipMap->size(); }
    const char* getCategory() const override { return "mipmap"; }
    SkDiscardableMemory* diagnostic_only_getDiscardable() const override {
        return fMipMap->diagnostic_only_getDiscardable();
    }

    static bool Finder(const SkResourceCache::Rec& baseRec, void* contextMip) {
        const MipMapRec& rec = static_cast<const MipMapRec&>(baseRec);
        const SkMipMap* mm = SkRef(rec.fMipMap);
        // the call to ref() above triggers a "lock" in the case of discardable memory,
        // which means we can now check for null (in case the lock failed).
        if (nullptr == mm->data()) {
            mm->unref();    // balance our call to ref()
            return false;
        }
        // the call must call unref() when they are done.
        *(const SkMipMap**)contextMip = mm;
        return true;
    }

private:
    MipMapKey       fKey;
    const SkMipMap* fMipMap;
};
}

const SkMipMap* SkMipMapCache::FindAndRef(const SkBitmapCacheDesc& desc,
                                          SkSourceGammaTreatment treatment,
                                          SkResourceCache* localCache) {
    // Note: we ignore width/height from desc, just need id and bounds
    MipMapKey key(desc.fImageID, treatment, desc.fBounds);
    const SkMipMap* result;

    if (!CHECK_LOCAL(localCache, find, Find, key, MipMapRec::Finder, &result)) {
        result = nullptr;
    }
    return result;
}

static SkResourceCache::DiscardableFactory get_fact(SkResourceCache* localCache) {
    return localCache ? localCache->GetDiscardableFactory()
                      : SkResourceCache::GetDiscardableFactory();
}

const SkMipMap* SkMipMapCache::AddAndRef(const SkBitmap& src, SkSourceGammaTreatment treatment,
                                         SkResourceCache* localCache) {
    SkMipMap* mipmap = SkMipMap::Build(src, treatment, get_fact(localCache));
    if (mipmap) {
        MipMapRec* rec = new MipMapRec(src, treatment, mipmap);
        CHECK_LOCAL(localCache, add, Add, rec);
        src.pixelRef()->notifyAddedToCache();
    }
    return mipmap;
}
<commit_msg>minor simplification: use SkBitmapCacheDesc<commit_after>/*
 * Copyright 2014 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBitmapCache.h"
#include "SkImage.h"
#include "SkResourceCache.h"
#include "SkMipMap.h"
#include "SkPixelRef.h"
#include "SkRect.h"

/**
 *  Use this for bitmapcache and mipmapcache entries.
 */
uint64_t SkMakeResourceCacheSharedIDForBitmap(uint32_t bitmapGenID) {
    uint64_t sharedID = SkSetFourByteTag('b', 'm', 'a', 'p');
    return (sharedID << 32) | bitmapGenID;
}

void SkNotifyBitmapGenIDIsStale(uint32_t bitmapGenID) {
    SkResourceCache::PostPurgeSharedID(SkMakeResourceCacheSharedIDForBitmap(bitmapGenID));
}

///////////////////////////////////////////////////////////////////////////////////////////////////

SkBitmap::Allocator* SkBitmapCache::GetAllocator() {
    return SkResourceCache::GetAllocator();
}

/**
 This function finds the bounds of the bitmap *within its pixelRef*.
 If the bitmap lacks a pixelRef, it will return an empty rect, since
 that doesn't make sense.  This may be a useful enough function that
 it should be somewhere else (in SkBitmap?).
 */
static SkIRect get_bounds_from_bitmap(const SkBitmap& bm) {
    if (!(bm.pixelRef())) {
        return SkIRect::MakeEmpty();
    }
    SkIPoint origin = bm.pixelRefOrigin();
    return SkIRect::MakeXYWH(origin.fX, origin.fY, bm.width(), bm.height());
}

/**
 *  This function finds the bounds of the image. Today this is just the entire bounds,
 *  but in the future we may support subsets within an image, in which case this should
 *  return that subset (see get_bounds_from_bitmap).
 */
static SkIRect get_bounds_from_image(const SkImage* image) {
    return SkIRect::MakeWH(image->width(), image->height());
}

SkBitmapCacheDesc SkBitmapCacheDesc::Make(const SkBitmap& bm, int width, int height) {
    return { bm.getGenerationID(), width, height, get_bounds_from_bitmap(bm) };
}

SkBitmapCacheDesc SkBitmapCacheDesc::Make(const SkBitmap& bm) {
    return Make(bm, bm.width(), bm.height());
}

SkBitmapCacheDesc SkBitmapCacheDesc::Make(const SkImage* image, int width, int height) {
    return { image->uniqueID(), width, height, get_bounds_from_image(image) };
}

SkBitmapCacheDesc SkBitmapCacheDesc::Make(const SkImage* image) {
    return Make(image, image->width(), image->height());
}

namespace {
static unsigned gBitmapKeyNamespaceLabel;

struct BitmapKey : public SkResourceCache::Key {
public:
    BitmapKey(uint32_t genID, int width, int height, const SkIRect& bounds)
        : fDesc({ genID, width, height, bounds })
    {
        this->init(&gBitmapKeyNamespaceLabel, SkMakeResourceCacheSharedIDForBitmap(fDesc.fImageID),
                   sizeof(fDesc));
    }

    BitmapKey(const SkBitmapCacheDesc& desc) : fDesc(desc) {
        this->init(&gBitmapKeyNamespaceLabel, SkMakeResourceCacheSharedIDForBitmap(fDesc.fImageID),
                   sizeof(fDesc));
    }

    void dump() const {
        SkDebugf("-- add [%d %d] %d [%d %d %d %d]\n", fDesc.fWidth, fDesc.fHeight, fDesc.fImageID,
            fDesc.fBounds.x(), fDesc.fBounds.y(), fDesc.fBounds.width(), fDesc.fBounds.height());
    }

    const SkBitmapCacheDesc fDesc;
};

struct BitmapRec : public SkResourceCache::Rec {
    BitmapRec(uint32_t genID, int width, int height, const SkIRect& bounds, const SkBitmap& result)
        : fKey(genID, width, height, bounds)
        , fBitmap(result)
    {
#ifdef TRACE_NEW_BITMAP_CACHE_RECS
        fKey.dump();
#endif
    }

    BitmapRec(const SkBitmapCacheDesc& desc, const SkBitmap& result)
        : fKey(desc)
        , fBitmap(result)
    {
#ifdef TRACE_NEW_BITMAP_CACHE_RECS
        fKey.dump();
#endif
    }

    const Key& getKey() const override { return fKey; }
    size_t bytesUsed() const override { return sizeof(fKey) + fBitmap.getSize(); }

    const char* getCategory() const override { return "bitmap"; }
    SkDiscardableMemory* diagnostic_only_getDiscardable() const override {
        return fBitmap.pixelRef()->diagnostic_only_getDiscardable();
    }

    static bool Finder(const SkResourceCache::Rec& baseRec, void* contextBitmap) {
        const BitmapRec& rec = static_cast<const BitmapRec&>(baseRec);
        SkBitmap* result = (SkBitmap*)contextBitmap;

        *result = rec.fBitmap;
        result->lockPixels();
        return SkToBool(result->getPixels());
    }

private:
    BitmapKey   fKey;
    SkBitmap    fBitmap;
};
} // namespace

#define CHECK_LOCAL(localCache, localName, globalName, ...) \
    ((localCache) ? localCache->localName(__VA_ARGS__) : SkResourceCache::globalName(__VA_ARGS__))

bool SkBitmapCache::FindWH(const SkBitmapCacheDesc& desc, SkBitmap* result,
                           SkResourceCache* localCache) {
    if (0 == desc.fWidth || 0 == desc.fHeight) {
        // degenerate
        return false;
    }
    return CHECK_LOCAL(localCache, find, Find, BitmapKey(desc), BitmapRec::Finder, result);
}

bool SkBitmapCache::AddWH(const SkBitmapCacheDesc& desc, const SkBitmap& result,
                          SkResourceCache* localCache) {
    if (0 == desc.fWidth || 0 == desc.fHeight) {
        // degenerate, and the key we use for mipmaps
        return false;
    }
    SkASSERT(result.isImmutable());
    BitmapRec* rec = new BitmapRec(desc, result);
    CHECK_LOCAL(localCache, add, Add, rec);
    return true;
}

bool SkBitmapCache::Find(uint32_t genID, const SkIRect& subset, SkBitmap* result,
                         SkResourceCache* localCache) {
    BitmapKey key(genID, SK_Scalar1, SK_Scalar1, subset);

    return CHECK_LOCAL(localCache, find, Find, key, BitmapRec::Finder, result);
}

bool SkBitmapCache::Add(SkPixelRef* pr, const SkIRect& subset, const SkBitmap& result,
                        SkResourceCache* localCache) {
    SkASSERT(result.isImmutable());

    if (subset.isEmpty()
        || subset.top() < 0
        || subset.left() < 0
        || result.width() != subset.width()
        || result.height() != subset.height()) {
        return false;
    } else {
        BitmapRec* rec = new BitmapRec(pr->getGenerationID(), 1, 1, subset, result);

        CHECK_LOCAL(localCache, add, Add, rec);
        pr->notifyAddedToCache();
        return true;
    }
}

bool SkBitmapCache::Find(uint32_t genID, SkBitmap* result, SkResourceCache* localCache) {
    BitmapKey key(genID, SK_Scalar1, SK_Scalar1, SkIRect::MakeEmpty());

    return CHECK_LOCAL(localCache, find, Find, key, BitmapRec::Finder, result);
}

void SkBitmapCache::Add(uint32_t genID, const SkBitmap& result, SkResourceCache* localCache) {
    SkASSERT(result.isImmutable());

    BitmapRec* rec = new BitmapRec(genID, 1, 1, SkIRect::MakeEmpty(), result);

    CHECK_LOCAL(localCache, add, Add, rec);
}

//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////

namespace {
static unsigned gMipMapKeyNamespaceLabel;

struct MipMapKey : public SkResourceCache::Key {
public:
    MipMapKey(uint32_t genID, SkSourceGammaTreatment treatment, const SkIRect& bounds)
        : fGenID(genID), fSrcGammaTreatment(static_cast<uint32_t>(treatment)), fBounds(bounds)
    {
        this->init(&gMipMapKeyNamespaceLabel, SkMakeResourceCacheSharedIDForBitmap(genID),
                   sizeof(fGenID) + sizeof(fSrcGammaTreatment) + sizeof(fBounds));
    }

    uint32_t    fGenID;
    uint32_t    fSrcGammaTreatment;
    SkIRect     fBounds;
};

struct MipMapRec : public SkResourceCache::Rec {
    MipMapRec(const SkBitmap& src, SkSourceGammaTreatment treatment, const SkMipMap* result)
        : fKey(src.getGenerationID(), treatment, get_bounds_from_bitmap(src))
        , fMipMap(result)
    {
        fMipMap->attachToCacheAndRef();
    }

    virtual ~MipMapRec() {
        fMipMap->detachFromCacheAndUnref();
    }

    const Key& getKey() const override { return fKey; }
    size_t bytesUsed() const override { return sizeof(fKey) + fMipMap->size(); }
    const char* getCategory() const override { return "mipmap"; }
    SkDiscardableMemory* diagnostic_only_getDiscardable() const override {
        return fMipMap->diagnostic_only_getDiscardable();
    }

    static bool Finder(const SkResourceCache::Rec& baseRec, void* contextMip) {
        const MipMapRec& rec = static_cast<const MipMapRec&>(baseRec);
        const SkMipMap* mm = SkRef(rec.fMipMap);
        // the call to ref() above triggers a "lock" in the case of discardable memory,
        // which means we can now check for null (in case the lock failed).
        if (nullptr == mm->data()) {
            mm->unref();    // balance our call to ref()
            return false;
        }
        // the call must call unref() when they are done.
        *(const SkMipMap**)contextMip = mm;
        return true;
    }

private:
    MipMapKey       fKey;
    const SkMipMap* fMipMap;
};
}

const SkMipMap* SkMipMapCache::FindAndRef(const SkBitmapCacheDesc& desc,
                                          SkSourceGammaTreatment treatment,
                                          SkResourceCache* localCache) {
    // Note: we ignore width/height from desc, just need id and bounds
    MipMapKey key(desc.fImageID, treatment, desc.fBounds);
    const SkMipMap* result;

    if (!CHECK_LOCAL(localCache, find, Find, key, MipMapRec::Finder, &result)) {
        result = nullptr;
    }
    return result;
}

static SkResourceCache::DiscardableFactory get_fact(SkResourceCache* localCache) {
    return localCache ? localCache->GetDiscardableFactory()
                      : SkResourceCache::GetDiscardableFactory();
}

const SkMipMap* SkMipMapCache::AddAndRef(const SkBitmap& src, SkSourceGammaTreatment treatment,
                                         SkResourceCache* localCache) {
    SkMipMap* mipmap = SkMipMap::Build(src, treatment, get_fact(localCache));
    if (mipmap) {
        MipMapRec* rec = new MipMapRec(src, treatment, mipmap);
        CHECK_LOCAL(localCache, add, Add, rec);
        src.pixelRef()->notifyAddedToCache();
    }
    return mipmap;
}
<|endoftext|>


<commit_before>#include "config.hpp"
#include "vfs.hpp"
#include <iostream>
#include <fstream>
//#include <streambuf>
#include <sstream>

#ifdef PLATFORM_WINDOWS
#include <windows.h>
#include <Winerror.h>
#elif defined(PLATFORM_OSX)
#include <mach-o/dyld.h>
#else
#include <unistd.h>
#include <linux/limits.h>
#endif

static std::string basePath;
static std::string homePath;
#if OSX_APP_BUNDLE
static std::string appPath;
#endif

ttvfs::Root VFS;

namespace MgCore
{
    std::string read_raw_file(std::string filename)
    {
        std::ifstream in(filename, std::ios::in | std::ios_base::ate);
        if (in) {
            std::string contents;
            contents.resize(static_cast<unsigned int>(in.tellg()));
            in.seekg(0, std::ios::beg);
            in.read(&contents[0], contents.size());
            in.close();
            return contents;
        } else {
            return "";
        }
    }

    std::string read_file(std::string filename)
    {
        ttvfs::File *vf = VFS.GetFile( filename.c_str() );

        if ( vf && vf->open("r") ) {
            std::string contents;
            contents.resize( static_cast<unsigned int>(vf->size()) );
            vf->read(&contents[0], contents.size());
            vf->close();
            return contents;
        } else {
            return "";
        }
    }

    bool getFileStream(std::string filename, std::istream &stream)
    {
            std::stringbuf contents( read_file( filename ) );
            stream.rdbuf( &contents );
            return stream.good();
    }

    std::string GetBasePath() // executable path
    {
        if ( basePath.empty() )
        {
#if defined(PLATFORM_WINDOWS)
            char buffer[MAX_PATH];//always use MAX_PATH for filepaths
            GetModuleFileName( NULL, buffer, sizeof(buffer) );

            basePath = buffer;

#elif defined(PLATFORM_OSX)
            char path[8192];
            uint32_t size = sizeof(path);

            if ( _NSGetExecutablePath( path, &size ) < 0 )
            {
                return "";
            }

            basePath = path;

#elif defined(PLATFORM_LINUX)
            char buff[PATH_MAX];
            ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
            if (len != -1)
            {
                buff[len] = '\0';
                basePath = buff;
            } else
                basePath = "";
#endif

            // remove executable name so we just have the path
            int pos = basePath.rfind( PATH_SEP );

            basePath = basePath.substr( 0, pos+1 );

#if OSX_APP_BUNDLE
            appPath = basePath; // store full appPath

            // on osx we only want the path containing the app when checking BasePath
            pos = basePath.rfind( "MacOS" );

            if ( pos != std::string::npos )
            {
                basePath = basePath.substr( 0, pos+1 );

                pos = basePath.rfind( "Contents" );

                if ( pos != std::string::npos )
                {
                    basePath = basePath.substr( 0, pos+1 );

                    pos = basePath.rfind( APP_NAME );

                    if ( pos != std::string::npos )
                        basePath = basePath.substr( 0, pos );
                }
            }
#endif
        }

        return basePath;
    }

    std::string GetHomePath() // home/library path to store configs
    {
#if defined(PLATFORM_WINDOWS)
        TCHAR szPath[MAX_PATH];
        FARPROC qSHGetFolderPath;
        HMODULE shfolder = LoadLibrary("shfolder.dll");

        if(shfolder == NULL)
            return NULL;

        if( homePath.empty() )
        {
            qSHGetFolderPath = GetProcAddress(shfolder, "SHGetFolderPathA");
            if(qSHGetFolderPath == NULL)
            {
                FreeLibrary(shfolder);
                return NULL;
            }

            if( !SUCCEEDED( qSHGetFolderPath( NULL, CSIDL_APPDATA, NULL, 0, szPath ) ) )
            {
                FreeLibrary(shfolder);
                return NULL;
            }

            homePath = szPath;
            homePath += PATH_SEP;

            homePath += HOMEPATH_NAME;
        }

        FreeLibrary(shfolder);
#else
        char *p;

        if( homePath.empty() )
        {

            if( ( p = getenv( "HOME" ) ) != NULL )
            {
                homePath = p ;
                homePath += PATH_SEP ;

#if defined(PLATFORM_OSX)
                homePath += "Library/Application Support/";
#endif

                homePath += HOMEPATH_NAME;
            }
        }
#endif
        return homePath;
    }

#if OSX_APP_BUNDLE
    std::string GetAppPath() // OSX get internal app path
    {
        return appPath;
    }
#endif
}
<commit_msg>More windows fixes.<commit_after>#include "config.hpp"
#include "vfs.hpp"
#include <iostream>
#include <fstream>
//#include <streambuf>
#include <sstream>

#ifdef PLATFORM_WINDOWS
#include <windows.h>
#include <Winerror.h>
#elif defined(PLATFORM_OSX)
#include <mach-o/dyld.h>
#else
#include <unistd.h>
#include <linux/limits.h>
#endif

static std::string basePath;
static std::string homePath;
#if OSX_APP_BUNDLE
static std::string appPath;
#endif

ttvfs::Root VFS;

namespace MgCore
{
    std::string read_raw_file(std::string filename)
    {
        std::ifstream in(filename, std::ios::in | std::ios_base::ate);
        if (in) {
            std::string contents;
            contents.resize(static_cast<unsigned int>(in.tellg()));
            in.seekg(0, std::ios::beg);
            in.read(&contents[0], contents.size());
            in.close();
            return contents;
        } else {
            return "";
        }
    }

    std::string read_file(std::string filename)
    {
        ttvfs::File *vf = VFS.GetFile( filename.c_str() );

        if ( vf && vf->open("r") ) {
            std::string contents;
            contents.resize( static_cast<unsigned int>(vf->size()) );
            vf->read(&contents[0], contents.size());
            vf->close();
            return contents;
        } else {
            return "";
        }
    }

    bool getFileStream(std::string filename, std::istream &stream)
    {
            std::stringbuf contents( read_file( filename ) );
            stream.rdbuf( &contents );
            return stream.good();
    }

    std::string GetBasePath() // executable path
    {
        if ( basePath.empty() )
        {
#if defined(PLATFORM_WINDOWS)
            char buffer[MAX_PATH];//always use MAX_PATH for filepaths
            GetModuleFileName( NULL, buffer, sizeof(buffer) );

            basePath = buffer;

#elif defined(PLATFORM_OSX)
            char path[8192];
            uint32_t size = sizeof(path);

            if ( _NSGetExecutablePath( path, &size ) < 0 )
            {
                return "";
            }

            basePath = path;

#elif defined(PLATFORM_LINUX)
            char buff[PATH_MAX];
            ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
            if (len != -1)
            {
                buff[len] = '\0';
                basePath = buff;
            } else
                basePath = "";
#endif

            // remove executable name so we just have the path
            int pos = basePath.rfind( PATH_SEP );

            basePath = basePath.substr( 0, pos+1 );

#if OSX_APP_BUNDLE
            appPath = basePath; // store full appPath

            // on osx we only want the path containing the app when checking BasePath
            pos = basePath.rfind( "MacOS" );

            if ( pos != std::string::npos )
            {
                basePath = basePath.substr( 0, pos+1 );

                pos = basePath.rfind( "Contents" );

                if ( pos != std::string::npos )
                {
                    basePath = basePath.substr( 0, pos+1 );

                    pos = basePath.rfind( APP_NAME );

                    if ( pos != std::string::npos )
                        basePath = basePath.substr( 0, pos );
                }
            }
#endif
        }

        return basePath;
    }

    std::string GetHomePath() // home/library path to store configs
    {
#if defined(PLATFORM_WINDOWS)
        TCHAR szPath[MAX_PATH];

        if( homePath.empty() )
        {
            if( !SUCCEEDED( SHGetFolderPath( NULL, CSIDL_APPDATA, NULL, 0, szPath ) ) )
            {
                return NULL;
            }

            homePath = szPath;
            homePath += PATH_SEP;

            homePath += HOMEPATH_NAME;
        }
#else
        char *p;

        if( homePath.empty() )
        {

            if( ( p = getenv( "HOME" ) ) != NULL )
            {
                homePath = p ;
                homePath += PATH_SEP ;

#if defined(PLATFORM_OSX)
                homePath += "Library/Application Support/";
#endif

                homePath += HOMEPATH_NAME;
            }
        }
#endif
        return homePath;
    }

#if OSX_APP_BUNDLE
    std::string GetAppPath() // OSX get internal app path
    {
        return appPath;
    }
#endif
}
<|endoftext|>


<commit_before>/*
Copyright 2014-2015 Adam Grandquist

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.
 */
/**
 * @author Adam Grandquist
 * @copyright Apache
 */

#ifndef REQL_EXPR_HPP_
#define REQL_EXPR_HPP_

#include "./cpp/new.hpp"

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

namespace ReQL {

class Query;

class Expr {
public:
  bool operator<(const Expr &other) const;

  explicit Expr(const Expr &other);
  explicit Expr(Expr &&other);

  Expr &operator=(const Expr &other);
  Expr &operator=(Expr &&other);

  ReQL_Obj_t *data() const;

protected:
  Expr();
  explicit Expr(const ReQL_AST_Function &f, const std::vector<Query> &args, const std::map<std::string, Query> &kwargs);
  explicit Expr(const std::string &val);
  explicit Expr(const double &val);
  explicit Expr(const bool &val);
  explicit Expr(const std::vector<Query> &val);
  explicit Expr(const std::map<std::string, Query> &val);
  virtual void copy(const Expr &other);
  virtual void move(Expr &&other);

private:
  ReQL p_query;
  ReQL_AST_Function p_func;
  std::vector<Expr> p_array;
  std::map<Expr, Expr> p_object;
};

}  // namespace ReQL

#endif  // REQL_EXPR_HPP_
<commit_msg>Remove virtual table from Expr class.<commit_after>/*
Copyright 2014-2015 Adam Grandquist

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.
 */
/**
 * @author Adam Grandquist
 * @copyright Apache
 */

#ifndef REQL_EXPR_HPP_
#define REQL_EXPR_HPP_

#include "./cpp/new.hpp"

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

namespace ReQL {

class Query;

class Expr {
public:
  bool operator<(const Expr &other) const;

  explicit Expr(const Expr &other);
  explicit Expr(Expr &&other);

  Expr &operator=(const Expr &other);
  Expr &operator=(Expr &&other);

  ReQL_Obj_t *data() const;

protected:
  Expr();
  explicit Expr(const ReQL_AST_Function &f, const std::vector<Query> &args, const std::map<std::string, Query> &kwargs);
  explicit Expr(const std::string &val);
  explicit Expr(const double &val);
  explicit Expr(const bool &val);
  explicit Expr(const std::vector<Query> &val);
  explicit Expr(const std::map<std::string, Query> &val);
  void copy(const Expr &other);
  void move(Expr &&other);

private:
  ReQL p_query;
  ReQL_AST_Function p_func;
  std::vector<Expr> p_array;
  std::map<Expr, Expr> p_object;
};

}  // namespace ReQL

#endif  // REQL_EXPR_HPP_
<|endoftext|>


<commit_before>/**************************************************
 * Source Code for the Original Compiler for the
 * Programming Language Wake
 *
 * wake.cpp
 *
 * Licensed under the MIT license
 * See LICENSE.TXT for details
 *
 * Author: Michael Fairhurst
 * Revised By:
 *
 **************************************************/

#include <stdio.h>
#include <iostream>
#include <sstream>
#include <fstream>

#include "tree.h"
extern "C" {
	#include "node.h"
	#include "wake.tab.h"
	extern int yyparse();
	extern Node* parsetree;
	extern FILE *yyin;
}

#include "error.h"
#include "Parser.h"
#include "Linker.h"
#include "ParseTreeTraverser.h"
#include "SemanticErrorPrinter.h"
#include "LibraryLoader.h"
#include "ObjectFileGenerator.h"
#include "ObjectFileHeaderData.h"
#include "ObjectFileHeaderRenderer.h"
#include "CompilationExceptions.h"
#include "OptionsParser.h"
#include "EntryPointAnalyzer.h"
#include "AddressAllocator.h"
#include "TableFileWriter.h"
#include "SimpleAddressTable.h"
#include "ImportParseTreeTraverser.h"
#include "ErrorTracker.h"
#include <boost/filesystem.hpp>

void writeTableFiles(std::string dirname, ClassSpaceSymbolTable& table) {
	vector<PropertySymbolTable*> tables = table.getDefinedClasses();
	for(vector<PropertySymbolTable*>::iterator it = tables.begin(); it != tables.end(); ++it) {
		fstream file;

		string filename = dirname;
		if(table.getModule().size()) {
			filename += "/" + table.getModule();
			boost::filesystem::create_directory(filename);
		}
		filename += "/" + (*it)->classname + ".table";

		file.open((filename).c_str(), ios::out | ios::binary);
		TableFileWriter writer;
		writer.write(file, *it);
		file.close();
	}
}

void compileFile(Options* options) {

	if(options->compileFilename == "") {
		printf("[ no file provided ]\n"); exit(1);
	}

	FILE *myfile = fopen(options->compileFilename.c_str(), "r");
	error_open_file(options->compileFilename.c_str());

	if (!myfile) {
		printf("[ couldn't open file ]\n");
		exit(2);
	}

	Parser parser;

	// Parse the shit out of this
	if(parser.parse(myfile)) exit(3);
	//parser.print();exit(0);

	ClassSpaceSymbolTable table;
	ErrorTracker errors;
	LibraryLoader loader;
	loader.loadStdLibToTable(&table);
	ImportParseTreeTraverser importer;
	errors.pushContext("Import header");
	importer.traverse(parser.getParseTree(), table, loader, errors, options->tabledir);
	errors.popContext();

	if(parser.getParseTree()->node_data.nodes[0]->node_type == NT_MODULE) {
		table.setModule(parser.getParseTree()->node_data.nodes[0]->node_data.string);
	}
	// Now do all the semantic analysis
	ParseTreeTraverser traverser(&table, errors);
	traverser.traverse(parser.getParseTree());

	SemanticErrorPrinter printer;

	if(!traverser.passesForCompilation()) {
		traverser.printErrors(printer);
		exit(4);
	}

	if(options->table) {
		writeTableFiles(options->tabledir, table);
		return;
	}

	basic_ostringstream<char> object;
	ObjectFileHeaderData header;

	ObjectFileGenerator gen(object, &table, &header);
	gen.generate(parser.getParseTree());

	fstream file;
	ObjectFileHeaderRenderer renderer;

	file.open(options->outFilename.c_str(), ios::out);
	renderer.writeOut(file, &header);
	file << object.str();
	file.close();

	writeTableFiles(options->tabledir.c_str(), table);
}

int main(int argc, char** argv) {
	OptionsParser optionsparser;
	Options options = optionsparser.parse(argc, argv);
	if(options.showVersion) {
		printf("[ Wake    ---- std compiler ]\n");
		printf("[ v0.2.1  Michael Fairhurst ]\n");
		exit(0);
	}

	if(options.showHelp) {
		printf("usage: wake flags filename\n");
		printf("flags: -o|--out file             - compile to this file\n");
		printf("       -c|--mainclass class      - begin execution with this file\n");
		printf("       -m|--mainemethod method   - begin execution with this method\n");
		printf("       -v|--version              - show version and exit\n");
		printf("       -h|--help                 - show help and exit\n");
		printf("       -i|--listmains            - list compilable entrypoints\n");
		printf("       -l|--link                 - link compiled files into an executable\n");
		printf("       -t|--table                - only generate table files\n");
		printf("       -d|--tabledir             - dir for finding and creating .table files\n");
		exit(0);
	}

	if(!options.link) compileFile(&options);
	else {
		try {
			AddressAllocator classAllocator;
			AddressAllocator propAllocator;
			ClassSpaceSymbolTable table;
			SimpleAddressTable classTable(classAllocator);
			SimpleAddressTable propTable(propAllocator);
			Linker linker(classTable, propTable);
			for(std::vector<std::string>::iterator it = options.linkFilenames.begin(); it != options.linkFilenames.end(); ++it) {
				linker.loadObject(*it);
			}

			LibraryLoader loader;
			loader.loadStdLibToTable(&table);
			linker.loadTables(options.tabledir, table);

			try {
				table.assertNoNeedsAreCircular();
			} catch(SemanticError* e) {
				e->token = NULL;
				SemanticErrorPrinter printer;
				printer.print(e);
				delete e;
				return 1;
			}

			fstream file;
			file.open(options.outFilename.c_str(), ios::out);

			linker.write(file);
			linker.writeDebugSymbols(file); // @todo make this optional

			EntryPointAnalyzer entrypointanalyzer;
			if(options.listMains) {
				table.printEntryPoints(&entrypointanalyzer);
				exit(0);
			} else {
				if(!entrypointanalyzer.checkFQClassMethodCanBeMain(options.mainclass, options.mainmethod, &table)) {
					printf("Entry point %s.%s in not valid, cannot continue.\nTry wake yourfile --listmains to get entry points\n", options.mainclass.c_str(), options.mainmethod.c_str());
					exit(5);
				}
			}

			linker.setMain(file, options.mainclass, options.mainmethod, table);
		} catch(SymbolNotFoundException* e) {
			cout << "Missing symbol in object files at link time: " << e->errormsg << endl;
			delete e;
		}

	}

}
<commit_msg>Compilation option for printing recursive dependency info<commit_after>/**************************************************
 * Source Code for the Original Compiler for the
 * Programming Language Wake
 *
 * wake.cpp
 *
 * Licensed under the MIT license
 * See LICENSE.TXT for details
 *
 * Author: Michael Fairhurst
 * Revised By:
 *
 **************************************************/

#include <stdio.h>
#include <iostream>
#include <sstream>
#include <fstream>

#include "tree.h"
extern "C" {
	#include "node.h"
	#include "wake.tab.h"
	extern int yyparse();
	extern Node* parsetree;
	extern FILE *yyin;
}

#include "error.h"
#include "Parser.h"
#include "Linker.h"
#include "ParseTreeTraverser.h"
#include "SemanticErrorPrinter.h"
#include "LibraryLoader.h"
#include "ObjectFileGenerator.h"
#include "ObjectFileHeaderData.h"
#include "ObjectFileHeaderRenderer.h"
#include "CompilationExceptions.h"
#include "OptionsParser.h"
#include "EntryPointAnalyzer.h"
#include "AddressAllocator.h"
#include "TableFileWriter.h"
#include "SimpleAddressTable.h"
#include "ImportParseTreeTraverser.h"
#include "ErrorTracker.h"
#include <boost/filesystem.hpp>
#include <boost/unordered_set.hpp>
using namespace boost;

void writeTableFiles(std::string dirname, ClassSpaceSymbolTable& table) {
	vector<PropertySymbolTable*> tables = table.getDefinedClasses();
	for(vector<PropertySymbolTable*>::iterator it = tables.begin(); it != tables.end(); ++it) {
		fstream file;

		string filename = dirname;
		if(table.getModule().size()) {
			filename += "/" + table.getModule();
			boost::filesystem::create_directory(filename);
		}
		filename += "/" + (*it)->classname + ".table";

		file.open((filename).c_str(), ios::out | ios::binary);
		TableFileWriter writer;
		writer.write(file, *it);
		file.close();
	}
}

void compileFile(Options* options) {

	if(options->compileFilename == "") {
		printf("[ no file provided ]\n"); exit(1);
	}

	FILE *myfile = fopen(options->compileFilename.c_str(), "r");
	error_open_file(options->compileFilename.c_str());

	if (!myfile) {
		printf("[ couldn't open file ]\n");
		exit(2);
	}

	Parser parser;

	// Parse the shit out of this
	if(parser.parse(myfile)) exit(3);
	//parser.print();exit(0);

	ClassSpaceSymbolTable table;
	ErrorTracker errors;
	LibraryLoader loader;
	loader.loadStdLibToTable(&table);
	ImportParseTreeTraverser importer;
	errors.pushContext("Import header");
	importer.traverse(parser.getParseTree(), table, loader, errors, options->tabledir);
	errors.popContext();

	if(parser.getParseTree()->node_data.nodes[0]->node_type == NT_MODULE) {
		table.setModule(parser.getParseTree()->node_data.nodes[0]->node_data.string);
	}
	// Now do all the semantic analysis
	ParseTreeTraverser traverser(&table, errors);
	traverser.traverse(parser.getParseTree());

	SemanticErrorPrinter printer;

	if(!traverser.passesForCompilation()) {
		traverser.printErrors(printer);
		exit(4);
	}

	if(options->table) {
		writeTableFiles(options->tabledir, table);
		return;
	}

	basic_ostringstream<char> object;
	ObjectFileHeaderData header;

	ObjectFileGenerator gen(object, &table, &header);
	gen.generate(parser.getParseTree());

	fstream file;
	ObjectFileHeaderRenderer renderer;

	file.open(options->outFilename.c_str(), ios::out);
	renderer.writeOut(file, &header);
	file << object.str();
	file.close();

	writeTableFiles(options->tabledir.c_str(), table);
}

void findRecursiveDeps(string module, string classname, map<pair<string, string>, vector<pair<string, string> > >& depInfoMap, unordered_set<pair<string, string> >& recursiveDeps) {
	if(recursiveDeps.find(pair<string, string>(module, classname)) != recursiveDeps.end()) {
		return;
	}

	recursiveDeps.insert(pair<string, string>(module, classname));

	vector<pair<string, string> > importingClasses = depInfoMap[pair<string, string>(module, classname)];

	for(vector<pair<string, string> >::iterator it = importingClasses.begin(); it != importingClasses.end(); ++it) {
		findRecursiveDeps(it->first, it->second, depInfoMap, recursiveDeps);
	}
}

void gatherDependencyInfo(Options* options, string module, string classname, map<pair<string, string>, vector<pair<string, string> > >& depInfoMap, unordered_set<pair<string, string> >& allDeps) {
	boost::filesystem::path p(options->compileFilename);
	boost::filesystem::path dir = p.parent_path();
	dir /=  classname + ".wk"; // sweet operator overloading!
	string filename = dir.string();

	if(allDeps.count(pair<string, string>(module, classname))) {
		return;
	}

	allDeps.insert(pair<string, string>(module, classname));

	vector<pair<string, string> > singleFileImports;

	FILE *myfile = fopen(filename.c_str(), "r");

	if (!myfile) {
		cerr << "Warning: couldn't find dependency " << filename << endl;
		cerr << "It won't be searched for cyclical dependencies." << endl;
		cerr << "Is it in a different source directory, or misnamed?" << endl;
		return;
	}

	{
		Parser parser;
		if(parser.parse(myfile)) return;

		ImportParseTreeTraverser importer;
		singleFileImports = importer.gatherImports(parser.getParseTree());
		fclose(myfile);
	}

	for(vector<pair<string, string> >::iterator it = singleFileImports.begin(); it != singleFileImports.end(); ++it) {
		if(depInfoMap.find(*it) == depInfoMap.end()) {
			vector<pair<string, string> > vec;
			vec.push_back(pair<string, string>(module, classname));
			depInfoMap[*it] = vec;
		} else {
			depInfoMap.find(*it)->second.push_back(pair<string, string>(module, classname));
		}

		if(it->first == module) {
			gatherDependencyInfo(options, it->first, it->second, depInfoMap, allDeps);
		} else {
			allDeps.insert(*it);
		}
	}
}

void printDependencies(Options* options) {
	vector<pair<string, string> > singleFileImports;
	unordered_set<pair<string, string> > allDeps;
	unordered_set<pair<string, string> > recursiveDeps;
	map<pair<string, string>, vector<pair<string, string> > > depInfoMap;
	string module;
	string classname;

	if(options->compileFilename == "") {
		printf("[ no file provided ]\n"); exit(1);
	}

	FILE *myfile = fopen(options->compileFilename.c_str(), "r");

	if (!myfile) {
		printf("[ couldn't open file ]\n");
		exit(2);
	}

	{
		Parser parser;
		if(parser.parse(myfile)) return;

		Node* tree = parser.getParseTree();
		module = tree->node_data.nodes[0]->node_data.string;

		tree = tree->node_data.nodes[tree->subnodes - 1];
		while(tree->node_type != NT_TYPEDATA) {
			tree = tree->node_data.nodes[0];
		}

		classname = tree->node_data.pure_type->typedata._class.classname;

		ImportParseTreeTraverser importer;
		singleFileImports = importer.gatherImports(parser.getParseTree());
		fclose(myfile);
	}

	for(vector<pair<string, string> >::iterator it = singleFileImports.begin(); it != singleFileImports.end(); ++it) {
		vector<pair<string, string> > vec;
		vec.push_back(pair<string, string>(module, classname));
		depInfoMap[*it] = vec;
	}

	allDeps.insert(pair<string, string>(module, classname));

	for(vector<pair<string, string> >::iterator it = singleFileImports.begin(); it != singleFileImports.end(); ++it)
	if(it->first == module) {
		gatherDependencyInfo(options, it->first, it->second, depInfoMap, allDeps);
	}

	if(depInfoMap.count(pair<string, string>(module, classname))) {
		findRecursiveDeps(module, classname, depInfoMap, recursiveDeps);
	}

	for(unordered_set<pair<string, string> >::iterator it = allDeps.begin(); it != allDeps.end(); ++it)
	if(it->first != module || it->second != classname) {
		if(recursiveDeps.count(*it)) {
			cout << it->first << "," << it->second << ",TRUE" << endl;
		} else {
			cout << it->first << "," << it->second << ",FALSE" << endl;
		}
	}
}

int main(int argc, char** argv) {
	OptionsParser optionsparser;
	Options options = optionsparser.parse(argc, argv);
	if(options.showVersion) {
		printf("[ Wake    ---- std compiler ]\n");
		printf("[ v0.2.1  Michael Fairhurst ]\n");
		exit(0);
	}

	if(options.showHelp) {
		printf("usage: wake flags filename\n");
		printf("flags: -o|--out file             - compile to this file\n");
		printf("       -c|--mainclass class      - begin execution with this file\n");
		printf("       -m|--mainemethod method   - begin execution with this method\n");
		printf("       -v|--version              - show version and exit\n");
		printf("       -h|--help                 - show help and exit\n");
		printf("       -i|--listmains            - list compilable entrypoints\n");
		printf("       -l|--link                 - link compiled files into an executable\n");
		printf("       -t|--table                - only generate table files\n");
		printf("       -d|--tabledir             - dir for finding and creating .table files\n");
		printf("       -e|--dependencies         - print out dependency information instead of compiling\n");
		exit(0);
	}

	if(!options.link) {
		options.listDeps ? printDependencies(&options) : compileFile(&options);
	} else {
		try {
			AddressAllocator classAllocator;
			AddressAllocator propAllocator;
			ClassSpaceSymbolTable table;
			SimpleAddressTable classTable(classAllocator);
			SimpleAddressTable propTable(propAllocator);
			Linker linker(classTable, propTable);
			for(std::vector<std::string>::iterator it = options.linkFilenames.begin(); it != options.linkFilenames.end(); ++it) {
				linker.loadObject(*it);
			}

			LibraryLoader loader;
			loader.loadStdLibToTable(&table);
			linker.loadTables(options.tabledir, table);

			try {
				table.assertNoNeedsAreCircular();
			} catch(SemanticError* e) {
				e->token = NULL;
				SemanticErrorPrinter printer;
				printer.print(e);
				delete e;
				return 1;
			}

			fstream file;
			file.open(options.outFilename.c_str(), ios::out);

			linker.write(file);
			linker.writeDebugSymbols(file); // @todo make this optional

			EntryPointAnalyzer entrypointanalyzer;
			if(options.listMains) {
				table.printEntryPoints(&entrypointanalyzer);
				exit(0);
			} else {
				if(!entrypointanalyzer.checkFQClassMethodCanBeMain(options.mainclass, options.mainmethod, &table)) {
					printf("Entry point %s.%s in not valid, cannot continue.\nTry wake yourfile --listmains to get entry points\n", options.mainclass.c_str(), options.mainmethod.c_str());
					exit(5);
				}
			}

			linker.setMain(file, options.mainclass, options.mainmethod, table);
		} catch(SymbolNotFoundException* e) {
			cout << "Missing symbol in object files at link time: " << e->errormsg << endl;
			delete e;
		}

	}

}
<|endoftext|>