<commit_before>//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <numeric>
#include <unordered_map>
#include <unordered_set>

#include "cpp_utils/assert.hpp"

#include "summary.hpp"
#include "console.hpp"
#include "accounts.hpp"
#include "compute.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "fortune.hpp"
#include "objectives.hpp"
#include "budget_exception.hpp"
#include "config.hpp"
#include "utils.hpp"
#include "writer.hpp"

using namespace budget;

namespace {

void print_columns(const std::vector<std::string>& columns){
    std::vector<std::vector<std::string>> split_columns;

    for(auto& column : columns){
        split_columns.push_back(budget::split(column, '\n'));
    }

    std::vector<std::string> composed_columns;

    // Compute the total width

    size_t total_max_width = composed_columns.size() * 2;
    size_t max_length = 0;

    for(auto& column : split_columns){
        size_t max_width = 0;

        for(auto& row : column){
            max_width = std::max(max_width, rsize_after(row));
        }

        total_max_width += max_width;

        max_length = std::max(max_length, column.size());
    }

    if (terminal_width() - 3 > total_max_width) {
        // By default, print the columns side by side

        for (auto& column : split_columns) {
            size_t max_width = 0;

            for (auto& row : column) {
                max_width = std::max(max_width, rsize_after(row));
            }

            for (size_t i = 0; i < column.size(); ++i) {
                auto& row = column[i];

                if (i >= composed_columns.size()) {
                    composed_columns.emplace_back();
                }

                composed_columns[i] += row;

                auto length = rsize_after(row);

                if (length < max_width) {
                    composed_columns[i] += std::string(max_width - length, ' ');
                }
            }

            for (size_t i = column.size(); i < max_length; ++i) {
                if (i >= composed_columns.size()) {
                    composed_columns.emplace_back();
                }

                composed_columns[i] += std::string(max_width, ' ');
            }

            // Add some spacing from previous column
            for (auto& row : composed_columns) {
                row += " ";
            }
        }

        for (auto& row : composed_columns) {
            std::cout << row << std::endl;
        }
    } else {
        // If the columns cannot be printed side by side
        // print them one after another

        for (auto& column : split_columns) {
            for(auto& row : column){
                std::cout << row << std::endl;
            }

            std::cout << std::endl;
        }
    }
}

void month_overview(budget::month month, budget::year year) {
    // First display overview of the accounts
    std::stringstream summary_ss;
    console_writer summary_w(summary_ss);
    budget::account_summary(summary_w, month, year);
    std::string m_summary = summary_ss.str();

    // Second display a summary of the objectives
    std::stringstream objectives_ss;
    console_writer objectives_w(objectives_ss);
    budget::objectives_summary(objectives_w);
    std::string m_objectives_summary = objectives_ss.str();

    // Third display a summary of the fortune
    std::stringstream fortune_ss;
    console_writer fortune_w(fortune_ss);
    budget::fortune_summary(fortune_w);
    std::string m_fortune_summary = fortune_ss.str();

    // Print each column
    print_columns({m_summary, m_objectives_summary, m_fortune_summary});
}

void month_overview(budget::month m) {
    month_overview(m, local_day().year());
}

void month_overview() {
    month_overview(local_day().month(), local_day().year());
}

} // end of anonymous namespace

constexpr const std::array<std::pair<const char*, const char*>, 1> budget::module_traits<budget::summary_module>::aliases;

void budget::summary_module::load() {
    load_accounts();
    load_expenses();
    load_earnings();
    load_objectives();
    load_fortunes();
}

void budget::summary_module::handle(std::vector<std::string>& args) {
    if (all_accounts().empty()) {
        throw budget_exception("No accounts defined, you should start by defining some of them");
    }

    if (args.empty() || args.size() == 1) {
        month_overview();
    } else {
        auto& subcommand = args[1];

        if (subcommand == "month") {
            auto today = local_day();

            if (args.size() == 2) {
                month_overview();
            } else if (args.size() == 3) {
                auto m = budget::month(to_number<unsigned short>(args[2]));

                if (m > today.month()) {
                    throw budget_exception("Cannot compute the summary of the future");
                }

                month_overview(m);
            } else if (args.size() == 4) {
                auto m = budget::month(to_number<unsigned short>(args[2]));
                auto y = budget::year(to_number<unsigned short>(args[3]));

                if (y > today.year()) {
                    throw budget_exception("Cannot compute the summary of the future");
                }

                if (y == today.year() && m > today.month()) {
                    throw budget_exception("Cannot compute the summary of the future");
                }

                month_overview(m, y);
            } else {
                throw budget_exception("Too many arguments to overview month");
            }
        } else {
            throw budget_exception("Invalid subcommand \"" + subcommand + "\"");
        }
    }
}

void budget::account_summary(budget::writer& w, budget::month month, budget::year year){
    std::vector<std::string> columns;
    std::vector<std::vector<std::string>> contents;

    auto sm = start_month(year);

    columns.push_back("Account");
    columns.push_back("Expenses");
    columns.push_back("Earnings");
    columns.push_back("Balance");
    columns.push_back("Local");

    std::unordered_map<std::string, budget::money> account_previous;

    //Fill the table

    budget::money month_tot_expenses;
    budget::money month_tot_earnings;
    budget::money month_tot_balance;
    budget::money month_tot_local;

    budget::money tot_expenses;
    budget::money tot_earnings;
    budget::money tot_balance;
    budget::money tot_local;

    budget::money prev_expenses;
    budget::money prev_earnings;
    budget::money prev_balance;
    budget::money prev_local;

    for (unsigned short i = sm; i <= month; ++i) {
        budget::month m = i;

        for (auto& account : all_accounts(year, m)) {
            auto total_expenses = accumulate_amount_if(all_expenses(), [account, year, m](budget::expense& e) { return e.account == account.id && e.date.year() == year && e.date.month() == m; });
            auto total_earnings = accumulate_amount_if(all_earnings(), [account, year, m](budget::earning& e) { return e.account == account.id && e.date.year() == year && e.date.month() == m; });

            auto balance       = account_previous[account.name] + account.amount - total_expenses + total_earnings;
            auto local_balance = account.amount - total_expenses + total_earnings;

            if (i == month) {
                contents.push_back({account.name});

                contents.back().push_back(format_money(total_expenses));
                contents.back().push_back(format_money(total_earnings));
                contents.back().push_back(format_money(balance));
                contents.back().push_back(format_money(local_balance));

                month_tot_expenses += total_expenses;
                month_tot_earnings += total_earnings;
                month_tot_balance += balance;
                month_tot_local += local_balance;
            } else if (month > 1 && m == month - 1) {
                prev_expenses += total_expenses;
                prev_earnings += total_earnings;
                prev_balance  += balance;
                prev_local    += local_balance;
            }

            tot_expenses += total_expenses;
            tot_earnings += total_earnings;
            tot_balance += balance;
            tot_local += local_balance;

            account_previous[account.name] = balance;
        }
    }

    contents.push_back({"Total"});

    contents.back().push_back(format_money(month_tot_expenses));
    contents.back().push_back(format_money(month_tot_earnings));
    contents.back().push_back(format_money(month_tot_balance));
    contents.back().push_back(format_money(month_tot_local));

    if(month > 1){
        contents.push_back({"Previous"});

        contents.back().push_back(format_money(prev_expenses));
        contents.back().push_back(format_money(prev_earnings));
        contents.back().push_back(format_money(prev_balance));
        contents.back().push_back(format_money(prev_local));

        contents.push_back({"Average"});

        contents.back().push_back(format_money(tot_expenses / month.value));
        contents.back().push_back(format_money(tot_earnings / month.value));
        contents.back().push_back(format_money(tot_balance / month.value));
        contents.back().push_back(format_money(tot_local / month.value));
    }

    w.display_table(columns, contents, 1, {}, 1);
}

void budget::objectives_summary(budget::writer& w){
    budget::yearly_objective_status(w, false, true);
    budget::current_monthly_objective_status(w, true);
}

