<commit_before>#ifndef NAMED_TUPLES_TUPLE_VISITOR_HEADER
#define NAMED_TUPLES_TUPLE_VISITOR_HEADER

#include <type_traits>
#include "tuple.hpp"

namespace named_tuples {

using std::declval;
using std::enable_if;
using std::is_same;

template <size_t Index, typename Id, typename ValueType> class attribute_reference {
  ValueType& value_;

 public:
  using id_type = Id;
  using value_type = ValueType;
  static const size_t index = Index;

  attribute_reference(ValueType & value) : value_(value) {}
  ValueType& get() { return value_; }
};

template <typename ... T> struct tuple_visit;
template <typename ... Ids, typename ... Types, typename Visitor> struct tuple_visit<named_tuple<Types(Ids)...>, Visitor> {
  using tuple_type = named_tuple<Types(Ids)...>;
  using visitor_type = Visitor;

 private:

  // Apply begin if exists, supports template resolution
  template <typename Vis>
  inline static auto apply_begin(tuple_type& value, Vis& visitor) ->
  typename enable_if<is_same<decltype(declval<Vis>().begin(value)),void>::value, void>::type
  { visitor.begin(value); }

  template <typename ... T> inline static void apply_begin(tuple_type&, T& ...) {}

  // Apply end if exists
  template <typename Vis>
  inline static auto apply_end(tuple_type& value, Vis& visitor) ->
  typename enable_if<is_same<decltype(declval<Vis>().end(value)),void>::value, void>::type
  { visitor.end(value); }

  template <typename ... T> inline static void apply_end(tuple_type&, T& ...) {}

  // Apply between if exists
  template <typename Attr1, typename Attr2, typename Vis>
  inline static auto apply_between(tuple_type& value, Attr1& attr1, Attr2& attr2, Vis& visitor) ->
  typename enable_if<is_same<decltype(declval<Vis>().between(value,attr1,attr2)),void>::value, void>::type
  { visitor.between(value,attr1,attr2); }

  template <typename Attr1, typename Attr2, typename ... T> inline static void apply_between(tuple_type&, Attr1&, Attr2&, T& ...) {}

  // Apply beforeFirst if exists
  template <typename Attr, typename Vis>
  inline static auto apply_beforeFirst(tuple_type& value, Attr& attr, Vis& visitor) ->
  typename enable_if<is_same<decltype(declval<Vis>().beforeFirst(value,attr)),void>::value, void>::type
  { visitor.beforeFirst(value,attr); }

  template <typename Attr, typename ... T> inline static void apply_beforeFirst(tuple_type&, Attr&, T& ...) {}

  // Apply afterLast if exists
  template <typename Attr, typename Vis>
  inline static auto apply_afterLast(tuple_type& value, Attr& attr, Vis& visitor) ->
  typename enable_if<is_same<decltype(declval<Vis>().afterLast(value,attr)),void>::value, void>::type
  { visitor.afterLast(value,attr); }

  template <typename Attr, typename ... T> inline static void apply_afterLast(tuple_type&, Attr&, T& ...) {}

  // Apply apply if exists
  template <typename Attr, typename Vis>
  inline static auto apply_apply(tuple_type& value, Attr& attr, Vis& visitor) ->
  typename enable_if<is_same<decltype(declval<Vis>().apply(value,attr)),void>::value, void>::type
  { visitor.apply(value,attr); }

  template <typename Attr, typename ... T> inline static void apply_apply(tuple_type&, Attr&, T& ...) {}

  template <size_t Current>
  inline static auto apply(tuple_type& value, visitor_type& visitor) ->
  typename std::enable_if<(Current == 0),void>::type
  {
    using Id = typename type_at<Current, type_list<Ids...>>::type;
    using Type = typename type_at<Current, type_list<Types...>>::type;
    attribute_reference<Current, Id, Type> ref(value.template _<Id>());
    apply_beforeFirst(value, ref, visitor);
    apply_apply(value, ref, visitor);
    apply<Current+1>(value, ref, visitor);
  }

  template <size_t Current, typename PreviousAttrRef>
  inline static auto apply(tuple_type& value, PreviousAttrRef& attr, visitor_type& visitor) ->
  typename std::enable_if<(0 < Current && Current < sizeof ... (Ids)),void>::type
  {
    using Id = typename type_at<Current, type_list<Ids...>>::type;
    using Type = typename type_at<Current, type_list<Types...>>::type;
    attribute_reference<Current, Id, Type> ref(value.template _<Id>());
    apply_between(value, attr, ref, visitor);
    apply_apply(value,ref,visitor);
    apply<Current+1>(value, ref, visitor);
  }

  template <size_t Current, typename PreviousAttrRef>
  inline static auto apply(tuple_type& value, PreviousAttrRef& attr, visitor_type& visitor) ->
  typename std::enable_if<(sizeof ... (Ids) <= Current),void>::type
  {
    apply_afterLast(value, attr, visitor);
  }
 public:

  static void visit(tuple_type& value, visitor_type& visitor) {
    apply_begin(value,visitor);
    apply<0>(value, visitor);
    apply_end(value,visitor);
  }
};

template <typename Tuple, typename Visitor> void visit(Tuple& tuple, Visitor& visitor) {
  tuple_visit<Tuple,Visitor>::visit(tuple,visitor);
}

}  // namespace name_tuple

#endif  // NAMED_TUPLES_TUPLE_VISITOR_HEADER
<commit_msg>Empty tuple optim<commit_after>#ifndef NAMED_TUPLES_TUPLE_VISITOR_HEADER
#define NAMED_TUPLES_TUPLE_VISITOR_HEADER

#include <type_traits>
#include "tuple.hpp"

namespace named_tuples {

using std::declval;
using std::enable_if;
using std::is_same;

template <size_t Index, typename Id, typename ValueType> class attribute_reference {
  ValueType& value_;

 public:
  using id_type = Id;
  using value_type = ValueType;
  static const size_t index = Index;

  attribute_reference(ValueType & value) : value_(value) {}
  ValueType& get() { return value_; }
};

template <typename ... T> struct tuple_visit;
template <typename ... Ids, typename ... Types, typename Visitor> struct tuple_visit<named_tuple<Types(Ids)...>, Visitor> {
  using tuple_type = named_tuple<Types(Ids)...>;
  using visitor_type = Visitor;

 private:

  // Apply begin if exists, supports template resolution
  template <typename Vis>
  inline static auto apply_begin(tuple_type& value, Vis& visitor) ->
  typename enable_if<is_same<decltype(declval<Vis>().begin(value)),void>::value, void>::type
  { visitor.begin(value); }

  template <typename ... T> inline static void apply_begin(tuple_type&, T& ...) {}

  // Apply end if exists
  template <typename Vis>
  inline static auto apply_end(tuple_type& value, Vis& visitor) ->
  typename enable_if<is_same<decltype(declval<Vis>().end(value)),void>::value, void>::type
  { visitor.end(value); }

  template <typename ... T> inline static void apply_end(tuple_type&, T& ...) {}

  // Apply between if exists
  template <typename Attr1, typename Attr2, typename Vis>
  inline static auto apply_between(tuple_type& value, Attr1& attr1, Attr2& attr2, Vis& visitor) ->
  typename enable_if<is_same<decltype(declval<Vis>().between(value,attr1,attr2)),void>::value, void>::type
  { visitor.between(value,attr1,attr2); }

  template <typename Attr1, typename Attr2, typename ... T> inline static void apply_between(tuple_type&, Attr1&, Attr2&, T& ...) {}

  // Apply beforeFirst if exists
  template <typename Attr, typename Vis>
  inline static auto apply_beforeFirst(tuple_type& value, Attr& attr, Vis& visitor) ->
  typename enable_if<is_same<decltype(declval<Vis>().beforeFirst(value,attr)),void>::value, void>::type
  { visitor.beforeFirst(value,attr); }

  template <typename Attr, typename ... T> inline static void apply_beforeFirst(tuple_type&, Attr&, T& ...) {}

  // Apply afterLast if exists
  template <typename Attr, typename Vis>
  inline static auto apply_afterLast(tuple_type& value, Attr& attr, Vis& visitor) ->
  typename enable_if<is_same<decltype(declval<Vis>().afterLast(value,attr)),void>::value, void>::type
  { visitor.afterLast(value,attr); }

  template <typename Attr, typename ... T> inline static void apply_afterLast(tuple_type&, Attr&, T& ...) {}

  // Apply apply if exists
  template <typename Attr, typename Vis>
  inline static auto apply_apply(tuple_type& value, Attr& attr, Vis& visitor) ->
  typename enable_if<is_same<decltype(declval<Vis>().apply(value,attr)),void>::value, void>::type
  { visitor.apply(value,attr); }

  template <typename Attr, typename ... T> inline static void apply_apply(tuple_type&, Attr&, T& ...) {}

  template <size_t Current>
  inline static auto apply(tuple_type& value, visitor_type& visitor) ->
  typename std::enable_if<(Current == 0),void>::type
  {
    using Id = typename type_at<Current, type_list<Ids...>>::type;
    using Type = typename type_at<Current, type_list<Types...>>::type;
    attribute_reference<Current, Id, Type> ref(value.template _<Id>());
    apply_beforeFirst(value, ref, visitor);
    apply_apply(value, ref, visitor);
    apply<Current+1>(value, ref, visitor);
  }

  template <size_t Current, typename PreviousAttrRef>
  inline static auto apply(tuple_type& value, PreviousAttrRef& attr, visitor_type& visitor) ->
  typename std::enable_if<(0 < Current && Current < sizeof ... (Ids)),void>::type
  {
    using Id = typename type_at<Current, type_list<Ids...>>::type;
    using Type = typename type_at<Current, type_list<Types...>>::type;
    attribute_reference<Current, Id, Type> ref(value.template _<Id>());
    apply_between(value, attr, ref, visitor);
    apply_apply(value,ref,visitor);
    apply<Current+1>(value, ref, visitor);
  }

  template <size_t Current, typename PreviousAttrRef>
  inline static auto apply(tuple_type& value, PreviousAttrRef& attr, visitor_type& visitor) ->
  typename std::enable_if<(sizeof ... (Ids) <= Current),void>::type
  {
    apply_afterLast(value, attr, visitor);
  }
 public:

  static void visit(tuple_type& value, visitor_type& visitor) {
    apply_begin(value,visitor);
    apply<0>(value, visitor);
    apply_end(value,visitor);
  }
};

// Empty tuple version
template <typename Visitor> struct tuple_visit<named_tuple<>, Visitor> {
  using tuple_type = named_tuple<>;
  using visitor_type = Visitor;

 private:
  // Apply begin if exists, supports template resolution
  template <typename Vis>
  inline static auto apply_begin(tuple_type& value, Vis& visitor) ->
  typename enable_if<is_same<decltype(declval<Vis>().begin(value)),void>::value, void>::type
  { visitor.begin(value); }

  template <typename ... T> inline static void apply_begin(tuple_type&, T& ...) {}

  // Apply end if exists
  template <typename Vis>
  inline static auto apply_end(tuple_type& value, Vis& visitor) ->
  typename enable_if<is_same<decltype(declval<Vis>().end(value)),void>::value, void>::type
  { visitor.end(value); }

  template <typename ... T> inline static void apply_end(tuple_type&, T& ...) {}

 public:
  static void visit(tuple_type& value, visitor_type& visitor) {
    apply_begin(value,visitor);
    apply_end(value,visitor);
  }
};

template <typename Tuple, typename Visitor> void visit(Tuple& tuple, Visitor& visitor) {
  tuple_visit<Tuple,Visitor>::visit(tuple,visitor);
}

}  // namespace name_tuple

