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

#include <iostream>

#include "report.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "budget_exception.hpp"
#include "accounts.hpp"
#include "console.hpp"

using namespace budget;

namespace {

typedef std::vector<std::vector<std::string>> graph_type;

void render(graph_type& graph){
    std::reverse(graph.begin(), graph.end());

    for(auto& line : graph){
        for(auto& col : line){
            std::cout << col;
        }
        std::cout << std::endl;
    }
}

void write(graph_type& graph, int row, int col, const std::string& value){
    for(size_t i = 0; i < value.size(); ++i){
        graph[row][col + i] = value[i];
    }
}

template<typename Predicate>
void report(budget::year year, Predicate predicate){
    auto today = budget::local_day();

    budget::money max_expenses;
    budget::money max_earnings;
    budget::money max_balance;
    budget::money min_expenses;
    budget::money min_earnings;
    budget::money min_balance;

    auto sm = start_month(year);

    std::vector<int> expenses(12);
    std::vector<int> earnings(12);
    std::vector<int> balances(12);

    for(auto i = sm; i <= today.month(); ++i){
        budget::month month = i;

        budget::money total_expenses;
        budget::money total_earnings;
        budget::money total_balance;

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

                total_expenses += expenses;
                total_earnings += earnings;

                auto balance = account.amount;
                balance -= expenses;
                balance += earnings;

                total_balance += balance;
            }
        }

        expenses[month - 1] = total_expenses.dollars();
        earnings[month - 1] = total_earnings.dollars();
        balances[month - 1] = total_balance.dollars();

        max_expenses = std::max(max_expenses, total_expenses);
        max_earnings = std::max(max_earnings, total_earnings);
        max_balance = std::max(max_balance, total_balance);
        min_expenses = std::min(min_expenses, total_expenses);
        min_earnings = std::min(min_earnings, total_earnings);
        min_balance = std::min(min_balance, total_balance);
    }

    auto max_number = std::max(std::max(
        std::max(std::abs(max_expenses.dollars()), std::abs(max_earnings.dollars())),
        std::max(std::abs(max_balance.dollars()), std::abs(min_expenses.dollars()))),
        std::max(std::abs(min_balance.dollars()), std::abs(min_earnings.dollars())));

    size_t height = terminal_height() - 9;
    size_t width = terminal_width() - 6;

    size_t scale_width = 5;

    // Compute the scale based on the data
    size_t scale = 1;
    if (max_number < 600) {
        scale = 100;
    } else if (max_number < 1500) {
        scale = 200;
    } else if (max_number < 3000) {
        scale = 500;
    } else if (max_number < 6000) {
        scale = 1000;
    } else {
        scale = 2000;
    }

    auto graph_width_func = [sm](size_t col_width){
        return 6 + (13 - sm) * (3 * col_width + 2) + (13 - sm - 1) * 2;
    };

    // Compute the best column width

    size_t col_width = 1;
    if(width > graph_width_func(4)){
        col_width = 4;
    } else if(width > graph_width_func(3)){
        col_width = 3;
    } else if(width > graph_width_func(2)){
        col_width = 2;
    }

    int min = 0;
    if(min_expenses.negative() || min_earnings.negative() || min_balance.negative()){
        min = std::min(min_expenses, std::min(min_earnings, min_balance)).dollars();
        min = -1 * ((std::abs(min) / scale) + 1) * scale;
    }

    unsigned int max = std::max(max_earnings, std::max(max_expenses, max_balance)).dollars();
    max = ((max / scale) + 1) * scale;

    unsigned int levels = max / scale + std::abs(min) / scale;

    unsigned int step_height = height / levels;
    unsigned int precision = scale / step_height;

    auto graph_height = 9 + step_height * levels;
    auto graph_width = graph_width_func(col_width);

    graph_type graph(graph_height, std::vector<std::string>(graph_width, " "));

    //Display graph title

    write(graph, graph_height - 2, 8, "Monthly report of " + to_string(year));

    //Display scale

    for(size_t i = 0; i <= levels; ++i){
        int level = min + i * scale;

        write(graph, 4 + step_height * i, 1, to_string(level));
    }

    //Display bar

    unsigned int min_index = 3;
    unsigned int zero_index = min_index + 1 + (std::abs(min) / scale) * step_height;

    const auto first_bar = scale_width + 2;

    for(auto i = sm; i <= today.month(); ++i){
        budget::month month = i;

        auto col_start = first_bar + (3 * col_width + 4) * (i - sm);

        //Display month legend
        auto month_str = month.as_short_string();
        write(graph, 1, col_start + 2, month_str);

        for (size_t j = 0; j < expenses[month - 1] / precision; ++j) {
            for (size_t x = 0; x < col_width; ++x) {
                graph[zero_index + j][col_start + x] = "\033[1;41m \033[0m";
            }
        }

        col_start += col_width + 1;

        for (size_t j = 0; j < earnings[month - 1] / precision; ++j) {
            for (size_t x = 0; x < col_width; ++x) {
                graph[zero_index + j][col_start + x] = "\033[1;42m \033[0m";
            }
        }

        col_start += col_width + 1;

        if (balances[month - 1] >= 0) {
            for (size_t j = 0; j < balances[month - 1] / precision; ++j) {
                for (size_t x = 0; x < col_width; ++x) {
                    graph[zero_index + j][col_start + x] = "\033[1;44m \033[0m";
                }
            }
        } else {
            for (size_t j = 0; j < std::abs(balances[month - 1]) / precision; ++j) {
                for (size_t x = 0; x < col_width; ++x) {
                    graph[zero_index - 1 - j][col_start + x] = "\033[1;44m \033[0m";
                }
            }
        }
    }

    //Display legend

    int start_legend = first_bar + (3 * col_width + 4) * (today.month() - sm + 1) + 4;

    graph[4][start_legend - 2] = "|";
    graph[3][start_legend - 2] = "|";
    graph[2][start_legend - 2] = "|";

    graph[4][start_legend] = "\033[1;41m \033[0m";
    graph[3][start_legend] = "\033[1;42m \033[0m";
    graph[2][start_legend] = "\033[1;44m \033[0m";

    write(graph, 6, start_legend - 2, " ____________ ");
    write(graph, 5, start_legend - 2, "|            |");
    write(graph, 4, start_legend + 2, "Expenses |");
    write(graph, 3, start_legend + 2, "Earnings |");
    write(graph, 2, start_legend + 2, "Balance  |");
    write(graph, 1, start_legend - 2, "|____________|");

    //Render the graph

    render(graph);
}

} //end of anonymous namespace

void budget::report_module::load(){
    load_accounts();
    load_expenses();
    load_earnings();
}

void budget::report_module::handle(const std::vector<std::string>& args){
    auto today = budget::local_day();

    if(args.size() == 1){
        report(today.year(), [](budget::account&){ return true; });
    } else {
        auto& subcommand = args[1];

        if(subcommand == "monthly"){
            report(today.year(), [](budget::account&){ return true; });
        } else if(subcommand == "account"){
            std::string account_name;
            edit_string_complete(account_name, "Account", all_account_names(), not_empty_checker(), account_checker());

            report(today.year(), [&account_name](budget::account& account){ return account.name == account_name; });
        } else {
            throw budget_exception("Invalid subcommand \"" + subcommand + "\"");
        }
    }
}
<commit_msg>Fixes the report<commit_after>//=======================================================================
// Copyright (c) 2013-2017 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <iostream>

#include "report.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "budget_exception.hpp"
#include "accounts.hpp"
#include "console.hpp"

using namespace budget;

namespace {

using graph_type = std::vector<std::vector<std::string>>;

void render(graph_type& graph) {
    std::reverse(graph.begin(), graph.end());

    for (auto& line : graph) {
        for (auto& col : line) {
            std::cout << col;
        }
        std::cout << std::endl;
    }
}

void write(graph_type& graph, int row, int col, const std::string& value) {
    for (size_t i = 0; i < value.size(); ++i) {
        graph[row][col + i] = value[i];
    }
}

template <typename Predicate>
void report(budget::year year, Predicate predicate) {
    auto today = budget::local_day();

    budget::money max_expenses;
    budget::money max_earnings;
    budget::money max_balance;
    budget::money min_expenses;
    budget::money min_earnings;
    budget::money min_balance;

    auto sm = start_month(year);

    std::vector<int> expenses(12);
    std::vector<int> earnings(12);
    std::vector<int> balances(12);

    for (auto i = sm; i <= today.month(); ++i) {
        budget::month month = i;

        budget::money total_expenses;
        budget::money total_earnings;
        budget::money total_balance;

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

                total_expenses += expenses;
                total_earnings += earnings;

                auto balance = account.amount;
                balance -= expenses;
                balance += earnings;

                total_balance += balance;
            }
        }

        expenses[month - 1] = total_expenses.dollars();
        earnings[month - 1] = total_earnings.dollars();
        balances[month - 1] = total_balance.dollars();