void budget::fortune_summary(budget::writer& w){
    budget::status_fortunes(w, true);
}
<commit_msg>Fix warning<commit_after>//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <numeric>
#include <unordered_map>
#include <unordered_set>

#include "cpp_utils/assert.hpp"

#include "summary.hpp"
#include "console.hpp"
#include "accounts.hpp"
#include "compute.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "fortune.hpp"
#include "objectives.hpp"
#include "budget_exception.hpp"
#include "config.hpp"
#include "utils.hpp"
#include "writer.hpp"

using namespace budget;

namespace {

void print_columns(const std::vector<std::string>& columns){
    std::vector<std::vector<std::string>> split_columns;

    for(auto& column : columns){
        split_columns.push_back(budget::split(column, '\n'));
    }

    std::vector<std::string> composed_columns;

    // Compute the total width

    size_t total_max_width = composed_columns.size() * 2;
    size_t max_length = 0;

    for(auto& column : split_columns){
        size_t max_width = 0;

        for(auto& row : column){
            max_width = std::max(max_width, rsize_after(row));
        }

        total_max_width += max_width;

        max_length = std::max(max_length, column.size());
    }

    if (terminal_width() > total_max_width + 3) {
        // By default, print the columns side by side

        for (auto& column : split_columns) {
            size_t max_width = 0;

            for (auto& row : column) {
                max_width = std::max(max_width, rsize_after(row));
            }

            for (size_t i = 0; i < column.size(); ++i) {
                auto& row = column[i];

                if (i >= composed_columns.size()) {
                    composed_columns.emplace_back();
                }

                composed_columns[i] += row;

                auto length = rsize_after(row);

                if (length < max_width) {
                    composed_columns[i] += std::string(max_width - length, ' ');
                }
            }

            for (size_t i = column.size(); i < max_length; ++i) {
                if (i >= composed_columns.size()) {
                    composed_columns.emplace_back();
                }

                composed_columns[i] += std::string(max_width, ' ');
            }

            // Add some spacing from previous column
            for (auto& row : composed_columns) {
                row += " ";
            }
        }

        for (auto& row : composed_columns) {
            std::cout << row << std::endl;
        }
    } else {
        // If the columns cannot be printed side by side
        // print them one after another

        for (auto& column : split_columns) {
            for(auto& row : column){
                std::cout << row << std::endl;
            }

            std::cout << std::endl;
        }
    }
}

void month_overview(budget::month month, budget::year year) {
    // First display overview of the accounts
    std::stringstream summary_ss;
    console_writer summary_w(summary_ss);
    budget::account_summary(summary_w, month, year);
    std::string m_summary = summary_ss.str();

    // Second display a summary of the objectives
    std::stringstream objectives_ss;
    console_writer objectives_w(objectives_ss);
    budget::objectives_summary(objectives_w);
    std::string m_objectives_summary = objectives_ss.str();

    // Third display a summary of the fortune
    std::stringstream fortune_ss;
    console_writer fortune_w(fortune_ss);
    budget::fortune_summary(fortune_w);
    std::string m_fortune_summary = fortune_ss.str();

    // Print each column
    print_columns({m_summary, m_objectives_summary, m_fortune_summary});
}

void month_overview(budget::month m) {
    month_overview(m, local_day().year());
}

void month_overview() {
    month_overview(local_day().month(), local_day().year());
}

} // end of anonymous namespace

constexpr const std::array<std::pair<const char*, const char*>, 1> budget::module_traits<budget::summary_module>::aliases;

void budget::summary_module::load() {
    load_accounts();
    load_expenses();
    load_earnings();
    load_objectives();
    load_fortunes();
}

void budget::summary_module::handle(std::vector<std::string>& args) {
    if (all_accounts().empty()) {
        throw budget_exception("No accounts defined, you should start by defining some of them");
    }

    if (args.empty() || args.size() == 1) {
        month_overview();
    } else {
        auto& subcommand = args[1];

        if (subcommand == "month") {
            auto today = local_day();

            if (args.size() == 2) {
                month_overview();
            } else if (args.size() == 3) {
                auto m = budget::month(to_number<unsigned short>(args[2]));

                if (m > today.month()) {
                    throw budget_exception("Cannot compute the summary of the future");
                }

                month_overview(m);
            } else if (args.size() == 4) {
                auto m = budget::month(to_number<unsigned short>(args[2]));
                auto y = budget::year(to_number<unsigned short>(args[3]));

                if (y > today.year()) {
                    throw budget_exception("Cannot compute the summary of the future");
                }

                if (y == today.year() && m > today.month()) {
                    throw budget_exception("Cannot compute the summary of the future");
                }

                month_overview(m, y);
            } else {
                throw budget_exception("Too many arguments to overview month");
            }
        } else {
            throw budget_exception("Invalid subcommand \"" + subcommand + "\"");
        }
    }
}

void budget::account_summary(budget::writer& w, budget::month month, budget::year year){
    std::vector<std::string> columns;
    std::vector<std::vector<std::string>> contents;

    auto sm = start_month(year);

    columns.push_back("Account");
    columns.push_back("Expenses");
    columns.push_back("Earnings");
    columns.push_back("Balance");
    columns.push_back("Local");

    std::unordered_map<std::string, budget::money> account_previous;

    //Fill the table

    budget::money month_tot_expenses;
    budget::money month_tot_earnings;
    budget::money month_tot_balance;
    budget::money month_tot_local;

    budget::money tot_expenses;
    budget::money tot_earnings;
    budget::money tot_balance;
    budget::money tot_local;

    budget::money prev_expenses;
    budget::money prev_earnings;
    budget::money prev_balance;
    budget::money prev_local;

    for (unsigned short i = sm; i <= month; ++i) {
        budget::month m = i;

        for (auto& account : all_accounts(year, m)) {
            auto total_expenses = accumulate_amount_if(all_expenses(), [account, year, m](budget::expense& e) { return e.account == account.id && e.date.year() == year && e.date.month() == m; });
            auto total_earnings = accumulate_amount_if(all_earnings(), [account, year, m](budget::earning& e) { return e.account == account.id && e.date.year() == year && e.date.month() == m; });

            auto balance       = account_previous[account.name] + account.amount - total_expenses + total_earnings;
            auto local_balance = account.amount - total_expenses + total_earnings;

            if (i == month) {
                contents.push_back({account.name});

                contents.back().push_back(format_money(total_expenses));
                contents.back().push_back(format_money(total_earnings));
                contents.back().push_back(format_money(balance));
                contents.back().push_back(format_money(local_balance));

                month_tot_expenses += total_expenses;
                month_tot_earnings += total_earnings;
                month_tot_balance += balance;
                month_tot_local += local_balance;
            } else if (month > 1 && m == month - 1) {
                prev_expenses += total_expenses;
                prev_earnings += total_earnings;
                prev_balance  += balance;
                prev_local    += local_balance;
            }

            tot_expenses += total_expenses;
            tot_earnings += total_earnings;
            tot_balance += balance;
            tot_local += local_balance;

            account_previous[account.name] = balance;
        }
    }

    contents.push_back({"Total"});

    contents.back().push_back(format_money(month_tot_expenses));
    contents.back().push_back(format_money(month_tot_earnings));
    contents.back().push_back(format_money(month_tot_balance));
    contents.back().push_back(format_money(month_tot_local));

    if(month > 1){
        contents.push_back({"Previous"});

        contents.back().push_back(format_money(prev_expenses));
        contents.back().push_back(format_money(prev_earnings));
        contents.back().push_back(format_money(prev_balance));
        contents.back().push_back(format_money(prev_local));

        contents.push_back({"Average"});

        contents.back().push_back(format_money(tot_expenses / month.value));
        contents.back().push_back(format_money(tot_earnings / month.value));
        contents.back().push_back(format_money(tot_balance / month.value));
        contents.back().push_back(format_money(tot_local / month.value));
    }

    w.display_table(columns, contents, 1, {}, 1);
}