#endif  // NAMED_TUPLES_TUPLE_VISITOR_HEADER
<|endoftext|>


<commit_before>/*
  Copyright (c) 2014 DataStax

  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 "cassandra.hpp"
#include "result_response.hpp"

extern "C" {

void cass_result_free(const CassResult* result) {
  delete result->from();
}

size_t cass_result_row_count(const CassResult* result) {
  if (result->kind == CASS_RESULT_KIND_ROWS) {
    return result->row_count;
  }
  return 0;
}

size_t cass_result_column_count(const CassResult* result) {
  if (result->kind == CASS_RESULT_KIND_ROWS) {
    return result->column_count;
  }
  return 0;
}

CassValueType cass_result_column_type(const CassResult* result, size_t index) {
  if (result->kind == CASS_RESULT_KIND_ROWS &&
      index < result->column_metadata.size()) {
    return static_cast<CassValueType>(result->column_metadata[index].type);
  }
  return CASS_VALUE_TYPE_UNKNOWN;
}

const CassRow* cass_result_first_row(const CassResult* result) {
  if (result->kind == CASS_RESULT_KIND_ROWS && result->row_count > 0) {
    return CassRow::to(&result->first_row);
  }
  return nullptr;
}
}
<commit_msg>Implement function for getting column name<commit_after>/*
  Copyright (c) 2014 DataStax

  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 "cassandra.hpp"
#include "result_response.hpp"

extern "C" {

void cass_result_free(const CassResult* result) {
  delete result->from();
}

size_t cass_result_row_count(const CassResult* result) {
  if (result->kind == CASS_RESULT_KIND_ROWS) {
    return result->row_count;
  }
  return 0;
}

size_t cass_result_column_count(const CassResult* result) {
  if (result->kind == CASS_RESULT_KIND_ROWS) {
    return result->column_count;
  }
  return 0;
}

CassString cass_result_column_name(const CassResult* result, size_t index) {
    CassString str;
    if (result->kind == CASS_RESULT_KIND_ROWS &&
        index < result->column_metadata.size()) {
        str.data = result->column_metadata[index].name;
        str.length = result->column_metadata[index].name_size;
    }
    else {
        str.data = "";
        str.length = 0;
    }
    return str;
}

CassValueType cass_result_column_type(const CassResult* result, size_t index) {
  if (result->kind == CASS_RESULT_KIND_ROWS &&
      index < result->column_metadata.size()) {
    return static_cast<CassValueType>(result->column_metadata[index].type);
  }
  return CASS_VALUE_TYPE_UNKNOWN;
}

const CassRow* cass_result_first_row(const CassResult* result) {
  if (result->kind == CASS_RESULT_KIND_ROWS && result->row_count > 0) {
    return CassRow::to(&result->first_row);
  }
  return nullptr;
}
}
<|endoftext|>


<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: nadavs@google.com <Nadav Samet>
//         Jin Qing (http://blog.csdn.net/jq0123)

#include "server_impl.hpp"

#include <signal.h>
#include <string.h>
#include <functional>
#include <iostream>
#include <utility>

#include <boost/bind.hpp>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include <google/protobuf/stubs/common.h>
#include <zmq.hpp>

#include "client_connection.hpp"
#include "connection_manager.hpp"
#include "logging.hpp"
#include "reactor.hpp"
#include "rpcz/application.hpp"
#include "rpcz/callback.hpp"
#include "rpcz/rpc_controller.hpp"
#include "rpcz/rpcz.pb.h"
#include "rpcz/service.hpp"
#include "zmq_utils.hpp"

namespace rpcz {

class server_channel_impl : public server_channel {
 public:
  server_channel_impl(const client_connection& connection)
      : connection_(connection) {
      }

  virtual void send(const google::protobuf::Message& response) {
    rpc_response_header generic_rpc_response;
    int msg_size = response.ByteSize();
    scoped_ptr<zmq::message_t> payload(new zmq::message_t(msg_size));
    if (!response.SerializeToArray(payload->data(), msg_size)) {
      throw invalid_message_error("Invalid response message");
    }
    send_generic_response(generic_rpc_response,
                        payload.release());
  }

  virtual void send0(const std::string& response) {
    rpc_response_header generic_rpc_response;
    send_generic_response(generic_rpc_response,
                        string_to_message(response));
  }

  virtual void send_error(int application_error,
                          const std::string& error_message="") {
    rpc_response_header generic_rpc_response;
    zmq::message_t* payload = new zmq::message_t();
    generic_rpc_response.set_status(status::APPLICATION_ERROR);
    generic_rpc_response.set_application_error(application_error);
    if (!error_message.empty()) {
      generic_rpc_response.set_error(error_message);
    }
    send_generic_response(generic_rpc_response,
                        payload);
  }

 private:
  client_connection connection_;
  scoped_ptr<google::protobuf::Message> request_;

  // Sends the response back to a function server_impl through the reply function.
  // Takes ownership of the provided payload message.
  void send_generic_response(const rpc_response_header& generic_rpc_response,
                           zmq::message_t* payload) {
    size_t msg_size = generic_rpc_response.ByteSize();
    zmq::message_t* zmq_response_message = new zmq::message_t(msg_size);
    CHECK(generic_rpc_response.SerializeToArray(
            zmq_response_message->data(),
            msg_size));

    message_vector v;
    v.push_back(zmq_response_message);
    v.push_back(payload);
    connection_.reply(&v);
  }

  friend class proto_rpc_service;
};

class proto_rpc_service : public rpc_service {
 public:
  explicit proto_rpc_service(service* service) : service_(service) {
  }

  virtual void dispatch_request(const std::string& method,
                               const void* payload, size_t payload_len,
                               server_channel* channel_) {
    scoped_ptr<server_channel_impl> channel(
        static_cast<server_channel_impl*>(channel_));

    const ::google::protobuf::MethodDescriptor* descriptor =
        service_->GetDescriptor()->FindMethodByName(
            method);
    if (descriptor == NULL) {
      // Invalid method name
      DLOG(INFO) << "Invalid method name: " << method,
      channel->send_error(application_error::NO_SUCH_METHOD);
      return;
    }
    channel->request_.reset(CHECK_NOTNULL(
            service_->GetRequestPrototype(descriptor).New()));
    if (!channel->request_->ParseFromArray(payload, payload_len)) {
      DLOG(INFO) << "Failed to parse request.";
      // Invalid proto;
      channel->send_error(application_error::INVALID_MESSAGE);
      return;
    }
    server_channel_impl* channel_ptr = channel.release();
    service_->call_method(descriptor,
                         *channel_ptr->request_,
                         channel_ptr);
  }

 private:
  scoped_ptr<service> service_;
};

server_impl::server_impl()
  : connection_manager_ptr_(connection_manager::get()) {
  assert(connection_manager_ptr_);
}

server_impl::~server_impl() { }

void server_impl::register_service(rpcz::service & service) {
  register_service(service, service.GetDescriptor()->name());
}

void server_impl::register_service(rpcz::service & service, const std::string& name) {
  register_rpc_service(new proto_rpc_service(&service), name);
  // TODO: delete proto_rpc_service
}

void server_impl::register_rpc_service(rpcz::rpc_service *rpc_service,
                              const std::string& name) {
  service_map_[name] = rpc_service;
}

void server_impl::bind(const std::string& endpoint) {
  connection_manager::server_function f = boost::bind(
      &server_impl::handle_request, this, _1, _2);
  connection_manager_ptr_->bind(endpoint, f);
}

void server_impl::handle_request(const client_connection& connection,
                            message_iterator& iter) {
  if (!iter.has_more()) {
    return;
  }
  rpc_request_header rpc_request_header;
  scoped_ptr<server_channel> channel(new server_channel_impl(connection));
  {
    zmq::message_t& msg = iter.next();
    if (!rpc_request_header.ParseFromArray(msg.data(), msg.size())) {
      // Handle bad rpc.
      DLOG(INFO) << "Received bad header.";
      channel->send_error(application_error::INVALID_HEADER);
      return;
    };
  }
  if (!iter.has_more()) {
    return;
  }
  zmq::message_t& payload = iter.next();
  if (iter.has_more()) {
    return;
  }

  rpc_service_map::const_iterator service_it = service_map_.find(
      rpc_request_header.service());
  if (service_it == service_map_.end()) {
    // Handle invalid service.
    DLOG(INFO) << "Invalid service: " << rpc_request_header.service();
    channel->send_error(application_error::NO_SUCH_SERVICE);
    return;
  }
  rpcz::rpc_service* service = service_it->second;
  service->dispatch_request(rpc_request_header.method(),
                           payload.data(), payload.size(),
                           channel.release());
}
}  // namespace
<commit_msg>fix service's ownership<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: nadavs@google.com <Nadav Samet>
//         Jin Qing (http://blog.csdn.net/jq0123)

#include "server_impl.hpp"

#include <signal.h>
#include <string.h>
#include <functional>
#include <iostream>
#include <utility>

#include <boost/bind.hpp>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include <google/protobuf/stubs/common.h>
#include <zmq.hpp>

#include "client_connection.hpp"
#include "connection_manager.hpp"
#include "logging.hpp"
#include "reactor.hpp"
#include "rpcz/application.hpp"
#include "rpcz/callback.hpp"
#include "rpcz/rpc_controller.hpp"
#include "rpcz/rpcz.pb.h"
#include "rpcz/service.hpp"
#include "zmq_utils.hpp"

namespace rpcz {

class server_channel_impl : public server_channel {
 public:
  server_channel_impl(const client_connection& connection)
      : connection_(connection) {
      }

  virtual void send(const google::protobuf::Message& response) {
    rpc_response_header generic_rpc_response;
    int msg_size = response.ByteSize();
    scoped_ptr<zmq::message_t> payload(new zmq::message_t(msg_size));
    if (!response.SerializeToArray(payload->data(), msg_size)) {
      throw invalid_message_error("Invalid response message");
    }
    send_generic_response(generic_rpc_response,
                        payload.release());
  }

  virtual void send0(const std::string& response) {
    rpc_response_header generic_rpc_response;
    send_generic_response(generic_rpc_response,
                        string_to_message(response));
  }

  virtual void send_error(int application_error,
                          const std::string& error_message="") {
    rpc_response_header generic_rpc_response;
    zmq::message_t* payload = new zmq::message_t();
    generic_rpc_response.set_status(status::APPLICATION_ERROR);
    generic_rpc_response.set_application_error(application_error);
    if (!error_message.empty()) {
      generic_rpc_response.set_error(error_message);
    }
    send_generic_response(generic_rpc_response,
                        payload);
  }

 private:
  client_connection connection_;
  scoped_ptr<google::protobuf::Message> request_;

  // Sends the response back to a function server_impl through the reply function.
  // Takes ownership of the provided payload message.
  void send_generic_response(const rpc_response_header& generic_rpc_response,
                           zmq::message_t* payload) {
    size_t msg_size = generic_rpc_response.ByteSize();
    zmq::message_t* zmq_response_message = new zmq::message_t(msg_size);
    CHECK(generic_rpc_response.SerializeToArray(
            zmq_response_message->data(),
            msg_size));

    message_vector v;
    v.push_back(zmq_response_message);
    v.push_back(payload);
    connection_.reply(&v);
  }

  friend class proto_rpc_service;
};

class proto_rpc_service : public rpc_service {
 public:
  // Does not take ownership of the provided service.
  explicit proto_rpc_service(service & service) : service_(service) {
  }

  virtual void dispatch_request(const std::string& method,
                               const void* payload, size_t payload_len,
                               server_channel* channel_) {
    scoped_ptr<server_channel_impl> channel(
        static_cast<server_channel_impl*>(channel_));

    const ::google::protobuf::MethodDescriptor* descriptor =
        service_.GetDescriptor()->FindMethodByName(
            method);
    if (descriptor == NULL) {
      // Invalid method name
      DLOG(INFO) << "Invalid method name: " << method,
      channel->send_error(application_error::NO_SUCH_METHOD);
      return;
    }
    channel->request_.reset(CHECK_NOTNULL(
            service_.GetRequestPrototype(descriptor).New()));
    if (!channel->request_->ParseFromArray(payload, payload_len)) {
      DLOG(INFO) << "Failed to parse request.";
      // Invalid proto;
      channel->send_error(application_error::INVALID_MESSAGE);
      return;
    }
    server_channel_impl* channel_ptr = channel.release();
    service_.call_method(descriptor,
                         *channel_ptr->request_,
                         channel_ptr);
  }

 private:
  service & service_;
};

server_impl::server_impl()
  : connection_manager_ptr_(connection_manager::get()) {
  assert(connection_manager_ptr_);
}

server_impl::~server_impl() { }

void server_impl::register_service(rpcz::service & service) {
  register_service(service, service.GetDescriptor()->name());
}

void server_impl::register_service(rpcz::service & service, const std::string& name) {
  register_rpc_service(new proto_rpc_service(service), name);
  // TODO: delete proto_rpc_service
}

void server_impl::register_rpc_service(rpcz::rpc_service *rpc_service,
                              const std::string& name) {
  service_map_[name] = rpc_service;
}

void server_impl::bind(const std::string& endpoint) {
  connection_manager::server_function f = boost::bind(
      &server_impl::handle_request, this, _1, _2);
  connection_manager_ptr_->bind(endpoint, f);
}

void server_impl::handle_request(const client_connection& connection,
                            message_iterator& iter) {
  if (!iter.has_more()) {
    return;
  }
  rpc_request_header rpc_request_header;
  scoped_ptr<server_channel> channel(new server_channel_impl(connection));
  {
    zmq::message_t& msg = iter.next();
    if (!rpc_request_header.ParseFromArray(msg.data(), msg.size())) {
      // Handle bad rpc.
      DLOG(INFO) << "Received bad header.";
      channel->send_error(application_error::INVALID_HEADER);
      return;
    };
  }
  if (!iter.has_more()) {
    return;
  }
  zmq::message_t& payload = iter.next();
  if (iter.has_more()) {
    return;
  }

  rpc_service_map::const_iterator service_it = service_map_.find(
      rpc_request_header.service());
  if (service_it == service_map_.end()) {
    // Handle invalid service.
    DLOG(INFO) << "Invalid service: " << rpc_request_header.service();
    channel->send_error(application_error::NO_SUCH_SERVICE);
    return;
  }
  rpcz::rpc_service* service = service_it->second;
  service->dispatch_request(rpc_request_header.method(),
                           payload.data(), payload.size(),
                           channel.release());
}
}  // namespace
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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 _XPATHAPI_HXX
#define _XPATHAPI_HXX

#include <map>
#include <vector>

#include <sal/types.h>
#include <cppuhelper/implbase2.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Sequence.h>

#include <com/sun/star/uno/XInterface.hpp>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/xml/xpath/XXPathAPI.hpp>
#include <com/sun/star/xml/dom/XNode.hpp>
#include <com/sun/star/xml/dom/XNodeList.hpp>
#include <com/sun/star/xml/xpath/XXPathAPI.hpp>
#include <com/sun/star/xml/xpath/XXPathObject.hpp>
#include <com/sun/star/xml/xpath/XXPathExtension.hpp>
#include <com/sun/star/xml/xpath/Libxml2ExtensionHandle.hpp>
#include <com/sun/star/xml/xpath/XPathException.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

#include "libxml/tree.h"

using ::rtl::OUString;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::xml::dom;
using namespace com::sun::star::xml::xpath;

namespace XPath
{
    typedef std::map<OUString, OUString> nsmap_t;
    typedef std::vector< Reference<XXPathExtension> > extensions_t;

    class  CXPathAPI
        : public ::cppu::WeakImplHelper2< XXPathAPI, XServiceInfo >
    {

    private:
        nsmap_t m_nsmap;
        const Reference < XMultiServiceFactory >& m_aFactory;
        extensions_t m_extensions;

    public:
        // ctor
        CXPathAPI(const Reference< XMultiServiceFactory >& rSMgr);

        // call for factory
        static Reference< XInterface > getInstance(const Reference < XMultiServiceFactory >& xFactory);

        // static helpers for service info and component management
        static const char* aImplementationName;
        static const char* aSupportedServiceNames[];
        static OUString _getImplementationName();
        static Sequence< OUString > _getSupportedServiceNames();
        static Reference< XInterface > _getInstance(const Reference< XMultiServiceFactory >& rSMgr);

        // XServiceInfo
        virtual OUString SAL_CALL getImplementationName()
            throw (RuntimeException);
        virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName)
            throw (RuntimeException);
        virtual Sequence< OUString > SAL_CALL getSupportedServiceNames ()
            throw (RuntimeException);

        // --- XXPathAPI ---

        virtual void SAL_CALL registerNS(const OUString& aPrefix, const OUString& aURI)
            throw (RuntimeException);

        virtual void SAL_CALL unregisterNS(const OUString& aPrefix, const OUString& aURI)
            throw (RuntimeException);

        /**
        Use an XPath string to select a nodelist.
        */
        virtual Reference< XNodeList > SAL_CALL selectNodeList(const Reference< XNode >& contextNode, const OUString& str)
            throw (RuntimeException, XPathException);

        /**
        Use an XPath string to select a nodelist.
        */
        virtual Reference< XNodeList > SAL_CALL selectNodeListNS(const Reference< XNode >& contextNode, const OUString& str, const Reference< XNode >&  namespaceNode)
            throw (RuntimeException, XPathException);

        /**
        Use an XPath string to select a single node.
        */
        virtual Reference< XNode > SAL_CALL selectSingleNode(const Reference< XNode >& contextNode, const OUString& str)
            throw (RuntimeException, XPathException);

        /**
        Use an XPath string to select a single node.
        */
        virtual Reference< XNode > SAL_CALL selectSingleNodeNS(const Reference< XNode >& contextNode, const OUString& str, const Reference< XNode >&  namespaceNode)
            throw (RuntimeException, XPathException);

        virtual Reference< XXPathObject > SAL_CALL eval(const Reference< XNode >& contextNode, const OUString& str)
            throw (RuntimeException, XPathException);

        virtual Reference< XXPathObject > SAL_CALL evalNS(const Reference< XNode >& contextNode, const OUString& str, const Reference< XNode >&  namespaceNode)
            throw (RuntimeException, XPathException);

        virtual void SAL_CALL registerExtension(const OUString& aName) throw (RuntimeException);
        virtual void SAL_CALL registerExtensionInstance(const Reference< XXPathExtension>& aExtension) throw (RuntimeException);

    };
}