        max_expenses = std::max(max_expenses, total_expenses);
        max_earnings = std::max(max_earnings, total_earnings);
        max_balance  = std::max(max_balance, total_balance);
        min_expenses = std::min(min_expenses, total_expenses);
        min_earnings = std::min(min_earnings, total_earnings);
        min_balance  = std::min(min_balance, total_balance);
    }

    auto max_number = std::max(std::max(
                                   std::max(std::abs(max_expenses.dollars()), std::abs(max_earnings.dollars())),
                                   std::max(std::abs(max_balance.dollars()), std::abs(min_expenses.dollars()))),
                               std::max(std::abs(min_balance.dollars()), std::abs(min_earnings.dollars())));

    size_t height = terminal_height() - 9;
    size_t width  = terminal_width() - 6;

    size_t scale_width = 5;

    // Compute the scale based on the data
    size_t scale = 1;
    if (max_number < 600) {
        scale = 100;
    } else if (max_number < 1500) {
        scale = 200;
    } else if (max_number < 3000) {
        scale = 500;
    } else if (max_number < 6000) {
        scale = 1000;
    } else {
        scale = 2000;
    }

    auto graph_width_func = [sm](size_t col_width) {
        constexpr size_t left_space = 7;
        constexpr size_t legend_width = 20;

        return left_space + (13 - sm) * (3 * col_width + 2) + (13 - sm - 1) * 2 + legend_width;
    };

    // Compute the best column width

    size_t col_width = 2;
    if (width > graph_width_func(4)) {
        col_width = 4;
    } else if (width > graph_width_func(3)) {
        col_width = 3;
    } else if (width > graph_width_func(2)) {
        col_width = 2;
    }

    std::cout << "col_width:" << col_width << std::endl;

    int min = 0;
    if (min_expenses.negative() || min_earnings.negative() || min_balance.negative()) {
        min = std::min(min_expenses, std::min(min_earnings, min_balance)).dollars();
        min = -1 * ((std::abs(min) / scale) + 1) * scale;
    }

    unsigned int max = std::max(max_earnings, std::max(max_expenses, max_balance)).dollars();
    max              = ((max / scale) + 1) * scale;

    unsigned int levels = max / scale + std::abs(min) / scale;

    unsigned int step_height = height / levels;
    unsigned int precision   = scale / step_height;

    std::cout << precision << std::endl;

    auto graph_height = 9 + step_height * levels;
    auto graph_width  = graph_width_func(col_width);

    graph_type graph(graph_height, std::vector<std::string>(graph_width, " "));

    //Display graph title

    write(graph, graph_height - 2, 8, "Monthly report of " + to_string(year));

    //Display scale

    for (size_t i = 0; i <= levels; ++i) {
        int level = min + i * scale;

        write(graph, 4 + step_height * i, 1, to_string(level));
    }

    //Display bar

    unsigned int min_index  = 3;
    unsigned int zero_index = min_index + 1 + (std::abs(min) / scale) * step_height;

    const auto first_bar = scale_width + 2;

    for (auto i = sm; i <= today.month(); ++i) {
        budget::month month = i;

        auto col_start = first_bar + (3 * col_width + 4) * (i - sm);

        //Display month legend
        auto month_str = month.as_short_string();
        write(graph, 1, col_start + 2, month_str);

        for (size_t j = 0; j < expenses[month - 1] / precision; ++j) {
            for (size_t x = 0; x < col_width; ++x) {
                graph[zero_index + j][col_start + x] = "\033[1;41m \033[0m";
            }
        }

        col_start += col_width + 1;

        for (size_t j = 0; j < earnings[month - 1] / precision; ++j) {
            for (size_t x = 0; x < col_width; ++x) {
                graph[zero_index + j][col_start + x] = "\033[1;42m \033[0m";
            }
        }

        col_start += col_width + 1;

        if (balances[month - 1] >= 0) {
            for (size_t j = 0; j < balances[month - 1] / precision; ++j) {
                for (size_t x = 0; x < col_width; ++x) {
                    std::cout << col_start << std::endl;
                    std::cout << col_start + x << std::endl;
                    std::cout << graph[zero_index + j].size() << std::endl;

                    graph[zero_index + j][col_start + x] = "\033[1;44m \033[0m";
                }
            }
        } else {
            for (size_t j = 0; j < std::abs(balances[month - 1]) / precision; ++j) {
                for (size_t x = 0; x < col_width; ++x) {
                    graph[zero_index - 1 - j][col_start + x] = "\033[1;44m \033[0m";
                }
            }
        }
    }

    //Display legend

    int start_legend = first_bar + (3 * col_width + 4) * (today.month() - sm + 1) + 4;

    std::cout << start_legend << std::endl;

    graph[4][start_legend - 2] = "|";
    graph[3][start_legend - 2] = "|";
    graph[2][start_legend - 2] = "|";

    graph[4][start_legend] = "\033[1;41m \033[0m";
    graph[3][start_legend] = "\033[1;42m \033[0m";
    graph[2][start_legend] = "\033[1;44m \033[0m";

    write(graph, 6, start_legend - 2, " ____________ ");
    write(graph, 5, start_legend - 2, "|            |");
    write(graph, 4, start_legend + 2, "Expenses |");
    write(graph, 3, start_legend + 2, "Earnings |");
    write(graph, 2, start_legend + 2, "Balance  |");
    write(graph, 1, start_legend - 2, "|____________|");

    //Render the graph

    render(graph);
}

} //end of anonymous namespace

void budget::report_module::load() {
    load_accounts();
    load_expenses();
    load_earnings();
}

void budget::report_module::handle(const std::vector<std::string>& args) {
    auto today = budget::local_day();

    if (args.size() == 1) {
        report(today.year(), [](budget::account&) { return true; });
    } else {
        auto& subcommand = args[1];

        if (subcommand == "monthly") {
            report(today.year(), [](budget::account&) { return true; });
        } else if (subcommand == "account") {
            std::string account_name;
            edit_string_complete(account_name, "Account", all_account_names(), not_empty_checker(), account_checker());

            report(today.year(), [&account_name](budget::account& account) { return account.name == account_name; });
        } else {
            throw budget_exception("Invalid subcommand \"" + subcommand + "\"");
        }
    }
}
<|endoftext|>


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

#include "android_webview/common/aw_content_client.h"

#include "base/basictypes.h"
#include "base/command_line.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/user_agent.h"
#include "ipc/ipc_message.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"

namespace {

std::string GetProduct() {
  // "Chrome/XX.0.0.0" identifies that this WebView is derived from the
  // corresponding Chromium version XX.
  // TODO(torne): Use chrome/VERSION file. See http://crbug.com/297522
  return "Chrome/38.0.0.0";
}

}

namespace android_webview {

std::string GetUserAgent() {
  // "Version/4.0" had been hardcoded in the legacy WebView.
  std::string product = "Version/4.0 " + GetProduct();
  if (CommandLine::ForCurrentProcess()->HasSwitch(
        switches::kUseMobileUserAgent)) {
    product += " Mobile";
  }
  return content::BuildUserAgentFromProduct(product);
}

std::string AwContentClient::GetProduct() const {
  return ::GetProduct();
}

std::string AwContentClient::GetUserAgent() const {
  return android_webview::GetUserAgent();
}

base::string16 AwContentClient::GetLocalizedString(int message_id) const {
  // TODO(boliu): Used only by WebKit, so only bundle those resources for
  // Android WebView.
  return l10n_util::GetStringUTF16(message_id);
}

base::StringPiece AwContentClient::GetDataResource(
    int resource_id,
    ui::ScaleFactor scale_factor) const {
  // TODO(boliu): Used only by WebKit, so only bundle those resources for
  // Android WebView.
  return ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(
      resource_id, scale_factor);
}

bool AwContentClient::CanSendWhileSwappedOut(const IPC::Message* message) {
  // For legacy API support we perform a few browser -> renderer synchronous IPC
  // messages that block the browser. However, the synchronous IPC replies might
  // be dropped by the renderer during a swap out, deadlocking the browser.
  // Because of this we should never drop any synchronous IPC replies.
  return message->type() == IPC_REPLY_ID;
}

}  // namespace android_webview
<commit_msg>Update WebView user agent to reflect M39.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "android_webview/common/aw_content_client.h"

#include "base/basictypes.h"
#include "base/command_line.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/user_agent.h"
#include "ipc/ipc_message.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"

namespace {

std::string GetProduct() {
  // "Chrome/XX.0.0.0" identifies that this WebView is derived from the
  // corresponding Chromium version XX.
  // TODO(torne): Use chrome/VERSION file. See http://crbug.com/297522
  return "Chrome/39.0.0.0";
}

}

namespace android_webview {

std::string GetUserAgent() {
  // "Version/4.0" had been hardcoded in the legacy WebView.
  std::string product = "Version/4.0 " + GetProduct();
  if (CommandLine::ForCurrentProcess()->HasSwitch(
        switches::kUseMobileUserAgent)) {
    product += " Mobile";
  }
  return content::BuildUserAgentFromProduct(product);
}

std::string AwContentClient::GetProduct() const {
  return ::GetProduct();
}

std::string AwContentClient::GetUserAgent() const {
  return android_webview::GetUserAgent();
}

base::string16 AwContentClient::GetLocalizedString(int message_id) const {
  // TODO(boliu): Used only by WebKit, so only bundle those resources for
  // Android WebView.
  return l10n_util::GetStringUTF16(message_id);
}

base::StringPiece AwContentClient::GetDataResource(
    int resource_id,
    ui::ScaleFactor scale_factor) const {
  // TODO(boliu): Used only by WebKit, so only bundle those resources for
  // Android WebView.
  return ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(
      resource_id, scale_factor);
}

bool AwContentClient::CanSendWhileSwappedOut(const IPC::Message* message) {
  // For legacy API support we perform a few browser -> renderer synchronous IPC
  // messages that block the browser. However, the synchronous IPC replies might
  // be dropped by the renderer during a swap out, deadlocking the browser.
  // Because of this we should never drop any synchronous IPC replies.
  return message->type() == IPC_REPLY_ID;
}

}  // namespace android_webview
<|endoftext|>