void budget::objectives_summary(budget::writer& w){
    budget::yearly_objective_status(w, false, true);
    budget::current_monthly_objective_status(w, true);
}

void budget::fortune_summary(budget::writer& w){
    budget::status_fortunes(w, true);
}
<|endoftext|>


<commit_before>#include "terminal.h"
#include <iostream>
#include "logging.h"
#include "config.h"
#include "project.h"

Terminal::InProgress::InProgress(const std::string& start_msg): stop(false) {
  start(start_msg);
}

Terminal::InProgress::~InProgress() {
  stop_mutex.lock();
  stop=true;
  stop_mutex.unlock();
  if(wait_thread.joinable())
    wait_thread.join();
}

void Terminal::InProgress::start(const std::string& msg) {
  line_nr=Terminal::get().print(msg+"...\n");
  wait_thread=std::thread([this](){
    size_t c=0;
    while(true) {
      stop_mutex.lock();
      if(stop) {
        stop_mutex.unlock();
        break;
      }
      else
        stop_mutex.unlock();
      if(c%100==0)
        Terminal::get().async_print(line_nr-1, ".");
      std::this_thread::sleep_for(std::chrono::milliseconds(10));
      c++;
    }
  });
}

void Terminal::InProgress::done(const std::string& msg) {
  stop_mutex.lock();
  if(!stop) {
    stop=true;
    stop_mutex.unlock();
    Terminal::get().async_print(line_nr-1, msg);
  }
  else
    stop_mutex.unlock();
}

void Terminal::InProgress::cancel(const std::string& msg) {
  stop_mutex.lock();
  if(!stop) {
    stop=true;
    stop_mutex.unlock();
    Terminal::get().async_print(line_nr-1, msg);
  }
  else
    stop_mutex.unlock();
}

Terminal::Terminal() {
  bold_tag=get_buffer()->create_tag();
  bold_tag->property_weight()=PANGO_WEIGHT_BOLD;
}

int Terminal::process(const std::string &command, const boost::filesystem::path &path, bool use_pipes) {
  std::unique_ptr<Process> process;
  if(use_pipes)
    process=std::unique_ptr<Process>(new Process(command, path.string(), [this](const char* bytes, size_t n) {
      async_print(std::string(bytes, n));
    }, [this](const char* bytes, size_t n) {
      async_print(std::string(bytes, n), true);
    }));
  else
    process=std::unique_ptr<Process>(new Process(command, path.string()));

  if(process->get_id()<=0) {
    async_print("Error: failed to run command: " + command + "\n", true);
    return -1;
  }

  return process->get_exit_status();
}

int Terminal::process(std::istream &stdin_stream, std::ostream &stdout_stream, const std::string &command, const boost::filesystem::path &path) {
  Process process(command, path.string(), [this, &stdout_stream](const char* bytes, size_t n) {
    Glib::ustring umessage(std::string(bytes, n));
    Glib::ustring::iterator iter;
    while(!umessage.validate(iter)) {
      auto next_char_iter=iter;
      next_char_iter++;
      umessage.replace(iter, next_char_iter, "?");
    }
    stdout_stream.write(umessage.data(), n);
  }, [this](const char* bytes, size_t n) {
    async_print(std::string(bytes, n), true);
  }, true);

  if(process.get_id()<=0) {
    async_print("Error: failed to run command: " + command + "\n", true);
    return -1;
  }

  char buffer[131072];
  for(;;) {
    stdin_stream.readsome(buffer, 131072);
    auto read_n=stdin_stream.gcount();
    if(read_n==0)
      break;
    if(!process.write(buffer, read_n)) {
      break;
    }
  }
  process.close_stdin();

  return process.get_exit_status();
}

void Terminal::async_process(const std::string &command, const boost::filesystem::path &path, std::function<void(int exit_status)> callback) {
  std::thread async_execute_thread([this, command, path, callback](){
    processes_mutex.lock();
    stdin_buffer.clear();
    std::shared_ptr<Process> process(new Process(command, path.string(), [this](const char* bytes, size_t n) {
      async_print(std::string(bytes, n));
    }, [this](const char* bytes, size_t n) {
      async_print(std::string(bytes, n), true);
    }, true));
    auto pid=process->get_id();
    if (pid<=0) {
      processes_mutex.unlock();
      async_print("Error: failed to run command: " + command + "\n", true);
      if(callback)
        callback(-1);
      return;
    }
    else {
      processes.emplace_back(process);
      processes_mutex.unlock();
    }

    auto exit_status=process->get_exit_status();

    processes_mutex.lock();
    for(auto it=processes.begin();it!=processes.end();it++) {
      if((*it)->get_id()==pid) {
        processes.erase(it);
        break;
      }
    }
    stdin_buffer.clear();
    processes_mutex.unlock();

    if(callback)
      callback(exit_status);
  });
  async_execute_thread.detach();
}

void Terminal::kill_last_async_process(bool force) {
  processes_mutex.lock();
  if(processes.size()>0)
    processes.back()->kill(force);
  processes_mutex.unlock();
}

void Terminal::kill_async_processes(bool force) {
  processes_mutex.lock();
  for(auto &process: processes)
    process->kill(force);
  processes_mutex.unlock();
}

size_t Terminal::print(const std::string &message, bool bold){
#ifdef _WIN32
  //Remove color codes
  auto message_no_color=message; //copy here since operations on Glib::ustring is too slow
  size_t pos=0;
  while((pos=message_no_color.find('\e', pos))!=std::string::npos) {
    if((pos+2)>=message_no_color.size())
      break;
    if(message_no_color[pos+1]=='[') {
      size_t end_pos=pos+2;
      bool color_code_found=false;
      while(end_pos<message_no_color.size()) {
        if((message_no_color[end_pos]>='0' && message_no_color[end_pos]<='9') || message_no_color[end_pos]==';')
          end_pos++;
        else if(message_no_color[end_pos]=='m') {
          color_code_found=true;
          break;
        }
        else
          break;
      }
      if(color_code_found)
        message_no_color.erase(pos, end_pos-pos+1);
    }
  }
  Glib::ustring umessage=message_no_color;
#else
  Glib::ustring umessage=message;
#endif

  Glib::ustring::iterator iter;
  while(!umessage.validate(iter)) {
    auto next_char_iter=iter;
    next_char_iter++;
    umessage.replace(iter, next_char_iter, "?");
  }

  if(bold)
    get_buffer()->insert_with_tag(get_buffer()->end(), umessage, bold_tag);
  else
    get_buffer()->insert(get_buffer()->end(), umessage);

  if(get_buffer()->get_line_count()>Config::get().terminal.history_size) {
    int lines=get_buffer()->get_line_count()-Config::get().terminal.history_size;
    get_buffer()->erase(get_buffer()->begin(), get_buffer()->get_iter_at_line(lines));
    deleted_lines+=static_cast<size_t>(lines);
  }

  return static_cast<size_t>(get_buffer()->end().get_line())+deleted_lines;
}

std::shared_ptr<Terminal::InProgress> Terminal::print_in_progress(std::string start_msg) {
  auto in_progress=std::shared_ptr<Terminal::InProgress>(new Terminal::InProgress(start_msg), [this](Terminal::InProgress *in_progress) {
    in_progresses_mutex.lock();
    in_progresses.erase(in_progress);
    in_progresses_mutex.unlock();
  });
  in_progresses_mutex.lock();
  in_progresses.emplace(in_progress.get());
  in_progresses_mutex.unlock();
  return in_progress;
}

void Terminal::async_print(const std::string &message, bool bold) {
  dispatcher.post([this, message, bold] {
    Terminal::get().print(message, bold);
  });
}

void Terminal::async_print(size_t line_nr, const std::string &message) {
  dispatcher.post([this, line_nr, message] {
    if(line_nr<deleted_lines)
      return;

    Glib::ustring umessage=message;
    Glib::ustring::iterator iter;
    while(!umessage.validate(iter)) {
      auto next_char_iter=iter;
      next_char_iter++;
      umessage.replace(iter, next_char_iter, "?");
    }

    auto end_line_iter=get_buffer()->get_iter_at_line(static_cast<int>(line_nr-deleted_lines));
    while(!end_line_iter.ends_line() && end_line_iter.forward_char()) {}
    get_buffer()->insert(end_line_iter, umessage);
  });
}