#endif
<commit_msg>fix some more ownerships<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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 _XPATHAPI_HXX
#define _XPATHAPI_HXX

#include <map>
#include <vector>

#include <sal/types.h>
#include <cppuhelper/implbase2.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Sequence.h>

#include <com/sun/star/uno/XInterface.hpp>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/xml/xpath/XXPathAPI.hpp>
#include <com/sun/star/xml/dom/XNode.hpp>
#include <com/sun/star/xml/dom/XNodeList.hpp>
#include <com/sun/star/xml/xpath/XXPathAPI.hpp>
#include <com/sun/star/xml/xpath/XXPathObject.hpp>
#include <com/sun/star/xml/xpath/XXPathExtension.hpp>
#include <com/sun/star/xml/xpath/Libxml2ExtensionHandle.hpp>
#include <com/sun/star/xml/xpath/XPathException.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

#include "libxml/tree.h"

using ::rtl::OUString;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::xml::dom;
using namespace com::sun::star::xml::xpath;

namespace XPath
{
    typedef std::map<OUString, OUString> nsmap_t;
    typedef std::vector< Reference<XXPathExtension> > extensions_t;

    class  CXPathAPI
        : public ::cppu::WeakImplHelper2< XXPathAPI, XServiceInfo >
    {

    private:
        nsmap_t m_nsmap;
        const Reference < XMultiServiceFactory > m_aFactory;
        extensions_t m_extensions;

    public:
        // ctor
        CXPathAPI(const Reference< XMultiServiceFactory >& rSMgr);

        // call for factory
        static Reference< XInterface > getInstance(const Reference < XMultiServiceFactory >& xFactory);

        // static helpers for service info and component management
        static const char* aImplementationName;
        static const char* aSupportedServiceNames[];
        static OUString _getImplementationName();
        static Sequence< OUString > _getSupportedServiceNames();
        static Reference< XInterface > _getInstance(const Reference< XMultiServiceFactory >& rSMgr);

        // XServiceInfo
        virtual OUString SAL_CALL getImplementationName()
            throw (RuntimeException);
        virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName)
            throw (RuntimeException);
        virtual Sequence< OUString > SAL_CALL getSupportedServiceNames ()
            throw (RuntimeException);

