<commit_before>// Copyright (c) 2006-2008 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 "chrome/browser/gtk/standard_menus.h"

#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>

#include "app/l10n_util.h"
#include "base/basictypes.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/encoding_menu_controller.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"

namespace {

struct MenuCreateMaterial zoom_menu_materials[] = {
  { MENU_NORMAL, IDC_ZOOM_PLUS, IDS_ZOOM_PLUS, 0, NULL,
    GDK_KP_Add, GDK_CONTROL_MASK },
  { MENU_NORMAL, IDC_ZOOM_NORMAL, IDS_ZOOM_NORMAL, 0, NULL,
    GDK_KP_0, GDK_CONTROL_MASK },
  { MENU_NORMAL, IDC_ZOOM_MINUS, IDS_ZOOM_MINUS, 0, NULL,
    GDK_KP_Subtract, GDK_CONTROL_MASK },
  { MENU_END }
};

struct MenuCreateMaterial developer_menu_materials[] = {
  { MENU_NORMAL, IDC_VIEW_SOURCE, IDS_VIEW_SOURCE, 0, NULL,
    GDK_u, GDK_CONTROL_MASK },
  { MENU_NORMAL, IDC_DEV_TOOLS, IDS_DEV_TOOLS, 0, NULL,
    GDK_j, GDK_CONTROL_MASK | GDK_SHIFT_MASK },
  { MENU_NORMAL, IDC_TASK_MANAGER, IDS_TASK_MANAGER, 0, NULL,
    GDK_Escape, GDK_SHIFT_MASK },
  { MENU_END }
};

struct MenuCreateMaterial standard_page_menu_materials[] = {
  // The Create App Shortcuts menu item hasn't been implemented yet.
  // Remove it until it is.
  // http://code.google.com/p/chromium/issues/detail?id=17251
  // { MENU_NORMAL, IDC_CREATE_SHORTCUTS, IDS_CREATE_SHORTCUTS },
  // { MENU_SEPARATOR },

  { MENU_NORMAL, IDC_CUT, IDS_CUT, 0, NULL, GDK_x, GDK_CONTROL_MASK, true },
  { MENU_NORMAL, IDC_COPY, IDS_COPY, 0, NULL, GDK_c, GDK_CONTROL_MASK, true },
  { MENU_NORMAL, IDC_PASTE, IDS_PASTE, 0, NULL, GDK_v, GDK_CONTROL_MASK, true },
  { MENU_SEPARATOR },
  { MENU_NORMAL, IDC_FIND, IDS_FIND, 0, NULL, GDK_f, GDK_CONTROL_MASK },
  { MENU_NORMAL, IDC_SAVE_PAGE, IDS_SAVE_PAGE, 0, NULL, GDK_s,
    GDK_CONTROL_MASK },
  // Printing hasn't been implemented yet.  Remove it from the menu until
  // someone implements it.
  // http://code.google.com/p/chromium/issues/detail?id=9847
  //{ MENU_NORMAL, IDC_PRINT, IDS_PRINT, 0, NULL, GDK_p, GDK_CONTROL_MASK },
  { MENU_SEPARATOR },
  { MENU_NORMAL, IDC_ZOOM_MENU, IDS_ZOOM_MENU, 0, zoom_menu_materials },
  // The encoding menu submenu is filled in by code below.
  { MENU_NORMAL, IDC_ENCODING_MENU, IDS_ENCODING_MENU },
  { MENU_SEPARATOR },
  { MENU_NORMAL, IDC_DEVELOPER_MENU, IDS_DEVELOPER_MENU, 0,
    developer_menu_materials },

  // The Report Bug menu hasn't been implemented yet.  Remove it until it is.
  // http://code.google.com/p/chromium/issues/detail?id=11600
  // { MENU_SEPARATOR },
  // { MENU_NORMAL, IDC_REPORT_BUG, IDS_REPORT_BUG },

  { MENU_END }
};

// -----------------------------------------------------------------------

struct MenuCreateMaterial standard_app_menu_materials[] = {
  { MENU_NORMAL, IDC_NEW_TAB, IDS_NEW_TAB, 0, NULL,
    GDK_t, GDK_CONTROL_MASK },
  { MENU_NORMAL, IDC_NEW_WINDOW, IDS_NEW_WINDOW, 0, NULL,
    GDK_n, GDK_CONTROL_MASK },
  { MENU_NORMAL, IDC_NEW_INCOGNITO_WINDOW, IDS_NEW_INCOGNITO_WINDOW, 0, NULL,
    GDK_n, GDK_CONTROL_MASK | GDK_SHIFT_MASK},
  { MENU_SEPARATOR },
  { MENU_CHECKBOX, IDC_SHOW_BOOKMARK_BAR, IDS_SHOW_BOOKMARK_BAR, 0, NULL,
    GDK_b, GDK_CONTROL_MASK },
  { MENU_SEPARATOR },
  { MENU_NORMAL, IDC_SHOW_HISTORY, IDS_SHOW_HISTORY, 0, NULL,
    GDK_h, GDK_CONTROL_MASK },
  { MENU_NORMAL, IDC_SHOW_BOOKMARK_MANAGER, IDS_BOOKMARK_MANAGER, 0, NULL,
    GDK_b, GDK_CONTROL_MASK | GDK_SHIFT_MASK },
  { MENU_NORMAL, IDC_SHOW_DOWNLOADS, IDS_SHOW_DOWNLOADS, 0, NULL,
    GDK_j, GDK_CONTROL_MASK },
  { MENU_SEPARATOR },
  // TODO(erg): P13N stuff goes here as soon as they get IDS strings.
  { MENU_NORMAL, IDC_CLEAR_BROWSING_DATA, IDS_CLEAR_BROWSING_DATA },
  { MENU_NORMAL, IDC_IMPORT_SETTINGS, IDS_IMPORT_SETTINGS },
  { MENU_SEPARATOR },
  { MENU_NORMAL, IDC_OPTIONS, IDS_OPTIONS, IDS_PRODUCT_NAME },
  { MENU_NORMAL, IDC_ABOUT, IDS_ABOUT, IDS_PRODUCT_NAME },
  { MENU_NORMAL, IDC_HELP_PAGE, IDS_HELP_PAGE, 0, NULL, GDK_F1 },
  { MENU_SEPARATOR },
  { MENU_NORMAL, IDC_EXIT, IDS_EXIT, 0, NULL, GDK_q, GDK_CONTROL_MASK },
  { MENU_END }
};

}  // namespace

const MenuCreateMaterial* GetStandardPageMenu(MenuGtk* encodings_menu) {
  // Find the encoding menu and attach this menu.
  for (MenuCreateMaterial* entry = standard_page_menu_materials;
       entry->type != MENU_END; ++entry) {
    if (entry->id == IDC_ENCODING_MENU) {
      entry->custom_submenu = encodings_menu;
      break;
    }
  }

  return standard_page_menu_materials;
}

const MenuCreateMaterial* GetStandardAppMenu() {
  return standard_app_menu_materials;
}
<commit_msg>GTK: Ctrl+shift+q for quit<commit_after>// Copyright (c) 2006-2008 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 "chrome/browser/gtk/standard_menus.h"

#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>

#include "app/l10n_util.h"
#include "base/basictypes.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/encoding_menu_controller.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"

namespace {

struct MenuCreateMaterial zoom_menu_materials[] = {
  { MENU_NORMAL, IDC_ZOOM_PLUS, IDS_ZOOM_PLUS, 0, NULL,
    GDK_KP_Add, GDK_CONTROL_MASK },
  { MENU_NORMAL, IDC_ZOOM_NORMAL, IDS_ZOOM_NORMAL, 0, NULL,
    GDK_KP_0, GDK_CONTROL_MASK },
  { MENU_NORMAL, IDC_ZOOM_MINUS, IDS_ZOOM_MINUS, 0, NULL,
    GDK_KP_Subtract, GDK_CONTROL_MASK },
  { MENU_END }
};

struct MenuCreateMaterial developer_menu_materials[] = {
  { MENU_NORMAL, IDC_VIEW_SOURCE, IDS_VIEW_SOURCE, 0, NULL,
    GDK_u, GDK_CONTROL_MASK },
  { MENU_NORMAL, IDC_DEV_TOOLS, IDS_DEV_TOOLS, 0, NULL,
    GDK_j, GDK_CONTROL_MASK | GDK_SHIFT_MASK },
  { MENU_NORMAL, IDC_TASK_MANAGER, IDS_TASK_MANAGER, 0, NULL,
    GDK_Escape, GDK_SHIFT_MASK },
  { MENU_END }
};

struct MenuCreateMaterial standard_page_menu_materials[] = {
  // The Create App Shortcuts menu item hasn't been implemented yet.
  // Remove it until it is.
  // http://code.google.com/p/chromium/issues/detail?id=17251
  // { MENU_NORMAL, IDC_CREATE_SHORTCUTS, IDS_CREATE_SHORTCUTS },
  // { MENU_SEPARATOR },

  { MENU_NORMAL, IDC_CUT, IDS_CUT, 0, NULL, GDK_x, GDK_CONTROL_MASK, true },
  { MENU_NORMAL, IDC_COPY, IDS_COPY, 0, NULL, GDK_c, GDK_CONTROL_MASK, true },
  { MENU_NORMAL, IDC_PASTE, IDS_PASTE, 0, NULL, GDK_v, GDK_CONTROL_MASK, true },
  { MENU_SEPARATOR },
  { MENU_NORMAL, IDC_FIND, IDS_FIND, 0, NULL, GDK_f, GDK_CONTROL_MASK },
  { MENU_NORMAL, IDC_SAVE_PAGE, IDS_SAVE_PAGE, 0, NULL, GDK_s,
    GDK_CONTROL_MASK },
  // Printing hasn't been implemented yet.  Remove it from the menu until
  // someone implements it.
  // http://code.google.com/p/chromium/issues/detail?id=9847
  //{ MENU_NORMAL, IDC_PRINT, IDS_PRINT, 0, NULL, GDK_p, GDK_CONTROL_MASK },
  { MENU_SEPARATOR },
  { MENU_NORMAL, IDC_ZOOM_MENU, IDS_ZOOM_MENU, 0, zoom_menu_materials },
  // The encoding menu submenu is filled in by code below.
  { MENU_NORMAL, IDC_ENCODING_MENU, IDS_ENCODING_MENU },
  { MENU_SEPARATOR },
  { MENU_NORMAL, IDC_DEVELOPER_MENU, IDS_DEVELOPER_MENU, 0,
    developer_menu_materials },

  // The Report Bug menu hasn't been implemented yet.  Remove it until it is.
  // http://code.google.com/p/chromium/issues/detail?id=11600
  // { MENU_SEPARATOR },
  // { MENU_NORMAL, IDC_REPORT_BUG, IDS_REPORT_BUG },

  { MENU_END }
};

// -----------------------------------------------------------------------

struct MenuCreateMaterial standard_app_menu_materials[] = {
  { MENU_NORMAL, IDC_NEW_TAB, IDS_NEW_TAB, 0, NULL,
    GDK_t, GDK_CONTROL_MASK },
  { MENU_NORMAL, IDC_NEW_WINDOW, IDS_NEW_WINDOW, 0, NULL,
    GDK_n, GDK_CONTROL_MASK },
  { MENU_NORMAL, IDC_NEW_INCOGNITO_WINDOW, IDS_NEW_INCOGNITO_WINDOW, 0, NULL,
    GDK_n, GDK_CONTROL_MASK | GDK_SHIFT_MASK},
  { MENU_SEPARATOR },
  { MENU_CHECKBOX, IDC_SHOW_BOOKMARK_BAR, IDS_SHOW_BOOKMARK_BAR, 0, NULL,
    GDK_b, GDK_CONTROL_MASK },
  { MENU_SEPARATOR },
  { MENU_NORMAL, IDC_SHOW_HISTORY, IDS_SHOW_HISTORY, 0, NULL,
    GDK_h, GDK_CONTROL_MASK },
  { MENU_NORMAL, IDC_SHOW_BOOKMARK_MANAGER, IDS_BOOKMARK_MANAGER, 0, NULL,
    GDK_b, GDK_CONTROL_MASK | GDK_SHIFT_MASK },
  { MENU_NORMAL, IDC_SHOW_DOWNLOADS, IDS_SHOW_DOWNLOADS, 0, NULL,
    GDK_j, GDK_CONTROL_MASK },
  { MENU_SEPARATOR },
  // TODO(erg): P13N stuff goes here as soon as they get IDS strings.
  { MENU_NORMAL, IDC_CLEAR_BROWSING_DATA, IDS_CLEAR_BROWSING_DATA },
  { MENU_NORMAL, IDC_IMPORT_SETTINGS, IDS_IMPORT_SETTINGS },
  { MENU_SEPARATOR },
  { MENU_NORMAL, IDC_OPTIONS, IDS_OPTIONS, IDS_PRODUCT_NAME },
  { MENU_NORMAL, IDC_ABOUT, IDS_ABOUT, IDS_PRODUCT_NAME },
  { MENU_NORMAL, IDC_HELP_PAGE, IDS_HELP_PAGE, 0, NULL, GDK_F1 },
  { MENU_SEPARATOR },
  { MENU_NORMAL, IDC_EXIT, IDS_EXIT, 0, NULL, GDK_q,
    GDK_CONTROL_MASK | GDK_SHIFT_MASK },
  { MENU_END }
};

}  // namespace