void Terminal::configure() {
  if(Config::get().terminal.font.size()>0) {
    override_font(Pango::FontDescription(Config::get().terminal.font));
  }
  else if(Config::get().source.font.size()>0) {
    Pango::FontDescription font_description(Config::get().source.font);
    auto font_description_size=font_description.get_size();
    if(font_description_size==0) {
      Pango::FontDescription default_font_description(Gtk::Settings::get_default()->property_gtk_font_name());
      font_description_size=default_font_description.get_size();
    }
    if(font_description_size>0)
      font_description.set_size(font_description_size*0.95);
    override_font(font_description);
  }
}

void Terminal::clear() {
  in_progresses_mutex.lock();
  for(auto &in_progress: in_progresses) {
    in_progress->stop_mutex.lock();
    in_progress->stop=true;
    in_progress->stop_mutex.unlock();
  }
  in_progresses_mutex.unlock();
  while(g_main_context_pending(NULL))
    g_main_context_iteration(NULL, false);
  get_buffer()->set_text("");
}

bool Terminal::on_key_press_event(GdkEventKey *event) {
  processes_mutex.lock();
  bool debug_is_running=false;
#ifdef JUCI_ENABLE_DEBUG
  debug_is_running=Project::current_language?Project::current_language->debug_is_running():false;
#endif
  if(processes.size()>0 || debug_is_running) {
    get_buffer()->place_cursor(get_buffer()->end());
    auto unicode=gdk_keyval_to_unicode(event->keyval);
    char chr=(char)unicode;
    if(unicode>=32 && unicode<=126) {
      stdin_buffer+=chr;
      get_buffer()->insert_at_cursor(stdin_buffer.substr(stdin_buffer.size()-1));
    }
    else if(event->keyval==GDK_KEY_BackSpace) {
      if(stdin_buffer.size()>0 && get_buffer()->get_char_count()>0) {
        auto iter=get_buffer()->end();
        iter--;
        stdin_buffer.pop_back();
        get_buffer()->erase(iter, get_buffer()->end());
      }
    }
    else if(event->keyval==GDK_KEY_Return) {
      stdin_buffer+='\n';
      if(debug_is_running) {
#ifdef JUCI_ENABLE_DEBUG
        Project::current_language->debug_write(stdin_buffer);
#endif
      }
      else
        processes.back()->write(stdin_buffer);
      get_buffer()->insert_at_cursor(stdin_buffer.substr(stdin_buffer.size()-1));
      stdin_buffer.clear();
    }
  }
  processes_mutex.unlock();
  return true;
}
<commit_msg>Fixed a minor memory leak in Terminal::InProgress shared_ptr destructor<commit_after>#include "terminal.h"
#include <iostream>
#include "logging.h"
#include "config.h"
#include "project.h"

Terminal::InProgress::InProgress(const std::string& start_msg): stop(false) {
  start(start_msg);
}

Terminal::InProgress::~InProgress() {
  stop_mutex.lock();
  stop=true;
  stop_mutex.unlock();
  if(wait_thread.joinable())
    wait_thread.join();
}

void Terminal::InProgress::start(const std::string& msg) {
  line_nr=Terminal::get().print(msg+"...\n");
  wait_thread=std::thread([this](){
    size_t c=0;
    while(true) {
      stop_mutex.lock();
      if(stop) {
        stop_mutex.unlock();
        break;
      }
      else
        stop_mutex.unlock();
      if(c%100==0)
        Terminal::get().async_print(line_nr-1, ".");
      std::this_thread::sleep_for(std::chrono::milliseconds(10));
      c++;
    }
  });
}

void Terminal::InProgress::done(const std::string& msg) {
  stop_mutex.lock();
  if(!stop) {
    stop=true;
    stop_mutex.unlock();
    Terminal::get().async_print(line_nr-1, msg);
  }
  else
    stop_mutex.unlock();
}

void Terminal::InProgress::cancel(const std::string& msg) {
  stop_mutex.lock();
  if(!stop) {
    stop=true;
    stop_mutex.unlock();
    Terminal::get().async_print(line_nr-1, msg);
  }
  else
    stop_mutex.unlock();
}

Terminal::Terminal() {
  bold_tag=get_buffer()->create_tag();
  bold_tag->property_weight()=PANGO_WEIGHT_BOLD;
}

int Terminal::process(const std::string &command, const boost::filesystem::path &path, bool use_pipes) {
  std::unique_ptr<Process> process;
  if(use_pipes)
    process=std::unique_ptr<Process>(new Process(command, path.string(), [this](const char* bytes, size_t n) {
      async_print(std::string(bytes, n));
    }, [this](const char* bytes, size_t n) {
      async_print(std::string(bytes, n), true);
    }));
  else
    process=std::unique_ptr<Process>(new Process(command, path.string()));

  if(process->get_id()<=0) {
    async_print("Error: failed to run command: " + command + "\n", true);
    return -1;
  }

  return process->get_exit_status();
}

int Terminal::process(std::istream &stdin_stream, std::ostream &stdout_stream, const std::string &command, const boost::filesystem::path &path) {
  Process process(command, path.string(), [this, &stdout_stream](const char* bytes, size_t n) {
    Glib::ustring umessage(std::string(bytes, n));
    Glib::ustring::iterator iter;
    while(!umessage.validate(iter)) {
      auto next_char_iter=iter;
      next_char_iter++;
      umessage.replace(iter, next_char_iter, "?");
    }
    stdout_stream.write(umessage.data(), n);
  }, [this](const char* bytes, size_t n) {
    async_print(std::string(bytes, n), true);
  }, true);

  if(process.get_id()<=0) {
    async_print("Error: failed to run command: " + command + "\n", true);
    return -1;
  }

  char buffer[131072];
  for(;;) {
    stdin_stream.readsome(buffer, 131072);
    auto read_n=stdin_stream.gcount();
    if(read_n==0)
      break;
    if(!process.write(buffer, read_n)) {
      break;
    }
  }
  process.close_stdin();

  return process.get_exit_status();
}

void Terminal::async_process(const std::string &command, const boost::filesystem::path &path, std::function<void(int exit_status)> callback) {
  std::thread async_execute_thread([this, command, path, callback](){
    processes_mutex.lock();
    stdin_buffer.clear();
    std::shared_ptr<Process> process(new Process(command, path.string(), [this](const char* bytes, size_t n) {
      async_print(std::string(bytes, n));
    }, [this](const char* bytes, size_t n) {
      async_print(std::string(bytes, n), true);
    }, true));
    auto pid=process->get_id();
    if (pid<=0) {
      processes_mutex.unlock();
      async_print("Error: failed to run command: " + command + "\n", true);
      if(callback)
        callback(-1);
      return;
    }
    else {
      processes.emplace_back(process);
      processes_mutex.unlock();
    }

    auto exit_status=process->get_exit_status();

    processes_mutex.lock();
    for(auto it=processes.begin();it!=processes.end();it++) {
      if((*it)->get_id()==pid) {
        processes.erase(it);
        break;
      }
    }
    stdin_buffer.clear();
    processes_mutex.unlock();

    if(callback)
      callback(exit_status);
  });
  async_execute_thread.detach();
}

void Terminal::kill_last_async_process(bool force) {
  processes_mutex.lock();
  if(processes.size()>0)
    processes.back()->kill(force);
  processes_mutex.unlock();
}

void Terminal::kill_async_processes(bool force) {
  processes_mutex.lock();
  for(auto &process: processes)
    process->kill(force);
  processes_mutex.unlock();
}