        // --- XXPathAPI ---

        virtual void SAL_CALL registerNS(const OUString& aPrefix, const OUString& aURI)
            throw (RuntimeException);

        virtual void SAL_CALL unregisterNS(const OUString& aPrefix, const OUString& aURI)
            throw (RuntimeException);

        /**
        Use an XPath string to select a nodelist.
        */
        virtual Reference< XNodeList > SAL_CALL selectNodeList(const Reference< XNode >& contextNode, const OUString& str)
            throw (RuntimeException, XPathException);

        /**
        Use an XPath string to select a nodelist.
        */
        virtual Reference< XNodeList > SAL_CALL selectNodeListNS(const Reference< XNode >& contextNode, const OUString& str, const Reference< XNode >&  namespaceNode)
            throw (RuntimeException, XPathException);

        /**
        Use an XPath string to select a single node.
        */
        virtual Reference< XNode > SAL_CALL selectSingleNode(const Reference< XNode >& contextNode, const OUString& str)
            throw (RuntimeException, XPathException);

        /**
        Use an XPath string to select a single node.
        */
        virtual Reference< XNode > SAL_CALL selectSingleNodeNS(const Reference< XNode >& contextNode, const OUString& str, const Reference< XNode >&  namespaceNode)
            throw (RuntimeException, XPathException);

        virtual Reference< XXPathObject > SAL_CALL eval(const Reference< XNode >& contextNode, const OUString& str)
            throw (RuntimeException, XPathException);

        virtual Reference< XXPathObject > SAL_CALL evalNS(const Reference< XNode >& contextNode, const OUString& str, const Reference< XNode >&  namespaceNode)
            throw (RuntimeException, XPathException);

        virtual void SAL_CALL registerExtension(const OUString& aName) throw (RuntimeException);
        virtual void SAL_CALL registerExtensionInstance(const Reference< XXPathExtension>& aExtension) throw (RuntimeException);

    };
}

#endif
<|endoftext|>


<commit_before>/* implementations of byte-at-a-time virtual read/writes for long mode that
   never cause faults/exceptions and maybe do not affect TLB content */

#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR

    Bit8u BX_CPP_AttrRegparmN(2)
BX_CPU_C::read_virtual_byte_64_nofail(unsigned s, Bit64u offset, uint8_t *error)
{
    Bit8u data;
    Bit64u laddr = get_laddr64(s, offset); // this is safe

    if (! IsCanonical(laddr)) {
        *error = 1;
        return 0;
    }

    access_read_linear_nofail(laddr, 1, 0, BX_READ, (void *) &data, error);
    return data;
}

int BX_CPU_C::access_read_linear_nofail(bx_address laddr, unsigned len, unsigned curr_pl, unsigned xlate_rw, void *data, uint8_t *error)
{
    BX_ASSERT(xlate_rw == BX_READ || xlate_rw == BX_RW); // this is safe

    Bit32u pageOffset = PAGE_OFFSET(laddr); // this is safe

    bx_TLB_entry *tlbEntry = BX_TLB_ENTRY_OF(laddr); // this is safe

    /* next line DOES THE PAGE TABLE WALK */
    BX_CPU_THIS_PTR address_xlation.paddress1 = translate_linear(tlbEntry, laddr, (curr_pl == 3), xlate_rw);
    BX_CPU_THIS_PTR address_xlation.pages     = 1;
    access_read_physical(BX_CPU_THIS_PTR address_xlation.paddress1, len, data);
    /* previous line SHOULD BE SAFE */

    return 0;
}

bx_phy_address BX_CPU_C::translate_linear_nofail(bx_TLB_entry *tlbEntry, bx_address laddr, unsigned user, unsigned rw)
{
    Bit32u combined_access = 0x06;
    Bit32u lpf_mask = 0xfff; // 4K pages

#if BX_SUPPORT_X86_64
    if (! long_mode()) laddr &= 0xffffffff;
#endif

    bx_phy_address paddress, ppf, poffset = PAGE_OFFSET(laddr);
    unsigned isWrite = rw & 1; // write or r-m-w
    unsigned isExecute = (rw == BX_EXECUTE);

    InstrTLB_Increment(tlbLookups);
    InstrTLB_Stats();

    bx_address lpf = LPFOf(laddr);

    // already looked up TLB for code access
    if (! isExecute && TLB_LPFOf(tlbEntry->lpf) == lpf)
    {
        paddress = tlbEntry->ppf | poffset;

        if (tlbEntry->accessBits & (1 << (/*(isExecute<<2) |*/ (isWrite<<1) | user)))
            return paddress;

        // The current access does not have permission according to the info
        // in our TLB cache entry.  Re-walk the page tables, in case there is
        // updated information in the memory image, and let the long path code
        // generate an exception if one is warranted.
    }

    InstrTLB_Increment(tlbMisses);

    if(BX_CPU_THIS_PTR cr0.get_PG())
    {
        BX_DEBUG(("page walk for address 0x" FMT_LIN_ADDRX, laddr));

#if BX_CPU_LEVEL >= 6
#if BX_SUPPORT_X86_64
        if (long_mode())
            paddress = translate_linear_long_mode(laddr, lpf_mask, combined_access, user, rw);
        else
#endif
            if (BX_CPU_THIS_PTR cr4.get_PAE())
                paddress = translate_linear_PAE(laddr, lpf_mask, combined_access, user, rw);
            else
#endif
                paddress = translate_linear_legacy(laddr, lpf_mask, combined_access, user, rw);

#if BX_CPU_LEVEL >= 5
        if (lpf_mask > 0xfff)
            BX_CPU_THIS_PTR TLB.split_large = 1;
#endif
    }
    else {
        // no paging
        paddress = (bx_phy_address) laddr;
    }

    // Calculate physical memory address and fill in TLB cache entry
#if BX_SUPPORT_VMX >= 2
    if (BX_CPU_THIS_PTR in_vmx_guest) {
        if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_EPT_ENABLE)) {
            paddress = translate_guest_physical(paddress, laddr, 1, 0, rw);
        }
    }
#endif
#if BX_SUPPORT_SVM
    if (BX_CPU_THIS_PTR in_svm_guest && SVM_NESTED_PAGING_ENABLED) {
        paddress = nested_walk(paddress, rw, 0);
    }
#endif
    paddress = A20ADDR(paddress);
    return paddress;
}
<commit_msg>fuck the TLB<commit_after>/* implementations of byte-at-a-time virtual read/writes for long mode that
   never cause faults/exceptions and maybe do not affect TLB content */

#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR

    Bit8u BX_CPP_AttrRegparmN(2)
BX_CPU_C::read_virtual_byte_64_nofail(unsigned s, Bit64u offset, uint8_t *error)
{
    Bit8u data;
    Bit64u laddr = get_laddr64(s, offset); // this is safe

    if (! IsCanonical(laddr)) {
        *error = 1;
        return 0;
    }

    access_read_linear_nofail(laddr, 1, 0, BX_READ, (void *) &data, error);
    return data;
}

int BX_CPU_C::access_read_linear_nofail(bx_address laddr, unsigned len, unsigned curr_pl, unsigned xlate_rw, void *data, uint8_t *error)
{
    BX_ASSERT(xlate_rw == BX_READ || xlate_rw == BX_RW); // this is safe

    Bit32u pageOffset = PAGE_OFFSET(laddr); // this is safe

    bx_TLB_entry *tlbEntry = BX_TLB_ENTRY_OF(laddr); // this is safe

    /* next line DOES THE PAGE TABLE WALK */
    BX_CPU_THIS_PTR address_xlation.paddress1 = translate_linear(tlbEntry, laddr, (curr_pl == 3), xlate_rw);
    BX_CPU_THIS_PTR address_xlation.pages     = 1;
    access_read_physical(BX_CPU_THIS_PTR address_xlation.paddress1, len, data);
    /* previous line SHOULD BE SAFE */

    return 0;
}