<commit_before>/***********************************************************************
    created:    24/9/2004
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2008 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "SampleBrowserBase.h"

#ifdef HAVE_CONFIG_H
#   include "config.h"
#endif
#include "CEGUISamplesConfig.h"

// includes for renderer selector classes
#if defined( __WIN32__ ) || defined( _WIN32 )
#   include "Win32CEGuiRendererSelector.h"
#elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)  || defined(__HAIKU__)
#   ifdef CEGUI_SAMPLES_USE_GTK2
#       include "GTK2CEGuiRendererSelector.h"
#   else
#       include "CLICEGuiRendererSelector.h"
#   endif
#elif defined(__APPLE__)
#   include "MacCEGuiRendererSelector.h"
#endif

// includes for application types
#ifdef CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE
#   include "CEGuiOgreBaseApplication.h"
#endif
#ifdef CEGUI_SAMPLES_RENDERER_OPENGL_ACTIVE
#   ifdef CEGUI_BUILD_RENDERER_OPENGL
#      include "CEGuiOpenGLBaseApplication.h"
#   endif
#   ifdef CEGUI_BUILD_RENDERER_OPENGL3
#      include "CEGuiOpenGL3BaseApplication.h"
#   endif
#endif
#ifdef CEGUI_SAMPLES_RENDERER_OPENGLES2_ACTIVE
#      include "CEGuiEGLBaseApplication.h"
#endif
#ifdef CEGUI_SAMPLES_RENDERER_IRRLICHT_ACTIVE
#   include "CEGuiIrrlichtBaseApplication.h"
#endif
#ifdef CEGUI_SAMPLES_RENDERER_DIRECTFB_ACTIVE
#   include "CEGuiDirectFBBaseApplication.h"
#endif
#if defined( __WIN32__ ) || defined( _WIN32 )
#   ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE
#       include "CEGuiD3D11BaseApplication.h"
#   endif
#endif
// now we include the base CEGuiBaseApplication just in case someone has managed to
// get this far without any of the renderers.  This ensures the framework will build,
// although there will be no renderers available for selection in the samples.
#include "CEGuiBaseApplication.h"

#include "CEGUI/CEGUI.h"
#include "CEGuiRendererSelector.h"

// Include iostream if not on windows.
#if defined( __WIN32__ ) || defined( _WIN32 )
#else
#    include <iostream>
#endif

/*************************************************************************
    Constructor
*************************************************************************/
SampleBrowserBase::SampleBrowserBase() :
        d_rendererSelector(0),
        d_baseApp(0),
        d_quitting(false),
        d_appWindowWidth(0),
        d_appWindowHeight(0)
{}

/*************************************************************************
    Destructor
*************************************************************************/
SampleBrowserBase::~SampleBrowserBase()
{
    if (d_baseApp)
    {
        d_baseApp->cleanup();
        delete d_baseApp;
    }

    if (d_rendererSelector)
    {
        delete d_rendererSelector;
    }

}

/*************************************************************************
    Application entry point
*************************************************************************/
int SampleBrowserBase::run()
{
    CEGUI_TRY
    {
        if(runApplication())
            cleanup();
    }
    CEGUI_CATCH (CEGUI::Exception& exc)
    {
        outputExceptionMessage(exc.getMessage().c_str());
    }
    CEGUI_CATCH (std::exception& exc)
    {
        outputExceptionMessage(exc.what());
    }
    CEGUI_CATCH (const char* exc)
    {
        outputExceptionMessage(exc);
    }
    CEGUI_CATCH(...)
    {
        outputExceptionMessage("Unknown exception was caught!");
    }

    return 0;
}

/*************************************************************************
    Start the SamplesFramework application
*************************************************************************/
bool SampleBrowserBase::runApplication()
{
    // Setup renderer selection dialog for Win32
#if defined( __WIN32__ ) || defined( _WIN32 )
    d_rendererSelector = new Win32CEGuiRendererSelector;

    // enable renderer types supported for Win32

#ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE
    d_rendererSelector->setRendererAvailability(Direct3D11GuiRendererType);
#endif

#elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__)
    // decide which method to use for renderer selection
#   ifdef CEGUI_SAMPLES_USE_GTK2
        d_rendererSelector = new GTK2CEGuiRendererSelector();
#   else
        d_rendererSelector = new CLICEGuiRendererSelector();
#   endif

#elif defined(__APPLE__)
     d_rendererSelector = new MacCEGuiRendererSelector();
#endif

    // enable available renderer types
#ifdef CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE
    d_rendererSelector->setRendererAvailability(OgreGuiRendererType);
#endif
#ifdef CEGUI_SAMPLES_RENDERER_OPENGL_ACTIVE
    #ifdef CEGUI_BUILD_RENDERER_OPENGL
        d_rendererSelector->setRendererAvailability(OpenGLGuiRendererType);
    #endif
    #ifdef CEGUI_BUILD_RENDERER_OPENGL3
        d_rendererSelector->setRendererAvailability(OpenGL3GuiRendererType);
    #endif
#endif
#ifdef CEGUI_SAMPLES_RENDERER_OPENGLES2_ACTIVE
    d_rendererSelector->setRendererAvailability(OpenGLES2GuiRendererType);
#endif
#ifdef CEGUI_SAMPLES_RENDERER_IRRLICHT_ACTIVE
    d_rendererSelector->setRendererAvailability(IrrlichtGuiRendererType);
#endif
#ifdef CEGUI_SAMPLES_RENDERER_DIRECTFB_ACTIVE
    d_rendererSelector->setRendererAvailability(DirectFBGuiRendererType);
#endif

    // get selection from user
    if (d_rendererSelector->invokeDialog())
    {
        // create appropriate application type based upon users selection
        switch(d_rendererSelector->getSelectedRendererType())
        {
#ifdef CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE
        case OgreGuiRendererType:
            {
                CEGuiOgreBaseApplication* ogreBaseApp = new CEGuiOgreBaseApplication();
                if(!ogreBaseApp->isInitialised())
                    return false;

                d_baseApp = ogreBaseApp;
            }
            break;
#endif
#if defined( __WIN32__ ) || defined( _WIN32 )
#ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE
        case Direct3D11GuiRendererType:
            d_baseApp = new CEGuiD3D11BaseApplication();
            break;
#endif // DX11
#endif // Win32
#ifdef CEGUI_SAMPLES_RENDERER_OPENGL_ACTIVE
    #ifdef CEGUI_BUILD_RENDERER_OPENGL
            case OpenGLGuiRendererType:
                d_baseApp = new CEGuiOpenGLBaseApplication();
                break;
    #endif
    #ifdef CEGUI_BUILD_RENDERER_OPENGL3
            case OpenGL3GuiRendererType:
                d_baseApp = new CEGuiOpenGL3BaseApplication();
                break;
    #endif
#endif
#ifdef CEGUI_SAMPLES_RENDERER_OPENGLES2_ACTIVE
            case OpenGLES2GuiRendererType:
                d_baseApp = new CEGuiEGLBaseApplication();
                break;
#endif
#ifdef CEGUI_SAMPLES_RENDERER_IRRLICHT_ACTIVE
        case IrrlichtGuiRendererType:
            d_baseApp = new CEGuiIrrlichtBaseApplication();
            break;
#endif
#ifdef CEGUI_SAMPLES_RENDERER_DIRECTFB_ACTIVE
        case DirectFBGuiRendererType:
            d_baseApp = new CEGuiDirectFBBaseApplication();
            break;
#endif

        default:
            CEGUI_THROW(CEGUI::GenericException("No renderer was selected!"));
            break;
        }

        // run the base application (which sets up the demo via 'this' and runs it.
        if (d_baseApp->execute(this))
        {
            // signal that app initialised and ran
            return true;
        }

        // sample app did not initialise, delete the object.
        delete d_baseApp;
        d_baseApp = 0;
    }

    // delete renderer selector object
    delete d_rendererSelector;
    d_rendererSelector = 0;

    // signal app did not initialise and run.
    return false;
}

/*************************************************************************
    Cleanup the sample application.
*************************************************************************/
void SampleBrowserBase::cleanup()
{
    delete d_baseApp;
    d_baseApp = 0;

    if (d_rendererSelector)
    {
        delete d_rendererSelector;
        d_rendererSelector = 0;
    }

}

/*************************************************************************
    Output a message to the user in some OS independant way.
*************************************************************************/
void SampleBrowserBase::outputExceptionMessage(const char* message)
{
#if defined(__WIN32__) || defined(_WIN32)
    MessageBoxA(0, message, "CEGUI - Exception", MB_OK|MB_ICONERROR);
#else
    std::cout << "An exception was thrown within the sample framework:" << std::endl;
    std::cout << message << std::endl;
#endif
}

void SampleBrowserBase::setQuitting(bool quit)
{
    d_quitting = quit;
}

bool SampleBrowserBase::isQuitting()
{
    return d_quitting;
}

void SampleBrowserBase::setApplicationWindowSize(int width, int height)
{
    d_appWindowWidth = width;
    d_appWindowHeight = height;
}
<commit_msg>whitespace removal<commit_after>/***********************************************************************
    created:    24/9/2004
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2008 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "SampleBrowserBase.h"

#ifdef HAVE_CONFIG_H
#   include "config.h"
#endif
#include "CEGUISamplesConfig.h"

// includes for renderer selector classes
#if defined( __WIN32__ ) || defined( _WIN32 )
#   include "Win32CEGuiRendererSelector.h"
#elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)  || defined(__HAIKU__)
#   ifdef CEGUI_SAMPLES_USE_GTK2
#       include "GTK2CEGuiRendererSelector.h"
#   else
#       include "CLICEGuiRendererSelector.h"
#   endif
#elif defined(__APPLE__)
#   include "MacCEGuiRendererSelector.h"
#endif

// includes for application types
#ifdef CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE
#   include "CEGuiOgreBaseApplication.h"
#endif
#ifdef CEGUI_SAMPLES_RENDERER_OPENGL_ACTIVE
#   ifdef CEGUI_BUILD_RENDERER_OPENGL
#      include "CEGuiOpenGLBaseApplication.h"
#   endif
#   ifdef CEGUI_BUILD_RENDERER_OPENGL3
#      include "CEGuiOpenGL3BaseApplication.h"
#   endif
#endif
#ifdef CEGUI_SAMPLES_RENDERER_OPENGLES2_ACTIVE
#      include "CEGuiEGLBaseApplication.h"
#endif
#ifdef CEGUI_SAMPLES_RENDERER_IRRLICHT_ACTIVE
#   include "CEGuiIrrlichtBaseApplication.h"
#endif
#ifdef CEGUI_SAMPLES_RENDERER_DIRECTFB_ACTIVE
#   include "CEGuiDirectFBBaseApplication.h"
#endif
#if defined( __WIN32__ ) || defined( _WIN32 )
#   ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE
#       include "CEGuiD3D11BaseApplication.h"
#   endif
#endif
// now we include the base CEGuiBaseApplication just in case someone has managed to
// get this far without any of the renderers.  This ensures the framework will build,
// although there will be no renderers available for selection in the samples.
#include "CEGuiBaseApplication.h"

#include "CEGUI/CEGUI.h"
#include "CEGuiRendererSelector.h"

// Include iostream if not on windows.
#if defined( __WIN32__ ) || defined( _WIN32 )
#else
#    include <iostream>
#endif

/*************************************************************************
    Constructor
*************************************************************************/
SampleBrowserBase::SampleBrowserBase() :
        d_rendererSelector(0),
        d_baseApp(0),
        d_quitting(false),
        d_appWindowWidth(0),
        d_appWindowHeight(0)
{}