size_t Terminal::print(const std::string &message, bool bold){
#ifdef _WIN32
  //Remove color codes
  auto message_no_color=message; //copy here since operations on Glib::ustring is too slow
  size_t pos=0;
  while((pos=message_no_color.find('\e', pos))!=std::string::npos) {
    if((pos+2)>=message_no_color.size())
      break;
    if(message_no_color[pos+1]=='[') {
      size_t end_pos=pos+2;
      bool color_code_found=false;
      while(end_pos<message_no_color.size()) {
        if((message_no_color[end_pos]>='0' && message_no_color[end_pos]<='9') || message_no_color[end_pos]==';')
          end_pos++;
        else if(message_no_color[end_pos]=='m') {
          color_code_found=true;
          break;
        }
        else
          break;
      }
      if(color_code_found)
        message_no_color.erase(pos, end_pos-pos+1);
    }
  }
  Glib::ustring umessage=message_no_color;
#else
  Glib::ustring umessage=message;
#endif

  Glib::ustring::iterator iter;
  while(!umessage.validate(iter)) {
    auto next_char_iter=iter;
    next_char_iter++;
    umessage.replace(iter, next_char_iter, "?");
  }

  if(bold)
    get_buffer()->insert_with_tag(get_buffer()->end(), umessage, bold_tag);
  else
    get_buffer()->insert(get_buffer()->end(), umessage);

  if(get_buffer()->get_line_count()>Config::get().terminal.history_size) {
    int lines=get_buffer()->get_line_count()-Config::get().terminal.history_size;
    get_buffer()->erase(get_buffer()->begin(), get_buffer()->get_iter_at_line(lines));
    deleted_lines+=static_cast<size_t>(lines);
  }

  return static_cast<size_t>(get_buffer()->end().get_line())+deleted_lines;
}

std::shared_ptr<Terminal::InProgress> Terminal::print_in_progress(std::string start_msg) {
  auto in_progress=std::shared_ptr<Terminal::InProgress>(new Terminal::InProgress(start_msg), [this](Terminal::InProgress *in_progress) {
    in_progresses_mutex.lock();
    in_progresses.erase(in_progress);
    in_progresses_mutex.unlock();
    delete in_progress;
  });
  in_progresses_mutex.lock();
  in_progresses.emplace(in_progress.get());
  in_progresses_mutex.unlock();
  return in_progress;
}

void Terminal::async_print(const std::string &message, bool bold) {
  dispatcher.post([this, message, bold] {
    Terminal::get().print(message, bold);
  });
}

void Terminal::async_print(size_t line_nr, const std::string &message) {
  dispatcher.post([this, line_nr, message] {
    if(line_nr<deleted_lines)
      return;

    Glib::ustring umessage=message;
    Glib::ustring::iterator iter;
    while(!umessage.validate(iter)) {
      auto next_char_iter=iter;
      next_char_iter++;
      umessage.replace(iter, next_char_iter, "?");
    }

    auto end_line_iter=get_buffer()->get_iter_at_line(static_cast<int>(line_nr-deleted_lines));
    while(!end_line_iter.ends_line() && end_line_iter.forward_char()) {}
    get_buffer()->insert(end_line_iter, umessage);
  });
}

void Terminal::configure() {
  if(Config::get().terminal.font.size()>0) {
    override_font(Pango::FontDescription(Config::get().terminal.font));
  }
  else if(Config::get().source.font.size()>0) {
    Pango::FontDescription font_description(Config::get().source.font);
    auto font_description_size=font_description.get_size();
    if(font_description_size==0) {
      Pango::FontDescription default_font_description(Gtk::Settings::get_default()->property_gtk_font_name());
      font_description_size=default_font_description.get_size();
    }
    if(font_description_size>0)
      font_description.set_size(font_description_size*0.95);
    override_font(font_description);
  }
}

void Terminal::clear() {
  in_progresses_mutex.lock();
  for(auto &in_progress: in_progresses) {
    in_progress->stop_mutex.lock();
    in_progress->stop=true;
    in_progress->stop_mutex.unlock();
  }
  in_progresses_mutex.unlock();
  while(g_main_context_pending(NULL))
    g_main_context_iteration(NULL, false);
  get_buffer()->set_text("");
}