bx_phy_address BX_CPU_C::translate_linear_nofail(bx_TLB_entry *tlbEntry, bx_address laddr, unsigned user, unsigned rw)
{
    Bit32u combined_access = 0x06;
    Bit32u lpf_mask = 0xfff; // 4K pages

#if BX_SUPPORT_X86_64
    if (! long_mode()) laddr &= 0xffffffff;
#endif

    bx_phy_address paddress, ppf, poffset = PAGE_OFFSET(laddr);
    unsigned isWrite = rw & 1; // write or r-m-w
    unsigned isExecute = (rw == BX_EXECUTE);

    bx_address lpf = LPFOf(laddr);

    if(BX_CPU_THIS_PTR cr0.get_PG())
    {
        BX_DEBUG(("page walk for address 0x" FMT_LIN_ADDRX, laddr));

#if BX_CPU_LEVEL >= 6
#if BX_SUPPORT_X86_64
        if (long_mode())
            paddress = translate_linear_long_mode(laddr, lpf_mask, combined_access, user, rw);
        else
#endif
            if (BX_CPU_THIS_PTR cr4.get_PAE())
                paddress = translate_linear_PAE(laddr, lpf_mask, combined_access, user, rw);
            else
#endif
                paddress = translate_linear_legacy(laddr, lpf_mask, combined_access, user, rw);

#if BX_CPU_LEVEL >= 5
        if (lpf_mask > 0xfff)
            BX_CPU_THIS_PTR TLB.split_large = 1;
#endif
    }
    else {
        // no paging
        paddress = (bx_phy_address) laddr;
    }

    // Calculate physical memory address and fill in TLB cache entry
#if BX_SUPPORT_VMX >= 2
    if (BX_CPU_THIS_PTR in_vmx_guest) {
        if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_EPT_ENABLE)) {
            paddress = translate_guest_physical(paddress, laddr, 1, 0, rw);
        }
    }
#endif
#if BX_SUPPORT_SVM
    if (BX_CPU_THIS_PTR in_svm_guest && SVM_NESTED_PAGING_ENABLED) {
        paddress = nested_walk(paddress, rw, 0);
    }
#endif
    paddress = A20ADDR(paddress);
    return paddress;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Jolla Ltd.
** Contact: Vesa-Matti Hartikainen <vesa-matti.hartikainen@jollamobile.com>
**
****************************************************************************/

#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include <QQmlEngine>
#include <QtQml>
#include <QTimer>
#include <QTranslator>
#include <QDir>
#include <QScreen>
#include <QDBusConnection>

//#include "qdeclarativemozview.h"
#include "quickmozview.h"
#include "qmozcontext.h"

#include "declarativebookmarkmodel.h"
#include "declarativewebutils.h"
#include "browserservice.h"
#include "downloadmanager.h"
#include "settingmanager.h"
#include "closeeventfilter.h"
#include "declarativetab.h"
#include "declarativetabmodel.h"
#include "declarativehistorymodel.h"

#ifdef HAS_BOOSTER
#include <MDeclarativeCache>
#endif

Q_DECL_EXPORT int main(int argc, char *argv[])
{
    // Gecko embedding crashes with threaded render loop
    // that's why this workaround.
    // See JB#7358
    setenv("QML_BAD_GUI_RENDER_LOOP", "1", 1);
#ifdef HAS_BOOSTER
    QScopedPointer<QGuiApplication> app(MDeclarativeCache::qApplication(argc, argv));
    QScopedPointer<QQuickView> view(MDeclarativeCache::qQuickView());
#else
    QScopedPointer<QGuiApplication> app(new QGuiApplication(argc, argv));
    QScopedPointer<QQuickView> view(new QQuickView);
#endif
    app->setQuitOnLastWindowClosed(false);

    BrowserService *service = new BrowserService(app.data());
    // Handle command line launch
    if (!service->registered()) {
        QDBusMessage message = QDBusMessage::createMethodCall(service->serviceName(), "/",
                                                              service->serviceName(), "openUrl");
        QStringList args;
        // Pass url argument if given
        if (app->arguments().count() > 1) {
            args << app->arguments().at(1);
        }
        message.setArguments(QVariantList() << args);

        QDBusConnection::sessionBus().asyncCall(message);
        if (QCoreApplication::hasPendingEvents()) {
            QCoreApplication::processEvents();
        }

        return 0;
    }

    //% "Browser"
    QT_TRID_NOOP("sailfish-browser-ap-name");

    QString translationPath("/usr/share/translations/");
    QTranslator engineeringEnglish;
    engineeringEnglish.load("sailfish-browser_eng_en", translationPath);
    qApp->installTranslator(&engineeringEnglish);

    QTranslator translator;
    translator.load(QLocale(), "sailfish-browser", "-", translationPath);
    qApp->installTranslator(&translator);

    qmlRegisterType<DeclarativeBookmarkModel>("Sailfish.Browser", 1, 0, "BookmarkModel");
    qmlRegisterType<DeclarativeTabModel>("Sailfish.Browser", 1, 0, "TabModel");
    qmlRegisterType<DeclarativeHistoryModel>("Sailfish.Browser", 1, 0, "HistoryModel");
    qmlRegisterType<DeclarativeTab>("Sailfish.Browser", 1, 0, "Tab");

    QString componentPath(DEFAULT_COMPONENTS_PATH);
    QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/components/EmbedLiteBinComponents.manifest"));
    QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/components/EmbedLiteJSComponents.manifest"));
    QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/chrome/EmbedLiteJSScripts.manifest"));
    QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/chrome/EmbedLiteOverrides.manifest"));

    app->setApplicationName(QString("sailfish-browser"));
    app->setOrganizationName(QString("org.sailfishos"));

    DeclarativeWebUtils * utils = new DeclarativeWebUtils(app->arguments(), service, app.data());
    view->rootContext()->setContextProperty("WebUtils", utils);
    view->rootContext()->setContextProperty("MozContext", QMozContext::GetInstance());

    DownloadManager  * dlMgr = new DownloadManager(service, app.data());
    CloseEventFilter * clsEventFilter = new CloseEventFilter(dlMgr, app.data());
    view->installEventFilter(clsEventFilter);
    QObject::connect(service, SIGNAL(openUrlRequested(QString)),
                     clsEventFilter, SLOT(cancelStopApplication()));

    SettingManager * settingMgr = new SettingManager(app.data());
    QObject::connect(QMozContext::GetInstance(), SIGNAL(onInitialized()),
                     settingMgr, SLOT(initialize()));

    QObject::connect(QMozContext::GetInstance(), SIGNAL(newWindowRequested(QString,uint,QNewWindowResponse*)),
                     utils, SLOT(openUrl(QString)));

    bool isDesktop = qApp->arguments().contains("-desktop");

    QString path;
    if (isDesktop) {
        path = qApp->applicationDirPath() + QDir::separator();
    } else {
        path = QString(DEPLOYMENT_PATH);
    }
    view->setSource(QUrl::fromLocalFile(path+"browser.qml"));
    view->showFullScreen();

    // Setup embedding
    QTimer::singleShot(0, QMozContext::GetInstance(), SLOT(runEmbedding()));

    return app->exec();
}
<commit_msg>[sailfish-browser] Use customized async message loop. Fixes JB#8078<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Jolla Ltd.
** Contact: Vesa-Matti Hartikainen <vesa-matti.hartikainen@jollamobile.com>
**
****************************************************************************/

#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include <QQmlEngine>
#include <QtQml>
#include <QTimer>
#include <QTranslator>
#include <QDir>
#include <QScreen>
#include <QDBusConnection>

//#include "qdeclarativemozview.h"
#include "quickmozview.h"
#include "qmozcontext.h"

#include "declarativebookmarkmodel.h"
#include "declarativewebutils.h"
#include "browserservice.h"
#include "downloadmanager.h"
#include "settingmanager.h"
#include "closeeventfilter.h"
#include "declarativetab.h"
#include "declarativetabmodel.h"
#include "declarativehistorymodel.h"

#ifdef HAS_BOOSTER
#include <MDeclarativeCache>
#endif

