<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include <string>
#include <utility>
#include <vector>

#include "atom/browser/api/atom_api_window.h"
#include "atom/browser/native_window.h"
#include "atom/browser/ui/certificate_trust.h"
#include "atom/browser/ui/file_dialog.h"
#include "atom/browser/ui/message_box.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "native_mate/dictionary.h"

#include "atom/common/node_includes.h"

namespace mate {

template<>
struct Converter<file_dialog::Filter> {
  static bool FromV8(v8::Isolate* isolate,
                     v8::Local<v8::Value> val,
                     file_dialog::Filter* out) {
    mate::Dictionary dict;
    if (!ConvertFromV8(isolate, val, &dict))
      return false;
    if (!dict.Get("name", &(out->first)))
      return false;
    if (!dict.Get("extensions", &(out->second)))
      return false;
    return true;
  }
};

template<>
struct Converter<file_dialog::DialogSettings> {
  static bool FromV8(v8::Isolate* isolate,
                     v8::Local<v8::Value> val,
                     file_dialog::DialogSettings* out) {
    mate::Dictionary dict;
    if (!ConvertFromV8(isolate, val, &dict))
      return false;
    dict.Get("window", &(out->parent_window));
    dict.Get("title", &(out->title));
    dict.Get("message", &(out->message));
    dict.Get("buttonLabel", &(out->button_label));
    dict.Get("nameFieldLabel", &(out->name_field_label));
    dict.Get("defaultPath", &(out->default_path));
    dict.Get("filters", &(out->filters));
    dict.Get("properties", &(out->properties));
    dict.Get("showsTagField", &(out->shows_tag_field));
    return true;
  }
};

}  // namespace mate

namespace {

void ShowMessageBox(int type,
                    const std::vector<std::string>& buttons,
                    int default_id,
                    int cancel_id,
                    int options,
                    const std::string& title,
                    const std::string& message,
                    const std::string& detail,
                    const std::string& checkbox_label,
                    bool checkbox_checked,
                    const gfx::ImageSkia& icon,
                    atom::NativeWindow* window,
                    mate::Arguments* args) {
  v8::Local<v8::Value> peek = args->PeekNext();
  atom::MessageBoxCallback callback;
  if (mate::Converter<atom::MessageBoxCallback>::FromV8(args->isolate(),
                                                        peek,
                                                        &callback)) {
    atom::ShowMessageBox(window, (atom::MessageBoxType)type, buttons,
                         default_id, cancel_id, options, title, message, detail,
                         checkbox_label, checkbox_checked, icon, callback);
  } else {
    int chosen = atom::ShowMessageBox(window, (atom::MessageBoxType)type,
                                      buttons, default_id, cancel_id,
                                      options, title, message, detail, icon);
    args->Return(chosen);
  }
}

void ShowOpenDialog(const file_dialog::DialogSettings& settings,
                    mate::Arguments* args) {
  v8::Local<v8::Value> peek = args->PeekNext();
  file_dialog::OpenDialogCallback callback;
  if (mate::Converter<file_dialog::OpenDialogCallback>::FromV8(args->isolate(),
                                                               peek,
                                                               &callback)) {
    file_dialog::ShowOpenDialog(settings, callback);
  } else {
    std::vector<base::FilePath> paths;
    if (file_dialog::ShowOpenDialog(settings, &paths))
      args->Return(paths);
  }
}

void ShowSaveDialog(const file_dialog::DialogSettings& settings,
                    mate::Arguments* args) {
  v8::Local<v8::Value> peek = args->PeekNext();
  file_dialog::SaveDialogCallback callback;
  if (mate::Converter<file_dialog::SaveDialogCallback>::FromV8(args->isolate(),
                                                               peek,
                                                               &callback)) {
    file_dialog::ShowSaveDialog(settings, callback);
  } else {
    base::FilePath path;
    if (file_dialog::ShowSaveDialog(settings, &path))
      args->Return(path);
  }
}

#if defined(OS_MACOSX)
void ShowCertificateTrust(atom::NativeWindow* parent_window,
                          const scoped_refptr<net::X509Certificate>& cert,
                          std::string message,
                          const certificate_trust::ShowTrustCallback& callback,
                          mate::Arguments* args) {
  certificate_trust::ShowCertificateTrust(parent_window, cert, message, callback);
}
#endif

void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
                v8::Local<v8::Context> context, void* priv) {
  mate::Dictionary dict(context->GetIsolate(), exports);
  dict.SetMethod("showMessageBox", &ShowMessageBox);
  dict.SetMethod("showErrorBox", &atom::ShowErrorBox);
  dict.SetMethod("showOpenDialog", &ShowOpenDialog);
  dict.SetMethod("showSaveDialog", &ShowSaveDialog);
#if defined(OS_MACOSX)
  dict.SetMethod("showCertificateTrustDialog", &ShowCertificateTrust);
#endif
}

}  // namespace

NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_dialog, Initialize)
<commit_msg>Linebreak to keep the linter happy<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include <string>
#include <utility>
#include <vector>

#include "atom/browser/api/atom_api_window.h"
#include "atom/browser/native_window.h"
#include "atom/browser/ui/certificate_trust.h"
#include "atom/browser/ui/file_dialog.h"
#include "atom/browser/ui/message_box.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "native_mate/dictionary.h"

#include "atom/common/node_includes.h"

namespace mate {

template<>
struct Converter<file_dialog::Filter> {
  static bool FromV8(v8::Isolate* isolate,
                     v8::Local<v8::Value> val,
                     file_dialog::Filter* out) {
    mate::Dictionary dict;
    if (!ConvertFromV8(isolate, val, &dict))
      return false;
    if (!dict.Get("name", &(out->first)))
      return false;
    if (!dict.Get("extensions", &(out->second)))
      return false;
    return true;
  }
};

template<>
struct Converter<file_dialog::DialogSettings> {
  static bool FromV8(v8::Isolate* isolate,
                     v8::Local<v8::Value> val,
                     file_dialog::DialogSettings* out) {
    mate::Dictionary dict;
    if (!ConvertFromV8(isolate, val, &dict))
      return false;
    dict.Get("window", &(out->parent_window));
    dict.Get("title", &(out->title));
    dict.Get("message", &(out->message));
    dict.Get("buttonLabel", &(out->button_label));
    dict.Get("nameFieldLabel", &(out->name_field_label));
    dict.Get("defaultPath", &(out->default_path));
    dict.Get("filters", &(out->filters));
    dict.Get("properties", &(out->properties));
    dict.Get("showsTagField", &(out->shows_tag_field));
    return true;
  }
};

}  // namespace mate

namespace {

void ShowMessageBox(int type,
                    const std::vector<std::string>& buttons,
                    int default_id,
                    int cancel_id,
                    int options,
                    const std::string& title,
                    const std::string& message,
                    const std::string& detail,
                    const std::string& checkbox_label,
                    bool checkbox_checked,
                    const gfx::ImageSkia& icon,
                    atom::NativeWindow* window,
                    mate::Arguments* args) {
  v8::Local<v8::Value> peek = args->PeekNext();
  atom::MessageBoxCallback callback;
  if (mate::Converter<atom::MessageBoxCallback>::FromV8(args->isolate(),
                                                        peek,
                                                        &callback)) {
    atom::ShowMessageBox(window, (atom::MessageBoxType)type, buttons,
                         default_id, cancel_id, options, title, message, detail,
                         checkbox_label, checkbox_checked, icon, callback);
  } else {
    int chosen = atom::ShowMessageBox(window, (atom::MessageBoxType)type,
                                      buttons, default_id, cancel_id,
                                      options, title, message, detail, icon);
    args->Return(chosen);
  }
}

void ShowOpenDialog(const file_dialog::DialogSettings& settings,
                    mate::Arguments* args) {
  v8::Local<v8::Value> peek = args->PeekNext();
  file_dialog::OpenDialogCallback callback;
  if (mate::Converter<file_dialog::OpenDialogCallback>::FromV8(args->isolate(),
                                                               peek,
                                                               &callback)) {
    file_dialog::ShowOpenDialog(settings, callback);
  } else {
    std::vector<base::FilePath> paths;
    if (file_dialog::ShowOpenDialog(settings, &paths))
      args->Return(paths);
  }
}

void ShowSaveDialog(const file_dialog::DialogSettings& settings,
                    mate::Arguments* args) {
  v8::Local<v8::Value> peek = args->PeekNext();
  file_dialog::SaveDialogCallback callback;
  if (mate::Converter<file_dialog::SaveDialogCallback>::FromV8(args->isolate(),
                                                               peek,
                                                               &callback)) {
    file_dialog::ShowSaveDialog(settings, callback);
  } else {
    base::FilePath path;
    if (file_dialog::ShowSaveDialog(settings, &path))
      args->Return(path);
  }
}

#if defined(OS_MACOSX)
void ShowCertificateTrust(atom::NativeWindow* parent_window,
                          const scoped_refptr<net::X509Certificate>& cert,
                          std::string message,
                          const certificate_trust::ShowTrustCallback& callback,
                          mate::Arguments* args) {
  certificate_trust::ShowCertificateTrust(parent_window, cert,
                                          message, callback);
}
#endif

void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
                v8::Local<v8::Context> context, void* priv) {
  mate::Dictionary dict(context->GetIsolate(), exports);
  dict.SetMethod("showMessageBox", &ShowMessageBox);
  dict.SetMethod("showErrorBox", &atom::ShowErrorBox);
  dict.SetMethod("showOpenDialog", &ShowOpenDialog);
  dict.SetMethod("showSaveDialog", &ShowSaveDialog);
#if defined(OS_MACOSX)
  dict.SetMethod("showCertificateTrustDialog", &ShowCertificateTrust);
#endif
}

}  // namespace

NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_dialog, Initialize)
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "common/sg/SceneGraph.h"
#include "common/sg/Renderer.h"
#include "common/sg/importer/Importer.h"
#include "ospcommon/FileName.h"
#include "ospcommon/networking/Socket.h"
#include "ospcommon/vec.h"

#include "sg/geometry/TriangleMesh.h"

#include "widgets/imguiViewerSg.h"
#include <sstream>

namespace dw {

  struct ServiceInfo {
    /* constructor that initializes everything to default values */
    ServiceInfo()
      : totalPixelsInWall(-1,-1),
        mpiPortName("<value not set>")
    {}

    /*! total pixels in the entire display wall, across all
      indvididual displays, and including bezels (future versios
      will allow to render to smaller resolutions, too - and have
      the clients upscale this - but for now the client(s) have to
      render at exactly this resolution */
    ospcommon::vec2i totalPixelsInWall;

    /*! the MPI port name that the service is listening on client
      connections for (ie, the one to use with
      client::establishConnection) */
    std::string mpiPortName;

    /*! whether this runs in stereo mode */
    int stereo;

    /*! read a service info from a given hostName:port. The service
      has to already be running on that port

      Note this may throw a std::runtime_error if the connection
      cannot be established
    */
    void getFrom(const std::string &hostName,
                 const int portNo);
  };
  /*! read a service info from a given hostName:port. The service
    has to already be running on that port */
  void ServiceInfo::getFrom(const std::string &hostName,
                            const int portNo)
  {
    ospcommon::socket_t sock = ospcommon::connect(hostName.c_str(),portNo);
    if (!sock)
      throw std::runtime_error("could not create display wall connection!");

    mpiPortName = read_string(sock);
    totalPixelsInWall.x = read_int(sock);
    totalPixelsInWall.y = read_int(sock);
    stereo = read_int(sock);
    close(sock);
  }
}

using namespace ospcommon;
using namespace ospray;

std::vector<std::string> files;
std::string initialRendererType;
bool addPlane = true;
bool debug = false;
bool fullscreen = false;
bool print = false;