/*************************************************************************
    Destructor
*************************************************************************/
SampleBrowserBase::~SampleBrowserBase()
{
    if (d_baseApp)
    {
        d_baseApp->cleanup();
        delete d_baseApp;
    }

    if (d_rendererSelector)
    {
        delete d_rendererSelector;
    }

}

/*************************************************************************
    Application entry point
*************************************************************************/
int SampleBrowserBase::run()
{
    CEGUI_TRY
    {
        if(runApplication())
            cleanup();
    }
    CEGUI_CATCH (CEGUI::Exception& exc)
    {
        outputExceptionMessage(exc.getMessage().c_str());
    }
    CEGUI_CATCH (std::exception& exc)
    {
        outputExceptionMessage(exc.what());
    }
    CEGUI_CATCH (const char* exc)
    {
        outputExceptionMessage(exc);
    }
    CEGUI_CATCH(...)
    {
        outputExceptionMessage("Unknown exception was caught!");
    }

    return 0;
}

/*************************************************************************
    Start the SamplesFramework application
*************************************************************************/
bool SampleBrowserBase::runApplication()
{
    // Setup renderer selection dialog for Win32
#if defined( __WIN32__ ) || defined( _WIN32 )
    d_rendererSelector = new Win32CEGuiRendererSelector;

    // enable renderer types supported for Win32

#ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE
    d_rendererSelector->setRendererAvailability(Direct3D11GuiRendererType);
#endif

#elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__)
    // decide which method to use for renderer selection
#   ifdef CEGUI_SAMPLES_USE_GTK2
        d_rendererSelector = new GTK2CEGuiRendererSelector();
#   else
        d_rendererSelector = new CLICEGuiRendererSelector();
#   endif

#elif defined(__APPLE__)
     d_rendererSelector = new MacCEGuiRendererSelector();
#endif

    // enable available renderer types
#ifdef CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE
    d_rendererSelector->setRendererAvailability(OgreGuiRendererType);
#endif
#ifdef CEGUI_SAMPLES_RENDERER_OPENGL_ACTIVE
    #ifdef CEGUI_BUILD_RENDERER_OPENGL
        d_rendererSelector->setRendererAvailability(OpenGLGuiRendererType);
    #endif
    #ifdef CEGUI_BUILD_RENDERER_OPENGL3
        d_rendererSelector->setRendererAvailability(OpenGL3GuiRendererType);
    #endif
#endif
#ifdef CEGUI_SAMPLES_RENDERER_OPENGLES2_ACTIVE
    d_rendererSelector->setRendererAvailability(OpenGLES2GuiRendererType);
#endif
#ifdef CEGUI_SAMPLES_RENDERER_IRRLICHT_ACTIVE
    d_rendererSelector->setRendererAvailability(IrrlichtGuiRendererType);
#endif
#ifdef CEGUI_SAMPLES_RENDERER_DIRECTFB_ACTIVE
    d_rendererSelector->setRendererAvailability(DirectFBGuiRendererType);
#endif

    // get selection from user
    if (d_rendererSelector->invokeDialog())
    {
        // create appropriate application type based upon users selection
        switch(d_rendererSelector->getSelectedRendererType())
        {
#ifdef CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE
        case OgreGuiRendererType:
            {
                CEGuiOgreBaseApplication* ogreBaseApp = new CEGuiOgreBaseApplication();
                if(!ogreBaseApp->isInitialised())
                    return false;

                d_baseApp = ogreBaseApp;
            }
            break;
#endif
#if defined( __WIN32__ ) || defined( _WIN32 )
#ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE
        case Direct3D11GuiRendererType:
            d_baseApp = new CEGuiD3D11BaseApplication();
            break;
#endif // DX11
#endif // Win32
#ifdef CEGUI_SAMPLES_RENDERER_OPENGL_ACTIVE
    #ifdef CEGUI_BUILD_RENDERER_OPENGL
            case OpenGLGuiRendererType:
                d_baseApp = new CEGuiOpenGLBaseApplication();
                break;
    #endif
    #ifdef CEGUI_BUILD_RENDERER_OPENGL3
            case OpenGL3GuiRendererType:
                d_baseApp = new CEGuiOpenGL3BaseApplication();
                break;
    #endif
#endif
#ifdef CEGUI_SAMPLES_RENDERER_OPENGLES2_ACTIVE
            case OpenGLES2GuiRendererType:
                d_baseApp = new CEGuiEGLBaseApplication();
                break;
#endif
#ifdef CEGUI_SAMPLES_RENDERER_IRRLICHT_ACTIVE
        case IrrlichtGuiRendererType:
            d_baseApp = new CEGuiIrrlichtBaseApplication();
            break;
#endif
#ifdef CEGUI_SAMPLES_RENDERER_DIRECTFB_ACTIVE
        case DirectFBGuiRendererType:
            d_baseApp = new CEGuiDirectFBBaseApplication();
            break;
#endif

        default:
            CEGUI_THROW(CEGUI::GenericException("No renderer was selected!"));
            break;
        }

        // run the base application (which sets up the demo via 'this' and runs it.
        if (d_baseApp->execute(this))
        {
            // signal that app initialised and ran
            return true;
        }

        // sample app did not initialise, delete the object.
        delete d_baseApp;
        d_baseApp = 0;
    }

    // delete renderer selector object
    delete d_rendererSelector;
    d_rendererSelector = 0;

    // signal app did not initialise and run.
    return false;
}

/*************************************************************************
    Cleanup the sample application.
*************************************************************************/
void SampleBrowserBase::cleanup()
{
    delete d_baseApp;
    d_baseApp = 0;

    if (d_rendererSelector)
    {
        delete d_rendererSelector;
        d_rendererSelector = 0;
    }

}

/*************************************************************************
    Output a message to the user in some OS independant way.
*************************************************************************/
void SampleBrowserBase::outputExceptionMessage(const char* message)
{
#if defined(__WIN32__) || defined(_WIN32)
    MessageBoxA(0, message, "CEGUI - Exception", MB_OK|MB_ICONERROR);
#else
    std::cout << "An exception was thrown within the sample framework:" << std::endl;
    std::cout << message << std::endl;
#endif
}

void SampleBrowserBase::setQuitting(bool quit)
{
    d_quitting = quit;
}

bool SampleBrowserBase::isQuitting()
{
    return d_quitting;
}

void SampleBrowserBase::setApplicationWindowSize(int width, int height)
{
    d_appWindowWidth = width;
    d_appWindowHeight = height;
}
<|endoftext|>


<commit_before>// Include standard headers
#include <stdio.h>
#include <stdlib.h>
#include <vector>

// Include GLEW
#include <GL/glew.h>

// Include GLFW
#include <glfw3.h>
GLFWwindow* window;

// Include GLM
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
using namespace glm;

#include <common/shader.hpp>
#include <common/texture.hpp>
#include <common/controls.hpp>
#include <common/objloader.hpp>

int main(void)
{
    // Initialise GLFW
    if (!glfwInit())
    {
        fprintf( stderr, "Failed to initialize GLFW\n" );
        return -1;
    }

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);

    // Open a window and create its OpenGL context
    window = glfwCreateWindow(1024, 768, "Tutorial 07 - Model Loading", NULL, NULL);
    if (window == NULL)
    {
        fprintf( stderr, "Failed to open GLFW window.\n" );
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    // Initialize GLEW
    if (glewInit() != GLEW_OK)
    {
        fprintf(stderr, "Failed to initialize GLEW\n");
        return -1;
    }

    // Ensure we can capture the escape key being pressed below
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
    glfwSetCursorPos(window, 1024/2, 768/2);

    // Dark blue background
    glClearColor(0.0f, 0.0f, 0.4f, 0.0f);

    // Enable depth test
    glEnable(GL_DEPTH_TEST);
    // Accept fragment if it closer to the camera than the former one
    glDepthFunc(GL_LESS);

    // Cull triangles which normal is not towards the camera
    glEnable(GL_CULL_FACE);

    // Create and compile our GLSL program from the shaders
    GLuint programID = LoadShaders( "TransformVertexShader.vertexshader", "TextureFragmentShader.fragmentshader" );

    // Get a handle for our "MVP" uniform
    GLuint MatrixID = glGetUniformLocation(programID, "MVP");

    // Get a handle for our buffers
    GLuint vertexPosition_modelspaceID = glGetAttribLocation(programID, "vertexPosition_modelspace");
    GLuint vertexUVID = glGetAttribLocation(programID, "vertexUV");

    // Load the texture
    GLuint Texture = loadBMP_custom("kuutio-uv-numerot.bmp");
    // GLuint Texture = loadBMP_custom("uvtemplate.bmp");
    // GLuint Texture = loadDDS("uvtemplate.DDS");
    // GLuint Texture = loadDDS("uvmap.DDS");

    // Get a handle for our "myTextureSampler" uniform
    GLuint TextureID  = glGetUniformLocation(programID, "myTextureSampler");

    // Read our .obj file
    std::vector<glm::vec3> vertices;
    std::vector<glm::vec2> uvs;
    std::vector<glm::vec3> normals; // Won't be used at the moment.
    // bool res = loadOBJ("cube.obj", vertices, uvs, normals);
    // bool res = loadOBJ("oma_icosphere.obj", vertices, uvs, normals);
    bool res = loadOBJ("kirjainkuutio.obj", vertices, uvs, normals);

    printf("vertices.size: %d", vertices.size());

    // Load it into a VBO
    GLuint vertexbuffer;
    glGenBuffers(1, &vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);

    GLuint uvbuffer;
    glGenBuffers(1, &uvbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
    glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(glm::vec2), &uvs[0], GL_STATIC_DRAW);

    do
    {
        // Clear the screen
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Use our shader
        glUseProgram(programID);

        // Compute the MVP matrix from keyboard and mouse input
        computeMatricesFromInputs();
        glm::mat4 ProjectionMatrix = getProjectionMatrix();
        glm::mat4 ViewMatrix = getViewMatrix();
        glm::mat4 ModelMatrix = glm::mat4(1.0);
        glm::mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix;

        // Send our transformation to the currently bound shader,
        // in the "MVP" uniform
        glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);

        // Bind our texture in Texture Unit 0
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, Texture);
        // Set our "myTextureSampler" sampler to user Texture Unit 0
        glUniform1i(TextureID, 0);

        // 1rst attribute buffer : vertices
        glEnableVertexAttribArray(vertexPosition_modelspaceID);
        glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
        glVertexAttribPointer(
                vertexPosition_modelspaceID,  // The attribute we want to configure
                3,                            // size
                GL_FLOAT,                     // type
                GL_FALSE,                     // normalized?
                0,                            // stride
                (void*)0                      // array buffer offset
                );

        // 2nd attribute buffer : UVs
        glEnableVertexAttribArray(vertexUVID);
        glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
        glVertexAttribPointer(
                vertexUVID,                   // The attribute we want to configure
                2,                            // size : U+V => 2
                GL_FLOAT,                     // type
                GL_FALSE,                     // normalized?
                0,                            // stride
                (void*)0                      // array buffer offset
                );

        // Draw the triangles !
        glDrawArrays(GL_TRIANGLES, 0, vertices.size() );

        glDisableVertexAttribArray(vertexPosition_modelspaceID);
        glDisableVertexAttribArray(vertexUVID);

        // Swap buffers
        glfwSwapBuffers(window);
        glfwPollEvents();

    } // Check if the ESC key was pressed or the window was closed
    while ((glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS)
            && (glfwWindowShouldClose(window) == 0 ));

    // Cleanup VBO and shader
    glDeleteBuffers(1, &vertexbuffer);
    glDeleteBuffers(1, &uvbuffer);
    glDeleteProgram(programID);
    glDeleteTextures(1, &TextureID);

    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    return 0;
}
<commit_msg>Mallitiedosto ja tekstuuritiedosto määritellään tiedoston alussa.<commit_after>// Include standard headers
#include <iostream>
#include <string>
#include <string.h>
#include <vector>
#include <stdio.h>
#include <stdlib.h>