Q_DECL_EXPORT int main(int argc, char *argv[])
{
    // EGL FPS are lower with threaded render loop
    // that's why this workaround.
    // See JB#7358
    setenv("QML_BAD_GUI_RENDER_LOOP", "1", 1);
    setenv("USE_ASYNC", "1", 1);
#ifdef HAS_BOOSTER
    QScopedPointer<QGuiApplication> app(MDeclarativeCache::qApplication(argc, argv));
    QScopedPointer<QQuickView> view(MDeclarativeCache::qQuickView());
#else
    QScopedPointer<QGuiApplication> app(new QGuiApplication(argc, argv));
    QScopedPointer<QQuickView> view(new QQuickView);
#endif
    app->setQuitOnLastWindowClosed(false);

    BrowserService *service = new BrowserService(app.data());
    // Handle command line launch
    if (!service->registered()) {
        QDBusMessage message = QDBusMessage::createMethodCall(service->serviceName(), "/",
                                                              service->serviceName(), "openUrl");
        QStringList args;
        // Pass url argument if given
        if (app->arguments().count() > 1) {
            args << app->arguments().at(1);
        }
        message.setArguments(QVariantList() << args);

        QDBusConnection::sessionBus().asyncCall(message);
        if (QCoreApplication::hasPendingEvents()) {
            QCoreApplication::processEvents();
        }

        return 0;
    }

    //% "Browser"
    QT_TRID_NOOP("sailfish-browser-ap-name");

    QString translationPath("/usr/share/translations/");
    QTranslator engineeringEnglish;
    engineeringEnglish.load("sailfish-browser_eng_en", translationPath);
    qApp->installTranslator(&engineeringEnglish);

    QTranslator translator;
    translator.load(QLocale(), "sailfish-browser", "-", translationPath);
    qApp->installTranslator(&translator);

    qmlRegisterType<DeclarativeBookmarkModel>("Sailfish.Browser", 1, 0, "BookmarkModel");
    qmlRegisterType<DeclarativeTabModel>("Sailfish.Browser", 1, 0, "TabModel");
    qmlRegisterType<DeclarativeHistoryModel>("Sailfish.Browser", 1, 0, "HistoryModel");
    qmlRegisterType<DeclarativeTab>("Sailfish.Browser", 1, 0, "Tab");

    QString componentPath(DEFAULT_COMPONENTS_PATH);
    QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/components/EmbedLiteBinComponents.manifest"));
    QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/components/EmbedLiteJSComponents.manifest"));
    QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/chrome/EmbedLiteJSScripts.manifest"));
    QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/chrome/EmbedLiteOverrides.manifest"));

    app->setApplicationName(QString("sailfish-browser"));
    app->setOrganizationName(QString("org.sailfishos"));

    DeclarativeWebUtils * utils = new DeclarativeWebUtils(app->arguments(), service, app.data());
    view->rootContext()->setContextProperty("WebUtils", utils);
    view->rootContext()->setContextProperty("MozContext", QMozContext::GetInstance());

    DownloadManager  * dlMgr = new DownloadManager(service, app.data());
    CloseEventFilter * clsEventFilter = new CloseEventFilter(dlMgr, app.data());
    view->installEventFilter(clsEventFilter);
    QObject::connect(service, SIGNAL(openUrlRequested(QString)),
                     clsEventFilter, SLOT(cancelStopApplication()));

    SettingManager * settingMgr = new SettingManager(app.data());
    QObject::connect(QMozContext::GetInstance(), SIGNAL(onInitialized()),
                     settingMgr, SLOT(initialize()));

    QObject::connect(QMozContext::GetInstance(), SIGNAL(newWindowRequested(QString,uint,QNewWindowResponse*)),
                     utils, SLOT(openUrl(QString)));

    bool isDesktop = qApp->arguments().contains("-desktop");

    QString path;
    if (isDesktop) {
        path = qApp->applicationDirPath() + QDir::separator();
    } else {
        path = QString(DEPLOYMENT_PATH);
    }
    view->setSource(QUrl::fromLocalFile(path+"browser.qml"));
    view->showFullScreen();

    // Setup embedding
    QTimer::singleShot(0, QMozContext::GetInstance(), SLOT(runEmbedding()));

    return app->exec();
}
<|endoftext|>


<commit_before>#include "opencog/spacetime/octomap/atom_types.definitions"

#define INHERITANCE_FILE "opencog/spacetime/octomap/atom_types.inheritance"
#define INITNAME octomap_types_init

#include <opencog/atoms/proto/atom_types.cc>
<commit_msg>Modify atom_types include path<commit_after>#include "opencog/spacetime/octomap/atom_types.definitions"

#define INHERITANCE_FILE "opencog/spacetime/octomap/atom_types.inheritance"
#define INITNAME octomap_types_init

#include <opencog/atoms/atom_types/atom_types.cc>
<|endoftext|>