void parseCommandLine(int ac, const char **&av)
{
  for (int i = 1; i < ac; i++) {
    const std::string arg = av[i];
    if (arg == "-np" || arg == "--no-plane") {
      addPlane = false;
    } else if (arg == "-d" || arg == "--debug") {
      debug = true;
    } else if (arg == "-r" || arg == "--renderer") {
      initialRendererType = av[++i];
    } else if (arg == "-m" || arg == "--module") {
      ospLoadModule(av[++i]);
    } else if (arg == "--print") {
      print=true;
    } else if (arg == "--fullscreen") {
      fullscreen = true;
    } else if (arg[0] != '-') {
      files.push_back(av[i]);
    }
  }
}

//parse command line arguments containing the format:
//  -nodeName:...:nodeName=value,value,value
void parseCommandLineSG(int ac, const char **&av, sg::Node &root)
{
  for(int i=1;i < ac; i++) {
    std::string arg(av[i]);
    size_t f;
    std::string value("");
    if (arg.size() < 2 || arg[0] != '-')
      continue;

    while ((f = arg.find(":")) != std::string::npos ||
           (f = arg.find(",")) != std::string::npos) {
      arg[f] = ' ';
    }

    f = arg.find("=");
    if (f != std::string::npos)
      value = arg.substr(f+1,arg.size());

    if (value != "") {
      std::stringstream ss;
      ss << arg.substr(1,f-1);
      std::string child;
      std::reference_wrapper<sg::Node> node_ref = root;
      while (ss >> child) {
        node_ref = node_ref.get().childRecursive(child);
      }
      auto &node = node_ref.get();
      //Carson: TODO: reimplement with a way of determining type of node value
      //  currently relies on exception on value cast
      try {
        node.valueAs<std::string>();
        node.setValue(value);
      } catch(...) {};
      try {
        std::stringstream vals(value);
        float x;
        vals >> x;
        node.valueAs<float>();
        node.setValue(x);
      } catch(...) {}
      try {
        std::stringstream vals(value);
        int x;
        vals >> x;
        node.valueAs<int>();
        node.setValue(x);
      } catch(...) {}
      try {
        std::stringstream vals(value);
        bool x;
        vals >> x;
        node.valueAs<bool>();
        node.setValue(x);
      } catch(...) {}
      try {
        std::stringstream vals(value);
        float x,y,z;
        vals >> x >> y >> z;
        node.valueAs<ospcommon::vec3f>();
        node.setValue(ospcommon::vec3f(x,y,z));
      } catch(...) {}
      try {
        std::stringstream vals(value);
        int x,y;
        vals >> x >> y;
        node.valueAs<ospcommon::vec2i>();
        node.setValue(ospcommon::vec2i(x,y));
      } catch(...) {}
    }
  }
}

void addPlaneToScene(sg::Node& world)
{
  auto bbox = world.bounds();
  if (bbox.empty()) {
    bbox.lower = vec3f(-5,0,-5);
    bbox.upper = vec3f(5,10,5);
  }

  osp::vec3f *vertices = new osp::vec3f[4];
  float ps = bbox.upper.x*3.f;
  float py = bbox.lower.z-.1f;

  py = bbox.lower.y+0.01f;
  vertices[0] = osp::vec3f{-ps, py, -ps};
  vertices[1] = osp::vec3f{-ps, py, ps};
  vertices[2] = osp::vec3f{ps, py, -ps};
  vertices[3] = osp::vec3f{ps, py, ps};
  auto position = std::make_shared<sg::DataArray3f>((vec3f*)&vertices[0],
                                                    size_t(4),
                                                    false);
  osp::vec3i *triangles = new osp::vec3i[2];
  triangles[0] = osp::vec3i{0,1,2};
  triangles[1] = osp::vec3i{1,2,3};
  auto index = std::make_shared<sg::DataArray3i>((vec3i*)&triangles[0],
                                                 size_t(2),
                                                 false);
  auto &plane = world.createChild("plane", "Instance");
  auto &mesh  = plane.child("model").createChild("mesh", "TriangleMesh");

  std::shared_ptr<sg::TriangleMesh> sg_plane =
    std::static_pointer_cast<sg::TriangleMesh>(mesh.shared_from_this());
  sg_plane->vertex = position;
  sg_plane->index = index;
  auto &planeMaterial = mesh["material"];
  planeMaterial["Kd"].setValue(vec3f(0.5f));
  planeMaterial["Ks"].setValue(vec3f(0.6f));
  planeMaterial["Ns"].setValue(2.f);
}

int main(int ac, const char **av)
{
  int init_error = ospInit(&ac, av);
  if (init_error != OSP_NO_ERROR) {
    std::cerr << "FATAL ERROR DURING INITIALIZATION!" << std::endl;
    return init_error;
  }

  auto device = ospGetCurrentDevice();
  ospDeviceSetStatusFunc(device,
                         [](const char *msg) { std::cout << msg; });

  ospDeviceSetErrorFunc(device,
                        [](OSPError e, const char *msg) {
                          std::cout << "OSPRAY ERROR [" << e << "]: "
                                    << msg << std::endl;
                          std::exit(1);
                        });

#ifdef _WIN32
  // TODO: Why do we not have the sg symbols already available for us
  // since we link against it?
  loadLibrary("ospray_sg");
#endif

  ospray::imgui3D::init(&ac,av);

  parseCommandLine(ac, av);

  auto renderer_ptr = sg::createNode("renderer", "Renderer");
  auto &renderer = *renderer_ptr;
  /*! the renderer we use for rendering on the display wall; null if
      no dw available */
  std::shared_ptr<sg::Node> rendererDW;
  /*! display wall service info - ignore if 'rendererDW' is null */
  dw::ServiceInfo dwService;

  const char *dwNodeName = getenv("DISPLAY_WALL");
  if (dwNodeName) {
    std::cout << "#######################################################"
              << std::endl;
    std::cout << "found a DISPLAY_WALL environment variable ...." << std::endl;
    std::cout << "trying to connect to display wall service on "
              << dwNodeName << ":2903" << std::endl;

    dwService.getFrom(dwNodeName,2903);
    std::cout << "found display wall service on MPI port "
              << dwService.mpiPortName << std::endl;
    std::cout << "#######################################################"
              << std::endl;
    rendererDW = sg::createNode("renderer", "Renderer");
  }

  renderer["shadowsEnabled"].setValue(true);
  renderer["aoSamples"].setValue(1);
  renderer["camera"]["fovy"].setValue(60.f);

  if (rendererDW.get()) {
    rendererDW->child("shadowsEnabled").setValue(true);
    rendererDW->child("aoSamples").setValue(1);
    rendererDW->child("camera")["fovy"].setValue(60.f);
  }

  if (!initialRendererType.empty()) {
    renderer["rendererType"].setValue(initialRendererType);
    if (rendererDW.get()) {
      rendererDW->child("rendererType").setValue(initialRendererType);
    }
  }

  auto &lights = renderer["lights"];

  auto &sun = lights.createChild("sun", "DirectionalLight");
  sun["color"].setValue(vec3f(1.f,232.f/255.f,166.f/255.f));
  sun["direction"].setValue(vec3f(0.462f,-1.f,-.1f));
  sun["intensity"].setValue(1.5f);

  auto &bounce = lights.createChild("bounce", "DirectionalLight");
  bounce["color"].setValue(vec3f(127.f/255.f,178.f/255.f,255.f/255.f));
  bounce["direction"].setValue(vec3f(-.93,-.54f,-.605f));
  bounce["intensity"].setValue(0.25f);

  auto &ambient = lights.createChild("ambient", "AmbientLight");
  ambient["intensity"].setValue(0.9f);
  ambient["color"].setValue(vec3f(174.f/255.f,218.f/255.f,255.f/255.f));

  auto &world = renderer["world"];

  for (auto file : files) {
    FileName fn = file;
    auto importerNode_ptr = sg::createNode(fn.name(), "Importer");
    auto &importerNode = *importerNode_ptr;
    importerNode["fileName"].setValue(fn.str());
    world += importerNode_ptr;
  }

  parseCommandLineSG(ac, av, renderer);

  if (rendererDW.get()) {
    rendererDW->setChild("world",  renderer["world"].shared_from_this());
    rendererDW->setChild("lights", renderer["lights"].shared_from_this());

    auto &frameBuffer = rendererDW->child("frameBuffer");
    frameBuffer["size"].setValue(dwService.totalPixelsInWall);
    frameBuffer["displayWall"].setValue(dwService.mpiPortName);
  }

  if (print || debug)
    renderer.traverse("print");

  sg::writeOSPSG(renderer_ptr,
     "/Users/cbrownle/git/osprayDev/build/test.osg");

  ospray::ImGuiViewerSg window(renderer_ptr, rendererDW);

  if (addPlane) addPlaneToScene(world);

  window.create("OSPRay Example Viewer App", fullscreen);

  ospray::imgui3D::run();
}

<commit_msg>removing debug write<commit_after>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "common/sg/SceneGraph.h"
#include "common/sg/Renderer.h"
#include "common/sg/importer/Importer.h"
#include "ospcommon/FileName.h"
#include "ospcommon/networking/Socket.h"
#include "ospcommon/vec.h"

#include "sg/geometry/TriangleMesh.h"

#include "widgets/imguiViewerSg.h"
#include <sstream>

namespace dw {

  struct ServiceInfo {
    /* constructor that initializes everything to default values */
    ServiceInfo()
      : totalPixelsInWall(-1,-1),
        mpiPortName("<value not set>")
    {}

    /*! total pixels in the entire display wall, across all
      indvididual displays, and including bezels (future versios
      will allow to render to smaller resolutions, too - and have
      the clients upscale this - but for now the client(s) have to
      render at exactly this resolution */
    ospcommon::vec2i totalPixelsInWall;

    /*! the MPI port name that the service is listening on client
      connections for (ie, the one to use with
      client::establishConnection) */
    std::string mpiPortName;

    /*! whether this runs in stereo mode */
    int stereo;

    /*! read a service info from a given hostName:port. The service
      has to already be running on that port

      Note this may throw a std::runtime_error if the connection
      cannot be established
    */
    void getFrom(const std::string &hostName,
                 const int portNo);
  };
  /*! read a service info from a given hostName:port. The service
    has to already be running on that port */
  void ServiceInfo::getFrom(const std::string &hostName,
                            const int portNo)
  {
    ospcommon::socket_t sock = ospcommon::connect(hostName.c_str(),portNo);
    if (!sock)
      throw std::runtime_error("could not create display wall connection!");

    mpiPortName = read_string(sock);
    totalPixelsInWall.x = read_int(sock);
    totalPixelsInWall.y = read_int(sock);
    stereo = read_int(sock);
    close(sock);
  }
}

using namespace ospcommon;
using namespace ospray;

std::vector<std::string> files;
std::string initialRendererType;
bool addPlane = true;
bool debug = false;
bool fullscreen = false;
bool print = false;

void parseCommandLine(int ac, const char **&av)
{
  for (int i = 1; i < ac; i++) {
    const std::string arg = av[i];
    if (arg == "-np" || arg == "--no-plane") {
      addPlane = false;
    } else if (arg == "-d" || arg == "--debug") {
      debug = true;
    } else if (arg == "-r" || arg == "--renderer") {
      initialRendererType = av[++i];
    } else if (arg == "-m" || arg == "--module") {
      ospLoadModule(av[++i]);
    } else if (arg == "--print") {
      print=true;
    } else if (arg == "--fullscreen") {
      fullscreen = true;
    } else if (arg[0] != '-') {
      files.push_back(av[i]);
    }
  }
}