// Include GLEW
#include <GL/glew.h>

// Include GLFW
#include <glfw3.h>
GLFWwindow* window;

// Include GLM
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
// using namespace glm;
using namespace std;

#include <common/shader.hpp>
#include <common/texture.hpp>
#include <common/controls.hpp>
#include <common/objloader.hpp>

// model file format: obj/bmp/...
// std::string g_model_file_format = "bmp";
std::string g_model_file_format = "obj";

// model filename.
// std::string g_model_filename = "cube.obj";
// std::string g_model_filename = "oma_icosphere.obj";
std::string g_model_filename = "kirjainkuutio.obj";

// texture file format: bmp/...
std::string g_texture_file_format = "bmp";

// texture filename.
std::string g_texture_filename = "kuutio-uv-numerot.bmp";

int main(void)
{
    // Initialise GLFW
    if (!glfwInit())
    {
        cerr << "Failed to initialize GLFW\n";
        return -1;
    }

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);

    // Open a window and create its OpenGL context
    window = glfwCreateWindow(1024, 768, "Tutorial 07 - Model Loading", NULL, NULL);
    if (window == NULL)
    {
        cerr << "Failed to open GLFW window.\n";
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    // Initialize GLEW
    if (glewInit() != GLEW_OK)
    {
        cerr << "Failed to initialize GLEW\n";
        return -1;
    }

    // Ensure we can capture the escape key being pressed below
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
    glfwSetCursorPos(window, 1024/2, 768/2);

    // Dark blue background
    glClearColor(0.0f, 0.0f, 0.4f, 0.0f);

    // Enable depth test
    glEnable(GL_DEPTH_TEST);
    // Accept fragment if it closer to the camera than the former one
    glDepthFunc(GL_LESS);

    // Cull triangles which normal is not towards the camera
    glEnable(GL_CULL_FACE);

    // Create and compile our GLSL program from the shaders
    GLuint programID = LoadShaders("TransformVertexShader.vertexshader", "TextureFragmentShader.fragmentshader");

    // Get a handle for our "MVP" uniform
    GLuint MatrixID = glGetUniformLocation(programID, "MVP");

    // Get a handle for our buffers
    GLuint vertexPosition_modelspaceID = glGetAttribLocation(programID, "vertexPosition_modelspace");
    GLuint vertexUVID = glGetAttribLocation(programID, "vertexUV");

    // Load the texture
    GLuint Texture;

    const char *char_g_texture_file_format = g_texture_file_format.c_str();
    const char *char_g_texture_filename = g_texture_filename.c_str();

    if (strcmp(char_g_texture_file_format, "bmp") == 0)
    {
        Texture = loadBMP_custom(char_g_texture_filename);
    }
    else
    {
        cerr << "no texture was loaded!\n";
        cerr << "texture file format: " << g_texture_file_format << "\n";
        return -1;
    }

    // Get a handle for our "myTextureSampler" uniform
    GLuint TextureID  = glGetUniformLocation(programID, "myTextureSampler");

    // Read our .obj file
    std::vector<glm::vec3> vertices;
    std::vector<glm::vec2> uvs;
    std::vector<glm::vec3> normals; // Won't be used at the moment.

    const char *char_g_model_file_format = g_model_file_format.c_str();
    const char *char_g_model_filename = g_model_filename.c_str();
    if (strcmp(char_g_model_file_format, "obj") == 0)
    {
        bool res = loadOBJ(char_g_model_filename, vertices, uvs, normals);
    }
    else
    {
        cerr << "no model was loaded!\n";
        cerr << "model file format: " << g_model_file_format << "\n";
        return -1;
    }
    cout << "vertices.size: " << vertices.size() << "\n";

    // Load it into a VBO
    GLuint vertexbuffer;
    glGenBuffers(1, &vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);

    GLuint uvbuffer;
    glGenBuffers(1, &uvbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
    glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(glm::vec2), &uvs[0], GL_STATIC_DRAW);

    do
    {
        // Clear the screen
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Use our shader
        glUseProgram(programID);

        // Compute the MVP matrix from keyboard and mouse input
        computeMatricesFromInputs();
        glm::mat4 ProjectionMatrix = getProjectionMatrix();
        glm::mat4 ViewMatrix = getViewMatrix();
        glm::mat4 ModelMatrix = glm::mat4(1.0);
        glm::mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix;

        // Send our transformation to the currently bound shader,
        // in the "MVP" uniform
        glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);

        // Bind our texture in Texture Unit 0
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, Texture);
        // Set our "myTextureSampler" sampler to user Texture Unit 0
        glUniform1i(TextureID, 0);

        // 1rst attribute buffer : vertices
        glEnableVertexAttribArray(vertexPosition_modelspaceID);
        glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
        glVertexAttribPointer(
                vertexPosition_modelspaceID,  // The attribute we want to configure
                3,                            // size
                GL_FLOAT,                     // type
                GL_FALSE,                     // normalized?
                0,                            // stride
                (void*)0                      // array buffer offset
                );

        // 2nd attribute buffer : UVs
        glEnableVertexAttribArray(vertexUVID);
        glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
        glVertexAttribPointer(
                vertexUVID,                   // The attribute we want to configure
                2,                            // size : U+V => 2
                GL_FLOAT,                     // type
                GL_FALSE,                     // normalized?
                0,                            // stride
                (void*)0                      // array buffer offset
                );

        // Draw the triangles !
        glDrawArrays(GL_TRIANGLES, 0, vertices.size());

        glDisableVertexAttribArray(vertexPosition_modelspaceID);
        glDisableVertexAttribArray(vertexUVID);

        // Swap buffers
        glfwSwapBuffers(window);
        glfwPollEvents();

    } // Check if the ESC key was pressed or the window was closed
    while ((glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS)
            && (glfwWindowShouldClose(window) == 0));

    // Cleanup VBO and shader
    glDeleteBuffers(1, &vertexbuffer);
    glDeleteBuffers(1, &uvbuffer);
    glDeleteProgram(programID);
    glDeleteTextures(1, &TextureID);

    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    return 0;
}
<|endoftext|>


<commit_before>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright 2011-2018 Dominik Charousset                                     *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#pragma once

#include <cstdint>

#include "caf/pec.hpp"

namespace caf {
namespace detail {
namespace parser {

template <class Iterator, class Sentinel = Iterator>
struct state {
  Iterator i;
  Sentinel e;
  pec code;
  int32_t line;
  int32_t column;

  state() : i(), e(), code(pec::success), line(1), column(1) {
    // nop
  }

  explicit state(Iterator first) : state() {
    i = first;
  }

  state(Iterator first, Sentinel last) : state() {
    i = first;
    e = last;
  }

  /// Returns the null terminator when reaching the end of the string,
  /// otherwise the next character.
  char next() noexcept {
    ++i;
    ++column;
    if (i != e) {
      auto c = *i;
      if (c == '\n') {
        ++line;
        column = 1;
      }
      return c;
    }
    return '\0';
  }

  /// Returns the null terminator if `i == e`, otherwise the current character.
  char current() const noexcept {
    return i != e ? *i : '\0';
  }
};

} // namespace parser
} // namespace detail
} // namespace caf
<commit_msg>Make all state constructors noexcept<commit_after>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright 2011-2018 Dominik Charousset                                     *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#pragma once

#include <cstdint>

#include "caf/pec.hpp"

namespace caf {
namespace detail {
namespace parser {

template <class Iterator, class Sentinel = Iterator>
struct state {
  Iterator i;
  Sentinel e;
  pec code;
  int32_t line;
  int32_t column;

  state() noexcept : i(), e(), code(pec::success), line(1), column(1) {
    // nop
  }

  explicit state(Iterator first) noexcept : state() {
    i = first;
  }

  state(Iterator first, Sentinel last) noexcept : state() {
    i = first;
    e = last;
  }

  /// Returns the null terminator when reaching the end of the string,
  /// otherwise the next character.
  char next() noexcept {
    ++i;
    ++column;
    if (i != e) {
      auto c = *i;
      if (c == '\n') {
        ++line;
        column = 1;
      }
      return c;
    }
    return '\0';
  }