const MenuCreateMaterial* GetStandardPageMenu(MenuGtk* encodings_menu) {
  // Find the encoding menu and attach this menu.
  for (MenuCreateMaterial* entry = standard_page_menu_materials;
       entry->type != MENU_END; ++entry) {
    if (entry->id == IDC_ENCODING_MENU) {
      entry->custom_submenu = encodings_menu;
      break;
    }
  }

  return standard_page_menu_materials;
}

const MenuCreateMaterial* GetStandardAppMenu() {
  return standard_app_menu_materials;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 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 "chrome/common/platform_util.h"

#include <gtk/gtk.h>

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/process_util.h"
#include "base/string_util.h"

namespace platform_util {

// TODO(estade): It would be nice to be able to select the file in the file
// manager, but that probably requires extending xdg-open. For now just
// show the folder.
void ShowItemInFolder(const FilePath& full_path) {
  FilePath dir = full_path.DirName();
  if (!file_util::DirectoryExists(dir))
    return;

  std::vector<std::string> argv;
  argv.push_back("xdg-open");
  argv.push_back(dir.value());
  base::file_handle_mapping_vector no_files;
  base::LaunchApp(argv, no_files, false, NULL);
}

gfx::NativeWindow GetTopLevel(gfx::NativeView view) {
  return GTK_WINDOW(gtk_widget_get_toplevel(view));
}

string16 GetWindowTitle(gfx::NativeWindow window) {
  const gchar* title = gtk_window_get_title(window);
  return UTF8ToUTF16(title);
}

bool IsWindowActive(gfx::NativeWindow window) {
  return gtk_window_is_active(window);
}

bool IsVisible(gfx::NativeView view) {
  return GTK_WIDGET_VISIBLE(view);
}

}  // namespace platform_util
<commit_msg>Don't assume that the widget has a toplevel ancestor in GetTopLevel. Review URL: http://codereview.chromium.org/115802<commit_after>// Copyright (c) 2009 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 "chrome/common/platform_util.h"

#include <gtk/gtk.h>

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/process_util.h"
#include "base/string_util.h"

namespace platform_util {

// TODO(estade): It would be nice to be able to select the file in the file
// manager, but that probably requires extending xdg-open. For now just
// show the folder.
void ShowItemInFolder(const FilePath& full_path) {
  FilePath dir = full_path.DirName();
  if (!file_util::DirectoryExists(dir))
    return;

  std::vector<std::string> argv;
  argv.push_back("xdg-open");
  argv.push_back(dir.value());
  base::file_handle_mapping_vector no_files;
  base::LaunchApp(argv, no_files, false, NULL);
}

gfx::NativeWindow GetTopLevel(gfx::NativeView view) {
  // A detached widget won't have a toplevel window as an ancestor, so we can't
  // assume that the query for toplevel will return a window.
  GtkWidget* toplevel = gtk_widget_get_ancestor(view, GTK_TYPE_WINDOW);
  return GTK_IS_WINDOW(toplevel) ? GTK_WINDOW(toplevel) : NULL;
}

string16 GetWindowTitle(gfx::NativeWindow window) {
  const gchar* title = gtk_window_get_title(window);
  return UTF8ToUTF16(title);
}

bool IsWindowActive(gfx::NativeWindow window) {
  return gtk_window_is_active(window);
}

bool IsVisible(gfx::NativeView view) {
  return GTK_WIDGET_VISIBLE(view);
}

}  // namespace platform_util
<|endoftext|>


<commit_before>#include <pybind11/pybind11.h>
#include <sirius.h>
#include <pybind11/stl.h>
#include <pybind11/operators.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <utility>
#include <memory>
#include "utils/json.hpp"

using namespace pybind11::literals; // to bring in the `_a` literal
namespace py = pybind11;
using namespace sirius;
using namespace geometry3d;
using json = nlohmann::json;
using nlohmann::basic_json;

//inspired by: https://github.com/mdcb/python-jsoncpp11/blob/master/extension.cpp
py::object pj_convert(json& node)
{
    switch (node.type()) {
        case json::value_t::null: {
            return py::reinterpret_borrow<py::object>(Py_None);
        }
        case json::value_t::boolean: {
            bool b(node);
            return py::bool_(b);
        }
        case json::value_t::string: {
            std::string s;
            s = static_cast<std::string const&>(node);
            return py::str(s);
        }
        case json::value_t::number_integer: {
            int i(node);
            return py::int_(i);
        }
        case json::value_t::number_unsigned: {
            unsigned int u(node);
            return py::int_(u);
        }
        case json::value_t::number_float: {
            float f(node);
            return py::float_(f);
        }
        case json::value_t::object: {
            py::dict result;
            for (auto it = node.begin(); it != node.end(); ++it) {
                json my_key(it.key());
                result[pj_convert(my_key)] = pj_convert(*it);
            }
            return result;
        }
        case json::value_t::array: {
            py::list result;
            for (auto it = node.begin(); it != node.end(); ++it) {
                result.append(pj_convert(*it));
            }
            return result;
        }
        default: {
            throw std::runtime_error("undefined json value");
            /* make compiler happy */
            return py::reinterpret_borrow<py::object>(Py_None);
        }
    }
}

std::string show_mat(const matrix3d<double>& mat)
{
  std::string str = "[";
  for (int i=0; i<2; ++i)
  {str = str +"[" + std::to_string(mat(i,0)) + "," + std::to_string(mat(i,1)) + "," + std::to_string(mat(i,2)) + "]"+"\n";}
  str = str + "[" + std::to_string(mat(2,0)) + "," + std::to_string(mat(2,1)) + "," + std::to_string(mat(2,2)) + "]"+ "]";
  return str;
}

template<class T>
std::string show_vec(const vector3d<T>& vec)
{
  std::string str = "[" + std::to_string(vec[0]) + "," + std::to_string(vec[1]) + "," + std::to_string(vec[2]) + "]";
  return str;
}

PYBIND11_MODULE(py_sirius, m){

// MPI_Init/Finalize
sirius::initialize();
auto atexit = py::module::import("atexit");
atexit.attr("register")(py::cpp_function([](){ sirius::finalize(); }));

py::class_<Parameters_input>(m, "Parameters_input")
    .def(py::init<>())
    .def_readwrite("potential_tol_", &Parameters_input::potential_tol_)
    .def_readwrite("energy_tol_", &Parameters_input::energy_tol_)
    .def_readwrite("num_dft_iter_", &Parameters_input::num_dft_iter_);

py::class_<Simulation_parameters>(m, "Simulation_parameters")
    .def(py::init<>())
    .def("pw_cutoff", &Simulation_parameters::pw_cutoff)
    .def("parameters_input",               (Parameters_input& (Simulation_parameters::*)()) &Simulation_parameters::parameters_input,
                                           py::return_value_policy::reference)
    .def("num_spin_dims",                  &Simulation_parameters::num_spin_dims)
    .def("num_mag_dims",                   &Simulation_parameters::num_mag_dims)
    .def("set_gamma_point",                &Simulation_parameters::set_gamma_point)
    .def("set_pw_cutoff",                  &Simulation_parameters::set_pw_cutoff)
    .def("set_iterative_solver_tolerance", &Simulation_parameters::set_iterative_solver_tolerance);

py::class_<Simulation_context, Simulation_parameters>(m, "Simulation_context")
    .def(py::init<>())
    .def(py::init<std::string const&>())
    .def("initialize", &Simulation_context::initialize)
    .def("num_bands", py::overload_cast<>(&Simulation_context::num_bands, py::const_))
    .def("num_bands", py::overload_cast<int>(&Simulation_context::num_bands))
    .def("set_verbosity", &Simulation_context::set_verbosity)
    .def("create_storage_file", &Simulation_context::create_storage_file)
    .def("gvec", &Simulation_context::gvec)
    .def("fft", &Simulation_context::fft)
    .def("unit_cell", (Unit_cell& (Simulation_context::*)()) &Simulation_context::unit_cell, py::return_value_policy::reference);

py::class_<Unit_cell>(m, "Unit_cell")
    .def("add_atom_type",              static_cast<void (Unit_cell::*)(const std::string, const std::string)>(&Unit_cell::add_atom_type))
    .def("add_atom",                   static_cast<void (Unit_cell::*)(const std::string, std::vector<double>)>(&Unit_cell::add_atom))
    .def("atom_type",                  static_cast<Atom_type& (Unit_cell::*)(int)>(&Unit_cell::atom_type), py::return_value_policy::reference)
    .def("set_lattice_vectors",        static_cast<void (Unit_cell::*)(matrix3d<double>)>(&Unit_cell::set_lattice_vectors))
    .def("get_symmetry",               &Unit_cell::get_symmetry)
    .def("reciprocal_lattice_vectors", &Unit_cell::reciprocal_lattice_vectors)
    .def("generate_radial_functions",  &Unit_cell::generate_radial_functions);

py::class_<z_column_descriptor> (m, "z_column_descriptor")
    .def_readwrite("x", &z_column_descriptor::x)
    .def_readwrite("y", &z_column_descriptor::y)
    .def_readwrite("z", &z_column_descriptor::z)
    .def(py::init<int, int , std::vector<int>>());

py::class_<Gvec>(m, "Gvec")
    .def(py::init<matrix3d<double>, double, bool>())
    .def("num_gvec", &sddk::Gvec::num_gvec)
    .def("count",    &sddk::Gvec::count)
    .def("offset",   &sddk::Gvec::offset)
    .def("gvec",     &sddk::Gvec::gvec)
    .def("num_zcol", &sddk::Gvec::num_zcol)
    .def("gvec_alt", [](Gvec &obj, int idx)
                     {
                         vector3d<int> vec(obj.gvec(idx));
                         std::vector<int> retr = {vec[0], vec[1], vec[2]};
                         return retr;
                     })
    .def("index_by_gvec", [](Gvec &obj, std::vector<int> vec)
                          {
                              vector3d<int> vec3d(vec);
                              return obj.index_by_gvec(vec3d);
                          })
    .def("zcol", [](Gvec &gvec, int idx)
                 {
                     z_column_descriptor obj(gvec.zcol(idx));
                     py::dict dict("x"_a = obj.x, "y"_a = obj.y, "z"_a = obj.z);
                     return dict;
                 })
    .def("index_by_gvec", &Gvec::index_by_gvec);

py::class_<vector3d<int>>(m, "vector3d_int")
    .def(py::init<std::vector<int>>())
    .def("__call__", [](const vector3d<int> &obj, int x)
                     {
                         return obj[x];
                     })
    .def("__repr__", [](const vector3d<int> &vec)
                     {
                         return show_vec(vec);
                     })
    .def(py::init<vector3d<int>>());

py::class_<vector3d<double>>(m, "vector3d_double")
    .def(py::init<std::vector<double>>())
    .def("__call__", [](const vector3d<double> &obj, int x)
                     {
                         return obj[x];
                     })
    .def("__repr__", [](const vector3d<double> &vec)
                     {
                         return show_vec(vec);
                     })
    .def("length", &vector3d<double>::length)
    .def(py::self - py::self)
    .def(py::self * float())
    .def(py::self + py::self)
    .def(py::init<vector3d<double>>());

py::class_<matrix3d<double>>(m, "matrix3d")
    .def(py::init<std::vector<std::vector<double>>>())
    .def(py::init<>())
    .def("__call__", [](const matrix3d<double> &obj, int x, int y)
                     {
                         return obj(x,y);
                     })
    .def(py::self * py::self)
    .def("__getitem__", [](const matrix3d<double> &obj, int x, int y)
                        {
                            return obj(x,y);
                        })
    .def("__mul__", [](const matrix3d<double> & obj, vector3d<double> const& b)
                    {
                        vector3d<double> res = obj * b;
                        return res;
                    })
    .def("__repr__", [](const matrix3d<double> &mat)
                     {
                         return show_mat(mat);
                     })
    .def(py::init<matrix3d<double>>())
    .def("det", &matrix3d<double>::det);

py::class_<Potential>(m, "Potential")
    .def(py::init<Simulation_context&>())
    .def("generate", &Potential::generate)
    .def("allocate", &Potential::allocate)
    .def("save", &Potential::save)
    .def("load", &Potential::load);

py::class_<Density>(m, "Density")
    .def(py::init<Simulation_context&>())
    .def("initial_density", &Density::initial_density)
    .def("allocate", &Density::allocate)
    .def("save", &Density::save)
    .def("load", &Density::load);

py::class_<Band>(m, "Band")
    .def(py::init<Simulation_context&>())
    .def("initialize_subspace", py::overload_cast<K_point_set&, Hamiltonian&>(&Band::initialize_subspace, py::const_))
    .def("solve", &Band::solve);

py::class_<DFT_ground_state>(m, "DFT_ground_state")
    .def(py::init<K_point_set&>())
    .def("print_info", &DFT_ground_state::print_info)
    .def("initial_state", &DFT_ground_state::initial_state)
    .def("print_magnetic_moment", &DFT_ground_state::print_magnetic_moment)
    .def("total_energy", &DFT_ground_state::total_energy)
    .def("density", &DFT_ground_state::density, py::return_value_policy::reference)
    .def("find", [](DFT_ground_state& dft, double potential_tol, double energy_tol, int num_dft_iter, bool write_state)
                 {
                     json js = dft.find(potential_tol, energy_tol, num_dft_iter, write_state);
                     return pj_convert(js);
                 })
    .def("k_point_set", &DFT_ground_state::k_point_set, py::return_value_policy::reference_internal)
    .def("hamiltonian", &DFT_ground_state::hamiltonian, py::return_value_policy::reference)
    .def("potential",   &DFT_ground_state::potential, py::return_value_policy::reference);

py::class_<K_point>(m, "K_point")
    .def("band_energy", py::overload_cast<int, int>(&K_point::band_energy))
    .def("vk", &K_point::vk, py::return_value_policy::reference);

py::class_<K_point_set>(m, "K_point_set")
    .def(py::init<Simulation_context&>())
    .def(py::init<Simulation_context&, std::vector<vector3d<double>>>())
    .def(py::init<Simulation_context&, vector3d<int>, vector3d<int>, bool>())
    .def(py::init<Simulation_context&, std::vector<int>, std::vector<int>, bool>())
    .def("initialize", py::overload_cast<>(&K_point_set::initialize))
    .def("num_kpoints", &K_point_set::num_kpoints)
    .def("energy_fermi", &K_point_set::energy_fermi)
    .def("get_band_energies", &K_point_set::get_band_energies, py::return_value_policy::reference)
    .def("sync_band_energies", &K_point_set::sync_band_energies)
    .def("__call__", &K_point_set::operator[], py::return_value_policy::reference)
    .def("add_kpoint", [](K_point_set &ks, std::vector<double> &v, double weight)
                       {
                           vector3d<double> vec3d(v);
                           ks.add_kpoint(&vec3d[0], weight);
                       })
    .def("add_kpoint", [](K_point_set &ks, vector3d<double> &v, double weight)
                       {
                           ks.add_kpoint(&v[0], weight);
                       });

py::class_<Hamiltonian>(m, "Hamiltonian")
    .def(py::init<Simulation_context&, Potential&>());

py::class_<Stress>(m, "Stress")
    .def(py::init<Simulation_context&, Density&, Potential&, Hamiltonian&, K_point_set&>())
    .def("calc_stress_total", &Stress::calc_stress_total, py::return_value_policy::reference_internal)
    .def("print_info", &Stress::print_info);

py::class_<Force>(m, "Force")
    .def(py::init<Simulation_context&, Density&, Potential&, Hamiltonian&, K_point_set&>())
    .def("calc_forces_total", &Force::calc_forces_total, py::return_value_policy::reference_internal)
    .def("print_info", &Force::print_info);

py::class_<Free_atom>(m, "Free_atom")
    .def(py::init<Simulation_parameters&, std::string>())
    .def(py::init<Simulation_parameters&, int>())
    .def("ground_state", [](Free_atom& atom, double energy_tol, double charge_tol, bool rel)
                         {
                             json js = atom.ground_state(energy_tol, charge_tol, rel);
                             return pj_convert(js);
                         });

}
<commit_msg>add to python module<commit_after>#include <pybind11/pybind11.h>
#include <sirius.h>
#include <pybind11/stl.h>
#include <pybind11/operators.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <utility>
#include <memory>
#include "utils/json.hpp"

using namespace pybind11::literals; // to bring in the `_a` literal
namespace py = pybind11;
using namespace sirius;
using namespace geometry3d;
using json = nlohmann::json;
using nlohmann::basic_json;

//inspired by: https://github.com/mdcb/python-jsoncpp11/blob/master/extension.cpp
py::object pj_convert(json& node)
{
    switch (node.type()) {
        case json::value_t::null: {
            return py::reinterpret_borrow<py::object>(Py_None);
        }
        case json::value_t::boolean: {
            bool b(node);
            return py::bool_(b);
        }
        case json::value_t::string: {
            std::string s;
            s = static_cast<std::string const&>(node);
            return py::str(s);
        }
        case json::value_t::number_integer: {
            int i(node);
            return py::int_(i);
        }
        case json::value_t::number_unsigned: {
            unsigned int u(node);
            return py::int_(u);
        }
        case json::value_t::number_float: {
            float f(node);
            return py::float_(f);
        }
        case json::value_t::object: {
            py::dict result;
            for (auto it = node.begin(); it != node.end(); ++it) {
                json my_key(it.key());
                result[pj_convert(my_key)] = pj_convert(*it);
            }
            return result;
        }
        case json::value_t::array: {
            py::list result;
            for (auto it = node.begin(); it != node.end(); ++it) {
                result.append(pj_convert(*it));
            }
            return result;
        }
        default: {
            throw std::runtime_error("undefined json value");
            /* make compiler happy */
            return py::reinterpret_borrow<py::object>(Py_None);
        }
    }
}

std::string show_mat(const matrix3d<double>& mat)
{
  std::string str = "[";
  for (int i=0; i<2; ++i)
  {str = str +"[" + std::to_string(mat(i,0)) + "," + std::to_string(mat(i,1)) + "," + std::to_string(mat(i,2)) + "]"+"\n";}
  str = str + "[" + std::to_string(mat(2,0)) + "," + std::to_string(mat(2,1)) + "," + std::to_string(mat(2,2)) + "]"+ "]";
  return str;
}

template<class T>
std::string show_vec(const vector3d<T>& vec)
{
  std::string str = "[" + std::to_string(vec[0]) + "," + std::to_string(vec[1]) + "," + std::to_string(vec[2]) + "]";
  return str;
}

PYBIND11_MODULE(py_sirius, m){

// MPI_Init/Finalize
sirius::initialize();
auto atexit = py::module::import("atexit");
atexit.attr("register")(py::cpp_function([](){ sirius::finalize(); }));

py::class_<Parameters_input>(m, "Parameters_input")
    .def(py::init<>())
    .def_readwrite("potential_tol_", &Parameters_input::potential_tol_)
    .def_readwrite("energy_tol_", &Parameters_input::energy_tol_)
    .def_readwrite("num_dft_iter_", &Parameters_input::num_dft_iter_);

py::class_<Simulation_parameters>(m, "Simulation_parameters")
    .def(py::init<>())
    .def("pw_cutoff", &Simulation_parameters::pw_cutoff)
    .def("parameters_input",               (Parameters_input& (Simulation_parameters::*)()) &Simulation_parameters::parameters_input,
                                           py::return_value_policy::reference)
    .def("num_spin_dims",                  &Simulation_parameters::num_spin_dims)
    .def("num_mag_dims",                   &Simulation_parameters::num_mag_dims)
    .def("set_gamma_point",                &Simulation_parameters::set_gamma_point)
    .def("set_pw_cutoff",                  &Simulation_parameters::set_pw_cutoff)
    .def("set_iterative_solver_tolerance", &Simulation_parameters::set_iterative_solver_tolerance);

py::class_<Simulation_context, Simulation_parameters>(m, "Simulation_context")
    .def(py::init<>())
    .def(py::init<std::string const&>())
    .def("initialize", &Simulation_context::initialize)
    .def("num_bands", py::overload_cast<>(&Simulation_context::num_bands, py::const_))
    .def("num_bands", py::overload_cast<int>(&Simulation_context::num_bands))
    .def("set_verbosity", &Simulation_context::set_verbosity)
    .def("create_storage_file", &Simulation_context::create_storage_file)
    .def("gvec", &Simulation_context::gvec)
    .def("fft", &Simulation_context::fft)
    .def("unit_cell", (Unit_cell& (Simulation_context::*)()) &Simulation_context::unit_cell, py::return_value_policy::reference);

py::class_<Unit_cell>(m, "Unit_cell")
    .def("add_atom_type",              static_cast<void (Unit_cell::*)(const std::string, const std::string)>(&Unit_cell::add_atom_type))
    .def("add_atom",                   static_cast<void (Unit_cell::*)(const std::string, std::vector<double>)>(&Unit_cell::add_atom))
    .def("atom_type",                  static_cast<Atom_type& (Unit_cell::*)(int)>(&Unit_cell::atom_type), py::return_value_policy::reference)
    .def("set_lattice_vectors",        static_cast<void (Unit_cell::*)(matrix3d<double>)>(&Unit_cell::set_lattice_vectors))
    .def("get_symmetry",               &Unit_cell::get_symmetry)
    .def("reciprocal_lattice_vectors", &Unit_cell::reciprocal_lattice_vectors)
    .def("generate_radial_functions",  &Unit_cell::generate_radial_functions);

py::class_<z_column_descriptor> (m, "z_column_descriptor")
    .def_readwrite("x", &z_column_descriptor::x)
    .def_readwrite("y", &z_column_descriptor::y)
    .def_readwrite("z", &z_column_descriptor::z)
    .def(py::init<int, int , std::vector<int>>());

py::class_<Gvec>(m, "Gvec")
    .def(py::init<matrix3d<double>, double, bool>())
    .def("num_gvec", &sddk::Gvec::num_gvec)
    .def("count",    &sddk::Gvec::count)
    .def("offset",   &sddk::Gvec::offset)
    .def("gvec",     &sddk::Gvec::gvec)
    .def("num_zcol", &sddk::Gvec::num_zcol)
    .def("gvec_alt", [](Gvec &obj, int idx)
                     {
                         vector3d<int> vec(obj.gvec(idx));
                         std::vector<int> retr = {vec[0], vec[1], vec[2]};
                         return retr;
                     })
    .def("index_by_gvec", [](Gvec &obj, std::vector<int> vec)
                          {
                              vector3d<int> vec3d(vec);
                              return obj.index_by_gvec(vec3d);
                          })
    .def("zcol", [](Gvec &gvec, int idx)
                 {
                     z_column_descriptor obj(gvec.zcol(idx));
                     py::dict dict("x"_a = obj.x, "y"_a = obj.y, "z"_a = obj.z);
                     return dict;
                 })
    .def("index_by_gvec", &Gvec::index_by_gvec);

py::class_<vector3d<int>>(m, "vector3d_int")
    .def(py::init<std::vector<int>>())
    .def("__call__", [](const vector3d<int> &obj, int x)
                     {
                         return obj[x];
                     })
    .def("__repr__", [](const vector3d<int> &vec)
                     {
                         return show_vec(vec);
                     })
    .def(py::init<vector3d<int>>());

py::class_<vector3d<double>>(m, "vector3d_double")
    .def(py::init<std::vector<double>>())
    .def("__call__", [](const vector3d<double> &obj, int x)
                     {
                         return obj[x];
                     })
    .def("__repr__", [](const vector3d<double> &vec)
                     {
                         return show_vec(vec);
                     })
    .def("length", &vector3d<double>::length)
    .def(py::self - py::self)
    .def(py::self * float())
    .def(py::self + py::self)
    .def(py::init<vector3d<double>>());

py::class_<matrix3d<double>>(m, "matrix3d")
    .def(py::init<std::vector<std::vector<double>>>())
    .def(py::init<>())
    .def("__call__", [](const matrix3d<double> &obj, int x, int y)
                     {
                         return obj(x,y);
                     })
    .def(py::self * py::self)
    .def("__getitem__", [](const matrix3d<double> &obj, int x, int y)
                        {
                            return obj(x,y);
                        })
    .def("__mul__", [](const matrix3d<double> & obj, vector3d<double> const& b)
                    {
                        vector3d<double> res = obj * b;
                        return res;
                    })
    .def("__repr__", [](const matrix3d<double> &mat)
                     {
                         return show_mat(mat);
                     })
    .def(py::init<matrix3d<double>>())
    .def("det", &matrix3d<double>::det);

py::class_<Potential>(m, "Potential")
    .def(py::init<Simulation_context&>())
    .def("generate", &Potential::generate)
    .def("allocate", &Potential::allocate)
    .def("save", &Potential::save)
    .def("load", &Potential::load);

py::class_<Density>(m, "Density")
    .def(py::init<Simulation_context&>())
    .def("initial_density", &Density::initial_density)
    .def("allocate", &Density::allocate)
    .def("save", &Density::save)
    .def("load", &Density::load);

py::class_<Band>(m, "Band")
    .def(py::init<Simulation_context&>())
    .def("initialize_subspace", py::overload_cast<K_point_set&, Hamiltonian&>(&Band::initialize_subspace, py::const_))
    .def("solve", &Band::solve);

py::class_<DFT_ground_state>(m, "DFT_ground_state")
    .def(py::init<K_point_set&>())
    .def("print_info", &DFT_ground_state::print_info)
    .def("initial_state", &DFT_ground_state::initial_state)
    .def("print_magnetic_moment", &DFT_ground_state::print_magnetic_moment)
    .def("total_energy", &DFT_ground_state::total_energy)
    .def("density", &DFT_ground_state::density, py::return_value_policy::reference)
    .def("find", [](DFT_ground_state& dft, double potential_tol, double energy_tol, int num_dft_iter, bool write_state)
                 {
                     json js = dft.find(potential_tol, energy_tol, num_dft_iter, write_state);
                     return pj_convert(js);
                 })
    .def("k_point_set", &DFT_ground_state::k_point_set, py::return_value_policy::reference_internal)
    .def("hamiltonian", &DFT_ground_state::hamiltonian, py::return_value_policy::reference)
    .def("potential",   &DFT_ground_state::potential, py::return_value_policy::reference);

py::class_<K_point>(m, "K_point")
    .def("band_energy", py::overload_cast<int, int>(&K_point::band_energy))
    .def("vk", &K_point::vk, py::return_value_policy::reference);

py::class_<K_point_set>(m, "K_point_set")
    .def(py::init<Simulation_context&>())
    .def(py::init<Simulation_context&, std::vector<vector3d<double>>>())
    .def(py::init<Simulation_context&, vector3d<int>, vector3d<int>, bool>())
    .def(py::init<Simulation_context&, std::vector<int>, std::vector<int>, bool>())
    .def("initialize", py::overload_cast<>(&K_point_set::initialize))
    .def("num_kpoints", &K_point_set::num_kpoints)
    .def("energy_fermi", &K_point_set::energy_fermi)
    .def("get_band_energies", &K_point_set::get_band_energies, py::return_value_policy::reference)
    .def("sync_band_energies", &K_point_set::sync_band_energies)
    .def("__call__", &K_point_set::operator[], py::return_value_policy::reference)
    .def("add_kpoint", [](K_point_set &ks, std::vector<double> &v, double weight)
                       {
                           vector3d<double> vec3d(v);
                           ks.add_kpoint(&vec3d[0], weight);
                       })
    .def("add_kpoint", [](K_point_set &ks, vector3d<double> &v, double weight)
                       {
                           ks.add_kpoint(&v[0], weight);
                       });

py::class_<Hamiltonian>(m, "Hamiltonian")
    .def(py::init<Simulation_context&, Potential&>());

py::class_<Stress>(m, "Stress")
    .def(py::init<Simulation_context&, Density&, Potential&, Hamiltonian&, K_point_set&>())
    .def("calc_stress_total", &Stress::calc_stress_total, py::return_value_policy::reference_internal)
    .def("print_info", &Stress::print_info);

py::class_<Force>(m, "Force")
    .def(py::init<Simulation_context&, Density&, Potential&, Hamiltonian&, K_point_set&>())
    .def("calc_forces_total", &Force::calc_forces_total, py::return_value_policy::reference_internal)
    .def("print_info", &Force::print_info);

py::class_<Free_atom>(m, "Free_atom")
    .def(py::init<std::string>())
    .def(py::init<int>())
    .def("ground_state", [](Free_atom& atom, double energy_tol, double charge_tol, bool rel)
                         {
                             json js = atom.ground_state(energy_tol, charge_tol, rel);
                             return pj_convert(js);
                         })
    .def("radial_grid_points", &Free_atom::radial_grid_points)
    .def("num_atomic_levels", &Free_atom::num_atomic_levels)
    .def("atomic_level", [](Free_atom& atom, int idx)
                         {
                            auto level = atom.atomic_level(idx);
                            json js;
                            js["n"]         = level.n;
                            js["l"]         = level.l;
                            js["k"]         = level.k;
                            js["occupancy"] = level.occupancy;
                            js["energy"]    = atom.atomic_level_energy(idx);
                            return pj_convert(js);
                         })
    .def("free_atom_electronic_potential", [](Free_atom& atom)
                                           {
                                               return atom.free_atom_electronic_potential();
                                           })
    .def("free_atom_wave_function", [](Free_atom& atom, int idx)
                                    {
                                        return atom.free_atom_wave_function(idx);
                                    });

}
<|endoftext|>


<commit_before>/*
 * $Id$
 *
 * Copyright(C) 1998-2003 Satoshi Nakamura
 * All rights reserved.
 *
 */

#include <qsencoder.h>
#include <qsstl.h>
#include <qstextutil.h>

using namespace qs;

/****************************************************************************
 *
 * TextUtil
 *
 */

QSTATUS qs::TextUtil::fold(const WCHAR* pwszText, size_t nLen,
	size_t nLineWidth, const WCHAR* pwszQuote, size_t nQuoteLen,
	size_t nTabWidth, WSTRING* pwstrText)
{
	assert(pwszText);
	assert(pwstrText);

	DECLARE_QSTATUS();

	*pwstrText = 0;

	if (nLen == -1)
		nLen = wcslen(pwszText);

	size_t nQuoteWidth = 0;
	for (size_t n = 0; n < nQuoteLen; ++n)
		nQuoteWidth += isHalfWidth(*(pwszQuote + n)) ? 1 : 2;

	if (nLineWidth > nQuoteWidth) {
		nLineWidth -= nQuoteWidth;
		if (nLineWidth < 10)
			nLineWidth = 10;
	}
	else {
		nLineWidth = 10;
	}

	StringBuffer<WSTRING> buf(&status);
	CHECK_QSTATUS();

	size_t nCurrentLen = 0;
	const WCHAR* pLine = pwszText;
	const WCHAR* pBreak = 0;
	for (const WCHAR* p = pwszText; p < pwszText + nLen; ++p) {
		WCHAR c = *p;
		size_t nCharLen = 1;
		if (c == L'\t')
			nCharLen = nTabWidth - nCurrentLen%nTabWidth;
		else if (!isHalfWidth(c))
			nCharLen = 2;

		if (isBreakSelf(c))
			pBreak = p;

		bool bFlushed = true;
		if (c == L'\n') {
			status = buf.append(pwszQuote, nQuoteLen);
			CHECK_QSTATUS();
			status = buf.append(pLine, p - pLine + 1);
			CHECK_QSTATUS();
			nCurrentLen = 0;
			pLine = p + 1;
			pBreak = 0;
		}
		else if (nCurrentLen + nCharLen > nLineWidth) {
			if (!pBreak) {
				if (pwszQuote) {
					status = buf.append(pwszQuote, nQuoteLen);
					CHECK_QSTATUS();
				}
				status = buf.append(pLine, p - pLine);
				CHECK_QSTATUS();
				status = buf.append(L'\n');
				CHECK_QSTATUS();
				nCurrentLen = nCharLen;
				pLine = p;
			}
			else {
				WCHAR cBreak = *pBreak;
				const WCHAR* pEnd = pBreak;
				const WCHAR* pNext = pBreak;
				if (isBreakSelf(cBreak)) {
					++pNext;
				}
				else if (isBreakBefore(cBreak)) {
					;
				}
				else if (isBreakAfter(cBreak)) {
					++pEnd;
					++pNext;
				}
				else {
					assert(false);
				}
				if (pwszQuote) {
					status = buf.append(pwszQuote, nQuoteLen);
					CHECK_QSTATUS();
				}
				status = buf.append(pLine, pEnd - pLine);
				CHECK_QSTATUS();
				status = buf.append(L'\n');
				CHECK_QSTATUS();
				pLine = pNext;
				nCurrentLen = 0;
				pBreak = 0;
				p = pNext - 1;
			}
		}
		else {
			nCurrentLen += nCharLen;
			bFlushed = false;
		}

		if (!bFlushed && isBreakChar(c) && p != pLine)
			pBreak = p;
	}
	if (p != pLine) {
		if (pwszQuote) {
			status = buf.append(pwszQuote, nQuoteLen);
			CHECK_QSTATUS();
		}
		status = buf.append(pLine, p - pLine);
		CHECK_QSTATUS();
	}

	*pwstrText = buf.getString();

	return QSTATUS_SUCCESS;
}

std::pair<size_t, size_t> qs::TextUtil::findURL(const WCHAR* pwszText,
	size_t nLen, const WCHAR* const* ppwszSchemas, size_t nSchemaCount)
{
	assert(pwszText);

	std::pair<size_t, size_t> url(-1, 0);
	if (nSchemaCount != 0) {
		const WCHAR* p = pwszText;
		while (nLen > 0) {
			if (p == pwszText || !isURLChar(*(p - 1))) {
				bool bFound = false;
				for (size_t n = 0; n < nSchemaCount; ++n) {
					if (ppwszSchemas[n][0] == *p) {
						size_t nSchemaLen = wcslen(ppwszSchemas[n]);
						if (nLen > nSchemaLen &&
							wcsncmp(p, ppwszSchemas[n], nSchemaLen) == 0 &&
							*(p + nSchemaLen) == L':') {
							bFound = true;
							break;
						}
					}
				}
				if (bFound)
					break;
			}
			else if (*p == L'@' &&
				p != pwszText && isURLChar(*(p - 1)) &&
				nLen > 1 && isURLChar(*(p + 1))) {
				while (p >= pwszText && isURLChar(*p)) {
					--p;
					++nLen;
				}
				++p;
				--nLen;
				break;
			}
			--nLen;
			++p;
		}
		if (nLen > 0) {
			url.first = p - pwszText;
			while (nLen > 0 && isURLChar(*p)) {
				--nLen;
				++p;
			}
			url.second = p - (pwszText + url.first);
		}
	}

	return url;
}

bool qs::TextUtil::isURLChar(WCHAR c)
{
	return (L'A' <= c && c <= L'Z') ||
		(L'a' <= c && c <= L'z') ||
		(L'0' <= c && c <= L'9') ||
		c == L'.' ||
		c == L':' ||
		c == L'/' ||
		c == L'?' ||
		c == L'%' ||
		c == L'&' ||
		c == L'@' ||
		c == L'!' ||
		c == L'#' ||
		c == L'$' ||
		c == L'~' ||
		c == L'*' ||
		c == L'=' ||
		c == L'+' ||
		c == L'-' ||
		c == L'_' ||
		c == L';' ||
		c == L',' ||
		c == L'(' ||
		c == L')';
}

QSTATUS qs::TextUtil::encodePassword(const WCHAR* pwsz, WSTRING* pwstr)
{
	assert(pwsz);
	assert(pwstr);

	DECLARE_QSTATUS();

	Base64Encoder encoder(false, &status);
	CHECK_QSTATUS();
	unsigned char* p = 0;
	size_t nLen = 0;
	status = encoder.encode(reinterpret_cast<const unsigned char*>(pwsz),
		wcslen(pwsz)*sizeof(WCHAR), &p, &nLen);
	CHECK_QSTATUS();
	malloc_ptr<unsigned char> pBuffer(p);

	string_ptr<WSTRING> wstr(allocWString(nLen*2 + 1));
	if (!wstr.get())
		return QSTATUS_OUTOFMEMORY;

	WCHAR* pDst = wstr.get();
	for (size_t n = 0; n < nLen; ++n) {
		swprintf(pDst, L"%02x", *(p + n) ^ 'q');
		pDst += 2;
	}
	*pDst = L'\0';

	*pwstr = wstr.release();

	return QSTATUS_SUCCESS;
}

QSTATUS qs::TextUtil::decodePassword(const WCHAR* pwsz, WSTRING* pwstr)
{
	assert(pwsz);
	assert(pwstr);

	DECLARE_QSTATUS();

	size_t nLen = wcslen(pwsz);

	malloc_ptr<unsigned char> pBuf(
		static_cast<unsigned char*>(malloc(nLen/2 + 1)));
	if (!pBuf.get())
		return QSTATUS_OUTOFMEMORY;
	unsigned char* p = pBuf.get();

	for (size_t n = 0; n < nLen; n += 2) {
		WCHAR wsz[3] = L"";
		wcsncpy(wsz, pwsz + n, 2);
		unsigned int m = 0;
		swscanf(wsz, L"%02x", &m);
		*p++ = m ^= 'q';
	}

	Base64Encoder encoder(false, &status);
	CHECK_QSTATUS();
	unsigned char* pDecode = 0;
	size_t nDecodeLen = 0;
	status = encoder.decode(pBuf.get(), p - pBuf.get(), &pDecode, &nDecodeLen);
	CHECK_QSTATUS();

	string_ptr<WSTRING> wstr(allocWString(
		reinterpret_cast<WCHAR*>(pDecode), nDecodeLen/sizeof(WCHAR)));
	if (!wstr.get())
		return QSTATUS_OUTOFMEMORY;

	*pwstr = wstr.release();

	return QSTATUS_SUCCESS;
}
<commit_msg>Fix memory leaks in TextUtil::decodePassword.<commit_after>/*
 * $Id$
 *
 * Copyright(C) 1998-2003 Satoshi Nakamura
 * All rights reserved.
 *
 */

#include <qsencoder.h>
#include <qsstl.h>
#include <qstextutil.h>

using namespace qs;

/****************************************************************************
 *
 * TextUtil
 *
 */

QSTATUS qs::TextUtil::fold(const WCHAR* pwszText, size_t nLen,
	size_t nLineWidth, const WCHAR* pwszQuote, size_t nQuoteLen,
	size_t nTabWidth, WSTRING* pwstrText)
{
	assert(pwszText);
	assert(pwstrText);

	DECLARE_QSTATUS();

	*pwstrText = 0;

	if (nLen == -1)
		nLen = wcslen(pwszText);

	size_t nQuoteWidth = 0;
	for (size_t n = 0; n < nQuoteLen; ++n)
		nQuoteWidth += isHalfWidth(*(pwszQuote + n)) ? 1 : 2;

	if (nLineWidth > nQuoteWidth) {
		nLineWidth -= nQuoteWidth;
		if (nLineWidth < 10)
			nLineWidth = 10;
	}
	else {
		nLineWidth = 10;
	}

	StringBuffer<WSTRING> buf(&status);
	CHECK_QSTATUS();

	size_t nCurrentLen = 0;
	const WCHAR* pLine = pwszText;
	const WCHAR* pBreak = 0;
	for (const WCHAR* p = pwszText; p < pwszText + nLen; ++p) {
		WCHAR c = *p;
		size_t nCharLen = 1;
		if (c == L'\t')
			nCharLen = nTabWidth - nCurrentLen%nTabWidth;
		else if (!isHalfWidth(c))
			nCharLen = 2;

		if (isBreakSelf(c))
			pBreak = p;

		bool bFlushed = true;
		if (c == L'\n') {
			status = buf.append(pwszQuote, nQuoteLen);
			CHECK_QSTATUS();
			status = buf.append(pLine, p - pLine + 1);
			CHECK_QSTATUS();
			nCurrentLen = 0;
			pLine = p + 1;
			pBreak = 0;
		}
		else if (nCurrentLen + nCharLen > nLineWidth) {
			if (!pBreak) {
				if (pwszQuote) {
					status = buf.append(pwszQuote, nQuoteLen);
					CHECK_QSTATUS();
				}
				status = buf.append(pLine, p - pLine);
				CHECK_QSTATUS();
				status = buf.append(L'\n');
				CHECK_QSTATUS();
				nCurrentLen = nCharLen;
				pLine = p;
			}
			else {
				WCHAR cBreak = *pBreak;
				const WCHAR* pEnd = pBreak;
				const WCHAR* pNext = pBreak;
				if (isBreakSelf(cBreak)) {
					++pNext;
				}
				else if (isBreakBefore(cBreak)) {
					;
				}
				else if (isBreakAfter(cBreak)) {
					++pEnd;
					++pNext;
				}
				else {
					assert(false);
				}
				if (pwszQuote) {
					status = buf.append(pwszQuote, nQuoteLen);
					CHECK_QSTATUS();
				}
				status = buf.append(pLine, pEnd - pLine);
				CHECK_QSTATUS();
				status = buf.append(L'\n');
				CHECK_QSTATUS();
				pLine = pNext;
				nCurrentLen = 0;
				pBreak = 0;
				p = pNext - 1;
			}
		}
		else {
			nCurrentLen += nCharLen;
			bFlushed = false;
		}

		if (!bFlushed && isBreakChar(c) && p != pLine)
			pBreak = p;
	}
	if (p != pLine) {
		if (pwszQuote) {
			status = buf.append(pwszQuote, nQuoteLen);
			CHECK_QSTATUS();
		}
		status = buf.append(pLine, p - pLine);
		CHECK_QSTATUS();
	}

	*pwstrText = buf.getString();

	return QSTATUS_SUCCESS;
}

std::pair<size_t, size_t> qs::TextUtil::findURL(const WCHAR* pwszText,
	size_t nLen, const WCHAR* const* ppwszSchemas, size_t nSchemaCount)
{
	assert(pwszText);

	std::pair<size_t, size_t> url(-1, 0);
	if (nSchemaCount != 0) {
		const WCHAR* p = pwszText;
		while (nLen > 0) {
			if (p == pwszText || !isURLChar(*(p - 1))) {
				bool bFound = false;
				for (size_t n = 0; n < nSchemaCount; ++n) {
					if (ppwszSchemas[n][0] == *p) {
						size_t nSchemaLen = wcslen(ppwszSchemas[n]);
						if (nLen > nSchemaLen &&
							wcsncmp(p, ppwszSchemas[n], nSchemaLen) == 0 &&
							*(p + nSchemaLen) == L':') {
							bFound = true;
							break;
						}
					}
				}
				if (bFound)
					break;
			}
			else if (*p == L'@' &&
				p != pwszText && isURLChar(*(p - 1)) &&
				nLen > 1 && isURLChar(*(p + 1))) {
				while (p >= pwszText && isURLChar(*p)) {
					--p;
					++nLen;
				}
				++p;
				--nLen;
				break;
			}
			--nLen;
			++p;
		}
		if (nLen > 0) {
			url.first = p - pwszText;
			while (nLen > 0 && isURLChar(*p)) {
				--nLen;
				++p;
			}
			url.second = p - (pwszText + url.first);
		}
	}

	return url;
}

bool qs::TextUtil::isURLChar(WCHAR c)
{
	return (L'A' <= c && c <= L'Z') ||
		(L'a' <= c && c <= L'z') ||
		(L'0' <= c && c <= L'9') ||
		c == L'.' ||
		c == L':' ||
		c == L'/' ||
		c == L'?' ||
		c == L'%' ||
		c == L'&' ||
		c == L'@' ||
		c == L'!' ||
		c == L'#' ||
		c == L'$' ||
		c == L'~' ||
		c == L'*' ||
		c == L'=' ||
		c == L'+' ||
		c == L'-' ||
		c == L'_' ||
		c == L';' ||
		c == L',' ||
		c == L'(' ||
		c == L')';
}

QSTATUS qs::TextUtil::encodePassword(const WCHAR* pwsz, WSTRING* pwstr)
{
	assert(pwsz);
	assert(pwstr);

	DECLARE_QSTATUS();

	Base64Encoder encoder(false, &status);
	CHECK_QSTATUS();
	unsigned char* p = 0;
	size_t nLen = 0;
	status = encoder.encode(reinterpret_cast<const unsigned char*>(pwsz),
		wcslen(pwsz)*sizeof(WCHAR), &p, &nLen);
	CHECK_QSTATUS();
	malloc_ptr<unsigned char> pBuffer(p);

	string_ptr<WSTRING> wstr(allocWString(nLen*2 + 1));
	if (!wstr.get())
		return QSTATUS_OUTOFMEMORY;

	WCHAR* pDst = wstr.get();
	for (size_t n = 0; n < nLen; ++n) {
		swprintf(pDst, L"%02x", *(p + n) ^ 'q');
		pDst += 2;
	}
	*pDst = L'\0';

	*pwstr = wstr.release();

	return QSTATUS_SUCCESS;
}

QSTATUS qs::TextUtil::decodePassword(const WCHAR* pwsz, WSTRING* pwstr)
{
	assert(pwsz);
	assert(pwstr);

	DECLARE_QSTATUS();

	size_t nLen = wcslen(pwsz);

	malloc_ptr<unsigned char> pBuf(
		static_cast<unsigned char*>(malloc(nLen/2 + 1)));
	if (!pBuf.get())
		return QSTATUS_OUTOFMEMORY;
	unsigned char* p = pBuf.get();

	for (size_t n = 0; n < nLen; n += 2) {
		WCHAR wsz[3] = L"";
		wcsncpy(wsz, pwsz + n, 2);
		unsigned int m = 0;
		swscanf(wsz, L"%02x", &m);
		*p++ = m ^= 'q';
	}

	Base64Encoder encoder(false, &status);
	CHECK_QSTATUS();
	unsigned char* pDecode = 0;
	size_t nDecodeLen = 0;
	status = encoder.decode(pBuf.get(), p - pBuf.get(), &pDecode, &nDecodeLen);
	CHECK_QSTATUS();
	malloc_ptr<unsigned char> pDecodeFree(pDecode);

	string_ptr<WSTRING> wstr(allocWString(
		reinterpret_cast<WCHAR*>(pDecode), nDecodeLen/sizeof(WCHAR)));
	if (!wstr.get())
		return QSTATUS_OUTOFMEMORY;

	*pwstr = wstr.release();

	return QSTATUS_SUCCESS;
}
<|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 "chrome/nacl/nacl_validation_query.h"

#include "base/logging.h"
#include "chrome/nacl/nacl_validation_db.h"
#include "native_client/src/trusted/validator/validation_cache.h"

NaClValidationQueryContext::NaClValidationQueryContext(
    NaClValidationDB* db,
    const std::string& profile_key,
    const std::string& nacl_version)
    : db_(db),
      profile_key_(profile_key),
      nacl_version_(nacl_version) {

  // Sanity checks.
  CHECK(profile_key.length() >= 8);
  CHECK(nacl_version.length() >= 4);
}

NaClValidationQuery* NaClValidationQueryContext::CreateQuery() {
  NaClValidationQuery* query = new NaClValidationQuery(db_, profile_key_);
  // Changing the version effectively invalidates existing hashes.
  query->AddData(nacl_version_);
  return query;
}

NaClValidationQuery::NaClValidationQuery(NaClValidationDB* db,
                                         const std::string& profile_key)
    : state_(READY),
      hasher_(crypto::HMAC::SHA256),
      db_(db),
      buffer_length_(0) {
  CHECK(hasher_.Init(profile_key));
}

void NaClValidationQuery::AddData(const char* data, size_t length) {
  CHECK(state_ == READY);
  CHECK(buffer_length_ >= 0);
  CHECK(buffer_length_ <= (int) sizeof(buffer_));
  // Chrome's HMAC class doesn't support incremental signing.  Work around
  // this by using a (small) temporary buffer to accumulate data.
  // Check if there is space in the buffer.
  if (buffer_length_ + kDigestLength > (int) sizeof(buffer_)) {
    // Hash the buffer to make space.
    CompressBuffer();
  }
  // Hash the input data into the buffer.  Assumes that sizeof(buffer_) >=
  // kDigestLength * 2 (the buffer can store at least two digests.)
  CHECK(hasher_.Sign(base::StringPiece(data, length),
                     reinterpret_cast<unsigned char*>(buffer_ + buffer_length_),
                     kDigestLength));
  buffer_length_ += kDigestLength;
}

void NaClValidationQuery::AddData(const unsigned char* data, size_t length) {
  AddData(reinterpret_cast<const char*>(data), length);
}

void NaClValidationQuery::AddData(const base::StringPiece& data) {
  AddData(data.data(), data.length());
}

int NaClValidationQuery::QueryKnownToValidate() {
  CHECK(state_ == READY);
  // It is suspicious if we have less than a digest's worth of data.
  CHECK(buffer_length_ >= kDigestLength);
  CHECK(buffer_length_ <= (int) sizeof(buffer_));
  state_ = GET_CALLED;
  // Ensure the buffer contains only one digest worth of data.
  CompressBuffer();
  return db_->QueryKnownToValidate(std::string(buffer_, buffer_length_));
}

void NaClValidationQuery::SetKnownToValidate() {
  CHECK(state_ == GET_CALLED);
  CHECK(buffer_length_ == kDigestLength);
  state_ = SET_CALLED;
  db_->SetKnownToValidate(std::string(buffer_, buffer_length_));
}

// Reduce the size of the data in the buffer by hashing it and writing it back
// to the buffer.
void NaClValidationQuery::CompressBuffer() {
  // Calculate the digest into a temp buffer.  It is likely safe to calculate it
  // directly back into the buffer, but this is an "accidental" semantic we're
  // avoiding depending on.
  unsigned char temp[kDigestLength];
  CHECK(hasher_.Sign(base::StringPiece(buffer_, buffer_length_), temp,
                     kDigestLength));
  memcpy(buffer_, temp, kDigestLength);
  buffer_length_ = kDigestLength;
}

// OO wrappers

static void* CreateQuery(void* handle) {
  return static_cast<NaClValidationQueryContext*>(handle)->CreateQuery();
}

static void AddData(void* query, const uint8* data, size_t length) {
  static_cast<NaClValidationQuery*>(query)->AddData(data, length);
}

static int QueryKnownToValidate(void* query) {
  return static_cast<NaClValidationQuery*>(query)->QueryKnownToValidate();
}

static void SetKnownToValidate(void* query) {
  static_cast<NaClValidationQuery*>(query)->SetKnownToValidate();
}

static void DestroyQuery(void* query) {
  delete static_cast<NaClValidationQuery*>(query);
}

struct NaClValidationCache* CreateValidationCache(
    NaClValidationDB* db, const std::string& profile_key,
    const std::string& nacl_version) {
  NaClValidationCache* cache =
      static_cast<NaClValidationCache*>(malloc(sizeof(NaClValidationCache)));
  // Make sure any fields introduced in a cross-repo change are zeroed.
  memset(cache, 0, sizeof(*cache));
  cache->handle = new NaClValidationQueryContext(db, profile_key, nacl_version);
  cache->CreateQuery = CreateQuery;
  cache->AddData = AddData;
  cache->QueryKnownToValidate = QueryKnownToValidate;
  cache->SetKnownToValidate = SetKnownToValidate;
  cache->DestroyQuery = DestroyQuery;
  return cache;
}
<commit_msg>NaCl validation caching: improve startup speed by ~70 ms on Linux.<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 "chrome/nacl/nacl_validation_query.h"

#include "base/logging.h"
#include "crypto/nss_util.h"
#include "chrome/nacl/nacl_validation_db.h"
#include "native_client/src/trusted/validator/validation_cache.h"

NaClValidationQueryContext::NaClValidationQueryContext(
    NaClValidationDB* db,
    const std::string& profile_key,
    const std::string& nacl_version)
    : db_(db),
      profile_key_(profile_key),
      nacl_version_(nacl_version) {

  // Sanity checks.
  CHECK(profile_key.length() >= 8);
  CHECK(nacl_version.length() >= 4);
}

NaClValidationQuery* NaClValidationQueryContext::CreateQuery() {
  NaClValidationQuery* query = new NaClValidationQuery(db_, profile_key_);
  // Changing the version effectively invalidates existing hashes.
  query->AddData(nacl_version_);
  return query;
}

NaClValidationQuery::NaClValidationQuery(NaClValidationDB* db,
                                         const std::string& profile_key)
    : state_(READY),
      hasher_(crypto::HMAC::SHA256),
      db_(db),
      buffer_length_(0) {
  // Without this line on Linux, HMAC::Init will instantiate a singleton that
  // in turn attempts to open a file.  Disabling this behavior avoids a ~70 ms
  // stall the first time HMAC is used.
#if defined(OS_LINUX)
  crypto::ForceNSSNoDBInit();
#endif
  CHECK(hasher_.Init(profile_key));
}

void NaClValidationQuery::AddData(const char* data, size_t length) {
  CHECK(state_ == READY);
  CHECK(buffer_length_ >= 0);
  CHECK(buffer_length_ <= (int) sizeof(buffer_));
  // Chrome's HMAC class doesn't support incremental signing.  Work around
  // this by using a (small) temporary buffer to accumulate data.
  // Check if there is space in the buffer.
  if (buffer_length_ + kDigestLength > (int) sizeof(buffer_)) {
    // Hash the buffer to make space.
    CompressBuffer();
  }
  // Hash the input data into the buffer.  Assumes that sizeof(buffer_) >=
  // kDigestLength * 2 (the buffer can store at least two digests.)
  CHECK(hasher_.Sign(base::StringPiece(data, length),
                     reinterpret_cast<unsigned char*>(buffer_ + buffer_length_),
                     kDigestLength));
  buffer_length_ += kDigestLength;
}

void NaClValidationQuery::AddData(const unsigned char* data, size_t length) {
  AddData(reinterpret_cast<const char*>(data), length);
}

void NaClValidationQuery::AddData(const base::StringPiece& data) {
  AddData(data.data(), data.length());
}

int NaClValidationQuery::QueryKnownToValidate() {
  CHECK(state_ == READY);
  // It is suspicious if we have less than a digest's worth of data.
  CHECK(buffer_length_ >= kDigestLength);
  CHECK(buffer_length_ <= (int) sizeof(buffer_));
  state_ = GET_CALLED;
  // Ensure the buffer contains only one digest worth of data.
  CompressBuffer();
  return db_->QueryKnownToValidate(std::string(buffer_, buffer_length_));
}

void NaClValidationQuery::SetKnownToValidate() {
  CHECK(state_ == GET_CALLED);
  CHECK(buffer_length_ == kDigestLength);
  state_ = SET_CALLED;
  db_->SetKnownToValidate(std::string(buffer_, buffer_length_));
}

// Reduce the size of the data in the buffer by hashing it and writing it back
// to the buffer.
void NaClValidationQuery::CompressBuffer() {
  // Calculate the digest into a temp buffer.  It is likely safe to calculate it
  // directly back into the buffer, but this is an "accidental" semantic we're
  // avoiding depending on.
  unsigned char temp[kDigestLength];
  CHECK(hasher_.Sign(base::StringPiece(buffer_, buffer_length_), temp,
                     kDigestLength));
  memcpy(buffer_, temp, kDigestLength);
  buffer_length_ = kDigestLength;
}

// OO wrappers

static void* CreateQuery(void* handle) {
  return static_cast<NaClValidationQueryContext*>(handle)->CreateQuery();
}

static void AddData(void* query, const uint8* data, size_t length) {
  static_cast<NaClValidationQuery*>(query)->AddData(data, length);
}

static int QueryKnownToValidate(void* query) {
  return static_cast<NaClValidationQuery*>(query)->QueryKnownToValidate();
}

static void SetKnownToValidate(void* query) {
  static_cast<NaClValidationQuery*>(query)->SetKnownToValidate();
}

static void DestroyQuery(void* query) {
  delete static_cast<NaClValidationQuery*>(query);
}

struct NaClValidationCache* CreateValidationCache(
    NaClValidationDB* db, const std::string& profile_key,
    const std::string& nacl_version) {
  NaClValidationCache* cache =
      static_cast<NaClValidationCache*>(malloc(sizeof(NaClValidationCache)));
  // Make sure any fields introduced in a cross-repo change are zeroed.
  memset(cache, 0, sizeof(*cache));
  cache->handle = new NaClValidationQueryContext(db, profile_key, nacl_version);
  cache->CreateQuery = CreateQuery;
  cache->AddData = AddData;
  cache->QueryKnownToValidate = QueryKnownToValidate;
  cache->SetKnownToValidate = SetKnownToValidate;
  cache->DestroyQuery = DestroyQuery;
  return cache;
}
<|endoftext|>


<commit_before>// ===============================================================
// Computer Graphics Homework Solutions
// Copyright (C) 2017 by George Wolberg
//
// HW1a.cpp - HW1a class
//
// Written by: George Wolberg, 2017
// ===============================================================

#include "HW1a.h"

// init array of 16 vertices for letter 'P'
float Vertices[] = {
	-0.5f , -0.75f,
	-0.5f , -0.5f,
	-0.5f , -0.25f,
	-0.5f ,  0.0f,
	-0.5f ,  0.25f,
	-0.5f ,  0.5f,
	-0.25f,  0.75f,
	 0.0f ,  0.75f,
	 0.25f,  0.75f,
	 0.5f ,  0.75f,
	 0.75f,  0.5f,
	 0.75f,  0.25f,
	 0.5f ,  0.0f,
	 0.25f,  0.0f,
	 0.0f ,  0.0f,
	-0.25f,  0.0f
};

static int DrawModes[] = {
	GL_POINTS,
	GL_LINES,
	GL_LINE_STRIP,
	GL_LINE_LOOP,
	GL_TRIANGLES,
	GL_TRIANGLE_STRIP,
	GL_TRIANGLE_FAN,
	GL_QUADS,
	GL_POLYGON
};

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW1a::HW1a:
//
// HW1a constructor.
//
HW1a::HW1a(const QGLFormat &glf, QWidget *parent)
	: HW(glf, parent)
{
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW1a::initializeGL:
//
// Initialization routine before display loop.
// Gets called once before the first time resizeGL() or paintGL() is called.
//
void
HW1a::initializeGL()
{
	// PUT YOUR CODE HERE
	glClearColor(0.0, 0.0, 0.0, 0.0);
	glColor3f		(1.0, 1.0, 1.0);
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW1a::resizeGL:
//
// Resize event handler.
// The input parameters are the window width (w) and height (h).
//
void
HW1a::resizeGL(int w, int h)
{
	// PUT YOUR CODE HERE
	// glViewport(0, 0, w, h);

	// glMatrixMode(GL_PROJECTION);
	// glLoadIdentity();
	// glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
	// save window dimensions
	m_winW = w;
	m_winH = h;

	// compute aspect ratio
	float ar = (float) w / h;

	// set xmax, ymax;
	float xmax, ymax;
	if(ar > 1.0) {		// wide screen
		xmax = ar;
		ymax = 1.;
	} else {		// tall screen
		xmax = 1.;
		ymax = 1 / ar;
	}

	// set viewport to occupy full canvas
	glViewport(0, 0, w, h);

	// init viewing coordinates for orthographic projection
	glLoadIdentity();
	glOrtho(-xmax, xmax, -ymax, ymax, -1.0, 1.0);
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW1a::paintGL:
//
// Update GL scene.
//
void
HW1a::paintGL()
{
	// PUT YOUR CODE HERE
	glClear(GL_COLOR_BUFFER_BIT);

	glColor3f(1.0, 1.0, 1.0);
	// glBegin(GL_LINES);
	// for(int i = 0; i < sizeof(Vertices)/2; i++) {
	// 	glVertex2f(Vertices[i*2], Vertices[(i*2)+1]);
	// }
	// glEnd();

	// glBegin(GL_POLYGON);
	// for(int i = 0; i < sizeof(Vertices)/2; i++) {
	// 	glVertex2f(Vertices[i*2], Vertices[(i*2)+1]);
	// }
	// glEnd();

	// glBegin(GL_TRIANGLES);
	// for(int i = 0; i < sizeof(Vertices)/2; i++) {
	// 	glVertex2f(Vertices[i*2], Vertices[(i*2)+1]);
	// }
	// glEnd();
	// 	glBegin(GL_POINTS);
	// for(int i = 0; i < sizeof(Vertices)/2; i++) {
	// 	glVertex2f(Vertices[i*2], Vertices[(i*2)+1]);
	// }
	// glEnd();

	// glBegin(GL_TRIANGLE_FAN);
	// for(int i = 0; i < sizeof(Vertices)/2; i++) {
	// 	glVertex2f(Vertices[i*2], Vertices[(i*2)+1]);
	// }
	// glEnd();

	for(int i = 0; i < sizeof(DrawModes); i++) {
		glBegin(DrawModes[i]);
			for(int j = 0; j < sizeof(Vertices)/2; j++) {
				glVertex2f(Vertices[j*2]/3+(0.67*i), Vertices[(j*2)+1]/3+(0.67*i));
			}
		glEnd();
		glFlush();
	}

}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW1a::controlPanel:
//
// Create control panel groupbox.
//
QGroupBox*
HW1a::controlPanel()
{
	// init group box
	QGroupBox *groupBox = new QGroupBox("Homework 1a");
	groupBox->setStyleSheet(GroupBoxStyle);

	return(groupBox);
}
<commit_msg>Add looping through DrawModes for Ps.<commit_after>// ===============================================================
// Computer Graphics Homework Solutions
// Copyright (C) 2017 by George Wolberg
//
// HW1a.cpp - HW1a class
//
// Written by: George Wolberg, 2017
// ===============================================================

#include "HW1a.h"

// init array of 16 vertices for letter 'P'
float Vertices[] = {
	-0.5f , -0.75f,
	-0.5f , -0.5f,
	-0.5f , -0.25f,
	-0.5f ,  0.0f,
	-0.5f ,  0.25f,
	-0.5f ,  0.5f,
	-0.25f,  0.75f,
	 0.0f ,  0.75f,
	 0.25f,  0.75f,
	 0.5f ,  0.75f,
	 0.75f,  0.5f,
	 0.75f,  0.25f,
	 0.5f ,  0.0f,
	 0.25f,  0.0f,
	 0.0f ,  0.0f,
	-0.25f,  0.0f
};

static int DrawModes[] = {
	GL_POINTS,
	GL_LINES,
	GL_LINE_STRIP,
	GL_LINE_LOOP,
	GL_TRIANGLES,
	GL_TRIANGLE_STRIP,
	GL_TRIANGLE_FAN,
	GL_QUADS,
	GL_POLYGON
};

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW1a::HW1a:
//
// HW1a constructor.
//
HW1a::HW1a(const QGLFormat &glf, QWidget *parent)
	: HW(glf, parent)
{
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW1a::initializeGL:
//
// Initialization routine before display loop.
// Gets called once before the first time resizeGL() or paintGL() is called.
//
void
HW1a::initializeGL()
{
	// PUT YOUR CODE HERE
	glClearColor(0.0, 0.0, 0.0, 0.0);
	glColor3f		(1.0, 1.0, 1.0);
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW1a::resizeGL:
//
// Resize event handler.
// The input parameters are the window width (w) and height (h).
//
void
HW1a::resizeGL(int w, int h)
{
	// PUT YOUR CODE HERE
	// save window dimensions
	m_winW = w;
	m_winH = h;

	// compute aspect ratio
	float ar = (float) w / h;

	// set xmax, ymax;
	float xmax, ymax;
	if(ar > 1.0) {		// wide screen
		xmax = ar;
		ymax = 1.;
	} else {		// tall screen
		xmax = 1.;
		ymax = 1 / ar;
	}

	// set viewport to occupy full canvas
	glViewport(0, 0, w, h);

	// init viewing coordinates for orthographic projection
	glLoadIdentity();
	glOrtho(-xmax, xmax, -ymax, ymax, -1.0, 1.0);
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW1a::paintGL:
//
// Update GL scene.
//
void
HW1a::paintGL()
{
	// PUT YOUR CODE HERE
	glClear(GL_COLOR_BUFFER_BIT);

	glColor3f(1.0, 1.0, 1.0);

	for(int i = 0; i < sizeof(DrawModes); i++) { // Loop through DrawModes
		glBegin(DrawModes[i]);
			for(int j = 0; j < sizeof(Vertices)/2; j++) {
				glVertex2f(((Vertices[j*2]/3) - 1)+(2*(i%3)/3), Vertices[(j*2)+1]/3);
			}
		glEnd();
		glFlush();
	}

}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW1a::controlPanel:
//
// Create control panel groupbox.
//
QGroupBox*
HW1a::controlPanel()
{
	// init group box
	QGroupBox *groupBox = new QGroupBox("Homework 1a");
	groupBox->setStyleSheet(GroupBoxStyle);

	return(groupBox);
}
<|endoftext|>


<commit_before>// Copyright (c) 2008 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 "chrome/renderer/user_script_slave.h"

#include "base/logging.h"
#include "base/pickle.h"
#include "base/shared_memory.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/renderer/renderer_resources.h"
#include "googleurl/src/gurl.h"

// These two strings are injected before and after the Greasemonkey API and
// user script to wrap it in an anonymous scope.
static const char kUserScriptHead[] = "(function (unsafeWindow) {";
static const char kUserScriptTail[] = "\n})(window);";

// UserScript

bool UserScript::MatchesUrl(const GURL& url) {
  for (std::vector<std::string>::iterator pattern = include_patterns_.begin();
       pattern != include_patterns_.end(); ++pattern) {
    if (MatchPattern(url.spec(), *pattern)) {
      return true;
    }
  }

  return false;
}

void UserScript::AddInclude(const std::string &glob_pattern) {
  include_patterns_.push_back(EscapeGlob(glob_pattern));
}

std::string UserScript::EscapeGlob(const std::string& input_pattern) {
  std::string output_pattern;

  for (size_t i = 0; i < input_pattern.length(); ++i) {
    switch (input_pattern[i]) {
      // These characters have special meaning to the MatchPattern() function,
      // so we escape them.
      case '\\':
      case '?':
        output_pattern += '\\';
        // fall through

      default:
        output_pattern += input_pattern[i];
    }
  }

  return output_pattern;
}

// UserScriptSlave
UserScriptSlave::UserScriptSlave()
    : shared_memory_(NULL),
      user_script_start_line_(0) {
  // TODO: Only windows supports resources and only windows supports user
  // scrips, so only load the Greasemonkey API on windows.  Fix this when
  // better cross platofrm support is available.
#if defined(OS_WIN)
  api_js_ = ResourceBundle::GetSharedInstance().GetRawDataResource(
                IDR_GREASEMONKEY_API_JS);
#endif

  // Count the number of lines that will be injected before the user script.
  StringPiece::size_type pos = 0;
  while ((pos = api_js_.find('\n', pos)) != StringPiece::npos) {
    user_script_start_line_++;
    pos++;
  }

  // Add one more line to account for the function that wraps everything.
  user_script_start_line_++;
}

bool UserScriptSlave::UpdateScripts(base::SharedMemoryHandle shared_memory) {
  scripts_.clear();

  // Create the shared memory object (read only).
  shared_memory_.reset(new base::SharedMemory(shared_memory, true));
  if (!shared_memory_.get())
    return false;

  // First get the size of the memory block.
  if (!shared_memory_->Map(sizeof(Pickle::Header)))
    return false;
  Pickle::Header* pickle_header =
      reinterpret_cast<Pickle::Header*>(shared_memory_->memory());

  // Now map in the rest of the block.
  int pickle_size = sizeof(Pickle::Header) + pickle_header->payload_size;
  shared_memory_->Unmap();
  if (!shared_memory_->Map(pickle_size))
    return false;

  // Unpickle scripts.
  void* iter = NULL;
  size_t num_scripts = 0;
  Pickle pickle(reinterpret_cast<char*>(shared_memory_->memory()),
                pickle_size);
  pickle.ReadSize(&iter, &num_scripts);

  for (size_t i = 0; i < num_scripts; ++i) {
    const char* url = NULL;
    int url_length = 0;
    const char* body = NULL;
    int body_length = 0;

    pickle.ReadData(&iter, &url, &url_length);
    pickle.ReadData(&iter, &body, &body_length);

    scripts_.push_back(UserScript(StringPiece(url, url_length),
                                  StringPiece(body, body_length)));
    UserScript& script = scripts_.back();

    size_t num_includes;
    pickle.ReadSize(&iter, &num_includes);
    for (size_t j = 0; j < num_includes; ++j) {
      std::string include;
      pickle.ReadString(&iter, &include);
      script.AddInclude(include);
    }
  }

  return true;
}

bool UserScriptSlave::InjectScripts(WebFrame* frame) {
  for (std::vector<UserScript>::iterator script = scripts_.begin();
       script != scripts_.end(); ++script) {
    if (script->MatchesUrl(frame->GetURL())) {
      std::string inject(kUserScriptHead);
      inject.append(api_js_.as_string());
      inject.append(script->GetBody().as_string());
      inject.append(kUserScriptTail);
      frame->ExecuteJavaScript(inject,
                               GURL(script->GetURL().as_string()),
                               -user_script_start_line_);
    }
  }

  return true;
}
<commit_msg>TBR: Fix error line numbers.<commit_after>// Copyright (c) 2008 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 "chrome/renderer/user_script_slave.h"

#include "base/logging.h"
#include "base/pickle.h"
#include "base/shared_memory.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/renderer/renderer_resources.h"
#include "googleurl/src/gurl.h"

// These two strings are injected before and after the Greasemonkey API and
// user script to wrap it in an anonymous scope.
static const char kUserScriptHead[] = "(function (unsafeWindow) {\n";
static const char kUserScriptTail[] = "\n})(window);";

// UserScript

bool UserScript::MatchesUrl(const GURL& url) {
  for (std::vector<std::string>::iterator pattern = include_patterns_.begin();
       pattern != include_patterns_.end(); ++pattern) {
    if (MatchPattern(url.spec(), *pattern)) {
      return true;
    }
  }

  return false;
}

void UserScript::AddInclude(const std::string &glob_pattern) {
  include_patterns_.push_back(EscapeGlob(glob_pattern));
}

std::string UserScript::EscapeGlob(const std::string& input_pattern) {
  std::string output_pattern;

  for (size_t i = 0; i < input_pattern.length(); ++i) {
    switch (input_pattern[i]) {
      // These characters have special meaning to the MatchPattern() function,
      // so we escape them.
      case '\\':
      case '?':
        output_pattern += '\\';
        // fall through

      default:
        output_pattern += input_pattern[i];
    }
  }

  return output_pattern;
}

// UserScriptSlave
UserScriptSlave::UserScriptSlave()
    : shared_memory_(NULL),
      user_script_start_line_(0) {
  // TODO: Only windows supports resources and only windows supports user
  // scrips, so only load the Greasemonkey API on windows.  Fix this when
  // better cross platofrm support is available.
#if defined(OS_WIN)
  api_js_ = ResourceBundle::GetSharedInstance().GetRawDataResource(
                IDR_GREASEMONKEY_API_JS);
#endif

  // Count the number of lines that will be injected before the user script.
  StringPiece::size_type pos = 0;
  while ((pos = api_js_.find('\n', pos)) != StringPiece::npos) {
    user_script_start_line_++;
    pos++;
  }

  // NOTE: There is actually one extra line in the injected script because the
  // function header includes a newline as well. But WebKit expects the
  // numbering to be one-based, not zero-based, so actually *not* accounting for
  // this extra line ends us up with the right offset.
}

bool UserScriptSlave::UpdateScripts(base::SharedMemoryHandle shared_memory) {
  scripts_.clear();

  // Create the shared memory object (read only).
  shared_memory_.reset(new base::SharedMemory(shared_memory, true));
  if (!shared_memory_.get())
    return false;

  // First get the size of the memory block.
  if (!shared_memory_->Map(sizeof(Pickle::Header)))
    return false;
  Pickle::Header* pickle_header =
      reinterpret_cast<Pickle::Header*>(shared_memory_->memory());

  // Now map in the rest of the block.
  int pickle_size = sizeof(Pickle::Header) + pickle_header->payload_size;
  shared_memory_->Unmap();
  if (!shared_memory_->Map(pickle_size))
    return false;

  // Unpickle scripts.
  void* iter = NULL;
  size_t num_scripts = 0;
  Pickle pickle(reinterpret_cast<char*>(shared_memory_->memory()),
                pickle_size);
  pickle.ReadSize(&iter, &num_scripts);

  for (size_t i = 0; i < num_scripts; ++i) {
    const char* url = NULL;
    int url_length = 0;
    const char* body = NULL;
    int body_length = 0;

    pickle.ReadData(&iter, &url, &url_length);
    pickle.ReadData(&iter, &body, &body_length);

    scripts_.push_back(UserScript(StringPiece(url, url_length),
                                  StringPiece(body, body_length)));
    UserScript& script = scripts_.back();

    size_t num_includes;
    pickle.ReadSize(&iter, &num_includes);
    for (size_t j = 0; j < num_includes; ++j) {
      std::string include;
      pickle.ReadString(&iter, &include);
      script.AddInclude(include);
    }
  }

  return true;
}

bool UserScriptSlave::InjectScripts(WebFrame* frame) {
  for (std::vector<UserScript>::iterator script = scripts_.begin();
       script != scripts_.end(); ++script) {
    if (script->MatchesUrl(frame->GetURL())) {
      std::string inject(kUserScriptHead);
      inject.append(api_js_.as_string());
      inject.append(script->GetBody().as_string());
      inject.append(kUserScriptTail);
      frame->ExecuteJavaScript(inject,
                               GURL(script->GetURL().as_string()),
                               -user_script_start_line_);
    }
  }

  return true;
}
<|endoftext|>


<commit_before><commit_msg>LCDDisplay.cpp fully updated to Linux coding standard,implemented all tokenising updates to remaining if statements  and removed irrelevant debug lines<commit_after><|endoftext|>


<commit_before><commit_msg>P4 to Git Change 1304815 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/08/19 03:00:08<commit_after><|endoftext|>


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

#include "ozone/impl/ozone_display.h"

#include <map>
#include "content/child/child_process.h"
#include "ozone/impl/desktop_aura/desktop_screen_wayland.h"
#include "ozone/impl/ipc/display_channel.h"
#include "ozone/impl/ipc/display_channel_host.h"
#include "ozone/ui/events/event_converter_in_process.h"
#include "ozone/ui/events/remote_event_dispatcher.h"
#include "ozone/wayland/display.h"
#include "ozone/wayland/screen.h"

namespace ozonewayland {

OzoneDisplay* OzoneDisplay::instance_ = NULL;
const int kMaxDisplaySize = 20;

OzoneDisplay* OzoneDisplay::GetInstance() {
  return instance_;
}

OzoneDisplay::OzoneDisplay() : desktop_screen_(NULL),
    display_(NULL),
    channel_(NULL),
    host_(NULL),
    event_converter_(NULL),
    spec_(NULL) {
  instance_ = this;
}

OzoneDisplay::~OzoneDisplay() {
  Terminate();
  instance_ = NULL;
}

const char* OzoneDisplay::DefaultDisplaySpec() {
  return spec_;
}

bool OzoneDisplay::InitializeHardware() {
  display_ = new WaylandDisplay(WaylandDisplay::RegisterAsNeeded);
  bool initialized_hardware = display_->display() ? true : false;
  if (initialized_hardware && !content::ChildProcess::current()) {
    // In the multi-process mode, DisplayChannel (in GPU process side) is in
    // charge of establishing an IPC channel with DisplayChannelHost (in
    // Browser Process side). At this moment the GPU process is still
    // initializing though, so DisplayChannel cannot establish the connection
    // and need to delay this to later. Therefore post a task to GpuChildThread
    // and let DisplayChannel handle this right after the GPU process is
    // initialized.
    base::MessageLoop::current()->message_loop_proxy()->PostTask(
        FROM_HERE, base::Bind(&OzoneDisplay::DelayedInitialization, this));
  }

  return initialized_hardware;
}

void OzoneDisplay::ShutdownHardware() {
  Terminate();
}

intptr_t OzoneDisplay::GetNativeDisplay() {
  return (intptr_t)display_->display();
}

gfx::Screen* OzoneDisplay::CreateDesktopScreen() {
  if (!desktop_screen_) {
    // TODO(Kalyan): Find a better way to handle this. Move all EventConverter
    // initialization to EventFactoryOzone.
    event_converter_ = new EventConverterInProcess();
    desktop_screen_ = new DesktopScreenWayland;
    LookAheadOutputGeometry();
  }

  return desktop_screen_;
}

gfx::AcceleratedWidget OzoneDisplay::GetAcceleratedWidget() {
  static int opaque_handle = 0;
  // Ensure Event Converter is initialized. This can be the case when support
  // for toolkit_views is disabled and we didn't recieve any call to
  // CreateDesktopScreen.
  if (!event_converter_)
    event_converter_ = new EventConverterInProcess();

  if (display_) {
    // TODO(Kalyan): Find a better way to handle this. Move the logic to
    // EventConverterOzone eventually.
    if (opaque_handle == 0)
      display_->StartProcessingEvents();
  } else if (!host_) {
      host_ = new OzoneDisplayChannelHost();
  }

  opaque_handle++;
  WindowStateChangeHandler::GetInstance()->SetWidgetState(opaque_handle,
                                                          CREATE,
                                                          0,
                                                          0);

  return (gfx::AcceleratedWidget)opaque_handle;
}

gfx::AcceleratedWidget OzoneDisplay::RealizeAcceleratedWidget(
    gfx::AcceleratedWidget w) {
  DCHECK(display_);
  // Event Converter should be already initialized unless we are in gpu process
  // side.
  if (!event_converter_) {
    event_converter_ = new RemoteEventDispatcher();
    display_->StartProcessingEvents();
  }

  return (gfx::AcceleratedWidget)display_->RealizeAcceleratedWidget();
}

void OzoneDisplay::DelayedInitialization(OzoneDisplay* display) {
  display->channel_ = new OzoneDisplayChannel();
  display->channel_->Register();
}

void OzoneDisplay::Terminate() {
  if (!event_converter_ && !desktop_screen_)
    return;

  if (spec_)
    delete[] spec_;

  delete channel_;
  if (desktop_screen_) {
    delete desktop_screen_;
    desktop_screen_ = NULL;
  }

  delete display_;
  if (event_converter_) {
    delete event_converter_;
    event_converter_ = NULL;
  }
}

// TODO(vignatti): GPU process conceptually is the one that deals with hardware
// details and therefore we assume that the window system connection should
// happen in there only. There's a glitch with Chrome though, that creates its
// frame contents requiring access to the window system, before the GPU process
// even exists. In other words, Chrome runs
// BrowserMainLoop::PreMainMessageLoopRun before GpuProcessHost::Get. If the
// assumption of window system connection belongs to the GPU process is valid,
// then I believe this Chrome behavior needs to be addressed upstream.
//
// For now, we create another window system connection to look ahead the needed
// output properties that Chrome (among others) need and then close right after
// that. I haven't measured how long it takes to open a Wayland connection,
// listen all the interface the compositor sends and close it, but _for_ _sure_
// it slows down the overall initialization time of Chromium targets.
// Therefore, this is something that has to be solved in the future, moving all
// Chrome tasks after GPU process is created.
//
void OzoneDisplay::LookAheadOutputGeometry() {
  DCHECK(event_converter_);
  WaylandDisplay disp_(WaylandDisplay::RegisterOutputOnly);
  CHECK(disp_.display()) << "Ozone: Wayland server connection not found.";

  while (disp_.PrimaryScreen()->Geometry().IsEmpty())
    disp_.SyncDisplay();

  EventConverterInProcess* coverter =
      static_cast<EventConverterInProcess*>(event_converter_);
  DCHECK(coverter->GetOutputChangeObserver());

  unsigned width = disp_.PrimaryScreen()->Geometry().width();
  unsigned height = disp_.PrimaryScreen()->Geometry().height();
  coverter->GetOutputChangeObserver()->OnOutputSizeChanged(width, height);
}

}  // namespace ozonewayland
<commit_msg>Missing changes related to RealizeAcceleratedWidget move to WaylandDisplay.<commit_after>// Copyright 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ozone/impl/ozone_display.h"

#include <map>
#include "content/child/child_process.h"
#include "ozone/impl/desktop_aura/desktop_screen_wayland.h"
#include "ozone/impl/ipc/display_channel.h"
#include "ozone/impl/ipc/display_channel_host.h"
#include "ozone/ui/events/event_converter_in_process.h"
#include "ozone/ui/events/remote_event_dispatcher.h"
#include "ozone/wayland/display.h"
#include "ozone/wayland/screen.h"

namespace ozonewayland {

OzoneDisplay* OzoneDisplay::instance_ = NULL;
const int kMaxDisplaySize = 20;

OzoneDisplay* OzoneDisplay::GetInstance() {
  return instance_;
}

OzoneDisplay::OzoneDisplay() : desktop_screen_(NULL),
    display_(NULL),
    channel_(NULL),
    host_(NULL),
    event_converter_(NULL),
    spec_(NULL) {
  instance_ = this;
}

OzoneDisplay::~OzoneDisplay() {
  Terminate();
  instance_ = NULL;
}

const char* OzoneDisplay::DefaultDisplaySpec() {
  return spec_;
}

bool OzoneDisplay::InitializeHardware() {
  display_ = new WaylandDisplay(WaylandDisplay::RegisterAsNeeded);
  bool initialized_hardware = display_->display() ? true : false;
  if (initialized_hardware && !content::ChildProcess::current()) {
    // In the multi-process mode, DisplayChannel (in GPU process side) is in
    // charge of establishing an IPC channel with DisplayChannelHost (in
    // Browser Process side). At this moment the GPU process is still
    // initializing though, so DisplayChannel cannot establish the connection
    // and need to delay this to later. Therefore post a task to GpuChildThread
    // and let DisplayChannel handle this right after the GPU process is
    // initialized.
    base::MessageLoop::current()->message_loop_proxy()->PostTask(
        FROM_HERE, base::Bind(&OzoneDisplay::DelayedInitialization, this));
  }

  return initialized_hardware;
}

void OzoneDisplay::ShutdownHardware() {
  Terminate();
}

intptr_t OzoneDisplay::GetNativeDisplay() {
  return (intptr_t)display_->display();
}

gfx::Screen* OzoneDisplay::CreateDesktopScreen() {
  if (!desktop_screen_) {
    // TODO(Kalyan): Find a better way to handle this. Move all EventConverter
    // initialization to EventFactoryOzone.
    event_converter_ = new EventConverterInProcess();
    desktop_screen_ = new DesktopScreenWayland;
    LookAheadOutputGeometry();
  }

  return desktop_screen_;
}

gfx::AcceleratedWidget OzoneDisplay::GetAcceleratedWidget() {
  static int opaque_handle = 0;
  // Ensure Event Converter is initialized. This can be the case when support
  // for toolkit_views is disabled and we didn't recieve any call to
  // CreateDesktopScreen.
  if (!event_converter_)
    event_converter_ = new EventConverterInProcess();

  if (display_) {
    // TODO(Kalyan): Find a better way to handle this. Move the logic to
    // EventConverterOzone eventually.
    if (opaque_handle == 0)
      display_->StartProcessingEvents();
  } else if (!host_) {
      host_ = new OzoneDisplayChannelHost();
  }

  opaque_handle++;
  WindowStateChangeHandler::GetInstance()->SetWidgetState(opaque_handle,
                                                          CREATE,
                                                          0,
                                                          0);

  return (gfx::AcceleratedWidget)opaque_handle;
}

gfx::AcceleratedWidget OzoneDisplay::RealizeAcceleratedWidget(
    gfx::AcceleratedWidget w) {
  DCHECK(display_);
  // Event Converter should be already initialized unless we are in gpu process
  // side.
  if (!event_converter_) {
    event_converter_ = new RemoteEventDispatcher();
    display_->StartProcessingEvents();
  }

  return (gfx::AcceleratedWidget)display_->RealizeAcceleratedWidget(w);
}

void OzoneDisplay::DelayedInitialization(OzoneDisplay* display) {
  display->channel_ = new OzoneDisplayChannel();
  display->channel_->Register();
}

void OzoneDisplay::Terminate() {
  if (!event_converter_ && !desktop_screen_)
    return;

  if (spec_)
    delete[] spec_;

  delete channel_;
  if (desktop_screen_) {
    delete desktop_screen_;
    desktop_screen_ = NULL;
  }

  delete display_;
  if (event_converter_) {
    delete event_converter_;
    event_converter_ = NULL;
  }
}

// TODO(vignatti): GPU process conceptually is the one that deals with hardware
// details and therefore we assume that the window system connection should
// happen in there only. There's a glitch with Chrome though, that creates its
// frame contents requiring access to the window system, before the GPU process
// even exists. In other words, Chrome runs
// BrowserMainLoop::PreMainMessageLoopRun before GpuProcessHost::Get. If the
// assumption of window system connection belongs to the GPU process is valid,
// then I believe this Chrome behavior needs to be addressed upstream.
//
// For now, we create another window system connection to look ahead the needed
// output properties that Chrome (among others) need and then close right after
// that. I haven't measured how long it takes to open a Wayland connection,
// listen all the interface the compositor sends and close it, but _for_ _sure_
// it slows down the overall initialization time of Chromium targets.
// Therefore, this is something that has to be solved in the future, moving all
// Chrome tasks after GPU process is created.
//
void OzoneDisplay::LookAheadOutputGeometry() {
  DCHECK(event_converter_);
  WaylandDisplay disp_(WaylandDisplay::RegisterOutputOnly);
  CHECK(disp_.display()) << "Ozone: Wayland server connection not found.";

  while (disp_.PrimaryScreen()->Geometry().IsEmpty())
    disp_.SyncDisplay();

  EventConverterInProcess* coverter =
      static_cast<EventConverterInProcess*>(event_converter_);
  DCHECK(coverter->GetOutputChangeObserver());

  unsigned width = disp_.PrimaryScreen()->Geometry().width();
  unsigned height = disp_.PrimaryScreen()->Geometry().height();
  coverter->GetOutputChangeObserver()->OnOutputSizeChanged(width, height);
}

}  // namespace ozonewayland
<|endoftext|>