//parse command line arguments containing the format:
//  -nodeName:...:nodeName=value,value,value
void parseCommandLineSG(int ac, const char **&av, sg::Node &root)
{
  for(int i=1;i < ac; i++) {
    std::string arg(av[i]);
    size_t f;
    std::string value("");
    if (arg.size() < 2 || arg[0] != '-')
      continue;

    while ((f = arg.find(":")) != std::string::npos ||
           (f = arg.find(",")) != std::string::npos) {
      arg[f] = ' ';
    }

    f = arg.find("=");
    if (f != std::string::npos)
      value = arg.substr(f+1,arg.size());

    if (value != "") {
      std::stringstream ss;
      ss << arg.substr(1,f-1);
      std::string child;
      std::reference_wrapper<sg::Node> node_ref = root;
      while (ss >> child) {
        node_ref = node_ref.get().childRecursive(child);
      }
      auto &node = node_ref.get();
      //Carson: TODO: reimplement with a way of determining type of node value
      //  currently relies on exception on value cast
      try {
        node.valueAs<std::string>();
        node.setValue(value);
      } catch(...) {};
      try {
        std::stringstream vals(value);
        float x;
        vals >> x;
        node.valueAs<float>();
        node.setValue(x);
      } catch(...) {}
      try {
        std::stringstream vals(value);
        int x;
        vals >> x;
        node.valueAs<int>();
        node.setValue(x);
      } catch(...) {}
      try {
        std::stringstream vals(value);
        bool x;
        vals >> x;
        node.valueAs<bool>();
        node.setValue(x);
      } catch(...) {}
      try {
        std::stringstream vals(value);
        float x,y,z;
        vals >> x >> y >> z;
        node.valueAs<ospcommon::vec3f>();
        node.setValue(ospcommon::vec3f(x,y,z));
      } catch(...) {}
      try {
        std::stringstream vals(value);
        int x,y;
        vals >> x >> y;
        node.valueAs<ospcommon::vec2i>();
        node.setValue(ospcommon::vec2i(x,y));
      } catch(...) {}
    }
  }
}

void addPlaneToScene(sg::Node& world)
{
  auto bbox = world.bounds();
  if (bbox.empty()) {
    bbox.lower = vec3f(-5,0,-5);
    bbox.upper = vec3f(5,10,5);
  }

  osp::vec3f *vertices = new osp::vec3f[4];
  float ps = bbox.upper.x*3.f;
  float py = bbox.lower.z-.1f;

  py = bbox.lower.y+0.01f;
  vertices[0] = osp::vec3f{-ps, py, -ps};
  vertices[1] = osp::vec3f{-ps, py, ps};
  vertices[2] = osp::vec3f{ps, py, -ps};
  vertices[3] = osp::vec3f{ps, py, ps};
  auto position = std::make_shared<sg::DataArray3f>((vec3f*)&vertices[0],
                                                    size_t(4),
                                                    false);
  osp::vec3i *triangles = new osp::vec3i[2];
  triangles[0] = osp::vec3i{0,1,2};
  triangles[1] = osp::vec3i{1,2,3};
  auto index = std::make_shared<sg::DataArray3i>((vec3i*)&triangles[0],
                                                 size_t(2),
                                                 false);
  auto &plane = world.createChild("plane", "Instance");
  auto &mesh  = plane.child("model").createChild("mesh", "TriangleMesh");

  std::shared_ptr<sg::TriangleMesh> sg_plane =
    std::static_pointer_cast<sg::TriangleMesh>(mesh.shared_from_this());
  sg_plane->vertex = position;
  sg_plane->index = index;
  auto &planeMaterial = mesh["material"];
  planeMaterial["Kd"].setValue(vec3f(0.5f));
  planeMaterial["Ks"].setValue(vec3f(0.6f));
  planeMaterial["Ns"].setValue(2.f);
}

int main(int ac, const char **av)
{
  int init_error = ospInit(&ac, av);
  if (init_error != OSP_NO_ERROR) {
    std::cerr << "FATAL ERROR DURING INITIALIZATION!" << std::endl;
    return init_error;
  }

  auto device = ospGetCurrentDevice();
  ospDeviceSetStatusFunc(device,
                         [](const char *msg) { std::cout << msg; });

  ospDeviceSetErrorFunc(device,
                        [](OSPError e, const char *msg) {
                          std::cout << "OSPRAY ERROR [" << e << "]: "
                                    << msg << std::endl;
                          std::exit(1);
                        });

#ifdef _WIN32
  // TODO: Why do we not have the sg symbols already available for us
  // since we link against it?
  loadLibrary("ospray_sg");
#endif

  ospray::imgui3D::init(&ac,av);

  parseCommandLine(ac, av);

  auto renderer_ptr = sg::createNode("renderer", "Renderer");
  auto &renderer = *renderer_ptr;
  /*! the renderer we use for rendering on the display wall; null if
      no dw available */
  std::shared_ptr<sg::Node> rendererDW;
  /*! display wall service info - ignore if 'rendererDW' is null */
  dw::ServiceInfo dwService;

  const char *dwNodeName = getenv("DISPLAY_WALL");
  if (dwNodeName) {
    std::cout << "#######################################################"
              << std::endl;
    std::cout << "found a DISPLAY_WALL environment variable ...." << std::endl;
    std::cout << "trying to connect to display wall service on "
              << dwNodeName << ":2903" << std::endl;

    dwService.getFrom(dwNodeName,2903);
    std::cout << "found display wall service on MPI port "
              << dwService.mpiPortName << std::endl;
    std::cout << "#######################################################"
              << std::endl;
    rendererDW = sg::createNode("renderer", "Renderer");
  }

  renderer["shadowsEnabled"].setValue(true);
  renderer["aoSamples"].setValue(1);
  renderer["camera"]["fovy"].setValue(60.f);

  if (rendererDW.get()) {
    rendererDW->child("shadowsEnabled").setValue(true);
    rendererDW->child("aoSamples").setValue(1);
    rendererDW->child("camera")["fovy"].setValue(60.f);
  }

  if (!initialRendererType.empty()) {
    renderer["rendererType"].setValue(initialRendererType);
    if (rendererDW.get()) {
      rendererDW->child("rendererType").setValue(initialRendererType);
    }
  }

  auto &lights = renderer["lights"];

  auto &sun = lights.createChild("sun", "DirectionalLight");
  sun["color"].setValue(vec3f(1.f,232.f/255.f,166.f/255.f));
  sun["direction"].setValue(vec3f(0.462f,-1.f,-.1f));
  sun["intensity"].setValue(1.5f);

  auto &bounce = lights.createChild("bounce", "DirectionalLight");
  bounce["color"].setValue(vec3f(127.f/255.f,178.f/255.f,255.f/255.f));
  bounce["direction"].setValue(vec3f(-.93,-.54f,-.605f));
  bounce["intensity"].setValue(0.25f);

  auto &ambient = lights.createChild("ambient", "AmbientLight");
  ambient["intensity"].setValue(0.9f);
  ambient["color"].setValue(vec3f(174.f/255.f,218.f/255.f,255.f/255.f));

  auto &world = renderer["world"];

  for (auto file : files) {
    FileName fn = file;
    auto importerNode_ptr = sg::createNode(fn.name(), "Importer");
    auto &importerNode = *importerNode_ptr;
    importerNode["fileName"].setValue(fn.str());
    world += importerNode_ptr;
  }

  parseCommandLineSG(ac, av, renderer);

  if (rendererDW.get()) {
    rendererDW->setChild("world",  renderer["world"].shared_from_this());
    rendererDW->setChild("lights", renderer["lights"].shared_from_this());

    auto &frameBuffer = rendererDW->child("frameBuffer");
    frameBuffer["size"].setValue(dwService.totalPixelsInWall);
    frameBuffer["displayWall"].setValue(dwService.mpiPortName);
  }

  if (print || debug)
    renderer.traverse("print");

  ospray::ImGuiViewerSg window(renderer_ptr, rendererDW);

  if (addPlane) addPlaneToScene(world);

  window.create("OSPRay Example Viewer App", fullscreen);

  ospray::imgui3D::run();
}

<|endoftext|>


<commit_before>#include "splash.h"
#include "ui_splash.h"

#include "util.h"
#include "version.h"

Splash::Splash(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Splash)
{
// general setup
    ui->setupUi(this);
	setWindowTitle(tr("LitecoinPlus") + " - " + QString::fromStdString(CLIENT_BUILD));

// adds a timer that randomly replace background
	timer = new QTimer(this);
	timer->setInterval(59000);
	connect(timer, SIGNAL(timeout()), this, SLOT(updateTimer()));
	timer->start();

// sets background once
	setRandomBackground();
}

void Splash::showSplash()
{
    // Center startup window in the screen
	QRect screenGeometry = QApplication::desktop()->screenGeometry();
	int x = 480;//(screenGeometry.width() - width()) / 2;
	int y = 320;//(screenGeometry.height() - height()) / 2;
	move(x, y);
    show();
}

void Splash::hideSplash()
{
	timer->stop();
	hide();
}

void Splash::systemOnTop()
{
	setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);
	setWindowModality(Qt::ApplicationModal);
}

void Splash::setMessage(const char *message)
{
// update the message
	ui->info->setText("" + tr(message) + "");
	QApplication::instance()->processEvents();
	Sleep(1);
	QApplication::instance()->processEvents();
}

void Splash::updateTimer()
{
	setRandomBackground();
}

void Splash::setRandomBackground()
{
// sets a random background each time is called
	int v = (time(NULL)) % 4 + 1;
	char s[32];
	sprintf(s, ":/images/startup%d", v);
	QPixmap bkgnd(s);
    bkgnd = bkgnd.scaled(this->size(), Qt::IgnoreAspectRatio);
    QPalette palette;
    palette.setBrush(QPalette::Background, bkgnd);
    this->setPalette(palette);
}

void Splash::closeEvent(QCloseEvent *event)
{
    event->ignore();
}

Splash::~Splash()
{
    delete ui;
}

<commit_msg>small spash screen edit<commit_after>#include "splash.h"
#include "ui_splash.h"

#include "util.h"
#include "version.h"

Splash::Splash(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Splash)
{
// general setup
    ui->setupUi(this);
	setWindowTitle(tr("Bitcoin sCrypt") + " - " + QString::fromStdString(CLIENT_BUILD));

// adds a timer that randomly replace background
	timer = new QTimer(this);
	timer->setInterval(59000);
	connect(timer, SIGNAL(timeout()), this, SLOT(updateTimer()));
	timer->start();

// sets background once
	setRandomBackground();
}

void Splash::showSplash()
{
    // Center startup window in the screen
	QRect screenGeometry = QApplication::desktop()->screenGeometry();
	int x = 478;//(screenGeometry.width() - width()) / 2;
	int y = 320;//(screenGeometry.height() - height()) / 2;
	move(x, y);
    show();
}

void Splash::hideSplash()
{
	timer->stop();
	hide();
}

void Splash::systemOnTop()
{
	setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);
	setWindowModality(Qt::ApplicationModal);
}

void Splash::setMessage(const char *message)
{
// update the message
	ui->info->setText("" + tr(message) + "");
	QApplication::instance()->processEvents();
	Sleep(1);
	QApplication::instance()->processEvents();
}

void Splash::updateTimer()
{
	setRandomBackground();
}

void Splash::setRandomBackground()
{
// sets a random background each time is called
	int v = (time(NULL)) % 4 + 1;
	char s[32];
	sprintf(s, ":/images/startup%d", v);
	QPixmap bkgnd(s);
    bkgnd = bkgnd.scaled(this->size(), Qt::IgnoreAspectRatio);
    QPalette palette;
    palette.setBrush(QPalette::Background, bkgnd);
    this->setPalette(palette);
}

void Splash::closeEvent(QCloseEvent *event)
{
    event->ignore();
}

Splash::~Splash()
{
    delete ui;
}