  /// Returns the null terminator if `i == e`, otherwise the current character.
  char current() const noexcept {
    return i != e ? *i : '\0';
  }
};

} // namespace parser
} // namespace detail
} // namespace caf
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "libcef/browser/javascript_dialog.h"
#include "libcef/browser/javascript_dialog_manager.h"
#include "libcef/browser/browser_host_impl.h"
#include "libcef_dll/resource.h"

#include "base/files/file_path.h"
#include "base/path_service.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"

class CefJavaScriptDialog;

HHOOK CefJavaScriptDialog::msg_hook_ = NULL;
int CefJavaScriptDialog::msg_hook_user_count_ = 0;

INT_PTR CALLBACK CefJavaScriptDialog::DialogProc(HWND dialog,
                                                 UINT message,
                                                 WPARAM wparam,
                                                 LPARAM lparam) {
  switch (message) {
    case WM_INITDIALOG: {
      SetWindowLongPtr(dialog, DWLP_USER, static_cast<LONG_PTR>(lparam));
      CefJavaScriptDialog* owner =
          reinterpret_cast<CefJavaScriptDialog*>(lparam);
      owner->dialog_win_ = dialog;
      SetDlgItemText(dialog, IDC_DIALOGTEXT, owner->message_text_.c_str());
      if (owner->message_type_ == content::JAVASCRIPT_MESSAGE_TYPE_PROMPT)
        SetDlgItemText(dialog, IDC_PROMPTEDIT,
                       owner->default_prompt_text_.c_str());
      break;
    }
    case WM_CLOSE: {
      CefJavaScriptDialog* owner = reinterpret_cast<CefJavaScriptDialog*>(
          GetWindowLongPtr(dialog, DWLP_USER));
      if (owner) {
        owner->Cancel();
        owner->callback_.Run(false, base::string16());
        owner->creator_->DialogClosed(owner);

        // No need for the system to call DestroyWindow() because it will be
        // called by the Cancel() method.
        return 0;
      }
      break;
    }
    case WM_COMMAND: {
      CefJavaScriptDialog* owner = reinterpret_cast<CefJavaScriptDialog*>(
          GetWindowLongPtr(dialog, DWLP_USER));
      base::string16 user_input;
      bool finish = false;
      bool result;
      switch (LOWORD(wparam)) {
        case IDOK:
          finish = true;
          result = true;
          if (owner->message_type_ == content::JAVASCRIPT_MESSAGE_TYPE_PROMPT) {
            size_t length =
                GetWindowTextLength(GetDlgItem(dialog, IDC_PROMPTEDIT)) + 1;
            if (length > 1) {
              GetDlgItemText(dialog, IDC_PROMPTEDIT,
                             WriteInto(&user_input, length), length);
            }
          }
          break;
        case IDCANCEL:
          finish = true;
          result = false;
          break;
      }
      if (finish) {
        owner->Cancel();
        owner->callback_.Run(result, user_input);
        owner->creator_->DialogClosed(owner);
      }
      break;
    }
    default:
      return DefWindowProc(dialog, message, wparam, lparam);
  }
  return 0;
}

CefJavaScriptDialog::CefJavaScriptDialog(
    CefJavaScriptDialogManager* creator,
    content::JavaScriptMessageType message_type,
    const base::string16& display_url,
    const base::string16& message_text,
    const base::string16& default_prompt_text,
    const content::JavaScriptDialogManager::DialogClosedCallback& callback)
    : creator_(creator),
      callback_(callback),
      message_text_(message_text),
      default_prompt_text_(default_prompt_text),
      message_type_(message_type) {
  InstallMessageHook();

  int dialog_type;
  if (message_type == content::JAVASCRIPT_MESSAGE_TYPE_ALERT)
    dialog_type = IDD_ALERT;
  else if (message_type == content::JAVASCRIPT_MESSAGE_TYPE_CONFIRM)
    dialog_type = IDD_CONFIRM;
  else  // JAVASCRIPT_MESSAGE_TYPE_PROMPT
    dialog_type = IDD_PROMPT;

  base::FilePath file_path;
  HMODULE hModule = NULL;

  // Try to load the dialog from the DLL.
  if (PathService::Get(base::FILE_MODULE, &file_path))
    hModule = ::GetModuleHandle(file_path.value().c_str());
  if (!hModule)
    hModule = ::GetModuleHandle(NULL);
  DCHECK(hModule);

  parent_win_ = GetAncestor(creator->browser()->GetWindowHandle(), GA_ROOT);
  dialog_win_ = CreateDialogParam(hModule,
                                  MAKEINTRESOURCE(dialog_type),
                                  parent_win_,
                                  DialogProc,
                                  reinterpret_cast<LPARAM>(this));
  DCHECK(dialog_win_);

  if (!display_url.empty()) {
    // Add the display URL to the window title.
    TCHAR text[64];
    GetWindowText(dialog_win_, text, sizeof(text)/sizeof(TCHAR));

    base::string16 new_window_text =
        text + base::ASCIIToUTF16(" - ") + display_url;
    SetWindowText(dialog_win_, new_window_text.c_str());
  }

  // Disable the parent window so the user can't interact with it.
  if (IsWindowEnabled(parent_win_))
    EnableWindow(parent_win_, FALSE);

  ShowWindow(dialog_win_, SW_SHOWNORMAL);
}

CefJavaScriptDialog::~CefJavaScriptDialog() {
  Cancel();
  UninstallMessageHook();
}

void CefJavaScriptDialog::Cancel() {
  HWND parent = NULL;

  // Re-enable the parent before closing the popup to avoid focus/activation/
  // z-order issues.
  if (parent_win_ && IsWindow(parent_win_) && !IsWindowEnabled(parent_win_)) {
    parent = parent_win_;
    EnableWindow(parent_win_, TRUE);
    parent_win_ = NULL;
  }

  if (dialog_win_ && IsWindow(dialog_win_)) {
    SetWindowLongPtr(dialog_win_, DWLP_USER, NULL);
    DestroyWindow(dialog_win_);
    dialog_win_ = NULL;
  }

  // Return focus to the parent window.
  if (parent)
    SetFocus(parent);
}

// static
LRESULT CALLBACK CefJavaScriptDialog::GetMsgProc(int code, WPARAM wparam,
                                                 LPARAM lparam) {
  // Mostly borrowed from http://support.microsoft.com/kb/q187988/
  // and http://www.codeproject.com/KB/atl/cdialogmessagehook.aspx.
  LPMSG msg = reinterpret_cast<LPMSG>(lparam);
  if (code >= 0 && wparam == PM_REMOVE &&
      msg->message >= WM_KEYFIRST && msg->message <= WM_KEYLAST) {
    HWND hwnd = GetActiveWindow();
    if (::IsWindow(hwnd) && ::IsDialogMessage(hwnd, msg)) {
      // The value returned from this hookproc is ignored, and it cannot
      // be used to tell Windows the message has been handled. To avoid
      // further processing, convert the message to WM_NULL before
      // returning.
      msg->hwnd = NULL;
      msg->message = WM_NULL;
      msg->lParam = 0L;
      msg->wParam = 0;
    }
  }

  // Passes the hook information to the next hook procedure in
  // the current hook chain.
  return ::CallNextHookEx(msg_hook_, code, wparam, lparam);
}

// static
bool CefJavaScriptDialog::InstallMessageHook() {
  msg_hook_user_count_++;

  // Make sure we only call this once.
  if (msg_hook_ != NULL)
    return true;

  msg_hook_ = ::SetWindowsHookEx(WH_GETMESSAGE,
                                 &CefJavaScriptDialog::GetMsgProc,
                                 NULL,
                                 GetCurrentThreadId());
  DCHECK(msg_hook_ != NULL);
  return msg_hook_ != NULL;
}