<commit_before>/*
 * Author: Florian Hager
 * Version: 0.1
 * License: BSD 2-Clause
 *
 * Copyright (c) 2014, Florian Hager
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <string>
#include <map>
using namespace std;

map<char, float> letterfreq_en = {
	{'E',12.702},{'T',9.056},
	{'A',8.167}, {'O',7.507},
	{'I',6.996}, {'N',6.749},
	{'S',6.327}, {'R',5.987},
	{'H',6.094}, {'D',4.253},
	{'L',4.025}, {'U',2.758},
	{'C',2.782}, {'M',2.406},
	{'F',2.228}, {'Y',1.974},
	{'W',2.360}, {'G',2.015},
	{'P',1.929}, {'B',1.492},
	{'V',0.978}, {'K',0.772},
	{'X',0.150}, {'Q',0.095},
	{'J',0.153}, {'Z',0.074}};

map<char, float> letterfreq_de = {
	{'E',16.693},{'N',9.905},
	{'I',7.812}, {'S',6.765},
	{'R',6.539}, {'A',6.506},
	{'T',6.742}, {'D',5.414},
	{'H',4.064}, {'U',3.703},
	{'L',2.825}, {'C',2.837},
	{'G',3.647}, {'M',3.005},
	{'O',2.285}, {'B',2.566},
	{'W',1.396}, {'F',2.044},
	{'K',1.879}, {'Z',1.002},
	{'P',0.944}, {'V',1.069},
	{'J',0.191}, {'Y',0.032},
	{'X',0.022}, {'Q',0.055}};

map<string, map<char, float>*> letterfreqs = {
	{"en", &letterfreq_en},
	{"de", &letterfreq_de}};
map<char, float> *letterfreq = &letterfreq_en;

char alphasq[25] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

struct coords {
	short row;
	short column;
	short index;
	};

string cleanString(string *text);
map<char, float> calcLetterFreq(string *text);
float calcOffset(string *text);
string restorePunctuation(string *wopunc, string *wpunc, bool encrypting);

string encipherCaesarString(string *plain, char key);
string decipherCaesarString(string *cipher, char key);

string crackCaesarString(string *cipher);

string encipherVigenereString(string *plain, string *key);
string decipherVigenereString(string *cipher, string *key);

float calcIC(string *cipher);
string crackVigenereString(string *cipher);

string encipherOTPString(string *plain, int seed);
string decipherOTPString(string *cipher, int seed);

char* genKeySquare(string *key);
string encipherPlayfairString(string *plain, char* keysq);
string decipherPlayfairString(string *cipher, char* keysq);
<commit_msg>Update crack*String returns key AND plaintext<commit_after>/*
 * Author: Florian Hager
 * Version: 0.1
 * License: BSD 2-Clause
 *
 * Copyright (c) 2014, Florian Hager
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <string>
#include <utility>
#include <map>
using namespace std;

map<char, float> letterfreq_en = {
	{'E',12.702},{'T',9.056},
	{'A',8.167}, {'O',7.507},
	{'I',6.996}, {'N',6.749},
	{'S',6.327}, {'R',5.987},
	{'H',6.094}, {'D',4.253},
	{'L',4.025}, {'U',2.758},
	{'C',2.782}, {'M',2.406},
	{'F',2.228}, {'Y',1.974},
	{'W',2.360}, {'G',2.015},
	{'P',1.929}, {'B',1.492},
	{'V',0.978}, {'K',0.772},
	{'X',0.150}, {'Q',0.095},
	{'J',0.153}, {'Z',0.074}};

map<char, float> letterfreq_de = {
	{'E',16.693},{'N',9.905},
	{'I',7.812}, {'S',6.765},
	{'R',6.539}, {'A',6.506},
	{'T',6.742}, {'D',5.414},
	{'H',4.064}, {'U',3.703},
	{'L',2.825}, {'C',2.837},
	{'G',3.647}, {'M',3.005},
	{'O',2.285}, {'B',2.566},
	{'W',1.396}, {'F',2.044},
	{'K',1.879}, {'Z',1.002},
	{'P',0.944}, {'V',1.069},
	{'J',0.191}, {'Y',0.032},
	{'X',0.022}, {'Q',0.055}};

map<string, map<char, float>*> letterfreqs = {
	{"en", &letterfreq_en},
	{"de", &letterfreq_de}};
map<char, float> *letterfreq = &letterfreq_en;

char alphasq[25] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

struct CaesarResult {
	int key;
	string text;
	};

struct VigenereResult {
	string key;
	string text;
	};

struct coords {
	short row;
	short column;
	short index;
	};

string cleanString(string *text);
map<char, float> calcLetterFreq(string *text);
float calcOffset(string *text);
string restorePunctuation(string *wopunc, string *wpunc, bool encrypting);

string encipherCaesarString(string *plain, char key);
string decipherCaesarString(string *cipher, char key);

CaesarResult crackCaesarString(string *cipher);

string encipherVigenereString(string *plain, string *key);
string decipherVigenereString(string *cipher, string *key);

float calcIC(string *cipher);
VigenereResult crackVigenereString(string *cipher);

string encipherOTPString(string *plain, int seed);
string decipherOTPString(string *cipher, int seed);

char* genKeySquare(string *key);
string encipherPlayfairString(string *plain, char* keysq);
string decipherPlayfairString(string *cipher, char* keysq);
<|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/app/atom_main.h"

#include <stdlib.h>

#if defined(OS_WIN)
#include <windows.h>
#include <shellscalingapi.h>
#include <tchar.h>
#include <shellapi.h>

#include "atom/app/atom_main_delegate.h"
#include "atom/common/crash_reporter/win/crash_service_main.h"
#include "base/environment.h"
#include "base/win/windows_version.h"
#include "content/public/app/sandbox_helper_win.h"
#include "sandbox/win/src/sandbox_types.h"
#include "ui/gfx/win/dpi.h"
#elif defined(OS_LINUX)  // defined(OS_WIN)
#include "atom/app/atom_main_delegate.h"  // NOLINT
#include "content/public/app/content_main.h"
#else  // defined(OS_LINUX)
#include "atom/app/atom_library_main.h"
#endif  // defined(OS_MACOSX)

#include "atom/app/node_main.h"
#include "atom/common/atom_command_line.h"
#include "base/at_exit.h"
#include "base/i18n/icu_util.h"

namespace {

const char* kRunAsNode = "ELECTRON_RUN_AS_NODE";
const char* kOldRunAsNode = "ATOM_SHELL_INTERNAL_RUN_AS_NODE";

bool IsEnvSet(const char* name) {
#if defined(OS_WIN)
  size_t required_size;
  getenv_s(&required_size, nullptr, 0, name);
  return required_size != 0;
#else
  char* indicator = getenv(name);
  return indicator && indicator[0] != '\0';
#endif
}

bool IsRunAsNode() {
  return IsEnvSet(kRunAsNode) || IsEnvSet(kOldRunAsNode);
}

}  // namespace

#if defined(OS_WIN)
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
  int argc = 0;
  wchar_t** wargv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);

  // Make output work in console if we are not in cygiwn.
  if (!IsEnvSet("TERM") && !IsEnvSet("ELECTRON_NO_ATTACH_CONSOLE")) {
    AttachConsole(ATTACH_PARENT_PROCESS);

    FILE* dontcare;
    freopen_s(&dontcare, "CON", "w", stdout);
    freopen_s(&dontcare, "CON", "w", stderr);
  }

  // Convert argv to to UTF8
  char** argv = new char*[argc];
  for (int i = 0; i < argc; i++) {
    // Compute the size of the required buffer
    DWORD size = WideCharToMultiByte(CP_UTF8,
                                     0,
                                     wargv[i],
                                     -1,
                                     NULL,
                                     0,
                                     NULL,
                                     NULL);
    if (size == 0) {
      // This should never happen.
      fprintf(stderr, "Could not convert arguments to utf8.");
      exit(1);
    }
    // Do the actual conversion
    argv[i] = new char[size];
    DWORD result = WideCharToMultiByte(CP_UTF8,
                                       0,
                                       wargv[i],
                                       -1,
                                       argv[i],
                                       size,
                                       NULL,
                                       NULL);
    if (result == 0) {
      // This should never happen.
      fprintf(stderr, "Could not convert arguments to utf8.");
      exit(1);
    }
  }

  if (IsRunAsNode()) {
    // Now that argv conversion is done, we can finally start.
    base::AtExitManager atexit_manager;
    base::i18n::InitializeICU();
    return atom::NodeMain(argc, argv);
  } else if (IsEnvSet("ATOM_SHELL_INTERNAL_CRASH_SERVICE")) {
    return crash_service::Main(cmd);
  }

  sandbox::SandboxInterfaceInfo sandbox_info = {0};
  content::InitializeSandboxInfo(&sandbox_info);
  atom::AtomMainDelegate delegate;

  content::ContentMainParams params(&delegate);
  params.instance = instance;
  params.sandbox_info = &sandbox_info;
  atom::AtomCommandLine::Init(argc, argv);
  return content::ContentMain(params);
}

#elif defined(OS_LINUX)  // defined(OS_WIN)

int main(int argc, const char* argv[]) {
  if (IsRunAsNode()) {
    base::i18n::InitializeICU();
    base::AtExitManager atexit_manager;
    return atom::NodeMain(argc, const_cast<char**>(argv));
  }

  atom::AtomMainDelegate delegate;
  content::ContentMainParams params(&delegate);
  params.argc = argc;
  params.argv = argv;
  atom::AtomCommandLine::Init(argc, argv);
  return content::ContentMain(params);
}

#else  // defined(OS_LINUX)

int main(int argc, const char* argv[]) {
  if (IsRunAsNode()) {
    return AtomInitializeICUandStartNode(argc, const_cast<char**>(argv));
  }

  return AtomMain(argc, argv);
}

#endif  // defined(OS_MACOSX)
<commit_msg>Remove ATOM_SHELL_INTERNAL_RUN_AS_NODE support<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/app/atom_main.h"

#include <stdlib.h>

#if defined(OS_WIN)
#include <windows.h>
#include <shellscalingapi.h>
#include <tchar.h>
#include <shellapi.h>

#include "atom/app/atom_main_delegate.h"
#include "atom/common/crash_reporter/win/crash_service_main.h"
#include "base/environment.h"
#include "base/win/windows_version.h"
#include "content/public/app/sandbox_helper_win.h"
#include "sandbox/win/src/sandbox_types.h"
#include "ui/gfx/win/dpi.h"
#elif defined(OS_LINUX)  // defined(OS_WIN)
#include "atom/app/atom_main_delegate.h"  // NOLINT
#include "content/public/app/content_main.h"
#else  // defined(OS_LINUX)
#include "atom/app/atom_library_main.h"
#endif  // defined(OS_MACOSX)

#include "atom/app/node_main.h"
#include "atom/common/atom_command_line.h"
#include "base/at_exit.h"
#include "base/i18n/icu_util.h"

namespace {

const char* kRunAsNode = "ELECTRON_RUN_AS_NODE";

bool IsEnvSet(const char* name) {
#if defined(OS_WIN)
  size_t required_size;
  getenv_s(&required_size, nullptr, 0, name);
  return required_size != 0;
#else
  char* indicator = getenv(name);
  return indicator && indicator[0] != '\0';
#endif
}

bool IsRunAsNode() {
  return IsEnvSet(kRunAsNode);
}

}  // namespace

#if defined(OS_WIN)
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
  int argc = 0;
  wchar_t** wargv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);

  // Make output work in console if we are not in cygiwn.
  if (!IsEnvSet("TERM") && !IsEnvSet("ELECTRON_NO_ATTACH_CONSOLE")) {
    AttachConsole(ATTACH_PARENT_PROCESS);

    FILE* dontcare;
    freopen_s(&dontcare, "CON", "w", stdout);
    freopen_s(&dontcare, "CON", "w", stderr);
  }

  // Convert argv to to UTF8
  char** argv = new char*[argc];
  for (int i = 0; i < argc; i++) {
    // Compute the size of the required buffer
    DWORD size = WideCharToMultiByte(CP_UTF8,
                                     0,
                                     wargv[i],
                                     -1,
                                     NULL,
                                     0,
                                     NULL,
                                     NULL);
    if (size == 0) {
      // This should never happen.
      fprintf(stderr, "Could not convert arguments to utf8.");
      exit(1);
    }
    // Do the actual conversion
    argv[i] = new char[size];
    DWORD result = WideCharToMultiByte(CP_UTF8,
                                       0,
                                       wargv[i],
                                       -1,
                                       argv[i],
                                       size,
                                       NULL,
                                       NULL);
    if (result == 0) {
      // This should never happen.
      fprintf(stderr, "Could not convert arguments to utf8.");
      exit(1);
    }
  }

  if (IsRunAsNode()) {
    // Now that argv conversion is done, we can finally start.
    base::AtExitManager atexit_manager;
    base::i18n::InitializeICU();
    return atom::NodeMain(argc, argv);
  } else if (IsEnvSet("ATOM_SHELL_INTERNAL_CRASH_SERVICE")) {
    return crash_service::Main(cmd);
  }

  sandbox::SandboxInterfaceInfo sandbox_info = {0};
  content::InitializeSandboxInfo(&sandbox_info);
  atom::AtomMainDelegate delegate;

  content::ContentMainParams params(&delegate);
  params.instance = instance;
  params.sandbox_info = &sandbox_info;
  atom::AtomCommandLine::Init(argc, argv);
  return content::ContentMain(params);
}

#elif defined(OS_LINUX)  // defined(OS_WIN)

int main(int argc, const char* argv[]) {
  if (IsRunAsNode()) {
    base::i18n::InitializeICU();
    base::AtExitManager atexit_manager;
    return atom::NodeMain(argc, const_cast<char**>(argv));
  }

  atom::AtomMainDelegate delegate;
  content::ContentMainParams params(&delegate);
  params.argc = argc;
  params.argv = argv;
  atom::AtomCommandLine::Init(argc, argv);
  return content::ContentMain(params);
}

#else  // defined(OS_LINUX)

int main(int argc, const char* argv[]) {
  if (IsRunAsNode()) {
    return AtomInitializeICUandStartNode(argc, const_cast<char**>(argv));
  }

  return AtomMain(argc, argv);
}

#endif  // defined(OS_MACOSX)
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: gtkobject.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: vg $ $Date: 2008-01-29 08:38:10 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#include <plugins/gtk/gtkobject.hxx>
#include <plugins/gtk/gtkframe.hxx>
#include <plugins/gtk/gtkdata.hxx>
#include <plugins/gtk/gtkinst.hxx>

GtkSalObject::GtkSalObject( GtkSalFrame* pParent, BOOL bShow )
        : m_pSocket( NULL ),
          m_pRegion( NULL )
{
    if( pParent )
    {
        // our plug window
        m_pSocket = gtk_drawing_area_new();
        Show( bShow );
        // insert into container
        gtk_fixed_put( pParent->getFixedContainer(),
                       m_pSocket,
                       0, 0 );
        // realize so we can get a window id
        gtk_widget_realize( m_pSocket );

        // make it transparent; some plugins may not insert
        // their own window here but use the socket window itself
        gtk_widget_set_app_paintable( m_pSocket, TRUE );

        //system data
        SalDisplay* pDisp = GetX11SalData()->GetDisplay();
        m_aSystemData.pDisplay      = pDisp->GetDisplay();
        m_aSystemData.aWindow       = GDK_WINDOW_XWINDOW(m_pSocket->window);
        m_aSystemData.pSalFrame     = NULL;
        m_aSystemData.pWidget       = m_pSocket;
        m_aSystemData.pVisual       = pDisp->GetVisual(pParent->getScreenNumber()).GetVisual();
        m_aSystemData.nDepth        = pDisp->GetVisual(pParent->getScreenNumber()).GetDepth();
        m_aSystemData.aColormap     = pDisp->GetColormap(pParent->getScreenNumber()).GetXColormap();
        m_aSystemData.pAppContext   = NULL;
        m_aSystemData.aShellWindow  = GDK_WINDOW_XWINDOW(GTK_WIDGET(pParent->getWindow())->window);
        m_aSystemData.pShellWidget  = GTK_WIDGET(pParent->getWindow());

        g_signal_connect( G_OBJECT(m_pSocket), "button-press-event", G_CALLBACK(signalButton), this );
        g_signal_connect( G_OBJECT(m_pSocket), "button-release-event", G_CALLBACK(signalButton), this );
        g_signal_connect( G_OBJECT(m_pSocket), "focus-in-event", G_CALLBACK(signalFocus), this );
        g_signal_connect( G_OBJECT(m_pSocket), "focus-out-event", G_CALLBACK(signalFocus), this );
        g_signal_connect( G_OBJECT(m_pSocket), "destroy", G_CALLBACK(signalDestroy), this );

        // #i59255# necessary due to sync effects with java child windows
        pParent->Sync();
    }
}

GtkSalObject::~GtkSalObject()
{
    if( m_pRegion )
        gdk_region_destroy( m_pRegion );
    if( m_pSocket )
    {
        // remove socket from parent frame's fixed container
        gtk_container_remove( GTK_CONTAINER(gtk_widget_get_parent(m_pSocket)),
                              m_pSocket );
        // get rid of the socket
        // actually the gtk_container_remove should let the ref count
        // of the socket sink to 0 and destroy it (see signalDestroy)
        // this is just a sanity check
        if( m_pSocket )
            gtk_widget_destroy( m_pSocket );
    }
}

void GtkSalObject::ResetClipRegion()
{
    if( m_pSocket )
        gdk_window_shape_combine_region( m_pSocket->window, NULL, 0, 0 );
}

USHORT GtkSalObject::GetClipRegionType()
{
    return SAL_OBJECT_CLIP_INCLUDERECTS;
}

void GtkSalObject::BeginSetClipRegion( ULONG )
{
    if( m_pRegion )
        gdk_region_destroy( m_pRegion );
    m_pRegion = gdk_region_new();
}

void GtkSalObject::UnionClipRegion( long nX, long nY, long nWidth, long nHeight )
{
    GdkRectangle aRect;
    aRect.x         = nX;
    aRect.y         = nY;
    aRect.width     = nWidth;
    aRect.height    = nHeight;

    gdk_region_union_with_rect( m_pRegion, &aRect );
}

void GtkSalObject::EndSetClipRegion()
{
    if( m_pSocket )
        gdk_window_shape_combine_region( m_pSocket->window, m_pRegion, 0, 0 );
}

void GtkSalObject::SetPosSize( long nX, long nY, long nWidth, long nHeight )
{
    if( m_pSocket )
    {
        GtkFixed* pContainer = GTK_FIXED(gtk_widget_get_parent(m_pSocket));
        gtk_fixed_move( pContainer, m_pSocket, nX, nY );
        gtk_widget_set_size_request( m_pSocket, nWidth, nHeight );
        gtk_container_resize_children( GTK_CONTAINER(pContainer) );
    }
}

void GtkSalObject::Show( BOOL bVisible )
{
    if( m_pSocket )
    {
        if( bVisible )
            gtk_widget_show( m_pSocket );
        else
            gtk_widget_hide( m_pSocket );
    }
}

void GtkSalObject::Enable( BOOL )
{
}

void GtkSalObject::GrabFocus()
{
}

void GtkSalObject::SetBackground()
{
}

void GtkSalObject::SetBackground( SalColor )
{
}

const SystemEnvData* GtkSalObject::GetSystemData() const
{
    return &m_aSystemData;
}

gboolean GtkSalObject::signalButton( GtkWidget*, GdkEventButton* pEvent, gpointer object )
{
    GtkSalObject* pThis = (GtkSalObject*)object;

    if( pEvent->type == GDK_BUTTON_PRESS )
    {
        GTK_YIELD_GRAB();
        pThis->CallCallback( SALOBJ_EVENT_TOTOP, NULL );
    }

    return FALSE;
}

gboolean GtkSalObject::signalFocus( GtkWidget*, GdkEventFocus* pEvent, gpointer object )
{
    GtkSalObject* pThis = (GtkSalObject*)object;

    GTK_YIELD_GRAB();

    pThis->CallCallback( pEvent->in ? SALOBJ_EVENT_GETFOCUS : SALOBJ_EVENT_LOSEFOCUS, NULL );

    return FALSE;
}

void GtkSalObject::signalDestroy( GtkObject* pObj, gpointer object )
{
    GtkSalObject* pThis = (GtkSalObject*)object;
    if( GTK_WIDGET(pObj) == pThis->m_pSocket )
    {
        pThis->m_pSocket = NULL;
    }
}
<commit_msg>INTEGRATION: CWS changefileheader (1.12.60); FILE MERGED 2008/03/28 15:45:11 rt 1.12.60.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: gtkobject.cxx,v $
 * $Revision: 1.13 $
 *
 * 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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#include <plugins/gtk/gtkobject.hxx>
#include <plugins/gtk/gtkframe.hxx>
#include <plugins/gtk/gtkdata.hxx>
#include <plugins/gtk/gtkinst.hxx>

GtkSalObject::GtkSalObject( GtkSalFrame* pParent, BOOL bShow )
        : m_pSocket( NULL ),
          m_pRegion( NULL )
{
    if( pParent )
    {
        // our plug window
        m_pSocket = gtk_drawing_area_new();
        Show( bShow );
        // insert into container
        gtk_fixed_put( pParent->getFixedContainer(),
                       m_pSocket,
                       0, 0 );
        // realize so we can get a window id
        gtk_widget_realize( m_pSocket );

        // make it transparent; some plugins may not insert
        // their own window here but use the socket window itself
        gtk_widget_set_app_paintable( m_pSocket, TRUE );

        //system data
        SalDisplay* pDisp = GetX11SalData()->GetDisplay();
        m_aSystemData.pDisplay      = pDisp->GetDisplay();
        m_aSystemData.aWindow       = GDK_WINDOW_XWINDOW(m_pSocket->window);
        m_aSystemData.pSalFrame     = NULL;
        m_aSystemData.pWidget       = m_pSocket;
        m_aSystemData.pVisual       = pDisp->GetVisual(pParent->getScreenNumber()).GetVisual();
        m_aSystemData.nDepth        = pDisp->GetVisual(pParent->getScreenNumber()).GetDepth();
        m_aSystemData.aColormap     = pDisp->GetColormap(pParent->getScreenNumber()).GetXColormap();
        m_aSystemData.pAppContext   = NULL;
        m_aSystemData.aShellWindow  = GDK_WINDOW_XWINDOW(GTK_WIDGET(pParent->getWindow())->window);
        m_aSystemData.pShellWidget  = GTK_WIDGET(pParent->getWindow());

        g_signal_connect( G_OBJECT(m_pSocket), "button-press-event", G_CALLBACK(signalButton), this );
        g_signal_connect( G_OBJECT(m_pSocket), "button-release-event", G_CALLBACK(signalButton), this );
        g_signal_connect( G_OBJECT(m_pSocket), "focus-in-event", G_CALLBACK(signalFocus), this );
        g_signal_connect( G_OBJECT(m_pSocket), "focus-out-event", G_CALLBACK(signalFocus), this );
        g_signal_connect( G_OBJECT(m_pSocket), "destroy", G_CALLBACK(signalDestroy), this );

        // #i59255# necessary due to sync effects with java child windows
        pParent->Sync();
    }
}

GtkSalObject::~GtkSalObject()
{
    if( m_pRegion )
        gdk_region_destroy( m_pRegion );
    if( m_pSocket )
    {
        // remove socket from parent frame's fixed container
        gtk_container_remove( GTK_CONTAINER(gtk_widget_get_parent(m_pSocket)),
                              m_pSocket );
        // get rid of the socket
        // actually the gtk_container_remove should let the ref count
        // of the socket sink to 0 and destroy it (see signalDestroy)
        // this is just a sanity check
        if( m_pSocket )
            gtk_widget_destroy( m_pSocket );
    }
}

void GtkSalObject::ResetClipRegion()
{
    if( m_pSocket )
        gdk_window_shape_combine_region( m_pSocket->window, NULL, 0, 0 );
}

USHORT GtkSalObject::GetClipRegionType()
{
    return SAL_OBJECT_CLIP_INCLUDERECTS;
}

void GtkSalObject::BeginSetClipRegion( ULONG )
{
    if( m_pRegion )
        gdk_region_destroy( m_pRegion );
    m_pRegion = gdk_region_new();
}

void GtkSalObject::UnionClipRegion( long nX, long nY, long nWidth, long nHeight )
{
    GdkRectangle aRect;
    aRect.x         = nX;
    aRect.y         = nY;
    aRect.width     = nWidth;
    aRect.height    = nHeight;

    gdk_region_union_with_rect( m_pRegion, &aRect );
}

void GtkSalObject::EndSetClipRegion()
{
    if( m_pSocket )
        gdk_window_shape_combine_region( m_pSocket->window, m_pRegion, 0, 0 );
}

void GtkSalObject::SetPosSize( long nX, long nY, long nWidth, long nHeight )
{
    if( m_pSocket )
    {
        GtkFixed* pContainer = GTK_FIXED(gtk_widget_get_parent(m_pSocket));
        gtk_fixed_move( pContainer, m_pSocket, nX, nY );
        gtk_widget_set_size_request( m_pSocket, nWidth, nHeight );
        gtk_container_resize_children( GTK_CONTAINER(pContainer) );
    }
}

void GtkSalObject::Show( BOOL bVisible )
{
    if( m_pSocket )
    {
        if( bVisible )
            gtk_widget_show( m_pSocket );
        else
            gtk_widget_hide( m_pSocket );
    }
}

void GtkSalObject::Enable( BOOL )
{
}

void GtkSalObject::GrabFocus()
{
}

void GtkSalObject::SetBackground()
{
}

void GtkSalObject::SetBackground( SalColor )
{
}

const SystemEnvData* GtkSalObject::GetSystemData() const
{
    return &m_aSystemData;
}

gboolean GtkSalObject::signalButton( GtkWidget*, GdkEventButton* pEvent, gpointer object )
{
    GtkSalObject* pThis = (GtkSalObject*)object;

    if( pEvent->type == GDK_BUTTON_PRESS )
    {
        GTK_YIELD_GRAB();
        pThis->CallCallback( SALOBJ_EVENT_TOTOP, NULL );
    }

    return FALSE;
}

gboolean GtkSalObject::signalFocus( GtkWidget*, GdkEventFocus* pEvent, gpointer object )
{
    GtkSalObject* pThis = (GtkSalObject*)object;

    GTK_YIELD_GRAB();

    pThis->CallCallback( pEvent->in ? SALOBJ_EVENT_GETFOCUS : SALOBJ_EVENT_LOSEFOCUS, NULL );

    return FALSE;
}

void GtkSalObject::signalDestroy( GtkObject* pObj, gpointer object )
{
    GtkSalObject* pThis = (GtkSalObject*)object;
    if( GTK_WIDGET(pObj) == pThis->m_pSocket )
    {
        pThis->m_pSocket = NULL;
    }
}
<|endoftext|>