<|endoftext|>


<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2020 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// C++ includes
#include <algorithm> // for std::fill
#include <cstdlib> // *must* precede <cmath> for proper std:abs() on PGI, Sun Studio CC
#include <cmath>    // for sqrt

// Local Includes
#include "libmesh/libmesh_common.h"
#include "libmesh/kelly_error_estimator.h"
#include "libmesh/error_vector.h"
#include "libmesh/fe_base.h"
#include "libmesh/libmesh_logging.h"
#include "libmesh/elem.h"
#include "libmesh/system.h"
#include "libmesh/dense_vector.h"
#include "libmesh/tensor_tools.h"
#include "libmesh/enum_error_estimator_type.h"
#include "libmesh/enum_norm_type.h"

namespace libMesh
{

KellyErrorEstimator::KellyErrorEstimator() :
  JumpErrorEstimator(),
  _bc_function(nullptr)
{
  error_norm = H1_SEMINORM;
}

ErrorEstimatorType
KellyErrorEstimator::type() const
{
  return KELLY;
}

void
KellyErrorEstimator::init_context(FEMContext & c)
{
  const unsigned int n_vars = c.n_vars();
  for (unsigned int v=0; v<n_vars; v++)
    {
      // Possibly skip this variable
      if (error_norm.weight(v) == 0.0) continue;

      // FIXME: Need to generalize this to vector-valued elements. [PB]
      FEBase * side_fe = nullptr;

      const std::set<unsigned char> & elem_dims =
        c.elem_dimensions();

      for (const auto & dim : elem_dims)
        {
          fine_context->get_side_fe( v, side_fe, dim );

          // We'll need gradients on both sides for flux jump computation
          side_fe->get_dphi();

          // But we only need normal vectors from one side
          if (&c != coarse_context.get())
            side_fe->get_normals();
        }
    }
}

void
KellyErrorEstimator::internal_side_integration ()
{
  const Elem & coarse_elem = coarse_context->get_elem();
  const Elem & fine_elem = fine_context->get_elem();

  FEBase * fe_fine = nullptr;
  fine_context->get_side_fe( var, fe_fine, fine_elem.dim() );

  FEBase * fe_coarse = nullptr;
  coarse_context->get_side_fe( var, fe_coarse, fine_elem.dim() );

  Real error = 1.e-30;
  unsigned int n_qp = fe_fine->n_quadrature_points();

  std::vector<std::vector<RealGradient>> dphi_coarse = fe_coarse->get_dphi();
  std::vector<std::vector<RealGradient>> dphi_fine = fe_fine->get_dphi();
  std::vector<Point> face_normals = fe_fine->get_normals();
  std::vector<Real> JxW_face = fe_fine->get_JxW();

  for (unsigned int qp=0; qp != n_qp; ++qp)
    {
      // Calculate solution gradients on fine and coarse elements
      // at this quadrature point
      Gradient
        grad_fine   = fine_context->side_gradient(var, qp),
        grad_coarse = coarse_context->side_gradient(var, qp);

      // Find the jump in the normal derivative
      // at this quadrature point
      const Number jump = (grad_fine - grad_coarse)*face_normals[qp];
      const Real jump2 = TensorTools::norm_sq(jump);

      // Accumulate the jump integral
      error += JxW_face[qp] * jump2;
    }

  // Add the h-weighted jump integral to each error term
  fine_error =
    error * fine_elem.hmax() * error_norm.weight(var);
  coarse_error =
    error * coarse_elem.hmax() * error_norm.weight(var);
}

bool
KellyErrorEstimator::boundary_side_integration ()
{
  const Elem & fine_elem = fine_context->get_elem();

  FEBase * fe_fine = nullptr;
  fine_context->get_side_fe( var, fe_fine, fine_elem.dim() );

  const std::string & var_name =
    fine_context->get_system().variable_name(var);

  std::vector<std::vector<RealGradient>> dphi_fine = fe_fine->get_dphi();
  std::vector<Point> face_normals = fe_fine->get_normals();
  std::vector<Real> JxW_face = fe_fine->get_JxW();
  std::vector<Point> qface_point = fe_fine->get_xyz();

  // The reinitialization also recomputes the locations of
  // the quadrature points on the side.  By checking if the
  // first quadrature point on the side is on a flux boundary
  // for a particular variable, we will determine if the whole
  // element is on a flux boundary (assuming quadrature points
  // are strictly contained in the side).
  if (this->_bc_function(fine_context->get_system(),
                         qface_point[0], var_name).first)
    {
      const Real h = fine_elem.hmax();

      // The number of quadrature points
      const unsigned int n_qp = fe_fine->n_quadrature_points();

      // The error contribution from this face
      Real error = 1.e-30;

      // loop over the integration points on the face.
      for (unsigned int qp=0; qp<n_qp; qp++)
        {
          // Value of the imposed flux BC at this quadrature point.
          const std::pair<bool,Real> flux_bc =
            this->_bc_function(fine_context->get_system(),
                               qface_point[qp], var_name);

          // Be sure the BC function still thinks we're on the
          // flux boundary.
          libmesh_assert_equal_to (flux_bc.first, true);

          // The solution gradient from each element
          Gradient grad_fine = fine_context->side_gradient(var, qp);

          // The difference between the desired BC and the approximate solution.
          const Number jump = flux_bc.second - grad_fine*face_normals[qp];

          // The flux jump squared.  If using complex numbers,
          // TensorTools::norm_sq(z) returns |z|^2, where |z| is the modulus of z.
          const Real jump2 = TensorTools::norm_sq(jump);

          // Integrate the error on the face.  The error is
          // scaled by an additional power of h, where h is
          // the maximum side length for the element.  This
          // arises in the definition of the indicator.
          error += JxW_face[qp]*jump2;

        } // End quadrature point loop

      fine_error = error*h*error_norm.weight(var);

      return true;
    } // end if side on flux boundary
  return false;
}

void
KellyErrorEstimator::attach_flux_bc_function (std::pair<bool,Real> fptr(const System & system,
                                                                        const Point & p,
                                                                        const std::string & var_name))
{
  _bc_function = fptr;

  // We may be turning boundary side integration on or off
  if (fptr)
    integrate_boundary_sides = true;
  else
    integrate_boundary_sides = false;
}

} // namespace libMesh
<commit_msg>Fix prerequests in KellyErrorEstimator<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2020 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// C++ includes
#include <algorithm> // for std::fill
#include <cstdlib> // *must* precede <cmath> for proper std:abs() on PGI, Sun Studio CC
#include <cmath>    // for sqrt

// Local Includes
#include "libmesh/libmesh_common.h"
#include "libmesh/kelly_error_estimator.h"
#include "libmesh/error_vector.h"
#include "libmesh/fe_base.h"
#include "libmesh/libmesh_logging.h"
#include "libmesh/elem.h"
#include "libmesh/system.h"
#include "libmesh/dense_vector.h"
#include "libmesh/tensor_tools.h"
#include "libmesh/enum_error_estimator_type.h"
#include "libmesh/enum_norm_type.h"

namespace libMesh
{

KellyErrorEstimator::KellyErrorEstimator() :
  JumpErrorEstimator(),
  _bc_function(nullptr)
{
  error_norm = H1_SEMINORM;
}

ErrorEstimatorType
KellyErrorEstimator::type() const
{
  return KELLY;
}

void
KellyErrorEstimator::init_context(FEMContext & c)
{
  const unsigned int n_vars = c.n_vars();
  for (unsigned int v=0; v<n_vars; v++)
    {
      // Possibly skip this variable
      if (error_norm.weight(v) == 0.0) continue;

      // FIXME: Need to generalize this to vector-valued elements. [PB]
      FEBase * side_fe = nullptr;

      const std::set<unsigned char> & elem_dims =
        c.elem_dimensions();

      for (const auto & dim : elem_dims)
        {
          c.get_side_fe( v, side_fe, dim );

          // We'll need gradients on both sides for flux jump computation
          side_fe->get_dphi();

          // But we only need normal vectors from one side
          if (&c != coarse_context.get())
            side_fe->get_normals();
        }
    }
}

void
KellyErrorEstimator::internal_side_integration ()
{
  const Elem & coarse_elem = coarse_context->get_elem();
  const Elem & fine_elem = fine_context->get_elem();

  FEBase * fe_fine = nullptr;
  fine_context->get_side_fe( var, fe_fine, fine_elem.dim() );

  FEBase * fe_coarse = nullptr;
  coarse_context->get_side_fe( var, fe_coarse, fine_elem.dim() );

  Real error = 1.e-30;
  unsigned int n_qp = fe_fine->n_quadrature_points();

  std::vector<std::vector<RealGradient>> dphi_coarse = fe_coarse->get_dphi();
  std::vector<std::vector<RealGradient>> dphi_fine = fe_fine->get_dphi();
  std::vector<Point> face_normals = fe_fine->get_normals();
  std::vector<Real> JxW_face = fe_fine->get_JxW();

  for (unsigned int qp=0; qp != n_qp; ++qp)
    {
      // Calculate solution gradients on fine and coarse elements
      // at this quadrature point
      Gradient
        grad_fine   = fine_context->side_gradient(var, qp),
        grad_coarse = coarse_context->side_gradient(var, qp);

      // Find the jump in the normal derivative
      // at this quadrature point
      const Number jump = (grad_fine - grad_coarse)*face_normals[qp];
      const Real jump2 = TensorTools::norm_sq(jump);

      // Accumulate the jump integral
      error += JxW_face[qp] * jump2;
    }

  // Add the h-weighted jump integral to each error term
  fine_error =
    error * fine_elem.hmax() * error_norm.weight(var);
  coarse_error =
    error * coarse_elem.hmax() * error_norm.weight(var);
}

bool
KellyErrorEstimator::boundary_side_integration ()
{
  const Elem & fine_elem = fine_context->get_elem();

  FEBase * fe_fine = nullptr;
  fine_context->get_side_fe( var, fe_fine, fine_elem.dim() );

  const std::string & var_name =
    fine_context->get_system().variable_name(var);

  std::vector<std::vector<RealGradient>> dphi_fine = fe_fine->get_dphi();
  std::vector<Point> face_normals = fe_fine->get_normals();
  std::vector<Real> JxW_face = fe_fine->get_JxW();
  std::vector<Point> qface_point = fe_fine->get_xyz();

  // The reinitialization also recomputes the locations of
  // the quadrature points on the side.  By checking if the
  // first quadrature point on the side is on a flux boundary
  // for a particular variable, we will determine if the whole
  // element is on a flux boundary (assuming quadrature points
  // are strictly contained in the side).
  if (this->_bc_function(fine_context->get_system(),
                         qface_point[0], var_name).first)
    {
      const Real h = fine_elem.hmax();

      // The number of quadrature points
      const unsigned int n_qp = fe_fine->n_quadrature_points();

      // The error contribution from this face
      Real error = 1.e-30;

      // loop over the integration points on the face.
      for (unsigned int qp=0; qp<n_qp; qp++)
        {
          // Value of the imposed flux BC at this quadrature point.
          const std::pair<bool,Real> flux_bc =
            this->_bc_function(fine_context->get_system(),
                               qface_point[qp], var_name);

          // Be sure the BC function still thinks we're on the
          // flux boundary.
          libmesh_assert_equal_to (flux_bc.first, true);

          // The solution gradient from each element
          Gradient grad_fine = fine_context->side_gradient(var, qp);

          // The difference between the desired BC and the approximate solution.
          const Number jump = flux_bc.second - grad_fine*face_normals[qp];

          // The flux jump squared.  If using complex numbers,
          // TensorTools::norm_sq(z) returns |z|^2, where |z| is the modulus of z.
          const Real jump2 = TensorTools::norm_sq(jump);

          // Integrate the error on the face.  The error is
          // scaled by an additional power of h, where h is
          // the maximum side length for the element.  This
          // arises in the definition of the indicator.
          error += JxW_face[qp]*jump2;

        } // End quadrature point loop

      fine_error = error*h*error_norm.weight(var);

      return true;
    } // end if side on flux boundary
  return false;
}

void
KellyErrorEstimator::attach_flux_bc_function (std::pair<bool,Real> fptr(const System & system,
                                                                        const Point & p,
                                                                        const std::string & var_name))
{
  _bc_function = fptr;

  // We may be turning boundary side integration on or off
  if (fptr)
    integrate_boundary_sides = true;
  else
    integrate_boundary_sides = false;
}

} // namespace libMesh
<|endoftext|>