// static
bool CefJavaScriptDialog::UninstallMessageHook() {
  msg_hook_user_count_--;
  DCHECK_GE(msg_hook_user_count_, 0);

  if (msg_hook_user_count_ > 0)
    return true;

  DCHECK(msg_hook_ != NULL);
  BOOL result = ::UnhookWindowsHookEx(msg_hook_);
  DCHECK(result);
  msg_hook_ = NULL;

  return result != FALSE;
}
<commit_msg>Windows: Fix display of default JavaScript dialogs (issue #760).<commit_after>// Copyright (c) 2012 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "libcef/browser/javascript_dialog.h"
#include "libcef/browser/javascript_dialog_manager.h"
#include "libcef/browser/browser_host_impl.h"
#include "libcef_dll/resource.h"

#include "base/files/file_path.h"
#include "base/path_service.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"

class CefJavaScriptDialog;

HHOOK CefJavaScriptDialog::msg_hook_ = NULL;
int CefJavaScriptDialog::msg_hook_user_count_ = 0;

INT_PTR CALLBACK CefJavaScriptDialog::DialogProc(HWND dialog,
                                                 UINT message,
                                                 WPARAM wparam,
                                                 LPARAM lparam) {
  switch (message) {
    case WM_INITDIALOG: {
      SetWindowLongPtr(dialog, DWLP_USER, static_cast<LONG_PTR>(lparam));
      CefJavaScriptDialog* owner =
          reinterpret_cast<CefJavaScriptDialog*>(lparam);
      owner->dialog_win_ = dialog;
      SetDlgItemText(dialog, IDC_DIALOGTEXT, owner->message_text_.c_str());
      if (owner->message_type_ == content::JAVASCRIPT_MESSAGE_TYPE_PROMPT)
        SetDlgItemText(dialog, IDC_PROMPTEDIT,
                       owner->default_prompt_text_.c_str());
      break;
    }
    case WM_CLOSE: {
      CefJavaScriptDialog* owner = reinterpret_cast<CefJavaScriptDialog*>(
          GetWindowLongPtr(dialog, DWLP_USER));
      if (owner) {
        owner->Cancel();
        owner->callback_.Run(false, base::string16());
        owner->creator_->DialogClosed(owner);

        // No need for the system to call DestroyWindow() because it will be
        // called by the Cancel() method.
        return 0;
      }
      break;
    }
    case WM_COMMAND: {
      CefJavaScriptDialog* owner = reinterpret_cast<CefJavaScriptDialog*>(
          GetWindowLongPtr(dialog, DWLP_USER));
      base::string16 user_input;
      bool finish = false;
      bool result;
      switch (LOWORD(wparam)) {
        case IDOK:
          finish = true;
          result = true;
          if (owner->message_type_ == content::JAVASCRIPT_MESSAGE_TYPE_PROMPT) {
            size_t length =
                GetWindowTextLength(GetDlgItem(dialog, IDC_PROMPTEDIT)) + 1;
            if (length > 1) {
              GetDlgItemText(dialog, IDC_PROMPTEDIT,
                             WriteInto(&user_input, length), length);
            }
          }
          break;
        case IDCANCEL:
          finish = true;
          result = false;
          break;
      }
      if (finish) {
        owner->Cancel();
        owner->callback_.Run(result, user_input);
        owner->creator_->DialogClosed(owner);
      }
      break;
    }
    default:
      break;
  }
  return 0;
}

CefJavaScriptDialog::CefJavaScriptDialog(
    CefJavaScriptDialogManager* creator,
    content::JavaScriptMessageType message_type,
    const base::string16& display_url,
    const base::string16& message_text,
    const base::string16& default_prompt_text,
    const content::JavaScriptDialogManager::DialogClosedCallback& callback)
    : creator_(creator),
      callback_(callback),
      message_text_(message_text),
      default_prompt_text_(default_prompt_text),
      message_type_(message_type) {
  InstallMessageHook();

  int dialog_type;
  if (message_type == content::JAVASCRIPT_MESSAGE_TYPE_ALERT)
    dialog_type = IDD_ALERT;
  else if (message_type == content::JAVASCRIPT_MESSAGE_TYPE_CONFIRM)
    dialog_type = IDD_CONFIRM;
  else  // JAVASCRIPT_MESSAGE_TYPE_PROMPT
    dialog_type = IDD_PROMPT;

  base::FilePath file_path;
  HMODULE hModule = NULL;

  // Try to load the dialog from the DLL.
  if (PathService::Get(base::FILE_MODULE, &file_path))
    hModule = ::GetModuleHandle(file_path.value().c_str());
  if (!hModule)
    hModule = ::GetModuleHandle(NULL);
  DCHECK(hModule);

  parent_win_ = GetAncestor(creator->browser()->GetWindowHandle(), GA_ROOT);
  dialog_win_ = CreateDialogParam(hModule,
                                  MAKEINTRESOURCE(dialog_type),
                                  parent_win_,
                                  DialogProc,
                                  reinterpret_cast<LPARAM>(this));
  DCHECK(dialog_win_);

  if (!display_url.empty()) {
    // Add the display URL to the window title.
    TCHAR text[64];
    GetWindowText(dialog_win_, text, sizeof(text)/sizeof(TCHAR));

    base::string16 new_window_text =
        text + base::ASCIIToUTF16(" - ") + display_url;
    SetWindowText(dialog_win_, new_window_text.c_str());
  }

  // Disable the parent window so the user can't interact with it.
  if (IsWindowEnabled(parent_win_))
    EnableWindow(parent_win_, FALSE);

  ShowWindow(dialog_win_, SW_SHOWNORMAL);
}

CefJavaScriptDialog::~CefJavaScriptDialog() {
  Cancel();
  UninstallMessageHook();
}

void CefJavaScriptDialog::Cancel() {
  HWND parent = NULL;

  // Re-enable the parent before closing the popup to avoid focus/activation/
  // z-order issues.
  if (parent_win_ && IsWindow(parent_win_) && !IsWindowEnabled(parent_win_)) {
    parent = parent_win_;
    EnableWindow(parent_win_, TRUE);
    parent_win_ = NULL;
  }

  if (dialog_win_ && IsWindow(dialog_win_)) {
    SetWindowLongPtr(dialog_win_, DWLP_USER, NULL);
    DestroyWindow(dialog_win_);
    dialog_win_ = NULL;
  }

  // Return focus to the parent window.
  if (parent)
    SetFocus(parent);
}

// static
LRESULT CALLBACK CefJavaScriptDialog::GetMsgProc(int code, WPARAM wparam,
                                                 LPARAM lparam) {
  // Mostly borrowed from http://support.microsoft.com/kb/q187988/
  // and http://www.codeproject.com/KB/atl/cdialogmessagehook.aspx.
  LPMSG msg = reinterpret_cast<LPMSG>(lparam);
  if (code >= 0 && wparam == PM_REMOVE &&
      msg->message >= WM_KEYFIRST && msg->message <= WM_KEYLAST) {
    HWND hwnd = GetActiveWindow();
    if (::IsWindow(hwnd) && ::IsDialogMessage(hwnd, msg)) {
      // The value returned from this hookproc is ignored, and it cannot
      // be used to tell Windows the message has been handled. To avoid
      // further processing, convert the message to WM_NULL before
      // returning.
      msg->hwnd = NULL;
      msg->message = WM_NULL;
      msg->lParam = 0L;
      msg->wParam = 0;
    }
  }

  // Passes the hook information to the next hook procedure in
  // the current hook chain.
  return ::CallNextHookEx(msg_hook_, code, wparam, lparam);
}

// static
bool CefJavaScriptDialog::InstallMessageHook() {
  msg_hook_user_count_++;

  // Make sure we only call this once.
  if (msg_hook_ != NULL)
    return true;

  msg_hook_ = ::SetWindowsHookEx(WH_GETMESSAGE,
                                 &CefJavaScriptDialog::GetMsgProc,
                                 NULL,
                                 GetCurrentThreadId());
  DCHECK(msg_hook_ != NULL);
  return msg_hook_ != NULL;
}

// static
bool CefJavaScriptDialog::UninstallMessageHook() {
  msg_hook_user_count_--;
  DCHECK_GE(msg_hook_user_count_, 0);

  if (msg_hook_user_count_ > 0)
    return true;

  DCHECK(msg_hook_ != NULL);
  BOOL result = ::UnhookWindowsHookEx(msg_hook_);
  DCHECK(result);
  msg_hook_ = NULL;

  return result != FALSE;
}
<|endoftext|>


<commit_before>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2008, 2009 Ames Laboratory
Iowa State University and The Regents of the University of Michigan All rights
reserved.

HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.

Redistribution and use of HOOMD-blue, in source and binary forms, with or
without modification, are permitted, provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions, and the following disclaimer in the documentation and/or
other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of HOOMD-blue's
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.

Disclaimer

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR
ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED.

IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// $Id$
// $URL$
// Maintainer: joaander

#include "NeighborListBinned.h"

#include <boost/python.hpp>
using namespace boost::python;

NeighborListBinned::NeighborListBinned(boost::shared_ptr<SystemDefinition> sysdef,
                                       Scalar r_cut,
                                       Scalar r_buff,
                                       boost::shared_ptr<CellList> cl)
    : NeighborList(sysdef, r_cut, r_buff), m_cl(cl)
    {
    // create a default cell list if one was not specified
    if (!m_cl)
        m_cl = boost::shared_ptr<CellList>(new CellList(sysdef));

    m_cl->setNominalWidth((r_cut + r_buff)/2.0);
    m_cl->setRadius(2);
    m_cl->setComputeTDB(false);
    m_cl->setFlagIndex();
    }

NeighborListBinned::~NeighborListBinned()
    {
    }

void NeighborListBinned::setRCut(Scalar r_cut, Scalar r_buff)
    {
    NeighborList::setRCut(r_cut, r_buff);

    m_cl->setNominalWidth((r_cut + r_buff)/2.0);
    }

void NeighborListBinned::buildNlist(unsigned int timestep)
    {
    m_cl->compute(timestep);

    // check that at least 3x3x3 cells are computed
    uint3 dim = m_cl->getDim();
    if (dim.x < 3 || dim.y < 3 || dim.z < 3)
        {
        cerr << endl << "***Error! NeighborListGPUBinned doesn't work on boxes where r_cut+r_buff is greater than 1/3 any box dimension" << endl << endl;
        throw runtime_error("Error computing neighbor list");
        }

    if (m_prof)
        m_prof->push(exec_conf, "compute");

    // precompute scale factor
    Scalar3 width = m_cl->getWidth();
    Scalar3 scale = make_scalar3(Scalar(1.0) / width.x,
                                 Scalar(1.0) / width.y,
                                 Scalar(1.0) / width.z);

    // acquire the particle data and box dimension
    const ParticleDataArraysConst& arrays = m_pdata->acquireReadOnly();
    const BoxDim& box = m_pdata->getBox();

    // start by creating a temporary copy of r_cut sqaured
    Scalar rmaxsq = (m_r_cut + m_r_buff) * (m_r_cut + m_r_buff);

    // precalculate box lenghts
    Scalar Lx = box.xhi - box.xlo;
    Scalar Ly = box.yhi - box.ylo;
    Scalar Lz = box.zhi - box.zlo;

    // access the cell list data arrays
    ArrayHandle<unsigned int> h_cell_size(m_cl->getCellSizeArray(), access_location::host, access_mode::read);
    ArrayHandle<Scalar4> h_cell_xyzf(m_cl->getXYZFArray(), access_location::host, access_mode::read);
    ArrayHandle<unsigned int> h_cell_adj(m_cl->getCellAdjArray(), access_location::host, access_mode::read);

    ArrayHandle<unsigned int> h_nlist(m_nlist, access_location::host, access_mode::overwrite);
    ArrayHandle<unsigned int> h_n_neigh(m_n_neigh, access_location::host, access_mode::overwrite);
    ArrayHandle<unsigned int> h_conditions(m_conditions, access_location::host, access_mode::readwrite);

    // access indexers
    Index3D ci = m_cl->getCellIndexer();
    Index2D cli = m_cl->getCellListIndexer();
    Index2D cadji = m_cl->getCellAdjIndexer();

    // for each particle
#pragma omp parallel for schedule(dynamic, 100)
    for (unsigned int i = 0; i < arrays.nparticles; i++)
        {
        unsigned int cur_n_neigh = 0;

        Scalar3 my_pos = make_scalar3(arrays.x[i], arrays.y[i], arrays.z[i]);

        // find the bin each particle belongs in
        unsigned int ib = (unsigned int)((my_pos.x-box.xlo)*scale.x);
        unsigned int jb = (unsigned int)((my_pos.y-box.ylo)*scale.y);
        unsigned int kb = (unsigned int)((my_pos.z-box.zlo)*scale.z);

        // need to handle the case where the particle is exactly at the box hi
        if (ib == dim.x)
            ib = 0;
        if (jb == dim.y)
            jb = 0;
        if (kb == dim.z)
            kb = 0;

        // identify the bin
        unsigned int my_cell = ci(ib,jb,kb);

        // loop through all neighboring bins
        for (unsigned int cur_adj = 0; cur_adj < cadji.getW(); cur_adj++)
            {
            unsigned int neigh_cell = h_cell_adj.data[cadji(cur_adj, my_cell)];

            // check against all the particles in that neighboring bin to see if it is a neighbor
            unsigned int size = h_cell_size.data[neigh_cell];
            for (unsigned int cur_offset = 0; cur_offset < size; cur_offset++)
                {
                Scalar4 cur_xyzf = h_cell_xyzf.data[cli(cur_offset, neigh_cell)];

                Scalar3 neigh_pos = make_scalar3(cur_xyzf.x, cur_xyzf.y, cur_xyzf.z);
                unsigned int cur_neigh = __scalar_as_int(cur_xyzf.w);

                Scalar dx = my_pos.x - neigh_pos.x;
                if (dx >= Lx/2.0)
                    dx -= Lx;
                if (dx <= -Lx/2.0)
                    dx += Lx;

                Scalar dy = my_pos.y - neigh_pos.y;
                if (dy >= Ly/2.0)
                    dy -= Ly;
                if (dy <= -Ly/2.0)
                    dy += Ly;

                Scalar dz = my_pos.z - neigh_pos.z;
                if (dz >= Lz/2.0)
                    dz -= Lz;
                if (dz <= -Lz/2.0)
                    dz += Lz;

                float dr_sq = dx*dx + dy*dy + dz*dz;

                if (dr_sq <= rmaxsq && i != cur_neigh)
                    {
                    if (m_storage_mode == full || i < cur_neigh)
                        {
                        if (cur_n_neigh < m_nlist_indexer.getH())
                            h_nlist.data[m_nlist_indexer(i, cur_n_neigh)] = cur_neigh;
                        else
                            h_conditions.data[0] = max(h_conditions.data[0], cur_n_neigh+1);

                        cur_n_neigh++;
                        }
                    }
                }
            }

        h_n_neigh.data[i] = cur_n_neigh;
        }

    m_pdata->release();

    if (m_prof)
        m_prof->pop(exec_conf);
    }

void export_NeighborListBinned()
    {
    class_<NeighborListBinned, boost::shared_ptr<NeighborListBinned>, bases<NeighborList>, boost::noncopyable >
                     ("NeighborListBinned", init< boost::shared_ptr<SystemDefinition>, Scalar, Scalar, boost::shared_ptr<CellList> >())
                     ;
    }
<commit_msg>Solve OpenMP warnings about unsigned loop vars<commit_after>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2008, 2009 Ames Laboratory
Iowa State University and The Regents of the University of Michigan All rights
reserved.

HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.

Redistribution and use of HOOMD-blue, in source and binary forms, with or
without modification, are permitted, provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions, and the following disclaimer in the documentation and/or
other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of HOOMD-blue's
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.

Disclaimer

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR
ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED.

IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// $Id$
// $URL$
// Maintainer: joaander

#include "NeighborListBinned.h"

#include <boost/python.hpp>
using namespace boost::python;

NeighborListBinned::NeighborListBinned(boost::shared_ptr<SystemDefinition> sysdef,
                                       Scalar r_cut,
                                       Scalar r_buff,
                                       boost::shared_ptr<CellList> cl)
    : NeighborList(sysdef, r_cut, r_buff), m_cl(cl)
    {
    // create a default cell list if one was not specified
    if (!m_cl)
        m_cl = boost::shared_ptr<CellList>(new CellList(sysdef));

    m_cl->setNominalWidth((r_cut + r_buff)/2.0);
    m_cl->setRadius(2);
    m_cl->setComputeTDB(false);
    m_cl->setFlagIndex();
    }

NeighborListBinned::~NeighborListBinned()
    {
    }

void NeighborListBinned::setRCut(Scalar r_cut, Scalar r_buff)
    {
    NeighborList::setRCut(r_cut, r_buff);

    m_cl->setNominalWidth((r_cut + r_buff)/2.0);
    }

void NeighborListBinned::buildNlist(unsigned int timestep)
    {
    m_cl->compute(timestep);

    // check that at least 3x3x3 cells are computed
    uint3 dim = m_cl->getDim();
    if (dim.x < 3 || dim.y < 3 || dim.z < 3)
        {
        cerr << endl << "***Error! NeighborListGPUBinned doesn't work on boxes where r_cut+r_buff is greater than 1/3 any box dimension" << endl << endl;
        throw runtime_error("Error computing neighbor list");
        }

    if (m_prof)
        m_prof->push(exec_conf, "compute");

    // precompute scale factor
    Scalar3 width = m_cl->getWidth();
    Scalar3 scale = make_scalar3(Scalar(1.0) / width.x,
                                 Scalar(1.0) / width.y,
                                 Scalar(1.0) / width.z);

    // acquire the particle data and box dimension
    const ParticleDataArraysConst& arrays = m_pdata->acquireReadOnly();
    const BoxDim& box = m_pdata->getBox();

    // start by creating a temporary copy of r_cut sqaured
    Scalar rmaxsq = (m_r_cut + m_r_buff) * (m_r_cut + m_r_buff);

    // precalculate box lenghts
    Scalar Lx = box.xhi - box.xlo;
    Scalar Ly = box.yhi - box.ylo;
    Scalar Lz = box.zhi - box.zlo;

    // access the cell list data arrays
    ArrayHandle<unsigned int> h_cell_size(m_cl->getCellSizeArray(), access_location::host, access_mode::read);
    ArrayHandle<Scalar4> h_cell_xyzf(m_cl->getXYZFArray(), access_location::host, access_mode::read);
    ArrayHandle<unsigned int> h_cell_adj(m_cl->getCellAdjArray(), access_location::host, access_mode::read);

    ArrayHandle<unsigned int> h_nlist(m_nlist, access_location::host, access_mode::overwrite);
    ArrayHandle<unsigned int> h_n_neigh(m_n_neigh, access_location::host, access_mode::overwrite);
    ArrayHandle<unsigned int> h_conditions(m_conditions, access_location::host, access_mode::readwrite);

    // access indexers
    Index3D ci = m_cl->getCellIndexer();
    Index2D cli = m_cl->getCellListIndexer();
    Index2D cadji = m_cl->getCellAdjIndexer();

    // for each particle
#pragma omp parallel for schedule(dynamic, 100)
    for (int i = 0; i < (int)arrays.nparticles; i++)
        {
        unsigned int cur_n_neigh = 0;

        Scalar3 my_pos = make_scalar3(arrays.x[i], arrays.y[i], arrays.z[i]);

        // find the bin each particle belongs in
        unsigned int ib = (unsigned int)((my_pos.x-box.xlo)*scale.x);
        unsigned int jb = (unsigned int)((my_pos.y-box.ylo)*scale.y);
        unsigned int kb = (unsigned int)((my_pos.z-box.zlo)*scale.z);

        // need to handle the case where the particle is exactly at the box hi
        if (ib == dim.x)
            ib = 0;
        if (jb == dim.y)
            jb = 0;
        if (kb == dim.z)
            kb = 0;

        // identify the bin
        unsigned int my_cell = ci(ib,jb,kb);

        // loop through all neighboring bins
        for (unsigned int cur_adj = 0; cur_adj < cadji.getW(); cur_adj++)
            {
            unsigned int neigh_cell = h_cell_adj.data[cadji(cur_adj, my_cell)];

            // check against all the particles in that neighboring bin to see if it is a neighbor
            unsigned int size = h_cell_size.data[neigh_cell];
            for (unsigned int cur_offset = 0; cur_offset < size; cur_offset++)
                {
                Scalar4 cur_xyzf = h_cell_xyzf.data[cli(cur_offset, neigh_cell)];

                Scalar3 neigh_pos = make_scalar3(cur_xyzf.x, cur_xyzf.y, cur_xyzf.z);
                unsigned int cur_neigh = __scalar_as_int(cur_xyzf.w);

                Scalar dx = my_pos.x - neigh_pos.x;
                if (dx >= Lx/2.0)
                    dx -= Lx;
                if (dx <= -Lx/2.0)
                    dx += Lx;

                Scalar dy = my_pos.y - neigh_pos.y;
                if (dy >= Ly/2.0)
                    dy -= Ly;
                if (dy <= -Ly/2.0)
                    dy += Ly;

                Scalar dz = my_pos.z - neigh_pos.z;
                if (dz >= Lz/2.0)
                    dz -= Lz;
                if (dz <= -Lz/2.0)
                    dz += Lz;

                float dr_sq = dx*dx + dy*dy + dz*dz;

                if (dr_sq <= rmaxsq && i != (int)cur_neigh)
                    {
                    if (m_storage_mode == full || i < (int)cur_neigh)
                        {
                        if (cur_n_neigh < m_nlist_indexer.getH())
                            h_nlist.data[m_nlist_indexer(i, cur_n_neigh)] = cur_neigh;
                        else
                            h_conditions.data[0] = max(h_conditions.data[0], cur_n_neigh+1);

                        cur_n_neigh++;
                        }
                    }
                }
            }

        h_n_neigh.data[i] = cur_n_neigh;
        }

    m_pdata->release();

    if (m_prof)
        m_prof->pop(exec_conf);
    }

void export_NeighborListBinned()
    {
    class_<NeighborListBinned, boost::shared_ptr<NeighborListBinned>, bases<NeighborList>, boost::noncopyable >
                     ("NeighborListBinned", init< boost::shared_ptr<SystemDefinition>, Scalar, Scalar, boost::shared_ptr<CellList> >())
                     ;
    }
<|endoftext|>