bool Terminal::on_key_press_event(GdkEventKey *event) {
  processes_mutex.lock();
  bool debug_is_running=false;
#ifdef JUCI_ENABLE_DEBUG
  debug_is_running=Project::current_language?Project::current_language->debug_is_running():false;
#endif
  if(processes.size()>0 || debug_is_running) {
    get_buffer()->place_cursor(get_buffer()->end());
    auto unicode=gdk_keyval_to_unicode(event->keyval);
    char chr=(char)unicode;
    if(unicode>=32 && unicode<=126) {
      stdin_buffer+=chr;
      get_buffer()->insert_at_cursor(stdin_buffer.substr(stdin_buffer.size()-1));
    }
    else if(event->keyval==GDK_KEY_BackSpace) {
      if(stdin_buffer.size()>0 && get_buffer()->get_char_count()>0) {
        auto iter=get_buffer()->end();
        iter--;
        stdin_buffer.pop_back();
        get_buffer()->erase(iter, get_buffer()->end());
      }
    }
    else if(event->keyval==GDK_KEY_Return) {
      stdin_buffer+='\n';
      if(debug_is_running) {
#ifdef JUCI_ENABLE_DEBUG
        Project::current_language->debug_write(stdin_buffer);
#endif
      }
      else
        processes.back()->write(stdin_buffer);
      get_buffer()->insert_at_cursor(stdin_buffer.substr(stdin_buffer.size()-1));
      stdin_buffer.clear();
    }
  }
  processes_mutex.unlock();
  return true;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pwd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>

using namespace boost;
using namespace std;

void parseCommand();
int isFile(const char*);
int isDirectory(const char*);
int exists(const char*);
bool check(const vector<string>&);
void parseFilePath(vector<string>&);
int runTestCommand(vector<string>&);

//Splits command line into seperate strings based on spaces
void parseCommand()
{
    string command;
    vector<string> commandLine;

    cout << "Enter a command.\n";
    getline(cin, command);

    typedef tokenizer<char_separator<char> > tokenizer;
    char_separator<char> sep(" ");
    tokenizer tok(command, sep);

    for(tokenizer::iterator it = tok.begin(); it != tok.end(); ++it)
    {
        commandLine.push_back(*it);
    }
    if(check(commandLine) == true)
    {
        runTestCommand(commandLine);
    }
    else
    {
        return;
    }
}

//1 if type, 0 if not
int isFile(const char *path)
{
    struct stat path_stat;
    stat(path, &path_stat);
    return S_ISREG(path_stat.st_mode);
}
int isDirectory(const char *path)
{
    struct stat path_stat;
    stat(path, &path_stat);
    return S_ISDIR(path_stat.st_mode);
}
// 0 if exists, -1 if it does not
int exists(const char* path)
{
    struct stat path_stat;
    return stat(path, &path_stat);
}
bool check(const vector<string>& cmdLine)
{
    //Checks if proper test call was made
    if(cmdLine.at(0) != "test" && cmdLine.at(0) != "[")
    {
        cout << "-bash: " << cmdLine.at(0) << ": command not found\n";
        return false;
    }
    //Checks if test command was closed correctly using bracket notation
    if(cmdLine.at(0) == "[" && cmdLine.at(cmdLine.size()-1) != "]")
    {
        cout << "-bash: syntax error near unexpected token '"
        << cmdLine.at(cmdLine.size()-1) << endl;
        return false;
    }
    //Check if proper flag was called. Note that other flags exist but for this
    //program user is limited to only 3 flags
    if(cmdLine.at(1) != "-e" && cmdLine.at(1) != "-f" && cmdLine.at(1) != "-d")
    {
        if(cmdLine.size() != 2 && cmdLine.size() != 3)
        {
            cout << "-bash: " << cmdLine.at(0) << ": " << cmdLine.at(1)
            << ": unary operator expected\n";
            return false;
        }
    }
    return true;
}

//Seperates command line into a string with just the file path
void parseFilePath(vector<string>& cmdLine)
{
    string filePath;
    if(cmdLine.at(1) == "-e" || cmdLine.at(1) == "-f" || cmdLine.at(1) == "-d")
    {
        filePath = cmdLine.at(2);
    }
    else //If no flag was specified
    {
        filePath = cmdLine.at(1);
    }
    cmdLine.clear();
    typedef tokenizer<char_separator<char> > tokenizer;
    char_separator<char> sep("/");
    tokenizer tok(filePath, sep);
    for (tokenizer::iterator it = tok.begin(); it != tok.end(); ++it)
    {
        cmdLine.push_back(*it);
    }
}

int runTestCommand(vector<string>& cmdLine)
{
    if(cmdLine.at(1) == "-f")
    {
        parseFilePath(cmdLine);
        //Saves the smaller paths. Note: Will only work with command lines with
        //no more than 3 commands
        string path1; string path2;
        if(cmdLine.size() == 2)
        {
             path1 = cmdLine.at(0) + "/" + cmdLine.at(1);
        }
        if(cmdLine.size() == 3)
        {
            path2 = cmdLine.at(0) + "/" + cmdLine.at(1) + "/" + cmdLine.at(2);
        }
        //Checks every single file within the path to see if it exists
        for(unsigned i = 0; i < cmdLine.size(); ++i)
        {
            char temp[cmdLine.at(i).size()+1];
            for(unsigned j = 0; j < cmdLine.at(i).size(); ++j)
            {
                temp[j] = cmdLine.at(i).at(j);
            }
            temp[cmdLine.at(i).size()] = '\0';
            //If file does not exist, check for current combined
            //file path existence
            if(exists(temp) == -1)
            {
                //If the file is the first in the path, return false
                if(i == 0)
                {
                    cout << "(False)\n";
                    return 1;
                }
                //Otherwise check the combined path
                else if(i == 1)
                {
                    char temp1[path1.size()+1];
                    for(unsigned j = 0; j < path1.size(); ++j)
                    {
                        temp1[j] = path1.at(j);
                    }
                    temp1[path1.size()] = '\0';
                    if(exists(temp1) == -1)
                    {
                        cout << "(False)\n";
                        return 1;
                    }
                }
                else //i ==2
                {
                    char temp2[path2.size()+1];
                    for(unsigned j = 0; j < path2.size(); ++j)
                    {
                        temp2[j] = path2.at(j);
                    }
                    temp2[path2.size()] = '\0';
                    if(exists(temp2) == -1)
                    {
                        cout << "(False)\n";
                        return 1;
                    }
                }
            }
            //If the first file in a path is regular, path is invalid.
            if(isFile(temp) == 1 && i == 0)
            {
                cout << "(False)\n";
                return 1;
            }
        }
        //At this point we know the file path exists. Now we will do a final
        //check for the file type on the last item in cmdLine
        char temp[cmdLine.at(cmdLine.size()-1).size()+1];
        for(unsigned i = 0; i < cmdLine.at(cmdLine.size()-1).size(); ++i)
        {
            temp[i] = cmdLine.at(cmdLine.size()-1).at(i);
        }
        if(isFile(temp) == 0)
        {
            cout << "(True)\n";
            return 0;
        }
        else
        {
            cout << "(False)\n";
            return 1;
        }
    }
    else if(cmdLine.at(1) == "-d")
    {
        parseFilePath(cmdLine);
        //Saves the smaller paths. Note: Will only work with command lines with
        //no more than 3 commands
        string path1; string path2;
        if(cmdLine.size() == 2)
        {
             path1 = cmdLine.at(0) + "/" + cmdLine.at(1);
        }
        if(cmdLine.size() == 3)
        {
            path2 = cmdLine.at(0) + "/" + cmdLine.at(1) + "/" + cmdLine.at(2);
        }
        for(unsigned i = 0; i < cmdLine.size(); ++i)
        {
            char temp[cmdLine.at(i).size()+1];
            for(unsigned j = 0; j < cmdLine.at(i).size(); ++j)
            {
                temp[j] = cmdLine.at(i).at(j);
            }
            temp[cmdLine.at(i).size()] = '\0';
            //If file does not exist, exit function and return false
            if(exists(temp) == -1)
            {
                //If the file is the first in the path, return false
                if(i == 0)
                {
                    cout << "(False)\n";
                    return 1;
                }
                //Otherwise check the combined path
                else if(i == 1)
                {
                    char temp1[path1.size()+1];
                    for(unsigned j = 0; j < path1.size(); ++j)
                    {
                        temp1[j] = path1.at(j);
                    }
                    temp1[path1.size()] = '\0';
                    if(exists(temp1) == -1)
                    {
                        cout << "(False)\n";
                        return 1;
                    }
                }
                else //i ==2
                {
                    char temp2[path2.size()+1];
                    for(unsigned j = 0; j < path2.size(); ++j)
                    {
                        temp2[j] = path2.at(j);
                    }
                    temp2[path2.size()] = '\0';
                    if(exists(temp2) == -1)
                    {
                        cout << "(False)\n";
                        return 1;
                    }
                }
            }
            //If the first file in a path is regular, path is invalid.
            if(isFile(temp) == 1 && i == 0)
            {
                cout << "(False)\n";
                return 1;
            }
        }
        //Does a final check for the file type on the last item in the file
        char temp[cmdLine.at(cmdLine.size()-1).size()+1];
        for(unsigned i = 0; i < cmdLine.at(cmdLine.size()-1).size(); ++i)
        {
            temp[i] = cmdLine.at(cmdLine.size()-1).at(i);
        }
        if(isDirectory(temp) == 0)
        {
            cout << "(True)\n";
            return 0;
        }
        else
        {
            cout << "(False)\n";
            return 1;
        }
    }
    else if(cmdLine.at(1) == "-e")
    {
        parseFilePath(cmdLine);
        for(unsigned i = 0; i < cmdLine.size(); ++i)
        {
            char temp[cmdLine.at(i).size()+1];
            for(unsigned j = 0; j < cmdLine.at(i).size(); ++j)
            {
                temp[j] = cmdLine.at(i).at(j);
            }
            temp[cmdLine.at(i).size()] = '\0';
            //If file does not exist, exit function and return false
            if(exists(temp) == -1)
            {
                cout << "(False)\n";
                return 1;
            }
            //If the first file in a path is regular, path is invalid.
            if(isFile(temp) == 1 && i == 0)
            {
                cout << "(False)\n";
                return 1;
            }
        }
        cout << "(True)\n";
        return 0;
    }
}

int main()
{
    parseCommand();
    return 0;
}<commit_msg>Fixed errors with linking filepaths<commit_after>#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pwd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>

using namespace boost;
using namespace std;

void parseCommand();
int isFile(const char*);
int isDirectory(const char*);
int exists(const char*);
bool check(const vector<string>&);
void parseFilePath(vector<string>&);
int runTestCommand(vector<string>&);

//Splits command line into seperate strings based on spaces
void parseCommand()
{
    string command;
    vector<string> commandLine;

    cout << "Enter a command.\n";
    getline(cin, command);

    typedef tokenizer<char_separator<char> > tokenizer;
    char_separator<char> sep(" ");
    tokenizer tok(command, sep);

    for(tokenizer::iterator it = tok.begin(); it != tok.end(); ++it)
    {
        commandLine.push_back(*it);
    }
    if(check(commandLine) == true)
    {
        runTestCommand(commandLine);
    }
    else
    {
        return;
    }
}

//1 if type, 0 if not
int isFile(const char *path)
{
    struct stat path_stat;
    stat(path, &path_stat);
    return S_ISREG(path_stat.st_mode);
}
int isDirectory(const char *path)
{
    struct stat path_stat;
    stat(path, &path_stat);
    return S_ISDIR(path_stat.st_mode);
}
// 0 if exists, -1 if it does not
int exists(const char* path)
{
    struct stat path_stat;
    return stat(path, &path_stat);
}
bool check(const vector<string>& cmdLine)
{
    //Checks if proper test call was made
    if(cmdLine.at(0) != "test" && cmdLine.at(0) != "[")
    {
        cout << "-bash: " << cmdLine.at(0) << ": command not found\n";
        return false;
    }
    //Checks if test command was closed correctly using bracket notation
    if(cmdLine.at(0) == "[" && cmdLine.at(cmdLine.size()-1) != "]")
    {
        cout << "-bash: syntax error near unexpected token '"
        << cmdLine.at(cmdLine.size()-1) << endl;
        return false;
    }
    //Check if proper flag was called. Note that other flags exist but for this
    //program user is limited to only 3 flags
    if(cmdLine.at(1) != "-e" && cmdLine.at(1) != "-f" && cmdLine.at(1) != "-d")
    {
        if(cmdLine.size() != 2 && cmdLine.size() != 3)
        {
            cout << "-bash: " << cmdLine.at(0) << ": " << cmdLine.at(1)
            << ": unary operator expected\n";
            return false;
        }
    }
    return true;
}

//Seperates command line into a string with just the file path
void parseFilePath(vector<string>& cmdLine)
{
    string filePath;
    if(cmdLine.at(1) == "-e" || cmdLine.at(1) == "-f" || cmdLine.at(1) == "-d")
    {
        filePath = cmdLine.at(2);
    }
    else //If no flag was specified
    {
        filePath = cmdLine.at(1);
    }
    cmdLine.clear();
    typedef tokenizer<char_separator<char> > tokenizer;
    char_separator<char> sep("/");
    tokenizer tok(filePath, sep);
    for (tokenizer::iterator it = tok.begin(); it != tok.end(); ++it)
    {
        cmdLine.push_back(*it);
    }
}

int runTestCommand(vector<string>& cmdLine)
{
    if(cmdLine.at(1) == "-f")
    {
        parseFilePath(cmdLine);
        //Saves the smaller paths. Note: Will only work with command lines with
        //no more than 3 commands
        string path1; string path2;
        if(cmdLine.size() == 2)
        {
             path1 = cmdLine.at(0) + "/" + cmdLine.at(1);
        }
        if(cmdLine.size() == 3)
        {
            path2 = cmdLine.at(0) + "/" + cmdLine.at(1) + "/" + cmdLine.at(2);
        }
        char temp1[path1.size()+1]; char temp2[path2.size()+1];
        //Checks every single file within the path to see if it exists
        for(unsigned i = 0; i < cmdLine.size(); ++i)
        {
            char temp[cmdLine.at(i).size()+1];
            for(unsigned j = 0; j < cmdLine.at(i).size(); ++j)
            {
                temp[j] = cmdLine.at(i).at(j);
            }
            temp[cmdLine.at(i).size()] = '\0';
            //If file does not exist, check for current combined
            //file path existence
            if(exists(temp) == -1)
            {
                //If the file is the first in the path, return false
                if(i == 0)
                {
                    cout << "(False)\n";
                    return 1;
                }
                //Otherwise check the combined path
                else if(i == 1)
                {
                    for(unsigned j = 0; j < path1.size(); ++j)
                    {
                        temp1[j] = path1.at(j);
                    }
                    temp1[path1.size()] = '\0';
                    if(exists(temp1) == -1)
                    {
                        cout << "(False)\n";
                        return 1;
                    }
                }
                else //i ==2
                {
                    for(unsigned j = 0; j < path2.size(); ++j)
                    {
                        temp2[j] = path2.at(j);
                    }
                    temp2[path2.size()] = '\0';
                    if(exists(temp2) == -1)
                    {
                        cout << "(False)\n";
                        return 1;
                    }
                }
            }
            //If the first file in a path is regular, path is invalid.
            if(isFile(temp) == 1 && i == 0)
            {
                cout << "(False)\n";
                return 1;
            }
        }
        //At this point we know the file path exists. Now we will do a final
        //check for the file type on the last item in cmdLine
        if(cmdLine.size() == 1)
        {
            char temp[cmdLine.at(cmdLine.size()-1).size()+1];
            for(unsigned i = 0; i < cmdLine.at(cmdLine.size()-1).size(); ++i)
            {
                temp[i] = cmdLine.at(cmdLine.size()-1).at(i);
            }
            temp[cmdLine.at(cmdLine.size()-1).size()] = '\0';

            if(isFile(temp) == 1)
            {
                cout << "(True)\n";
                return 0;
            }
            else
            {
                cout << "(False)\n";
                return 1;
            }
        }
        else if (cmdLine.size() == 2)
        {
            if(isFile(temp1) == 1)
            {
                cout << "(True)\n";
                return 0;
            }
            else
            {
                cout << "(False)\n";
                return 1;
            }
        }
        else
        {
            if(isFile(temp2) == 1)
            {
                cout << "(True)\n";
                return 0;
            }
            else
            {
                cout << "(False)\n";
                return 1;
            }
        }
    }
    else if(cmdLine.at(1) == "-d")
    {
        parseFilePath(cmdLine);
        //Saves the smaller paths. Note: Will only work with command lines with
        //no more than 3 commands
        string path1; string path2;
        if(cmdLine.size() == 2)
        {
             path1 = cmdLine.at(0) + "/" + cmdLine.at(1);
        }
        if(cmdLine.size() == 3)
        {
            path2 = cmdLine.at(0) + "/" + cmdLine.at(1) + "/" + cmdLine.at(2);
        }
        char temp1[path1.size()+1]; char temp2[path2.size()+1];
        for(unsigned i = 0; i < cmdLine.size(); ++i)
        {
            char temp[cmdLine.at(i).size()+1];
            for(unsigned j = 0; j < cmdLine.at(i).size(); ++j)
            {
                temp[j] = cmdLine.at(i).at(j);
            }
            temp[cmdLine.at(i).size()] = '\0';
            //If file does not exist, exit function and return false
            if(exists(temp) == -1)
            {
                //If the file is the first in the path, return false
                if(i == 0)
                {
                    cout << "(False)\n";
                    return 1;
                }
                //Otherwise check the combined path
                else if(i == 1)
                {
                    for(unsigned j = 0; j < path1.size(); ++j)
                    {
                        temp1[j] = path1.at(j);
                    }
                    temp1[path1.size()] = '\0';
                    if(exists(temp1) == -1)
                    {
                        cout << "(False)\n";
                        return 1;
                    }
                }
                else //i ==2
                {
                    for(unsigned j = 0; j < path2.size(); ++j)
                    {
                        temp2[j] = path2.at(j);
                    }
                    temp2[path2.size()] = '\0';
                    if(exists(temp2) == -1)
                    {
                        cout << "(False)\n";
                        return 1;
                    }
                }
            }
            //If the first file in a path is regular, path is invalid.
            if(isFile(temp) == 1 && i == 0)
            {
                cout << "(False)\n";
                return 1;
            }
        }
        //Does a final check for the file type on the last item in the file
        if(cmdLine.size() == 1)
        {
            char temp[cmdLine.at(cmdLine.size()-1).size()+1];
            for(unsigned i = 0; i < cmdLine.at(cmdLine.size()-1).size(); ++i)
            {
                temp[i] = cmdLine.at(cmdLine.size()-1).at(i);
            }
            temp[cmdLine.at(cmdLine.size()-1).size()] = '\0';

            if(isDirectory(temp) == 1)
            {
                cout << "(True)\n";
                return 0;
            }
            else
            {
                cout << "(False)\n";
                return 1;
            }
        }
        else if (cmdLine.size() == 2)
        {
            if(isDirectory(temp1) == 1)
            {
                cout << "(True)\n";
                return 0;
            }
            else
            {
                cout << "(False)\n";
                return 1;
            }
        }
        else
        {
            if(isDirectory(temp2) == 1)
            {
                cout << "(True)\n";
                return 0;
            }
            else
            {
                cout << "(False)\n";
                return 1;
            }
        }
    }
    else if(cmdLine.at(1) == "-e")
    {
        parseFilePath(cmdLine);
        for(unsigned i = 0; i < cmdLine.size(); ++i)
        {
            char temp[cmdLine.at(i).size()+1];
            for(unsigned j = 0; j < cmdLine.at(i).size(); ++j)
            {
                temp[j] = cmdLine.at(i).at(j);
            }
            temp[cmdLine.at(i).size()] = '\0';
            //If file does not exist, exit function and return false
            if(exists(temp) == -1)
            {
                cout << "(False)\n";
                return 1;
            }
            //If the first file in a path is regular, path is invalid.
            if(isFile(temp) == 1 && i == 0)
            {
                cout << "(False)\n";
                return 1;
            }
        }
        cout << "(True)\n";
        return 0;
    }
}

int main()
{
    parseCommand();
    return 0;
}<|endoftext|>


<commit_before>#include <stdio.h>
#include <vector>
#define OK 1
#define ERROR 0
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define ElemType int

using namespace std;
int main()
{
	std::vector<ElemType> v;
	int a, i;
	ElemType e, x;
	if(v.empty())    // 判断顺序表是否创建成功
	{
		printf("A Sequence List Has Created.\n");
	}
	while(1)
	{
		printf("1:Insert element\n2:Delete element\n3:Load all elements\n0:Exit\nPlease choose:\n");
		scanf("%d",&a);
		switch(a)
		{
			case 1: scanf("%d%d",&i,&x);

					if(v.insert(v.begin()+i,x)) printf("Insert Error!\n"); // 判断i值是否合法，请填空
					else printf("The Element %d is Successfully Inserted!\n", x);
					break;
			case 2: scanf("%d",&i);
					vector<ElemType>::iterator I = v.begin();
					I=I+i;

					if(v.erase(I)) printf("Delete Error!\n"); // 判断i值是否合法，请填空
					else printf("The Element %d is Successfully Deleted!\n", e);
					break;
			case 3:
			vector<ElemType>::iterator tempIterator;
			for( tempIterator = v.begin(); tempIterator != v.end(); tempIterator++ )
    				cout << *tempIterator;
    		cout << endl;
					break;
			case 0: return 1;
		}
	}
}<commit_msg>update uoj8576<commit_after>#include <stdio.h>
#include <vector>
#define OK 1
#define ERROR 0
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define ElemType int

using namespace std;
int main()
{
	std::vector<ElemType> v;
	int a, i;
	ElemType e, x;
	if(v.empty())    // 判断顺序表是否创建成功
	{
		printf("A Sequence List Has Created.\n");
	}
	while(1)
	{
		printf("1:Insert element\n2:Delete element\n3:Load all elements\n0:Exit\nPlease choose:\n");
		scanf("%d",&a);
		switch(a)
		{
			case 1: scanf("%d%d",&i,&x);

					 v.insert(v.begin()+i,x);
					if(0) printf("Insert Error!\n"); // 判断i值是否合法，请填空
					else printf("The Element %d is Successfully Inserted!\n", x);
					break;
			case 2: scanf("%d",&i);
					vector<ElemType>::iterator I = v.begin();
					I=I+i;

					if(v.erase(I)) printf("Delete Error!\n"); // 判断i值是否合法，请填空
					else printf("The Element %d is Successfully Deleted!\n", e);
					break;
			case 3:
			vector<ElemType>::iterator tempIterator;
			for( tempIterator = v.begin(); tempIterator != v.end(); tempIterator++ )
    				cout << *tempIterator;
    		cout << endl;
					break;
			case 0: return 1;
		}
	}
}<|endoftext|>


<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Copyright (c) 2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-foo"

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "$Format:%h$"
#    define GIT_COMMIT_DATE "$Format:%cD"
#endif

#define STRINGIFY(s) #s

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" STRINGIFY(maj) "." STRINGIFY(min) "." STRINGIFY(rev) "." STRINGIFY(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" STRINGIFY(maj) "." STRINGIFY(min) "." STRINGIFY(rev) "." STRINGIFY(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Update version.cpp<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Copyright (c) 2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Divisible By Two");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-even"

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "$Format:%h$"
#    define GIT_COMMIT_DATE "$Format:%cD"
#endif

#define STRINGIFY(s) #s

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" STRINGIFY(maj) "." STRINGIFY(min) "." STRINGIFY(rev) "." STRINGIFY(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" STRINGIFY(maj) "." STRINGIFY(min) "." STRINGIFY(rev) "." STRINGIFY(build) "-divisible_by_two"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-beta"

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "$Format:%h$"
#    define GIT_COMMIT_DATE "$Format:%cD$"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Updated client name<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Christiaan Huygens");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-beta"

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "$Format:%h$"
#    define GIT_COMMIT_DATE "$Format:%cD$"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("2GiveCoin");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-RC2"
#define BUILD_DATE __DATE__ ", " __TIME__

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
//#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID ""
#    define GIT_COMMIT_DATE "$Format:%cD$"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) ""

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Tick the version number forward to RC3-dev<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("2GiveCoin");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-RC3-DEV"
#define BUILD_DATE __DATE__ ", " __TIME__

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
//#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID ""
#    define GIT_COMMIT_DATE "$Format:%cD$"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) ""

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>


<commit_before>// Copyright (c) 2015 Jolla Mobile. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webview.h"

#include <QGuiApplication>
#include <QOpenGLContext>
#include <QDebug>
#include <qmozcontext.h>

#include <QOpenGLContext>

#include "webwindow.h"

WebView::WebView(WebWindow* window, QObject* parent)
    : QOpenGLWebPage(parent)
    , window_(window)
    , context_(0) {

  setWindow(window_);

  connect(this, SIGNAL(requestGLContext()),
          this, SLOT(CreateGLContext()), Qt::DirectConnection);
  connect(this, &QOpenGLWebPage::completedChanged,
          this, &WebView::OnCompletedChanged);
  connect(this, &QOpenGLWebPage::activeChanged,
          this, &WebView::OnActiveChanged);
}

WebView::~WebView() {
}

void
WebView::CreateGLContext() {
  if (!context_) {
    context_ = new QOpenGLContext();
    context_->setFormat(window_->requestedFormat());
    if (!context_->create())
      qFatal("Failed to create QOpenGLContext!");
    context_->makeCurrent(window_);
    qDebug() << "GL context requested after" << startup_timer_.elapsed() << "ms";
  } else {
    context_->makeCurrent(window_);
  }
}

void
WebView::OnCompletedChanged() {
  qDebug() << "WebView creation completed";
  startup_timer_.start();
}

void
WebView::OnActiveChanged() {
  if (active()) {
    window_->SetActiveWebView(this);
  }
}
<commit_msg>Add missing QOpenGLWebPage::initialize call.<commit_after>// Copyright (c) 2015 Jolla Mobile. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webview.h"

#include <QGuiApplication>
#include <QOpenGLContext>
#include <QDebug>
#include <qmozcontext.h>

#include <QOpenGLContext>

#include "webwindow.h"

WebView::WebView(WebWindow* window, QObject* parent)
    : QOpenGLWebPage(parent)
    , window_(window)
    , context_(0) {

  setWindow(window_);

  connect(this, SIGNAL(requestGLContext()),
          this, SLOT(CreateGLContext()), Qt::DirectConnection);
  connect(this, &QOpenGLWebPage::completedChanged,
          this, &WebView::OnCompletedChanged);
  connect(this, &QOpenGLWebPage::activeChanged,
          this, &WebView::OnActiveChanged);
  initialize();
}

WebView::~WebView() {
}

void
WebView::CreateGLContext() {
  if (!context_) {
    context_ = new QOpenGLContext();
    context_->setFormat(window_->requestedFormat());
    if (!context_->create())
      qFatal("Failed to create QOpenGLContext!");
    context_->makeCurrent(window_);
    qDebug() << "GL context requested after" << startup_timer_.elapsed() << "ms";
  } else {
    context_->makeCurrent(window_);
  }
}

void
WebView::OnCompletedChanged() {
  qDebug() << "WebView creation completed";
  startup_timer_.start();
}

void
WebView::OnActiveChanged() {
  if (active()) {
    window_->SetActiveWebView(this);
  }
}
<|endoftext|>