<commit_before>#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

int main(void) {
  std::atomic<bool> exit_flag(false);

  // Run threads

  std::vector<std::thread> threads;
  for (int i = 0; i < 100; ++i) {
    threads.emplace_back([&] {
      int counter = 0;
      while (!exit_flag) {
        std::cout << ++counter << std::endl;
      }
    });
  }

  // Sleep

  {
    using namespace std::chrono_literals;
    std::this_thread::sleep_for(10s);
  }

  // Stop threads

  exit_flag = true;
  for (auto&& t : threads) {
    t.join();
  }

  return 0;
}
<commit_msg>update appendix/stress_testing<commit_after>#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

int main(void) {
  std::atomic_flag lock = ATOMIC_FLAG_INIT;

  lock.test_and_set(std::memory_order_acquire);

  // Run threads

  std::vector<std::thread> threads;
  for (int i = 0; i < 8; ++i) {
    threads.emplace_back([i, &lock] {
      // spinlock
      while (lock.test_and_set(std::memory_order_acquire)) {
      }
      std::cout << "finished (" << i << ")" << std::endl;
      lock.clear(std::memory_order_release);
    });
  }

  // Sleep

  {
    using namespace std::chrono_literals;
    std::this_thread::sleep_for(10s);
  }

  lock.clear(std::memory_order_release);

  // Stop threads

  for (auto&& t : threads) {
    t.join();
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <FImage.h>
#include <stdint.h>

using namespace FImage;

Var x, y, c;

Func hot_pixel_suppression(Func input) {
    Expr max = Max(Max(input(x-2, y), input(x+2, y)),
                   Max(input(x, y-2), input(x, y+2)));
    Expr min = Min(Min(input(x-2, y), input(x+2, y)),
                   Min(input(x, y-2), input(x, y+2)));

    Func denoised("denoised");
    denoised(x, y) = Clamp(input(x, y), min, max);

    return denoised;
}

Expr abs(Expr e) {
    return Select(e < Cast(e.type(), 0), -e, e);
}

Func interleave_x(Func a, Func b) {
    Func out;
    out(x, y) = Select((x%2)==0, a(x/2, y), b(x/2, y));
    return out;
}

Func interleave_y(Func a, Func b) {
    Func out;
    out(x, y) = Select((y%2)==0, a(x, y/2), b(x, y/2));
    return out;
}

Func demosaic(Func raw) {
    // These are the values we already know from the input
    // x_y = the value of channel x at a site in the input of channel y
    // gb refers to green sites in the blue rows
    // gr refers to green sites in the red rows
    Func r_r("r_r"), g_gr("g_gr"), g_gb("g_gb"), b_b("b_b");
    g_gr(x, y) = raw(2*x, 2*y);
    r_r(x, y)  = raw(2*x+1, 2*y);
    b_b(x, y)  = raw(2*x, 2*y+1);
    g_gb(x, y) = raw(2*x+1, 2*y+1);

    // These are the ones we need to interpolate
    Func b_r("b_r"), g_r("g_r");
    Func b_gr("b_gr"), r_gr("r_gr");
    Func b_gb("b_gb"), r_gb("r_gb");
    Func r_b("r_b"), g_b("g_b");

    // First calculate green at the red and blue sites

    // Try interpolating vertically and horizontally. Also compute
    // differences vertically and horizontally. Use interpolation in
    // whichever direction had the smallest difference.
    Expr gv_r  =    (g_gb(x, y-1) + g_gb(x, y))/2;
    Expr gvd_r = abs(g_gb(x, y-1) - g_gb(x, y));
    Expr gh_r  =    (g_gr(x+1, y) + g_gr(x, y))/2;
    Expr ghd_r = abs(g_gr(x+1, y) - g_gr(x, y));

    g_r(x, y)  = Select(ghd_r < gvd_r, gh_r, gv_r);

    Expr gv_b  =    (g_gr(x, y+1) + g_gr(x, y))/2;
    Expr gvd_b = abs(g_gr(x, y+1) - g_gr(x, y));
    Expr gh_b  =    (g_gb(x-1, y) + g_gb(x, y))/2;
    Expr ghd_b = abs(g_gb(x-1, y) - g_gb(x, y));

    g_b(x, y)  = Select(ghd_b < gvd_b, gh_b, gv_b);

    // Next interpolate red at gr by first interpolating, then
    // correcting using the error green would have had if we had
    // interpolated it in the same way (i.e. add the second derivative
    // of the green channel at the same place).
    Expr correction;
    correction = g_gr(x, y) - (g_r(x, y) + g_r(x-1, y))/2;
    r_gr(x, y) = correction + (r_r(x-1, y) + r_r(x, y))/2;

    // Do the same for other reds and blues at green sites
    correction = g_gr(x, y) - (g_b(x, y) + g_b(x, y-1))/2;
    b_gr(x, y) = correction + (b_b(x, y) + b_b(x, y-1))/2;

    correction = g_gb(x, y) - (g_r(x, y) + g_r(x, y+1))/2;
    r_gb(x, y) = correction + (r_r(x, y) + r_r(x, y+1))/2;

    correction = g_gb(x, y) - (g_b(x, y) + g_b(x+1, y))/2;
    b_gb(x, y) = correction + (b_b(x, y) + b_b(x+1, y))/2;

    // Now interpolate diagonally to get red at blue and blue at
    // red. Hold onto your hats; this gets really fancy. We do the
    // same thing as for interpolating green where we try both
    // directions (in this case the positive and negative diagonals),
    // and use the one with the lowest absolute difference. But we
    // also use the same trick as interpolating red and blue at green
    // sites - we correct our interpolations using the second
    // derivative of green at the same sites.

    correction = g_b(x, y)  - (g_r(x, y) + g_r(x-1, y+1))/2;
    Expr rp_b  = correction + (r_r(x, y) + r_r(x-1, y+1))/2;
    Expr rpd_b = abs(r_r(x, y) - r_r(x-1, y+1));

    correction = g_b(x, y)  - (g_r(x-1, y) + g_r(x, y+1))/2;
    Expr rn_b  = correction + (r_r(x-1, y) + r_r(x, y+1))/2;
    Expr rnd_b = abs(r_r(x-1, y) - r_r(x, y+1));

    r_b(x, y)  = Select(rpd_b < rnd_b, rp_b, rn_b);

    // Same thing for blue at red
    correction = g_r(x, y)  - (g_b(x, y) + g_b(x+1, y-1))/2;
    Expr bp_r  = correction + (b_b(x, y) + b_b(x+1, y-1))/2;
    Expr bpd_r = abs(b_b(x, y) - b_b(x+1, y-1));

    correction = g_r(x, y)  - (g_b(x+1, y) + g_b(x, y-1))/2;
    Expr bn_r  = correction + (b_b(x+1, y) + b_b(x, y-1))/2;
    Expr bnd_r = abs(b_b(x+1, y) - b_b(x, y-1));

    b_r(x, y)  =  Select(bpd_r < bnd_r, bp_r, bn_r);

    // Interleave the resulting channels
    Func r = interleave_y(interleave_x(r_gr, r_r),
                          interleave_x(r_b, r_gb));
    Func g = interleave_y(interleave_x(g_gr, g_r),
                          interleave_x(g_b, g_gb));
    Func b = interleave_y(interleave_x(b_gr, b_r),
                          interleave_x(b_b, b_gb));

    Func output("dem");
    output(x, y) = (r(x, y), g(x, y), b(x, y));

    return output;
}

Func color_correct(Func input, UniformImage matrix_3200, UniformImage matrix_7000, Uniform<float> kelvin) {
    // Get a color matrix by linearly interpolating between two
    // calibrated matrices using inverse kelvin.

    Func matrix;
    Expr alpha = (1.0f/kelvin - 1.0f/3200) / (1.0f/7000 - 1.0f/3200);
    matrix(x, y) = (matrix_3200(x, y) * alpha +
                    matrix_7000(x, y) * (1 - alpha));

    Func corrected;
    RVar j(0, 3);
    corrected(x, y, c) = Cast<int16_t>(Sum(matrix(j, c)*Cast<float>(input(x, y, j))) + matrix(3, c));
    return corrected;
}

Func apply_curve(Func input, Uniform<float> gamma, Uniform<float> contrast) {
    // copied from FCam
    Func curve("curve");

    Expr xf = Cast<float>(x)/1024.0f;
    Expr g = pow(xf, 1.0f/gamma);
    Expr b = 2.0f - pow(2.0f, contrast/100.0f);
    Expr a = 2.0f - 2.0f*b;
    Expr z = Select(g > 0.5f,
                    1.0f - (a*(1.0f-g)*(1.0f-g) + b*(1.0f-g)),
                    a*g*g + b*g);
    Expr val = Cast<uint8_t>(Clamp(z*256.0f, 0.0f, 255.0f));
    curve(x) = val; //Debug(val, "curve ", x, xf, g, z, val);

    Func curved("curved");
    // This is after the color transform, so the input could be
    // negative or very large. Clamp it back to 10 bits before applying the curve.
    curved(x, y, c) = curve(Clamp(Cast<int32_t>(input(x, y, c)), 0, 1023));
    return curved;
}

/*
Func rgb_to_yuv422(Func rgb) {
    Func Y;
    Func U;
    Func V;
    Func UV;
    Func YUV;
}
*/

Func process(Func raw,
             UniformImage matrix_3200, UniformImage matrix_7000, Uniform<float> color_temp,
             Uniform<float> gamma, Uniform<float> contrast) {
    Func im = raw;
    im = hot_pixel_suppression(im);
    im = demosaic(im);
    im = color_correct(im, matrix_3200, matrix_7000, color_temp);
    im = apply_curve(im, gamma, contrast);

    /*
    Func check;
    Var x, y, c;
    check(x, y, c) = Debug(im(x, y, c), "after curve ", x, y, c, im(x, y, c));
    im = check;
    */

    //im = rgb_to_yuv422(im);
    return im;
}

int main(int argc, char **argv) {
    UniformImage input(UInt(16), 2, "raw");
    UniformImage matrix_3200(Float(32), 2, "m3200"), matrix_7000(Float(32), 2, "m7000");
    Uniform<float> color_temp("color_temp", 3200.0f);
    Uniform<float> gamma("gamma", 1.8f);
    Uniform<float> contrast("contrast", 10.0f);

    // add a boundary condition and treat things as signed ints
    // (demosaic might introduce negative values)
    Func clamped("in");
    clamped(x, y) = Cast<int16_t>(input(Clamp(x, 0, input.width()-1),
                                        Clamp(y, 0, input.height()-1)));

    // Run the pipeline
    Func processed = process(clamped, matrix_3200, matrix_7000, color_temp, gamma, contrast);

    // Pick a schedule

    if (argc > 1)
        srand(atoi(argv[1]));
    else
        srand(0);

    Var xo("xo"), yo("yo"), c("c"), xi("xi"), yi("yi");
    Func output;
    output(xo, yo, c) = processed(xo, yo, c);
    output.root().tile(xo, yo, xi, yi, 32, 16).transpose(yo, c).transpose(xo, c);

    std::vector<Func> funcs = output.rhs().funcs();

    for (size_t i = 0; i < funcs.size(); i++) {
      if (funcs[i].name() == "curve") funcs[i].root();
      else funcs[i].chunk(xo);
      //if (funcs[i].returnType() == UInt(8)) funcs[i].vectorize(x, 16);
      //if (funcs[i].returnType() == Int(16)) funcs[i].vectorize(x, 8);
      //if (funcs[i].returnType() == Float(32)) funcs[i].vectorize(x, 4);
    }

    output.compileToFile("curved");

    return 0;
}

<commit_msg>Updated camera_pipe example<commit_after>#include <FImage.h>
#include <stdint.h>

using namespace FImage;

Var x, y, c;

Func hot_pixel_suppression(Func input) {
    Expr max = Max(Max(input(x-2, y), input(x+2, y)),
                   Max(input(x, y-2), input(x, y+2)));
    Expr min = Min(Min(input(x-2, y), input(x+2, y)),
                   Min(input(x, y-2), input(x, y+2)));

    Func denoised("denoised");
    denoised(x, y) = Clamp(input(x, y), min, max);

    return denoised;
}

Expr abs(Expr e) {
    return Select(e < Cast(e.type(), 0), -e, e);
}

Func interleave_x(Func a, Func b) {
    Func out;
    out(x, y) = Select((x%2)==0, a(x/2, y), b(x/2, y));
    return out;
}

Func interleave_y(Func a, Func b) {
    Func out;
    out(x, y) = Select((y%2)==0, a(x, y/2), b(x, y/2));
    return out;
}

Func demosaic(Func raw) {
    // These are the values we already know from the input
    // x_y = the value of channel x at a site in the input of channel y
    // gb refers to green sites in the blue rows
    // gr refers to green sites in the red rows
    Func r_r("r_r"), g_gr("g_gr"), g_gb("g_gb"), b_b("b_b");
    g_gr(x, y) = raw(2*x, 2*y);
    r_r(x, y)  = raw(2*x+1, 2*y);
    b_b(x, y)  = raw(2*x, 2*y+1);
    g_gb(x, y) = raw(2*x+1, 2*y+1);

    // These are the ones we need to interpolate
    Func b_r("b_r"), g_r("g_r");
    Func b_gr("b_gr"), r_gr("r_gr");
    Func b_gb("b_gb"), r_gb("r_gb");
    Func r_b("r_b"), g_b("g_b");

    // First calculate green at the red and blue sites

    // Try interpolating vertically and horizontally. Also compute
    // differences vertically and horizontally. Use interpolation in
    // whichever direction had the smallest difference.
    Expr gv_r  =    (g_gb(x, y-1) + g_gb(x, y))/2;
    Expr gvd_r = abs(g_gb(x, y-1) - g_gb(x, y));
    Expr gh_r  =    (g_gr(x+1, y) + g_gr(x, y))/2;
    Expr ghd_r = abs(g_gr(x+1, y) - g_gr(x, y));

    g_r(x, y)  = Select(ghd_r < gvd_r, gh_r, gv_r);

    Expr gv_b  =    (g_gr(x, y+1) + g_gr(x, y))/2;
    Expr gvd_b = abs(g_gr(x, y+1) - g_gr(x, y));
    Expr gh_b  =    (g_gb(x-1, y) + g_gb(x, y))/2;
    Expr ghd_b = abs(g_gb(x-1, y) - g_gb(x, y));

    g_b(x, y)  = Select(ghd_b < gvd_b, gh_b, gv_b);

    // Next interpolate red at gr by first interpolating, then
    // correcting using the error green would have had if we had
    // interpolated it in the same way (i.e. add the second derivative
    // of the green channel at the same place).
    Expr correction;
    correction = g_gr(x, y) - (g_r(x, y) + g_r(x-1, y))/2;
    r_gr(x, y) = correction + (r_r(x-1, y) + r_r(x, y))/2;

    // Do the same for other reds and blues at green sites
    correction = g_gr(x, y) - (g_b(x, y) + g_b(x, y-1))/2;
    b_gr(x, y) = correction + (b_b(x, y) + b_b(x, y-1))/2;

    correction = g_gb(x, y) - (g_r(x, y) + g_r(x, y+1))/2;
    r_gb(x, y) = correction + (r_r(x, y) + r_r(x, y+1))/2;

    correction = g_gb(x, y) - (g_b(x, y) + g_b(x+1, y))/2;
    b_gb(x, y) = correction + (b_b(x, y) + b_b(x+1, y))/2;

    // Now interpolate diagonally to get red at blue and blue at
    // red. Hold onto your hats; this gets really fancy. We do the
    // same thing as for interpolating green where we try both
    // directions (in this case the positive and negative diagonals),
    // and use the one with the lowest absolute difference. But we
    // also use the same trick as interpolating red and blue at green
    // sites - we correct our interpolations using the second
    // derivative of green at the same sites.

    correction = g_b(x, y)  - (g_r(x, y) + g_r(x-1, y+1))/2;
    Expr rp_b  = correction + (r_r(x, y) + r_r(x-1, y+1))/2;
    Expr rpd_b = abs(r_r(x, y) - r_r(x-1, y+1));

    correction = g_b(x, y)  - (g_r(x-1, y) + g_r(x, y+1))/2;
    Expr rn_b  = correction + (r_r(x-1, y) + r_r(x, y+1))/2;
    Expr rnd_b = abs(r_r(x-1, y) - r_r(x, y+1));

    r_b(x, y)  = Select(rpd_b < rnd_b, rp_b, rn_b);

    // Same thing for blue at red
    correction = g_r(x, y)  - (g_b(x, y) + g_b(x+1, y-1))/2;
    Expr bp_r  = correction + (b_b(x, y) + b_b(x+1, y-1))/2;
    Expr bpd_r = abs(b_b(x, y) - b_b(x+1, y-1));

    correction = g_r(x, y)  - (g_b(x+1, y) + g_b(x, y-1))/2;
    Expr bn_r  = correction + (b_b(x+1, y) + b_b(x, y-1))/2;
    Expr bnd_r = abs(b_b(x+1, y) - b_b(x, y-1));

    b_r(x, y)  =  Select(bpd_r < bnd_r, bp_r, bn_r);

    // Interleave the resulting channels
    Func r = interleave_y(interleave_x(r_gr, r_r),
                          interleave_x(r_b, r_gb));
    Func g = interleave_y(interleave_x(g_gr, g_r),
                          interleave_x(g_b, g_gb));
    Func b = interleave_y(interleave_x(b_gr, b_r),
                          interleave_x(b_b, b_gb));

    Func output("dem");
    output(x, y) = (r(x, y), g(x, y), b(x, y));

    return output;
}

Func color_correct(Func input, UniformImage matrix_3200, UniformImage matrix_7000, Uniform<float> kelvin) {
    // Get a color matrix by linearly interpolating between two
    // calibrated matrices using inverse kelvin.

    Func matrix("matrix");
    Expr alpha = (1.0f/kelvin - 1.0f/3200) / (1.0f/7000 - 1.0f/3200);
    matrix(x, y) = (matrix_3200(x, y) * alpha +
                    matrix_7000(x, y) * (1 - alpha));

    Func corrected("corrected");
    RVar j(0, 3);
    corrected(x, y, c) = Cast<int16_t>(Sum(matrix(j, c)*Cast<float>(input(x, y, j))) + matrix(3, c));
    return corrected;
}

Func apply_curve(Func input, Uniform<float> gamma, Uniform<float> contrast) {
    // copied from FCam
    Func curve("curve");

    Expr xf = Cast<float>(x)/1024.0f;
    Expr g = pow(xf, 1.0f/gamma);
    Expr b = 2.0f - pow(2.0f, contrast/100.0f);
    Expr a = 2.0f - 2.0f*b;
    Expr z = Select(g > 0.5f,
                    1.0f - (a*(1.0f-g)*(1.0f-g) + b*(1.0f-g)),
                    a*g*g + b*g);
    Expr val = Cast<uint8_t>(Clamp(z*256.0f, 0.0f, 255.0f));
    curve(x) = val; //Debug(val, "curve ", x, xf, g, z, val);

    Func curved("curved");
    // This is after the color transform, so the input could be
    // negative or very large. Clamp it back to 10 bits before applying the curve.
    curved(x, y, c) = curve(Clamp(Cast<int32_t>(input(x, y, c)), 0, 1023));
    return curved;
}

/*
Func rgb_to_yuv422(Func rgb) {
    Func Y;
    Func U;
    Func V;
    Func UV;
    Func YUV;
}
*/

Func process(Func raw,
             UniformImage matrix_3200, UniformImage matrix_7000, Uniform<float> color_temp,
             Uniform<float> gamma, Uniform<float> contrast) {
    Func im = raw;
    im = hot_pixel_suppression(im);
    im = demosaic(im);
    im = color_correct(im, matrix_3200, matrix_7000, color_temp);
    im = apply_curve(im, gamma, contrast);

    /*
    Func check;
    Var x, y, c;
    check(x, y, c) = Debug(im(x, y, c), "after curve ", x, y, c, im(x, y, c));
    im = check;
    */

    //im = rgb_to_yuv422(im);
    return im;
}

int main(int argc, char **argv) {
    UniformImage input(UInt(16), 2, "raw");
    UniformImage matrix_3200(Float(32), 2, "m3200"), matrix_7000(Float(32), 2, "m7000");
    Uniform<float> color_temp("color_temp", 3200.0f);
    Uniform<float> gamma("gamma", 1.8f);
    Uniform<float> contrast("contrast", 10.0f);

    // add a boundary condition and treat things as signed ints
    // (demosaic might introduce negative values)
    Func clamped("in");
    clamped(x, y) = Cast<int16_t>(input(Clamp(x, 0, input.width()-1),
                                        Clamp(y, 0, input.height()-1)));

    // Run the pipeline
    Func processed = process(clamped, matrix_3200, matrix_7000, color_temp, gamma, contrast);

    // Pick a schedule

    if (argc > 1)
        srand(atoi(argv[1]));
    else
        srand(0);

    Var xo("xo"), yo("yo"), c("c"), xi("xi"), yi("yi");
    Func output;
    output(xo, yo, c) = processed(xo, yo, c);
    output.root().tile(xo, yo, xi, yi, 32, 16).transpose(yo, c).transpose(xo, c);

    std::vector<Func> funcs = output.rhs().funcs();

    for (size_t i = 0; i < funcs.size(); i++) {
      if (funcs[i] == processed) {} // inline
      else if (funcs[i].name() == "curve") funcs[i].root();
      else funcs[i].chunk(xo);
      //if (funcs[i].returnType() == UInt(8)) funcs[i].vectorize(x, 16);
      //if (funcs[i].returnType() == Int(16)) funcs[i].vectorize(x, 8);
      //if (funcs[i].returnType() == Float(32)) funcs[i].vectorize(x, 4);
    }

    output.compileToFile("curved");

    return 0;
}

<|endoftext|>


<commit_before>//
//
//
inline void memcpy_3d_array()
{

};
<commit_msg>Delete array__memcpy_3d_array.cpp<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/node_bindings_win.h"

#include <windows.h>

#include "base/logging.h"

extern "C" {
#include "vendor/node/deps/uv/src/win/internal.h"
}

namespace atom {

NodeBindingsWin::NodeBindingsWin(bool is_browser)
    : NodeBindings(is_browser) {
}

NodeBindingsWin::~NodeBindingsWin() {
}

void NodeBindingsWin::PollEvents() {
  // Unlike Unix, in which we can just rely on one backend fd to determine
  // whether we should iterate libuv loop, on Window, IOCP is just one part
  // of the libuv loop, we should also check whether we have other types of
  // events.
  bool block = uv_loop_->idle_handles == NULL &&
               uv_loop_->pending_reqs_tail == NULL &&
               uv_loop_->endgame_handles == NULL &&
               !uv_loop_->stop_flag &&
               (uv_loop_->active_handles > 0 ||
                !QUEUE_EMPTY(&uv_loop_->active_reqs));

  // When there is no other types of events, we block on the IOCP.
  if (block) {
    DWORD bytes, timeout;
    ULONG_PTR key;
    OVERLAPPED* overlapped;

    timeout = uv_backend_timeout(uv_loop_);
    GetQueuedCompletionStatus(uv_loop_->iocp,
                              &bytes,
                              &key,
                              &overlapped,
                              timeout);

    // Give the event back so libuv can deal with it.
    if (overlapped != NULL)
      PostQueuedCompletionStatus(uv_loop_->iocp,
                                 bytes,
                                 key,
                                 overlapped);
  }
}

// static
NodeBindings* NodeBindings::Create(bool is_browser) {
  return new NodeBindingsWin(is_browser);
}

}  // namespace atom
<commit_msg>Fix for issue 1968: use uv_backend_timeout to determine timeout to match other platforms<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/node_bindings_win.h"

#include <windows.h>

#include "base/logging.h"

extern "C" {
#include "vendor/node/deps/uv/src/win/internal.h"
}

namespace atom {

NodeBindingsWin::NodeBindingsWin(bool is_browser)
    : NodeBindings(is_browser) {
}

NodeBindingsWin::~NodeBindingsWin() {
}

void NodeBindingsWin::PollEvents() {
  // If there are other kinds of events pending, uv_backend_timeout will
  // instruct us not to wait.
  DWORD bytes, timeout;
  ULONG_PTR key;
  OVERLAPPED* overlapped;

  timeout = uv_backend_timeout(uv_loop_);

  GetQueuedCompletionStatus(uv_loop_->iocp,
                            &bytes,
                            &key,
                            &overlapped,
                            timeout);

  // Give the event back so libuv can deal with it.
  if (overlapped != NULL)
    PostQueuedCompletionStatus(uv_loop_->iocp,
                               bytes,
                               key,
                               overlapped);
}

// static
NodeBindings* NodeBindings::Create(bool is_browser) {
  return new NodeBindingsWin(is_browser);
}

}  // namespace atom
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: moduldlg.hxx,v $
 *
 *  $Revision: 1.23 $
 *
 *  last change: $Author: obo $ $Date: 2007-03-15 15:58:40 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _MODULDLG_HXX
#define _MODULDLG_HXX

#ifndef _SVHEADER_HXX
#include <svheader.hxx>
#endif

#include <bastype2.hxx>

#ifndef _SV_DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif

#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif

#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef _SVTABBX_HXX //autogen
#include <svtools/svtabbx.hxx>
#endif

#ifndef _SV_TABDLG_HXX //autogen
#include <vcl/tabdlg.hxx>
#endif

#ifndef _SV_TABPAGE_HXX //autogen
#include <vcl/tabpage.hxx>
#endif

#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include "com/sun/star/task/XInteractionHandler.hpp"
#endif

#include <vcl/tabctrl.hxx>
#include <vcl/lstbox.hxx>

class StarBASIC;

#define NEWOBJECTMODE_LIB       1
#define NEWOBJECTMODE_MOD       2
#define NEWOBJECTMODE_DLG       3
#define NEWOBJECTMODE_METH      4

class NewObjectDialog : public ModalDialog
{
private:
    FixedText       aText;
    Edit            aEdit;
    OKButton        aOKButton;
    CancelButton    aCancelButton;

    DECL_LINK(OkButtonHandler, Button *);

public:
    NewObjectDialog(Window * pParent, USHORT nMode, bool bCheckName = false);
                ~NewObjectDialog();

    String      GetObjectName() const { return aEdit.GetText(); }
    void        SetObjectName( const String& rName ) { aEdit.SetText( rName ); aEdit.SetSelection( Selection( 0, rName.Len() ) );}
};

class ExportDialog : public ModalDialog
{
private:
    RadioButton     maExportAsPackageButton;
    RadioButton     maExportAsBasicButton;
    OKButton        maOKButton;
    CancelButton    maCancelButton;

    sal_Bool        mbExportAsPackage;

    DECL_LINK(OkButtonHandler, Button *);

public:
    ExportDialog( Window * pParent );
    ~ExportDialog();

    sal_Bool        isExportAsPackage( void ) { return mbExportAsPackage; }
};

class ExtBasicTreeListBox : public BasicTreeListBox
{
protected:
    virtual BOOL    EditingEntry( SvLBoxEntry* pEntry, Selection& rSel  );
    virtual BOOL    EditedEntry( SvLBoxEntry* pEntry, const String& rNewText );

    virtual DragDropMode    NotifyStartDrag( TransferDataContainer& rData, SvLBoxEntry* pEntry );
    virtual BOOL            NotifyAcceptDrop( SvLBoxEntry* pEntry );

    virtual BOOL    NotifyMoving( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry,
                        SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos );
    virtual BOOL    NotifyCopying( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry,
                        SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos );
    BOOL            NotifyCopyingMoving( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry,
                        SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos, BOOL bMove );

public:
    ExtBasicTreeListBox( Window* pParent, const ResId& rRes );
    ~ExtBasicTreeListBox();
};

#define LIBMODE_CHOOSER     1
#define LIBMODE_MANAGER     2

class BasicCheckBox : public SvTabListBox
{
private:
    USHORT              nMode;
    SvLBoxButtonData*   pCheckButton;
    ScriptDocument      m_aDocument;
    void                Init();

public:
                    BasicCheckBox( Window* pParent, const ResId& rResId );
                    ~BasicCheckBox();

    SvLBoxEntry*    DoInsertEntry( const String& rStr, ULONG nPos = LISTBOX_APPEND );
    void            RemoveEntry( ULONG nPos );
    SvLBoxEntry*    FindEntry( const String& rName );

    void            SelectEntryPos( ULONG nPos, BOOL bSelect = TRUE );
    ULONG           GetSelectEntryPos() const;

    ULONG           GetCheckedEntryCount() const;
    void            CheckEntryPos( ULONG nPos, BOOL bCheck = TRUE );
    BOOL            IsChecked( ULONG nPos ) const;

    virtual void    InitEntry( SvLBoxEntry*, const XubString&, const Image&, const Image&, SvLBoxButtonKind eButtonKind );
    virtual BOOL    EditingEntry( SvLBoxEntry* pEntry, Selection& rSel );
    virtual BOOL    EditedEntry( SvLBoxEntry* pEntry, const String& rNewText );

    void            SetDocument( const ScriptDocument& rDocument ) { m_aDocument = rDocument; }

    void            SetMode( USHORT n );
    USHORT          GetMode() const         { return nMode; }
};

class LibDialog: public ModalDialog
{
private:
    OKButton        aOKButton;
    CancelButton    aCancelButton;
    FixedText       aStorageName;
    BasicCheckBox   aLibBox;
    FixedLine       aFixedLine;
    CheckBox        aReferenceBox;
    CheckBox        aReplaceBox;

public:
                    LibDialog( Window* pParent );
                    ~LibDialog();

    void            SetStorageName( const String& rName );

    BasicCheckBox&  GetLibBox()                 { return aLibBox; }
    BOOL            IsReference() const         { return aReferenceBox.IsChecked(); }
    BOOL            IsReplace() const           { return aReplaceBox.IsChecked(); }

    void            EnableReference( BOOL b )   { aReferenceBox.Enable( b ); }
    void            EnableReplace( BOOL b )     { aReplaceBox.Enable( b ); }
};

class OrganizeDialog : public TabDialog
{
private:
    TabControl              aTabCtrl;
    BasicEntryDescriptor    m_aCurEntry;

public:
                    OrganizeDialog( Window* pParent, INT16 tabId, BasicEntryDescriptor& rDesc );
                    ~OrganizeDialog();

    virtual short   Execute();

    DECL_LINK( ActivatePageHdl, TabControl * );
};

class ObjectPage: public TabPage
{
protected:
    FixedText           aLibText;
    ExtBasicTreeListBox aBasicBox;
    PushButton          aEditButton;
    CancelButton        aCloseButton;
    PushButton          aNewModButton;
    PushButton          aNewDlgButton;
    PushButton          aDelButton;

    DECL_LINK( BasicBoxHighlightHdl, BasicTreeListBox * );
    DECL_LINK( ButtonHdl, Button * );
    void                CheckButtons();
    bool                GetSelection( ScriptDocument& rDocument, String& rLibName );
    void                DeleteCurrent();
    void                NewModule();
    void                NewDialog();
    void                EndTabDialog( USHORT nRet );

    TabDialog*          pTabDlg;

    virtual void        ActivatePage();
    virtual void        DeactivatePage();

public:
                        ObjectPage( Window* pParent, const ResId& rResId, USHORT nMode );

    void                SetCurrentEntry( BasicEntryDescriptor& rDesc );
    void                SetTabDlg( TabDialog* p ) { pTabDlg = p;}
};

class SvxPasswordDialog;

class LibPage: public TabPage
{
protected:
    FixedText           aBasicsText;
    ListBox             aBasicsBox;
    FixedText           aLibText;
    BasicCheckBox       aLibBox;
    PushButton          aEditButton;
    CancelButton        aCloseButton;
    PushButton          aPasswordButton;
    PushButton          aExportButton;
    PushButton          aNewLibButton;
    PushButton          aInsertLibButton;
    PushButton          aDelButton;

    ScriptDocument      m_aCurDocument;
    LibraryLocation     m_eCurLocation;

    DECL_LINK( TreeListHighlightHdl, SvTreeListBox * );
    DECL_LINK( BasicSelectHdl, ListBox * );
    DECL_LINK( ButtonHdl, Button * );
    DECL_LINK( CheckPasswordHdl, SvxPasswordDialog * );
    void                CheckButtons();
    void                DeleteCurrent();
    void                NewLib();
    void                InsertLib();
    void                implExportLib( const String& aLibName, const String& aTargetURL,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& Handler );
    void                Export();
    void                ExportAsPackage( const String& aLibName );
    void                ExportAsBasic( const String& aLibName );
    void                EndTabDialog( USHORT nRet );
    void                FillListBox();
    void                InsertListBoxEntry( const ScriptDocument& rDocument, LibraryLocation eLocation );
    void                SetCurLib();
    SvLBoxEntry*        ImpInsertLibEntry( const String& rLibName, ULONG nPos );
    virtual void        ActivatePage();
    virtual void        DeactivatePage();

    TabDialog*          pTabDlg;

public:
                        LibPage( Window* pParent );
    virtual             ~LibPage();

    void                SetTabDlg( TabDialog* p ) { pTabDlg = p;}
};

// Helper functions
SbModule* createModImpl( Window* pWin, const ScriptDocument& rDocument,
    BasicTreeListBox& rBasicBox, const String& rLibName, String aModName, bool bMain = false );
void createLibImpl( Window* pWin, const ScriptDocument& rDocument,
                    BasicCheckBox* pLibBox, BasicTreeListBox* pBasicBox );

#endif // _MODULDLG_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.23.86); FILE MERGED 2008/04/01 15:00:38 thb 1.23.86.3: #i85898# Stripping all external header guards 2008/04/01 10:47:46 thb 1.23.86.2: #i85898# Stripping all external header guards 2008/03/28 16:04:48 rt 1.23.86.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: moduldlg.hxx,v $
 * $Revision: 1.24 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _MODULDLG_HXX
#define _MODULDLG_HXX

#include <svheader.hxx>

#include <bastype2.hxx>
#include <vcl/dialog.hxx>

#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#include <vcl/fixed.hxx>
#include <svtools/svtabbx.hxx>
#include <vcl/tabdlg.hxx>
#include <vcl/tabpage.hxx>
#include "com/sun/star/task/XInteractionHandler.hpp"

#include <vcl/tabctrl.hxx>
#include <vcl/lstbox.hxx>

class StarBASIC;

#define NEWOBJECTMODE_LIB       1
#define NEWOBJECTMODE_MOD       2
#define NEWOBJECTMODE_DLG       3
#define NEWOBJECTMODE_METH      4

class NewObjectDialog : public ModalDialog
{
private:
    FixedText       aText;
    Edit            aEdit;
    OKButton        aOKButton;
    CancelButton    aCancelButton;

    DECL_LINK(OkButtonHandler, Button *);

public:
    NewObjectDialog(Window * pParent, USHORT nMode, bool bCheckName = false);
                ~NewObjectDialog();

    String      GetObjectName() const { return aEdit.GetText(); }
    void        SetObjectName( const String& rName ) { aEdit.SetText( rName ); aEdit.SetSelection( Selection( 0, rName.Len() ) );}
};

class ExportDialog : public ModalDialog
{
private:
    RadioButton     maExportAsPackageButton;
    RadioButton     maExportAsBasicButton;
    OKButton        maOKButton;
    CancelButton    maCancelButton;

    sal_Bool        mbExportAsPackage;

    DECL_LINK(OkButtonHandler, Button *);

public:
    ExportDialog( Window * pParent );
    ~ExportDialog();

    sal_Bool        isExportAsPackage( void ) { return mbExportAsPackage; }
};

class ExtBasicTreeListBox : public BasicTreeListBox
{
protected:
    virtual BOOL    EditingEntry( SvLBoxEntry* pEntry, Selection& rSel  );
    virtual BOOL    EditedEntry( SvLBoxEntry* pEntry, const String& rNewText );

    virtual DragDropMode    NotifyStartDrag( TransferDataContainer& rData, SvLBoxEntry* pEntry );
    virtual BOOL            NotifyAcceptDrop( SvLBoxEntry* pEntry );

    virtual BOOL    NotifyMoving( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry,
                        SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos );
    virtual BOOL    NotifyCopying( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry,
                        SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos );
    BOOL            NotifyCopyingMoving( SvLBoxEntry* pTarget, SvLBoxEntry* pEntry,
                        SvLBoxEntry*& rpNewParent, ULONG& rNewChildPos, BOOL bMove );

public:
    ExtBasicTreeListBox( Window* pParent, const ResId& rRes );
    ~ExtBasicTreeListBox();
};

#define LIBMODE_CHOOSER     1
#define LIBMODE_MANAGER     2

class BasicCheckBox : public SvTabListBox
{
private:
    USHORT              nMode;
    SvLBoxButtonData*   pCheckButton;
    ScriptDocument      m_aDocument;
    void                Init();

public:
                    BasicCheckBox( Window* pParent, const ResId& rResId );
                    ~BasicCheckBox();

    SvLBoxEntry*    DoInsertEntry( const String& rStr, ULONG nPos = LISTBOX_APPEND );
    void            RemoveEntry( ULONG nPos );
    SvLBoxEntry*    FindEntry( const String& rName );

    void            SelectEntryPos( ULONG nPos, BOOL bSelect = TRUE );
    ULONG           GetSelectEntryPos() const;

    ULONG           GetCheckedEntryCount() const;
    void            CheckEntryPos( ULONG nPos, BOOL bCheck = TRUE );
    BOOL            IsChecked( ULONG nPos ) const;

    virtual void    InitEntry( SvLBoxEntry*, const XubString&, const Image&, const Image&, SvLBoxButtonKind eButtonKind );
    virtual BOOL    EditingEntry( SvLBoxEntry* pEntry, Selection& rSel );
    virtual BOOL    EditedEntry( SvLBoxEntry* pEntry, const String& rNewText );

    void            SetDocument( const ScriptDocument& rDocument ) { m_aDocument = rDocument; }

    void            SetMode( USHORT n );
    USHORT          GetMode() const         { return nMode; }
};

class LibDialog: public ModalDialog
{
private:
    OKButton        aOKButton;
    CancelButton    aCancelButton;
    FixedText       aStorageName;
    BasicCheckBox   aLibBox;
    FixedLine       aFixedLine;
    CheckBox        aReferenceBox;
    CheckBox        aReplaceBox;

public:
                    LibDialog( Window* pParent );
                    ~LibDialog();

    void            SetStorageName( const String& rName );

    BasicCheckBox&  GetLibBox()                 { return aLibBox; }
    BOOL            IsReference() const         { return aReferenceBox.IsChecked(); }
    BOOL            IsReplace() const           { return aReplaceBox.IsChecked(); }

    void            EnableReference( BOOL b )   { aReferenceBox.Enable( b ); }
    void            EnableReplace( BOOL b )     { aReplaceBox.Enable( b ); }
};

class OrganizeDialog : public TabDialog
{
private:
    TabControl              aTabCtrl;
    BasicEntryDescriptor    m_aCurEntry;

public:
                    OrganizeDialog( Window* pParent, INT16 tabId, BasicEntryDescriptor& rDesc );
                    ~OrganizeDialog();

    virtual short   Execute();

    DECL_LINK( ActivatePageHdl, TabControl * );
};

class ObjectPage: public TabPage
{
protected:
    FixedText           aLibText;
    ExtBasicTreeListBox aBasicBox;
    PushButton          aEditButton;
    CancelButton        aCloseButton;
    PushButton          aNewModButton;
    PushButton          aNewDlgButton;
    PushButton          aDelButton;

    DECL_LINK( BasicBoxHighlightHdl, BasicTreeListBox * );
    DECL_LINK( ButtonHdl, Button * );
    void                CheckButtons();
    bool                GetSelection( ScriptDocument& rDocument, String& rLibName );
    void                DeleteCurrent();
    void                NewModule();
    void                NewDialog();
    void                EndTabDialog( USHORT nRet );

    TabDialog*          pTabDlg;

    virtual void        ActivatePage();
    virtual void        DeactivatePage();

public:
                        ObjectPage( Window* pParent, const ResId& rResId, USHORT nMode );

    void                SetCurrentEntry( BasicEntryDescriptor& rDesc );
    void                SetTabDlg( TabDialog* p ) { pTabDlg = p;}
};

class SvxPasswordDialog;

class LibPage: public TabPage
{
protected:
    FixedText           aBasicsText;
    ListBox             aBasicsBox;
    FixedText           aLibText;
    BasicCheckBox       aLibBox;
    PushButton          aEditButton;
    CancelButton        aCloseButton;
    PushButton          aPasswordButton;
    PushButton          aExportButton;
    PushButton          aNewLibButton;
    PushButton          aInsertLibButton;
    PushButton          aDelButton;

    ScriptDocument      m_aCurDocument;
    LibraryLocation     m_eCurLocation;

    DECL_LINK( TreeListHighlightHdl, SvTreeListBox * );
    DECL_LINK( BasicSelectHdl, ListBox * );
    DECL_LINK( ButtonHdl, Button * );
    DECL_LINK( CheckPasswordHdl, SvxPasswordDialog * );
    void                CheckButtons();
    void                DeleteCurrent();
    void                NewLib();
    void                InsertLib();
    void                implExportLib( const String& aLibName, const String& aTargetURL,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& Handler );
    void                Export();
    void                ExportAsPackage( const String& aLibName );
    void                ExportAsBasic( const String& aLibName );
    void                EndTabDialog( USHORT nRet );
    void                FillListBox();
    void                InsertListBoxEntry( const ScriptDocument& rDocument, LibraryLocation eLocation );
    void                SetCurLib();
    SvLBoxEntry*        ImpInsertLibEntry( const String& rLibName, ULONG nPos );
    virtual void        ActivatePage();
    virtual void        DeactivatePage();

    TabDialog*          pTabDlg;

public:
                        LibPage( Window* pParent );
    virtual             ~LibPage();

    void                SetTabDlg( TabDialog* p ) { pTabDlg = p;}
};

// Helper functions
SbModule* createModImpl( Window* pWin, const ScriptDocument& rDocument,
    BasicTreeListBox& rBasicBox, const String& rLibName, String aModName, bool bMain = false );
void createLibImpl( Window* pWin, const ScriptDocument& rDocument,
                    BasicCheckBox* pLibBox, BasicTreeListBox* pBasicBox );

#endif // _MODULDLG_HXX
<|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 "base/android/path_utils.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"

#include "testing/gtest/include/gtest/gtest.h"

namespace base {
namespace android {

typedef testing::Test PathUtilsTest;

TEST_F(PathUtilsTest, TestGetDataDirectory) {
  // The string comes from the Java side and depends on the APK
  // we are running in. Assumes that we are packaged in
  // org.chromium.native_test
  FilePath path;
  GetDataDirectory(&path);
  EXPECT_STREQ("/data/data/org.chromium.native_test/app_chrome",
               path.value().c_str());
}

TEST_F(PathUtilsTest, TestGetCacheDirectory) {
  // The string comes from the Java side and depends on the APK
  // we are running in. Assumes that we are packaged in
  // org.chromium.native_test
  FilePath path;
  GetCacheDirectory(&path);
  EXPECT_STREQ("/data/data/org.chromium.native_test/cache",
               path.value().c_str());
}

TEST_F(PathUtilsTest, TestGetNativeLibraryDirectory) {
  // The string comes from the Java side and depends on the APK
  // we are running in. Assumes that the directory contains
  // the base tests shared object.
  FilePath path;
  GetNativeLibraryDirectory(&path);
  EXPECT_TRUE(base::PathExists(path.Append(("libbase_unittests.so"))) ||
              base::PathExists(path.Append(("libbase_unittests.cr.so"))));
}

}  // namespace android
}  // namespace base
<commit_msg>Fix base/android/path_utils_unittest.cc when running on an M device<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 "base/android/path_utils.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/strings/string_util.h"

#include "testing/gtest/include/gtest/gtest.h"

namespace base {
namespace android {

typedef testing::Test PathUtilsTest;

namespace {
void ExpectEither(const std::string& expected1,
                  const std::string& expected2,
                  const std::string& actual) {
  EXPECT_TRUE(expected1 == actual || expected2 == actual)
      << "Value of: " << actual << std::endl
      << "Expected either: " << expected1 << std::endl
      << "or: " << expected2;
}
}  // namespace

TEST_F(PathUtilsTest, TestGetDataDirectory) {
  // The string comes from the Java side and depends on the APK
  // we are running in. Assumes that we are packaged in
  // org.chromium.native_test
  FilePath path;
  GetDataDirectory(&path);

  ExpectEither("/data/data/org.chromium.native_test/app_chrome",
               "/data/user/0/org.chromium.native_test/app_chrome",
               path.value());
}

TEST_F(PathUtilsTest, TestGetCacheDirectory) {
  // The string comes from the Java side and depends on the APK
  // we are running in. Assumes that we are packaged in
  // org.chromium.native_test
  FilePath path;
  GetCacheDirectory(&path);
  ExpectEither("/data/data/org.chromium.native_test/cache",
               "/data/user/0/org.chromium.native_test/cache",
               path.value());
}

TEST_F(PathUtilsTest, TestGetNativeLibraryDirectory) {
  // The string comes from the Java side and depends on the APK
  // we are running in. Assumes that the directory contains
  // the base tests shared object.
  FilePath path;
  GetNativeLibraryDirectory(&path);
  EXPECT_TRUE(base::PathExists(path.Append(("libbase_unittests.so"))) ||
              base::PathExists(path.Append(("libbase_unittests.cr.so"))));
}

}  // namespace android
}  // namespace base
<|endoftext|>