<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. 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.
 *****************************************************************************/

#include "modules/dreamview/backend/simulation_world/simulation_world_updater.h"

#include "google/protobuf/util/json_util.h"
#include "modules/dreamview/backend/common/dreamview_gflags.h"
#include "modules/map/hdmap/hdmap_util.h"

namespace apollo {
namespace dreamview {

using apollo::common::adapter::AdapterManager;
using apollo::common::monitor::MonitorMessageItem;
using apollo::common::util::GetProtoFromASCIIFile;
using apollo::hdmap::EndWayPointFile;
using apollo::routing::RoutingRequest;
using google::protobuf::util::MessageToJsonString;
using Json = nlohmann::json;

SimulationWorldUpdater::SimulationWorldUpdater(WebSocketHandler *websocket,
                                               const MapService *map_service,
                                               bool routing_from_file)
    : sim_world_service_(map_service, routing_from_file),
      map_service_(map_service),
      websocket_(websocket) {
  // Initialize default end point
  LoadDefaultEndPoint();

  websocket_->RegisterMessageHandler(
      "RetrieveMapData",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        auto iter = json.find("elements");
        if (iter != json.end()) {
          MapElementIds map_element_ids(*iter);
          auto retrieved = map_service_->RetrieveMapElements(map_element_ids);

          std::string retrieved_json_string;
          MessageToJsonString(retrieved, &retrieved_json_string);

          Json response;
          response["type"] = "MapData";
          response["data"] = Json::parse(retrieved_json_string);

          websocket_->SendData(conn, response.dump());
        }
      });

  websocket_->RegisterMessageHandler(
      "RetrieveMapElementsByRadius",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        auto radius = json.find("radius");
        if (radius == json.end()) {
          AERROR << "Cannot retrieve map elements with unknown radius.";
          return;
        }

        Json response = sim_world_service_.GetMapElements(*radius);
        response["type"] = "MapElements";
        websocket_->SendData(conn, response.dump());
      });

  websocket_->RegisterMessageHandler(
      "SendRoutingRequest",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        RoutingRequest routing_request;

        bool succeed = ConstructRoutingRequest(json, &routing_request);
        if (succeed) {
          AdapterManager::FillRoutingRequestHeader(FLAGS_dreamview_module_name,
                                                   &routing_request);
          AdapterManager::PublishRoutingRequest(routing_request);
        }

        // Publish monitor message.
        if (succeed) {
          sim_world_service_.PublishMonitorMessage(MonitorMessageItem::INFO,
                                                   "Routing Request Sent");
        } else {
          sim_world_service_.PublishMonitorMessage(
              MonitorMessageItem::ERROR, "Failed to send routing request");
        }
      });

  websocket_->RegisterMessageHandler(
      "RequestSimulationWorld",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        if (!sim_world_service_.ReadyToPush()) {
          AWARN_EVERY(100)
              << "Not sending simulation world as the data is not ready!";
          return;
        }

        std::string to_send;
        {
          // Pay the price to copy the data instead of sending data over the
          // wire while holding the lock.
          boost::shared_lock<boost::shared_mutex> reader_lock(mutex_);
          to_send = simulation_world_json_;
        }
        websocket_->SendData(conn, to_send, true);
      });

  websocket_->RegisterMessageHandler(
      "GetDefaultEndPoint",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        Json response;
        response["type"] = "DefaultEndPoint";

        if (LoadDefaultEndPoint()) {
          response["end_x"] = default_end_point_.pose().x();
          response["end_y"] = default_end_point_.pose().y();
        }
        websocket_->SendData(conn, response.dump());
      });
}

bool SimulationWorldUpdater::ConstructRoutingRequest(
    const Json &json, RoutingRequest *routing_request) {
  // Input validations
  if (json.find("start") == json.end() ||
      json.find("sendDefaultRoute") == json.end()) {
    AERROR << "Cannot prepare a routing request: input validation failed.";
    return false;
  }

  // set start point
  auto start = json["start"];
  if (start.find("x") == start.end() || start.find("y") == start.end()) {
    AERROR << "Failed to prepare a routing request: start point not found";
    return false;
  }
  routing_request->clear_waypoint();
  map_service_->ConstructLaneWayPoint(start["x"], start["y"],
                                      routing_request->add_waypoint());

  // set way point(s) if any
  auto iter = json.find("waypoint");
  if (iter != json.end()) {
    auto *waypoint = routing_request->mutable_waypoint();
    for (size_t i = 0; i < iter->size(); ++i) {
      auto &point = (*iter)[i];
      if (!map_service_->ConstructLaneWayPoint(point["x"], point["y"],
                                               waypoint->Add())) {
        waypoint->RemoveLast();
      }
    }
  }

  // set end point
  auto *endLane = routing_request->add_waypoint();
  if (json["sendDefaultRoute"]) {
    // Try to reload end point if it hasn't been loaded yet.
    if (!LoadDefaultEndPoint()) {
      return false;
    }

    endLane->set_id(default_end_point_.id());
    endLane->set_s(default_end_point_.s());
    auto *pose = endLane->mutable_pose();
    pose->set_x(default_end_point_.pose().x());
    pose->set_y(default_end_point_.pose().y());
  } else {
    if (json.find("end") == json.end()) {
      AERROR << "Failed to prepare a routing request: end point not found";
      return false;
    }

    auto end = json["end"];
    if (end.find("x") == end.end() || end.find("y") == end.end()) {
      AERROR << "Failed to prepare a routing request: end point not found";
      return false;
    }
    map_service_->ConstructLaneWayPoint(end["x"], end["y"], endLane);
  }

  AINFO << "Constructed RoutingRequest to be sent, waypoints: "
        << routing_request->DebugString();

  return true;
}

void SimulationWorldUpdater::Start() {
  // start ROS timer, one-shot = false, auto-start = true
  timer_ = AdapterManager::CreateTimer(ros::Duration(kSimWorldTimeInterval),
                                       &SimulationWorldUpdater::OnTimer, this);
}

void SimulationWorldUpdater::OnTimer(const ros::TimerEvent &event) {
  sim_world_service_.Update();

  {
    boost::unique_lock<boost::shared_mutex> writer_lock(mutex_);

    simulation_world_json_ =
        sim_world_service_.GetUpdateAsJson(FLAGS_map_radius).dump();
  }
}

bool SimulationWorldUpdater::LoadDefaultEndPoint() {
  bool ret =
      default_end_point_.has_id()
          ? true
          : GetProtoFromASCIIFile(EndWayPointFile(), &default_end_point_);

  if (!ret) {
    AWARN << "Failed to load default end point from " << EndWayPointFile();
  }
  return ret;
}

}  // namespace dreamview
}  // namespace apollo
<commit_msg>Dreamview: simplify end point (#662)<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. 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.
 *****************************************************************************/

#include "modules/dreamview/backend/simulation_world/simulation_world_updater.h"

#include "google/protobuf/util/json_util.h"
#include "modules/dreamview/backend/common/dreamview_gflags.h"
#include "modules/map/hdmap/hdmap_util.h"

namespace apollo {
namespace dreamview {

using apollo::common::adapter::AdapterManager;
using apollo::common::monitor::MonitorMessageItem;
using apollo::common::util::GetProtoFromASCIIFile;
using apollo::hdmap::EndWayPointFile;
using apollo::routing::RoutingRequest;
using google::protobuf::util::MessageToJsonString;
using Json = nlohmann::json;

SimulationWorldUpdater::SimulationWorldUpdater(WebSocketHandler *websocket,
                                               const MapService *map_service,
                                               bool routing_from_file)
    : sim_world_service_(map_service, routing_from_file),
      map_service_(map_service),
      websocket_(websocket) {
  // Initialize default end point
  LoadDefaultEndPoint();

  websocket_->RegisterMessageHandler(
      "RetrieveMapData",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        auto iter = json.find("elements");
        if (iter != json.end()) {
          MapElementIds map_element_ids(*iter);
          auto retrieved = map_service_->RetrieveMapElements(map_element_ids);

          std::string retrieved_json_string;
          MessageToJsonString(retrieved, &retrieved_json_string);

          Json response;
          response["type"] = "MapData";
          response["data"] = Json::parse(retrieved_json_string);

          websocket_->SendData(conn, response.dump());
        }
      });

  websocket_->RegisterMessageHandler(
      "RetrieveMapElementsByRadius",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        auto radius = json.find("radius");
        if (radius == json.end()) {
          AERROR << "Cannot retrieve map elements with unknown radius.";
          return;
        }

        Json response = sim_world_service_.GetMapElements(*radius);
        response["type"] = "MapElements";
        websocket_->SendData(conn, response.dump());
      });

  websocket_->RegisterMessageHandler(
      "SendRoutingRequest",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        RoutingRequest routing_request;

        bool succeed = ConstructRoutingRequest(json, &routing_request);
        if (succeed) {
          AdapterManager::FillRoutingRequestHeader(FLAGS_dreamview_module_name,
                                                   &routing_request);
          AdapterManager::PublishRoutingRequest(routing_request);
        }

        // Publish monitor message.
        if (succeed) {
          sim_world_service_.PublishMonitorMessage(MonitorMessageItem::INFO,
                                                   "Routing Request Sent");
        } else {
          sim_world_service_.PublishMonitorMessage(
              MonitorMessageItem::ERROR, "Failed to send routing request");
        }
      });

  websocket_->RegisterMessageHandler(
      "RequestSimulationWorld",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        if (!sim_world_service_.ReadyToPush()) {
          AWARN_EVERY(100)
              << "Not sending simulation world as the data is not ready!";
          return;
        }

        std::string to_send;
        {
          // Pay the price to copy the data instead of sending data over the
          // wire while holding the lock.
          boost::shared_lock<boost::shared_mutex> reader_lock(mutex_);
          to_send = simulation_world_json_;
        }
        websocket_->SendData(conn, to_send, true);
      });

  websocket_->RegisterMessageHandler(
      "GetDefaultEndPoint",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        Json response;
        response["type"] = "DefaultEndPoint";

        if (LoadDefaultEndPoint()) {
          response["end_x"] = default_end_point_.pose().x();
          response["end_y"] = default_end_point_.pose().y();
        }
        websocket_->SendData(conn, response.dump());
      });
}

bool SimulationWorldUpdater::ConstructRoutingRequest(
    const Json &json, RoutingRequest *routing_request) {
  // Input validations
  if (json.find("start") == json.end() ||
      json.find("sendDefaultRoute") == json.end()) {
    AERROR << "Cannot prepare a routing request: input validation failed.";
    return false;
  }

  // set start point
  auto start = json["start"];
  if (start.find("x") == start.end() || start.find("y") == start.end()) {
    AERROR << "Failed to prepare a routing request: start point not found";
    return false;
  }
  routing_request->clear_waypoint();
  map_service_->ConstructLaneWayPoint(start["x"], start["y"],
                                      routing_request->add_waypoint());

  // set way point(s) if any
  auto iter = json.find("waypoint");
  if (iter != json.end()) {
    auto *waypoint = routing_request->mutable_waypoint();
    for (size_t i = 0; i < iter->size(); ++i) {
      auto &point = (*iter)[i];
      if (!map_service_->ConstructLaneWayPoint(point["x"], point["y"],
                                               waypoint->Add())) {
        waypoint->RemoveLast();
      }
    }
  }

  // set end point
  auto *end_point = routing_request->add_waypoint();
  if (json["sendDefaultRoute"]) {
    // Try to reload end point if it hasn't been loaded yet.
    if (!LoadDefaultEndPoint()) {
      return false;
    }
    end_point->CopyFrom(default_end_point_);
  } else {
    if (json.find("end") == json.end()) {
      AERROR << "Failed to prepare a routing request: end point not found";
      return false;
    }

    auto end = json["end"];
    if (end.find("x") == end.end() || end.find("y") == end.end()) {
      AERROR << "Failed to prepare a routing request: end point not found";
      return false;
    }
    map_service_->ConstructLaneWayPoint(end["x"], end["y"], end_point);
  }

  AINFO << "Constructed RoutingRequest to be sent, waypoints: "
        << routing_request->DebugString();

  return true;
}

void SimulationWorldUpdater::Start() {
  // start ROS timer, one-shot = false, auto-start = true
  timer_ = AdapterManager::CreateTimer(ros::Duration(kSimWorldTimeInterval),
                                       &SimulationWorldUpdater::OnTimer, this);
}

void SimulationWorldUpdater::OnTimer(const ros::TimerEvent &event) {
  sim_world_service_.Update();

  {
    boost::unique_lock<boost::shared_mutex> writer_lock(mutex_);

    simulation_world_json_ =
        sim_world_service_.GetUpdateAsJson(FLAGS_map_radius).dump();
  }
}

bool SimulationWorldUpdater::LoadDefaultEndPoint() {
  bool ret =
      default_end_point_.has_id()
          ? true
          : GetProtoFromASCIIFile(EndWayPointFile(), &default_end_point_);

  if (!ret) {
    AWARN << "Failed to load default end point from " << EndWayPointFile();
  }
  return ret;
}

}  // namespace dreamview
}  // namespace apollo
<|endoftext|>


<commit_before>/**
 * (c) Camille Scott, 2019
 * File   : utagger.hh
 * License: MIT
 * Author : Camille Scott <camille.scott.w@gmail.com>
 * Date   : 05.08.2019
 */

#ifndef BOINK_UTAGGER_HH
#define BOINK_UTAGGER_HH

#include <memory>
#include <optional>

#include "boink/traversal.hh"
#include "boink/hashing/kmeriterator.hh"
#include "boink/hashing/ukhs.hh"
#include "boink/hashing/hash_combine.hh"
#include "boink/dbg.hh"
#include "boink/cdbg/udbg.hh"
#include "boink/storage/storage.hh"

namespace boink {
namespace cdbg {

template <class StorageType>
struct UTagger {

    typedef dBG<StorageType,
                hashing::UKHS::LazyShifter>     dbg_type;
    typedef typename dbg_type::shifter_type     shifter_type;
    typedef Traverse<dbg_type>                  traversal_type;
    typedef typename traversal_type::dBG        traverser_type;

    typedef hashing::KmerIterator<shifter_type> kmer_iter_type;
    typedef typename shifter_type::hash_type    hash_type;
    typedef typename hashing::UKHS::value_type  value_type;
    typedef typename shifter_type::kmer_type    kmer_type;
    typedef typename shifter_type::shift_type   shift_type;
    typedef TraversalState::State               state_type;

    typedef std::tuple<value_type, value_type>  link_type;

    struct Tag {
        value_type left_partition;
        value_type right_partition;
        link_type  link;
    };

    class StreamingTagger : public traverser_type,
                            public events::EventNotifier {

    public:

        using traverser_type::filter_nodes;
        using traverser_type::find_left_kmers;
        using traverser_type::find_right_kmers;
        using traverser_type::gather_left;
        using traverser_type::gather_right;
        using traverser_type::traverse_left;
        using traverser_type::traverse_right;
        using traverser_type::get_decision_neighbors;

        typedef spp::sparse_hash_map<link_type,
                                     Tag,
                                     hash_tuple::hash<link_type>> tag_map_t;
        typedef typename tag_map_t::const_iterator                tag_map_iter_t;

        tag_map_t                                                 tag_map;

        std::shared_ptr<dbg_type>            dbg;
        std::shared_ptr<hashing::UKHS::Map>  ukhs;
        const uint16_t                       unikmer_k;

        StreamingTagger(std::shared_ptr<dbg_type> dbg,
                        std::shared_ptr<hashing::UKHS::Map> ukhs)
            : traverser_type(dbg->K(), ukhs->K(), ukhs),
              EventNotifier(),
              dbg(dbg),
              ukhs(ukhs),
              unikmer_k(ukhs->K())
        {
        }

        size_t insert_sequence(const std::string& sequence) {
            std::deque<hash_type> hashes;
            auto new_tags = find_new_tags(sequence, hashes);
            for (const auto& item : new_tags) {
                tag_map[item.first] = item.second;
            }

            return new_tags.size();
        }

        tag_map_t find_new_tags(const std::string&     sequence,
                                std::deque<hash_type>& hashes) {

            kmer_iter_type kmer_iter(sequence, this);
            std::set<hash_type> new_kmers;
            std::deque<std::pair<std::vector<shift_type>,
                                 std::vector<shift_type>>> neighbors;
            while(!kmer_iter.done()) {
                auto hash = kmer_iter.next();
                hashes.push_back(hash);
                if (dbg->insert(hash)) {
                    // If the k-mer is new, track it and gather it's potential
                    // neighbors to save on hashing later
                    new_kmers.insert(hash);
                    neighbors.push_back(std::make_pair(this->gather_left(),
                                                       this->gather_right()));
                }
            }

            tag_map_t tags;
            bool first_new = new_kmers.count(hashes.front()), second_new;
            auto first = hashes.cbegin();
            auto second = hashes.cbegin() + 1;
            while (second != hashes.cend()) {

                //std::cerr << "----------" << std::endl;
                //std::cerr << "first: " << *first << ", second: " << *second << std::endl;

                second_new = new_kmers.count(*second);

                if (first_new || second_new) {
                    //std::cerr << "  checking internal pair." << std::endl;
                    auto tag = create_tag(*first, *second);
                    if (tag) {
                        tags[tag.value().link] = std::move(tag.value());
                    }
                }

                if (first_new) {
                    //std::cerr << "  checking neighbors." << std::endl;
                    find_neighborhood_tags(*first,
                                           this->filter_nodes(dbg.get(),
                                                              neighbors.front()),
                                           tags);
                    neighbors.pop_front();
                }

                first_new = second_new;

                ++first;
                ++second;
            }

            if (second_new) {
                find_neighborhood_tags(hashes.back(),
                                       this->filter_nodes(dbg.get(),
                                                          neighbors.front()),
                                       tags);
            }

            return tags;
        }

        void find_neighborhood_tags(const hash_type&                          root,
                                    const std::pair<std::vector<shift_type>,
                                                    std::vector<shift_type>>& neighbors,
                                    tag_map_t&                                tags) {
            // check in-neighbors
            for (auto& in_neighbor : neighbors.first) {
                auto tag = create_tag(in_neighbor.hash, root);
                if (tag) {
                    tags[tag.value().link] = std::move(tag.value());
                }
            }
            // and out neighbors
            for (auto& out_neighbor : neighbors.second) {
                auto tag = create_tag(root, out_neighbor.hash);
                if (tag) {
                    tags[tag.value().link] = std::move(tag.value());
                }
            }

        }

        std::optional<Tag> create_tag(const hash_type& first, const hash_type& second) {
            if (first.unikmer.partition != second.unikmer.partition) {
                //std::cerr << "\tunikmers don't match" << std::endl;
                //std::cerr << "\tfirst: " << first << ", second:" << second << std::endl;
                Tag tag;
                tag.left_partition = first.unikmer.partition;
                tag.right_partition = second.unikmer.partition;
                tag.link = std::make_pair(first.hash,
                                          second.hash);
                return tag;
            } else {
                return {};
            }
        }

    };

};
}
}

#endif
<commit_msg>Add tag querying<commit_after>/**
 * (c) Camille Scott, 2019
 * File   : utagger.hh
 * License: MIT
 * Author : Camille Scott <camille.scott.w@gmail.com>
 * Date   : 05.08.2019
 */

#ifndef BOINK_UTAGGER_HH
#define BOINK_UTAGGER_HH

#include <memory>
#include <optional>

#include "boink/processors.hh"
#include "boink/traversal.hh"
#include "boink/hashing/kmeriterator.hh"
#include "boink/hashing/ukhs.hh"
#include "boink/hashing/hash_combine.hh"
#include "boink/dbg.hh"
#include "boink/cdbg/udbg.hh"
#include "boink/storage/storage.hh"

namespace boink {
namespace cdbg {

template <class StorageType>
struct UTagger {

    typedef dBG<StorageType,
                hashing::UKHS::LazyShifter>     dbg_type;
    typedef typename dbg_type::shifter_type     shifter_type;
    typedef Traverse<dbg_type>                  traversal_type;
    typedef typename traversal_type::dBG        traverser_type;

    typedef hashing::KmerIterator<shifter_type> kmer_iter_type;
    typedef typename shifter_type::hash_type    hash_type;
    typedef typename hashing::UKHS::value_type  value_type;
    typedef typename shifter_type::kmer_type    kmer_type;
    typedef typename shifter_type::shift_type   shift_type;
    typedef TraversalState::State               state_type;

    typedef std::tuple<value_type, value_type>  link_type;

    struct Tag {
        value_type left_partition;
        value_type right_partition;
        link_type  link;
    };

    class StreamingTagger : public traverser_type,
                            public events::EventNotifier {

    public:

        using traverser_type::filter_nodes;
        using traverser_type::find_left_kmers;
        using traverser_type::find_right_kmers;
        using traverser_type::gather_left;
        using traverser_type::gather_right;
        using traverser_type::traverse_left;
        using traverser_type::traverse_right;
        using traverser_type::get_decision_neighbors;

        typedef spp::sparse_hash_map<link_type,
                                     Tag,
                                     hash_tuple::hash<link_type>> tag_map_t;
        typedef typename tag_map_t::const_iterator                tag_map_iter_t;

        typedef spp::sparse_hash_set<link_type,
                                     hash_tuple::hash<link_type>> link_set_t;
        typedef typename link_set_t::const_iterator               link_set_iter_t;

        tag_map_t                                                 tag_map;

        std::shared_ptr<dbg_type>            dbg;
        std::shared_ptr<hashing::UKHS::Map>  ukhs;
        const uint16_t                       unikmer_k;

        StreamingTagger(std::shared_ptr<dbg_type> dbg,
                        std::shared_ptr<hashing::UKHS::Map> ukhs)
            : traverser_type(dbg->K(), ukhs->K(), ukhs),
              EventNotifier(),
              dbg(dbg),
              ukhs(ukhs),
              unikmer_k(ukhs->K())
        {
        }

        static std::shared_ptr<StreamingTagger> build(std::shared_ptr<dbg_type> dbg,
                                                      std::shared_ptr<hashing::UKHS::Map> ukhs) {
            return std::make_shared<StreamingTagger>(dbg, ukhs);
        }

        /**
         * @Synopsis  Creates all tags in sequence's neighborhood and adds them to the master
         *            tag map, while adding the hashes from sequence to the underlying de Bruijn graph.
         *
         * @Param sequence Sequence to insert.
         *
         * @Returns   Number of tags created.
         */
        size_t insert_sequence(const std::string& sequence) {
            auto new_tags = find_new_tags(sequence);
            if (new_tags.size()) {
                for (const auto& item : new_tags) {
                    tag_map[item.first] = item.second;
                }
                return new_tags.size();
            }

            return 0;
        }

        /**
         * @Synopsis  Finds all new tags induced by the insertion of sequence and returns them.
         *
         * @Param sequence
         *
         * @Returns   The new tags.
         */
        tag_map_t find_new_tags(const std::string& sequence) {

            kmer_iter_type kmer_iter(sequence, this);

            std::vector<hash_type> hashes;
            std::deque<std::pair<std::vector<shift_type>,
                                 std::vector<shift_type>>> neighbors;
            while(!kmer_iter.done()) {
                auto hash = kmer_iter.next();
                if (dbg->insert(hash)) {
                    hashes.push_back(hash);
                    neighbors.push_back(std::make_pair(this->gather_left(),
                                                       this->gather_right()));
                }
            }

            tag_map_t tags;
            if (hashes.size() == 0) {
                return tags;
            }

            for (const auto& hash : hashes) {
                create_neighborhood_tags(hash,
                                         this->filter_nodes(dbg.get(),
                                                            neighbors.front()),
                                         tags);
                neighbors.pop_front();
            }

            return tags;
        }

        /**
         * @Synopsis  Creates all possible tags in the given neighbood surrounding root
         *            and adds them to the map given by tags.
         *
         * @Param root      The neighborhood root.
         * @Param neighbors The (filtered) neighbors of root.
         * @Param tags      Map to store tags in.
         */
        void create_neighborhood_tags(const hash_type&                          root,
                                      const std::pair<std::vector<shift_type>,
                                                      std::vector<shift_type>>& neighbors,
                                      tag_map_t&                                tags) {
            // check in-neighbors
            for (auto& in_neighbor : neighbors.first) {
                auto tag = create_tag(in_neighbor.hash, root);
                if (tag) {
                    tags[tag.value().link] = std::move(tag.value());
                }
            }
            // and out neighbors
            for (auto& out_neighbor : neighbors.second) {
                auto tag = create_tag(root, out_neighbor.hash);
                if (tag) {
                    tags[tag.value().link] = std::move(tag.value());
                }
            }

        }

        /**
         * @Synopsis  Checks if (first, second) could be a Tag, and if so, creates the appropriate
         *            tag and returns it.
         *
         * @Param first
         * @Param second
         *
         * @Returns   An std::optional<Tag> containing the Tag if successful.
         */
        std::optional<Tag> create_tag(const hash_type& first, const hash_type& second) {
            if (is_tag(first, second)) {
                //std::cerr << "\tunikmers don't match" << std::endl;
                //std::cerr << "\tfirst: " << first << ", second:" << second << std::endl;
                Tag tag;
                tag.left_partition = first.unikmer.partition;
                tag.right_partition = second.unikmer.partition;
                tag.link = std::make_pair(first.hash,
                                          second.hash);
                return tag;
            } else {
                return {};
            }
        }

        /**
         * @Synopsis  True if the pair (u,v) could be a tag; assumes they are neighbors.
         *
         * @Param u
         * @Param v
         *
         * @Returns   True if possibly a tag.
         */
        bool is_tag(const hash_type& u, const hash_type& v) {
            return u.unikmer.partition != v.unikmer.partition;
        }

        /**
         * @Synopsis  Check if the pair (u,v) are a tag link and return the corresponding tag if so.
         *
         * @Param u
         * @Param v
         *
         * @Returns An std::optional<Tag> containing the tag if found.
         */
        std::optional<Tag> query_tag(const hash_type& u, const hash_type& v) {
            if (!is_tag(u, v)) {
                return {};
            }

            auto search = tag_map.find(std::make_pair(u, v));
            if (search != tag_map.end()) {
                return search->second;
            }

            return {};
        }

        /**
         * @Synopsis  Find tags within the given sequence.
         *
         * @Param sequence Sequence to search.
         *
         * @Returns   Ordered vector of tags from sequence.
         */
        std::vector<Tag> query_sequence_tags(const std::string& sequence) {
            std::vector<Tag> tags;
            kmer_iter_type kmer_iter(sequence, this);

            hash_type u = kmer_iter.next();
            if (kmer_iter.done()) {
                return tags;
            }
            while(!kmer_iter.done()) {
                hash_type v = kmer_iter.next();
                auto tag = query_tag(u, v);
                if (tag) {
                    tags.push_back(tag.value());
                }
                u = v;
            }

            return tags;
        }

        /**
         * @Synopsis  Find (unique) tags within the given sequence or directly adjacent to its k-mers.
         *
         * @Param sequence Sequence to search.
         *
         * @Returns   Set of links corresponding to neighboring tags.
         */
        link_set_t query_neighborhood_tags(const std::string& sequence) {
            kmer_iter_type kmer_iter(sequence, this);
            link_set_t found;

            while(!kmer_iter.done()) {
                hash_type root = kmer_iter.next();
                auto neighborhood = this->filter_nodes(dbg.get(),
                                                       std::make_pair(this->gather_left(),
                                                                      this->gather_right()));
                for (auto& in_neighbor : neighborhood.first) {
                    if (auto tag = query_tag(in_neighbor.hash, root)) {
                        found.insert(tag.value().link);
                    }
                }
                // and out neighbors
                for (auto& out_neighbor : neighborhood.second) {
                    if (auto tag = query_tag(root, out_neighbor.hash)) {
                        found.insert(tag.value().link);
                    }
                }
            }

            return found;
        }

    };

    using Processor = InserterProcessor<StreamingTagger>;

};
}
}

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: FillProperties.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 00:40:38 $
 *
 *  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 CHART_FILLPROPERTIES_HXX
#define CHART_FILLPROPERTIES_HXX

#include "PropertyHelper.hxx"
#include "FastPropertyIdRanges.hxx"

#ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_
#include <com/sun/star/beans/Property.hpp>
#endif

#include <vector>

namespace chart
{

// implements service FillProperties
class FillProperties
{
public:
    // FastProperty Ids for properties
    enum
    {
        // com.sun.star.drawing.FillProperties
        PROP_FILL_STYLE = FAST_PROPERTY_ID_START_FILL_PROP,
        PROP_FILL_COLOR,
        PROP_FILL_TRANSPARENCE,
        PROP_FILL_GRADIENT,
        PROP_FILL_HATCH,
        PROP_FILL_TRANSPARENCY_STYLE,
        PROP_FILL_TRANSPARENCY_GRADIENT
    };

    static void AddPropertiesToVector(
        ::std::vector< ::com::sun::star::beans::Property > & rOutProperties,
        bool bIncludeStyleProperties = false );

    static void AddDefaultsToMap( ::chart::helper::tPropertyValueMap & rOutMap, bool bIncludeStyleProperties = false );

private:
    // not implemented
    FillProperties();
};

} //  namespace chart

// CHART_FILLPROPERTIES_HXX
#endif
<commit_msg>INTEGRATION: CWS chart2mst3 (1.1.4); FILE MERGED 2006/10/20 20:30:55 iha 1.1.4.8: implement gradient step count 2005/10/07 11:41:06 bm 1.1.4.7: RESYNC: (1.1-1.2); FILE MERGED 2005/07/14 14:42:44 iha 1.1.4.6: cleanup Fillproperties 2005/07/14 12:32:49 iha 1.1.4.5: remove unused parameter 'bIncludeStyleProperties' 2005/07/12 12:57:06 bm 1.1.4.4: use named properties for gradients etc. in chart model 2005/06/16 07:56:48 iha 1.1.4.3: added missing Property FillBackground 2005/06/15 18:17:25 iha 1.1.4.2: correct name for Property FillTransparenceGradient + added comments 2004/02/13 16:51:23 bm 1.1.4.1: join from changes on branch bm_post_chart01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: FillProperties.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 18:16:44 $
 *
 *  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 CHART_FILLPROPERTIES_HXX
#define CHART_FILLPROPERTIES_HXX

#include "PropertyHelper.hxx"
#include "FastPropertyIdRanges.hxx"

#ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_
#include <com/sun/star/beans/Property.hpp>
#endif

#include <vector>

namespace chart
{

// implements service FillProperties
class FillProperties
{
public:
    // FastProperty Ids for properties
    enum
    {
        // com.sun.star.drawing.FillProperties
        // com.sun.star.drawing.FillProperties
        PROP_FILL_STYLE = FAST_PROPERTY_ID_START_FILL_PROP
        , PROP_FILL_COLOR
        , PROP_FILL_TRANSPARENCE
        , PROP_FILL_TRANSPARENCE_GRADIENT_NAME
//        , PROP_FILL_TRANSPARENCE_GRADIENT //optional
        , PROP_FILL_GRADIENT_NAME
        , PROP_FILL_GRADIENT_STEPCOUNT
//        , PROP_FILL_GRADIENT   //optional
        , PROP_FILL_HATCH_NAME
//        , PROP_FILL_HATCH  //optional
        //------------------------
        // bitmap properties start
        , PROP_FILL_BITMAP_NAME
//        , PROP_FILL_BITMAP //optional
//        , PROP_FILL_BITMAP_URL //optional
        , PROP_FILL_BITMAP_OFFSETX
        , PROP_FILL_BITMAP_OFFSETY
        , PROP_FILL_BITMAP_POSITION_OFFSETX
        , PROP_FILL_BITMAP_POSITION_OFFSETY
        , PROP_FILL_BITMAP_RECTANGLEPOINT
        , PROP_FILL_BITMAP_LOGICALSIZE
        , PROP_FILL_BITMAP_SIZEX
        , PROP_FILL_BITMAP_SIZEY
        , PROP_FILL_BITMAP_MODE
        // bitmap properties end
        //------------------------
        , PROP_FILL_BACKGROUND
    };

    static void AddPropertiesToVector(
        ::std::vector< ::com::sun::star::beans::Property > & rOutProperties );

    static void AddDefaultsToMap( ::chart::tPropertyValueMap & rOutMap );

private:
    // not implemented
    FillProperties();
};

} //  namespace chart

// CHART_FILLPROPERTIES_HXX
#endif
<|endoftext|>


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

#include "base/file_util.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "base/values.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request_unittest.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"

namespace {

// Given a page title, returns the expected window caption string.
std::wstring WindowCaptionFromPageTitle(std::wstring page_title) {
  if (page_title.empty())
    return l10n_util::GetString(IDS_PRODUCT_NAME);

  return l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT, page_title);
}

class BrowserTest : public UITest {
 protected:
   HWND GetMainWindow() {
     scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
     scoped_ptr<WindowProxy> window(browser->GetWindow());

     HWND window_handle;
     EXPECT_TRUE(window->GetHWND(&window_handle));
     return window_handle;
   }

   std::wstring GetWindowTitle() {
     HWND window_handle = GetMainWindow();
     std::wstring result;
     int length = ::GetWindowTextLength(window_handle) + 1;
     ::GetWindowText(window_handle, WriteInto(&result, length), length);
     return result;
   }
};

class VisibleBrowserTest : public UITest {
 protected:
  VisibleBrowserTest() : UITest() {
    show_window_ = true;
  }
};

}  // namespace

// Launch the app on a page with no title, check that the app title was set
// correctly.
TEST_F(BrowserTest, NoTitle) {
  std::wstring test_file = test_data_directory_;
  file_util::AppendToPath(&test_file, L"title1.html");

  NavigateToURL(net::FilePathToFileURL(test_file));
  Sleep(sleep_timeout_ms());  // The browser lazily updates the title.

  EXPECT_EQ(WindowCaptionFromPageTitle(L"title1.html"), GetWindowTitle());
  EXPECT_EQ(L"title1.html", GetActiveTabTitle());
}

// Launch the app, navigate to a page with a title, check that the app title
// was set correctly.
TEST_F(BrowserTest, Title) {
  std::wstring test_file = test_data_directory_;
  file_util::AppendToPath(&test_file, L"title2.html");

  NavigateToURL(net::FilePathToFileURL(test_file));
  Sleep(sleep_timeout_ms());  // The browser lazily updates the title.

  const std::wstring test_title(L"Title Of Awesomeness");
  EXPECT_EQ(WindowCaptionFromPageTitle(test_title), GetWindowTitle());
  EXPECT_EQ(test_title, GetActiveTabTitle());
}

// Create 34 tabs and verify that a lot of processes have been created. The
// exact number of processes depends on the amount of memory. Previously we
// had a hard limit of 31 processes and this test is mainly directed at
// verifying that we don't crash when we pass this limit.
TEST_F(BrowserTest, ThirtyFourTabs) {
  std::wstring test_file = test_data_directory_;
  file_util::AppendToPath(&test_file, L"title2.html");
  GURL url(net::FilePathToFileURL(test_file));
  scoped_ptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
  // There is one initial tab.
  for (int ix = 0; ix != 33; ++ix) {
    EXPECT_TRUE(window->AppendTab(url));
  }
  int tab_count = 0;
  EXPECT_TRUE(window->GetTabCount(&tab_count));
  EXPECT_EQ(34, tab_count);
  // Do not test the rest in single process mode.
  if (in_process_renderer())
    return;
  // See browser\renderer_host\render_process_host.cc for the algorithm to
  // decide how many processes to create.
  int process_count = GetBrowserProcessCount();
  if (base::SysInfo::AmountOfPhysicalMemoryMB() >= 2048) {
    EXPECT_GE(process_count, 24);
  } else {
    EXPECT_LE(process_count, 23);
  }
}

// The browser should quit quickly if it receives a WM_ENDSESSION message.
TEST_F(BrowserTest, WindowsSessionEnd) {
  std::wstring test_file = test_data_directory_;
  file_util::AppendToPath(&test_file, L"title1.html");

  NavigateToURL(net::FilePathToFileURL(test_file));
  Sleep(action_timeout_ms());

  // Simulate an end of session. Normally this happens when the user
  // shuts down the pc or logs off.
  HWND window_handle = GetMainWindow();
  ASSERT_TRUE(::PostMessageW(window_handle, WM_ENDSESSION, 0, 0));

  Sleep(action_timeout_ms());
  ASSERT_FALSE(IsBrowserRunning());

  // Make sure the UMA metrics say we didn't crash.
  scoped_ptr<DictionaryValue> local_prefs(GetLocalState());
  bool exited_cleanly;
  ASSERT_TRUE(local_prefs.get());
  ASSERT_TRUE(local_prefs->GetBoolean(prefs::kStabilityExitedCleanly,
                                      &exited_cleanly));
  ASSERT_TRUE(exited_cleanly);

  // And that session end was successful.
  bool session_end_completed;
  ASSERT_TRUE(local_prefs->GetBoolean(prefs::kStabilitySessionEndCompleted,
                                      &session_end_completed));
  ASSERT_TRUE(session_end_completed);

  // Make sure session restore says we didn't crash.
  scoped_ptr<DictionaryValue> profile_prefs(GetDefaultProfilePreferences());
  ASSERT_TRUE(profile_prefs.get());
  ASSERT_TRUE(profile_prefs->GetBoolean(prefs::kSessionExitedCleanly,
                                        &exited_cleanly));
  ASSERT_TRUE(exited_cleanly);
}

// This test is flakey, see bug 5668 for details.
TEST_F(BrowserTest, DISABLED_JavascriptAlertActivatesTab) {
  scoped_ptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
  int start_index;
  ASSERT_TRUE(window->GetActiveTabIndex(&start_index));
  ASSERT_TRUE(window->AppendTab(GURL("about:blank")));
  int javascript_tab_index;
  ASSERT_TRUE(window->GetActiveTabIndex(&javascript_tab_index));
  TabProxy* javascript_tab = window->GetActiveTab();
  // Switch back to the starting tab, then send the second tab a javascript
  // alert, which should force it to become active.
  ASSERT_TRUE(window->ActivateTab(start_index));
  ASSERT_TRUE(
      javascript_tab->NavigateToURLAsync(GURL("javascript:alert('Alert!')")));
  ASSERT_TRUE(window->WaitForTabToBecomeActive(javascript_tab_index,
                                               action_max_timeout_ms()));
}

// Test that scripts can fork a new renderer process for a tab in a particular
// case (which matches following a link in Gmail).  The script must open a new
// tab, set its window.opener to null, and redirect it to a cross-site URL.
// (Bug 1115708)
// This test can only run if V8 is in use, and not KJS, because KJS will not
// set window.opener to null properly.
#ifdef CHROME_V8
TEST_F(BrowserTest, NullOpenerRedirectForksProcess) {
  // This test only works in multi-process mode
  if (in_process_renderer())
    return;

  const wchar_t kDocRoot[] = L"chrome/test/data";
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  std::wstring test_file(test_data_directory_);
  scoped_ptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
  scoped_ptr<TabProxy> tab(window->GetActiveTab());

  // Start with a file:// url
  file_util::AppendToPath(&test_file, L"title2.html");
  tab->NavigateToURL(net::FilePathToFileURL(test_file));
  int orig_tab_count = -1;
  ASSERT_TRUE(window->GetTabCount(&orig_tab_count));
  int orig_process_count = GetBrowserProcessCount();
  ASSERT_TRUE(orig_process_count >= 1);

  // Use JavaScript URL to "fork" a new tab, just like Gmail.  (Open tab to a
  // blank page, set its opener to null, and redirect it cross-site.)
  std::wstring url_prefix(L"javascript:(function(){w=window.open();");
  GURL fork_url(url_prefix +
      L"w.opener=null;w.document.location=\"http://localhost:1337\";})()");

  // Make sure that a new tab has been created and that we have a new renderer
  // process for it.
  tab->NavigateToURLAsync(fork_url);
  Sleep(action_timeout_ms());
  ASSERT_EQ(orig_process_count + 1, GetBrowserProcessCount());
  int new_tab_count = -1;
  ASSERT_TRUE(window->GetTabCount(&new_tab_count));
  ASSERT_EQ(orig_tab_count + 1, new_tab_count);
}
#endif

// Tests that non-Gmail-like script redirects (i.e., non-null window.opener) or
// a same-page-redirect) will not fork a new process.
TEST_F(BrowserTest, OtherRedirectsDontForkProcess) {
  // This test only works in multi-process mode
  if (in_process_renderer())
    return;

  const wchar_t kDocRoot[] = L"chrome/test/data";
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  std::wstring test_file(test_data_directory_);
  scoped_ptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
  scoped_ptr<TabProxy> tab(window->GetActiveTab());

  // Start with a file:// url
  file_util::AppendToPath(&test_file, L"title2.html");
  tab->NavigateToURL(net::FilePathToFileURL(test_file));
  int orig_tab_count = -1;
  ASSERT_TRUE(window->GetTabCount(&orig_tab_count));
  int orig_process_count = GetBrowserProcessCount();
  ASSERT_TRUE(orig_process_count >= 1);

  // Use JavaScript URL to almost fork a new tab, but not quite.  (Leave the
  // opener non-null.)  Should not fork a process.
  std::wstring url_prefix(L"javascript:(function(){w=window.open();");
  GURL dont_fork_url(url_prefix +
      L"w.document.location=\"http://localhost:1337\";})()");

  // Make sure that a new tab but not new process has been created.
  tab->NavigateToURLAsync(dont_fork_url);
  Sleep(action_timeout_ms());
  ASSERT_EQ(orig_process_count, GetBrowserProcessCount());
  int new_tab_count = -1;
  ASSERT_TRUE(window->GetTabCount(&new_tab_count));
  ASSERT_EQ(orig_tab_count + 1, new_tab_count);

  // Same thing if the current tab tries to redirect itself.
  GURL dont_fork_url2(url_prefix +
      L"document.location=\"http://localhost:1337\";})()");

  // Make sure that no new process has been created.
  tab->NavigateToURLAsync(dont_fork_url2);
  Sleep(action_timeout_ms());
  ASSERT_EQ(orig_process_count, GetBrowserProcessCount());
}

TEST_F(VisibleBrowserTest, WindowOpenClose) {
  std::wstring test_file(test_data_directory_);
  file_util::AppendToPath(&test_file, L"window.close.html");

  NavigateToURL(net::FilePathToFileURL(test_file));

  int i;
  for (i = 0; i < 10; ++i) {
    Sleep(action_max_timeout_ms() / 10);
    std::wstring title = GetActiveTabTitle();
    if (title == L"PASSED") {
      // Success, bail out.
      break;
    }
  }

  if (i == 10)
    FAIL() << "failed to get error page title";
}

<commit_msg>Disable ThirtyFoudTabs test as it is failing consitently now on all buildbots.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_util.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "base/values.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request_unittest.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"

namespace {

// Given a page title, returns the expected window caption string.
std::wstring WindowCaptionFromPageTitle(std::wstring page_title) {
  if (page_title.empty())
    return l10n_util::GetString(IDS_PRODUCT_NAME);

  return l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT, page_title);
}

class BrowserTest : public UITest {
 protected:
   HWND GetMainWindow() {
     scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
     scoped_ptr<WindowProxy> window(browser->GetWindow());

     HWND window_handle;
     EXPECT_TRUE(window->GetHWND(&window_handle));
     return window_handle;
   }

   std::wstring GetWindowTitle() {
     HWND window_handle = GetMainWindow();
     std::wstring result;
     int length = ::GetWindowTextLength(window_handle) + 1;
     ::GetWindowText(window_handle, WriteInto(&result, length), length);
     return result;
   }
};

class VisibleBrowserTest : public UITest {
 protected:
  VisibleBrowserTest() : UITest() {
    show_window_ = true;
  }
};

}  // namespace

// Launch the app on a page with no title, check that the app title was set
// correctly.
TEST_F(BrowserTest, NoTitle) {
  std::wstring test_file = test_data_directory_;
  file_util::AppendToPath(&test_file, L"title1.html");

  NavigateToURL(net::FilePathToFileURL(test_file));
  Sleep(sleep_timeout_ms());  // The browser lazily updates the title.

  EXPECT_EQ(WindowCaptionFromPageTitle(L"title1.html"), GetWindowTitle());
  EXPECT_EQ(L"title1.html", GetActiveTabTitle());
}

// Launch the app, navigate to a page with a title, check that the app title
// was set correctly.
TEST_F(BrowserTest, Title) {
  std::wstring test_file = test_data_directory_;
  file_util::AppendToPath(&test_file, L"title2.html");

  NavigateToURL(net::FilePathToFileURL(test_file));
  Sleep(sleep_timeout_ms());  // The browser lazily updates the title.

  const std::wstring test_title(L"Title Of Awesomeness");
  EXPECT_EQ(WindowCaptionFromPageTitle(test_title), GetWindowTitle());
  EXPECT_EQ(test_title, GetActiveTabTitle());
}

// Create 34 tabs and verify that a lot of processes have been created. The
// exact number of processes depends on the amount of memory. Previously we
// had a hard limit of 31 processes and this test is mainly directed at
// verifying that we don't crash when we pass this limit.
// Disabling this test as it is making all the buildbots running ui tests red.
// see http://code.google.com/p/chromium/issues/detail?id=5668
TEST_F(BrowserTest, DISABLED_ThirtyFourTabs) {
  std::wstring test_file = test_data_directory_;
  file_util::AppendToPath(&test_file, L"title2.html");
  GURL url(net::FilePathToFileURL(test_file));
  scoped_ptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
  // There is one initial tab.
  for (int ix = 0; ix != 33; ++ix) {
    EXPECT_TRUE(window->AppendTab(url));
  }
  int tab_count = 0;
  EXPECT_TRUE(window->GetTabCount(&tab_count));
  EXPECT_EQ(34, tab_count);
  // Do not test the rest in single process mode.
  if (in_process_renderer())
    return;
  // See browser\renderer_host\render_process_host.cc for the algorithm to
  // decide how many processes to create.
  int process_count = GetBrowserProcessCount();
  if (base::SysInfo::AmountOfPhysicalMemoryMB() >= 2048) {
    EXPECT_GE(process_count, 24);
  } else {
    EXPECT_LE(process_count, 23);
  }
}

// The browser should quit quickly if it receives a WM_ENDSESSION message.
TEST_F(BrowserTest, WindowsSessionEnd) {
  std::wstring test_file = test_data_directory_;
  file_util::AppendToPath(&test_file, L"title1.html");

  NavigateToURL(net::FilePathToFileURL(test_file));
  Sleep(action_timeout_ms());

  // Simulate an end of session. Normally this happens when the user
  // shuts down the pc or logs off.
  HWND window_handle = GetMainWindow();
  ASSERT_TRUE(::PostMessageW(window_handle, WM_ENDSESSION, 0, 0));

  Sleep(action_timeout_ms());
  ASSERT_FALSE(IsBrowserRunning());

  // Make sure the UMA metrics say we didn't crash.
  scoped_ptr<DictionaryValue> local_prefs(GetLocalState());
  bool exited_cleanly;
  ASSERT_TRUE(local_prefs.get());
  ASSERT_TRUE(local_prefs->GetBoolean(prefs::kStabilityExitedCleanly,
                                      &exited_cleanly));
  ASSERT_TRUE(exited_cleanly);

  // And that session end was successful.
  bool session_end_completed;
  ASSERT_TRUE(local_prefs->GetBoolean(prefs::kStabilitySessionEndCompleted,
                                      &session_end_completed));
  ASSERT_TRUE(session_end_completed);

  // Make sure session restore says we didn't crash.
  scoped_ptr<DictionaryValue> profile_prefs(GetDefaultProfilePreferences());
  ASSERT_TRUE(profile_prefs.get());
  ASSERT_TRUE(profile_prefs->GetBoolean(prefs::kSessionExitedCleanly,
                                        &exited_cleanly));
  ASSERT_TRUE(exited_cleanly);
}

// This test is flakey, see bug 5668 for details.
TEST_F(BrowserTest, DISABLED_JavascriptAlertActivatesTab) {
  scoped_ptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
  int start_index;
  ASSERT_TRUE(window->GetActiveTabIndex(&start_index));
  ASSERT_TRUE(window->AppendTab(GURL("about:blank")));
  int javascript_tab_index;
  ASSERT_TRUE(window->GetActiveTabIndex(&javascript_tab_index));
  TabProxy* javascript_tab = window->GetActiveTab();
  // Switch back to the starting tab, then send the second tab a javascript
  // alert, which should force it to become active.
  ASSERT_TRUE(window->ActivateTab(start_index));
  ASSERT_TRUE(
      javascript_tab->NavigateToURLAsync(GURL("javascript:alert('Alert!')")));
  ASSERT_TRUE(window->WaitForTabToBecomeActive(javascript_tab_index,
                                               action_max_timeout_ms()));
}

// Test that scripts can fork a new renderer process for a tab in a particular
// case (which matches following a link in Gmail).  The script must open a new
// tab, set its window.opener to null, and redirect it to a cross-site URL.
// (Bug 1115708)
// This test can only run if V8 is in use, and not KJS, because KJS will not
// set window.opener to null properly.
#ifdef CHROME_V8
TEST_F(BrowserTest, NullOpenerRedirectForksProcess) {
  // This test only works in multi-process mode
  if (in_process_renderer())
    return;

  const wchar_t kDocRoot[] = L"chrome/test/data";
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  std::wstring test_file(test_data_directory_);
  scoped_ptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
  scoped_ptr<TabProxy> tab(window->GetActiveTab());

  // Start with a file:// url
  file_util::AppendToPath(&test_file, L"title2.html");
  tab->NavigateToURL(net::FilePathToFileURL(test_file));
  int orig_tab_count = -1;
  ASSERT_TRUE(window->GetTabCount(&orig_tab_count));
  int orig_process_count = GetBrowserProcessCount();
  ASSERT_TRUE(orig_process_count >= 1);

  // Use JavaScript URL to "fork" a new tab, just like Gmail.  (Open tab to a
  // blank page, set its opener to null, and redirect it cross-site.)
  std::wstring url_prefix(L"javascript:(function(){w=window.open();");
  GURL fork_url(url_prefix +
      L"w.opener=null;w.document.location=\"http://localhost:1337\";})()");

  // Make sure that a new tab has been created and that we have a new renderer
  // process for it.
  tab->NavigateToURLAsync(fork_url);
  Sleep(action_timeout_ms());
  ASSERT_EQ(orig_process_count + 1, GetBrowserProcessCount());
  int new_tab_count = -1;
  ASSERT_TRUE(window->GetTabCount(&new_tab_count));
  ASSERT_EQ(orig_tab_count + 1, new_tab_count);
}
#endif

// Tests that non-Gmail-like script redirects (i.e., non-null window.opener) or
// a same-page-redirect) will not fork a new process.
TEST_F(BrowserTest, OtherRedirectsDontForkProcess) {
  // This test only works in multi-process mode
  if (in_process_renderer())
    return;

  const wchar_t kDocRoot[] = L"chrome/test/data";
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  std::wstring test_file(test_data_directory_);
  scoped_ptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
  scoped_ptr<TabProxy> tab(window->GetActiveTab());

  // Start with a file:// url
  file_util::AppendToPath(&test_file, L"title2.html");
  tab->NavigateToURL(net::FilePathToFileURL(test_file));
  int orig_tab_count = -1;
  ASSERT_TRUE(window->GetTabCount(&orig_tab_count));
  int orig_process_count = GetBrowserProcessCount();
  ASSERT_TRUE(orig_process_count >= 1);

  // Use JavaScript URL to almost fork a new tab, but not quite.  (Leave the
  // opener non-null.)  Should not fork a process.
  std::wstring url_prefix(L"javascript:(function(){w=window.open();");
  GURL dont_fork_url(url_prefix +
      L"w.document.location=\"http://localhost:1337\";})()");

  // Make sure that a new tab but not new process has been created.
  tab->NavigateToURLAsync(dont_fork_url);
  Sleep(action_timeout_ms());
  ASSERT_EQ(orig_process_count, GetBrowserProcessCount());
  int new_tab_count = -1;
  ASSERT_TRUE(window->GetTabCount(&new_tab_count));
  ASSERT_EQ(orig_tab_count + 1, new_tab_count);

  // Same thing if the current tab tries to redirect itself.
  GURL dont_fork_url2(url_prefix +
      L"document.location=\"http://localhost:1337\";})()");

  // Make sure that no new process has been created.
  tab->NavigateToURLAsync(dont_fork_url2);
  Sleep(action_timeout_ms());
  ASSERT_EQ(orig_process_count, GetBrowserProcessCount());
}

TEST_F(VisibleBrowserTest, WindowOpenClose) {
  std::wstring test_file(test_data_directory_);
  file_util::AppendToPath(&test_file, L"window.close.html");

  NavigateToURL(net::FilePathToFileURL(test_file));

  int i;
  for (i = 0; i < 10; ++i) {
    Sleep(action_max_timeout_ms() / 10);
    std::wstring title = GetActiveTabTitle();
    if (title == L"PASSED") {
      // Success, bail out.
      break;
    }
  }

  if (i == 10)
    FAIL() << "failed to get error page title";
}

<|endoftext|>


<commit_before>
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#include <services.h>
#include <uielement/panelwrapper.hxx>
#include <threadhelp/resetableguard.hxx>
#include <helper/actiontriggerhelper.hxx>
#include <uielement/constitemcontainer.hxx>
#include <uielement/rootitemcontainer.hxx>
#include <uielement/panelwindow.hxx>
#include <services/modelwinservice.hxx>

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/awt/XSystemDependentMenuPeer.hpp>
#include <com/sun/star/awt/XMenuBar.hpp>
#include <com/sun/star/container/XIndexContainer.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/ui/UIElementType.hpp>

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#include <toolkit/unohlp.hxx>
#include <toolkit/awt/vclxwindow.hxx>
#include <comphelper/processfactory.hxx>
#include <svtools/miscopt.hxx>
#include <vcl/svapp.hxx>
#include <rtl/logfile.hxx>

using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star::frame;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace com::sun::star::awt;
using namespace ::com::sun::star::ui;

namespace framework
{

PanelWrapper::PanelWrapper( const Reference< XMultiServiceFactory >& xServiceManager ) :
    UIElementWrapperBase( UIElementType::DOCKINGWINDOW ),
    m_xServiceManager( xServiceManager ),
    m_bNoClose(false)
{
}

PanelWrapper::~PanelWrapper()
{
}

// XInterface
void SAL_CALL PanelWrapper::acquire() throw()
{
    UIElementWrapperBase::acquire();
}

void SAL_CALL PanelWrapper::release() throw()
{
    UIElementWrapperBase::release();
}

uno::Any SAL_CALL PanelWrapper::queryInterface( const uno::Type & rType )
throw( ::com::sun::star::uno::RuntimeException )
{
    return UIElementWrapperBase::queryInterface( rType );
}

// XComponent
void SAL_CALL PanelWrapper::dispose() throw ( RuntimeException )
{
    Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY );
    Reference< XMultiServiceFactory > xSMGR( m_xServiceManager );
    Reference< XWindow > xWindow;

    {
        ResetableGuard aLock( m_aLock );
        if ( m_bDisposed )
            return;
        xSMGR = m_xServiceManager;
    }

    com::sun::star::lang::EventObject aEvent( xThis );
    m_aListenerContainer.disposeAndClear( aEvent );

    rtl::OUString aModelWinService( SERVICENAME_MODELWINSERVICE );
    Reference< XNameAccess > xNameAccess( xSMGR->createInstance( aModelWinService ), UNO_QUERY );
    if ( xNameAccess.is() )
    {
        ModelWinService* pService = dynamic_cast< ModelWinService* >( xNameAccess.get() );
        if ( pService != 0 )
        {
            vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
            PanelWindow* pPanelWindow = dynamic_cast< PanelWindow* >( m_xPanelWindow.get() );
            if ( pPanelWindow != NULL )
            {
                xWindow = VCLUnoHelper::GetInterface( pPanelWindow->getContentWindow() );
                pService->deregisterModelForXWindow( xWindow );
            }
        }
    }

    ResetableGuard aLock( m_aLock );
    m_xPanelWindow.clear();
    m_bDisposed = sal_True;
}

// XInitialization
void SAL_CALL PanelWrapper::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( !m_bInitialized )
    {
        UIElementWrapperBase::initialize( aArguments );

        sal_Bool bPopupMode( sal_False );
        Reference< XWindow > xContentWindow;
        for ( sal_Int32 i = 0; i < aArguments.getLength(); i++ )
        {
            PropertyValue aPropValue;
            if ( aArguments[i] >>= aPropValue )
            {
                if ( aPropValue.Name.equalsAsciiL( "PopupMode", 9 ))
                    aPropValue.Value >>= bPopupMode;
                else if ( aPropValue.Name.equalsAsciiL( "ContentWindow", 13 ))
                    aPropValue.Value >>= xContentWindow;
            }
        }

        Reference< XFrame > xFrame( m_xWeakFrame );
        if ( xFrame.is() )
        {
            PanelWindow* pPanelWindow(0);
            Window*      pContentWindow(0);
            {
                vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
                Window* pWindow = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );
                pContentWindow  = VCLUnoHelper::GetWindow( xContentWindow );
                if ( pWindow )
                {
                    ULONG nStyles = WB_LINESPACING | WB_BORDER | WB_SCROLL | WB_MOVEABLE | WB_3DLOOK | WB_DOCKABLE | WB_SIZEABLE | WB_CLOSEABLE;

                    pPanelWindow = new PanelWindow( pWindow, nStyles );
                    m_xPanelWindow = VCLUnoHelper::GetInterface( pPanelWindow );
                    pPanelWindow->setResourceURL( m_aResourceURL );
                    pPanelWindow->setContentWindow( pContentWindow );
                }
            }

            try
            {
            }
            catch ( NoSuchElementException& )
            {
            }
        }
    }
}

// XEventListener
void SAL_CALL PanelWrapper::disposing( const ::com::sun::star::lang::EventObject& ) throw (::com::sun::star::uno::RuntimeException)
{
    // nothing todo
}

// XUpdatable
void SAL_CALL PanelWrapper::update() throw (::com::sun::star::uno::RuntimeException)
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();
}

// XUIElement interface
Reference< XInterface > SAL_CALL PanelWrapper::getRealInterface(  ) throw (::com::sun::star::uno::RuntimeException)
{
    ResetableGuard aLock( m_aLock );
    return m_xPanelWindow;
}

void SAL_CALL PanelWrapper::setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const com::sun::star::uno::Any&  aValue ) throw( com::sun::star::uno::Exception )
{
    ResetableGuard aLock( m_aLock );
    sal_Bool bNoClose( m_bNoClose );
    aLock.unlock();

    UIElementWrapperBase::setFastPropertyValue_NoBroadcast( nHandle, aValue );

    aLock.lock();

    sal_Bool bNewNoClose( m_bNoClose );
    if ( m_xPanelWindow.is() && !m_bDisposed && ( bNewNoClose != bNoClose ))
    {
        PanelWindow* pPanelWindow = dynamic_cast< PanelWindow* >( VCLUnoHelper::GetWindow( m_xPanelWindow ) );
        if ( pPanelWindow )
        {
            if ( bNewNoClose )
            {
                pPanelWindow->SetStyle( pPanelWindow->GetStyle() & ~WB_CLOSEABLE );
                pPanelWindow->SetFloatStyle( pPanelWindow->GetFloatStyle() & ~WB_CLOSEABLE );
            }
            else
            {
                pPanelWindow->SetStyle( pPanelWindow->GetStyle() | WB_CLOSEABLE );
                pPanelWindow->SetFloatStyle( pPanelWindow->GetFloatStyle() | WB_CLOSEABLE );
            }
        }
    }
}

} // namespace framework
<commit_msg>CWS gnumake2: another build breaker<commit_after>
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#include <services.h>
#include <uielement/panelwrapper.hxx>
#include <threadhelp/resetableguard.hxx>
#include <uielement/constitemcontainer.hxx>
#include <uielement/rootitemcontainer.hxx>
#include <uielement/panelwindow.hxx>
#include <services/modelwinservice.hxx>

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/awt/XSystemDependentMenuPeer.hpp>
#include <com/sun/star/awt/XMenuBar.hpp>
#include <com/sun/star/container/XIndexContainer.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/ui/UIElementType.hpp>

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#include <toolkit/unohlp.hxx>
#include <toolkit/awt/vclxwindow.hxx>
#include <comphelper/processfactory.hxx>
#include <svtools/miscopt.hxx>
#include <vcl/svapp.hxx>
#include <rtl/logfile.hxx>

using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star::frame;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace com::sun::star::awt;
using namespace ::com::sun::star::ui;

namespace framework
{

PanelWrapper::PanelWrapper( const Reference< XMultiServiceFactory >& xServiceManager ) :
    UIElementWrapperBase( UIElementType::DOCKINGWINDOW ),
    m_xServiceManager( xServiceManager ),
    m_bNoClose(false)
{
}

PanelWrapper::~PanelWrapper()
{
}

// XInterface
void SAL_CALL PanelWrapper::acquire() throw()
{
    UIElementWrapperBase::acquire();
}

void SAL_CALL PanelWrapper::release() throw()
{
    UIElementWrapperBase::release();
}

uno::Any SAL_CALL PanelWrapper::queryInterface( const uno::Type & rType )
throw( ::com::sun::star::uno::RuntimeException )
{
    return UIElementWrapperBase::queryInterface( rType );
}

// XComponent
void SAL_CALL PanelWrapper::dispose() throw ( RuntimeException )
{
    Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY );
    Reference< XMultiServiceFactory > xSMGR( m_xServiceManager );
    Reference< XWindow > xWindow;

    {
        ResetableGuard aLock( m_aLock );
        if ( m_bDisposed )
            return;
        xSMGR = m_xServiceManager;
    }

    com::sun::star::lang::EventObject aEvent( xThis );
    m_aListenerContainer.disposeAndClear( aEvent );

    rtl::OUString aModelWinService( SERVICENAME_MODELWINSERVICE );
    Reference< XNameAccess > xNameAccess( xSMGR->createInstance( aModelWinService ), UNO_QUERY );
    if ( xNameAccess.is() )
    {
        ModelWinService* pService = dynamic_cast< ModelWinService* >( xNameAccess.get() );
        if ( pService != 0 )
        {
            vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
            PanelWindow* pPanelWindow = dynamic_cast< PanelWindow* >( m_xPanelWindow.get() );
            if ( pPanelWindow != NULL )
            {
                xWindow = VCLUnoHelper::GetInterface( pPanelWindow->getContentWindow() );
                pService->deregisterModelForXWindow( xWindow );
            }
        }
    }

    ResetableGuard aLock( m_aLock );
    m_xPanelWindow.clear();
    m_bDisposed = sal_True;
}

// XInitialization
void SAL_CALL PanelWrapper::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( !m_bInitialized )
    {
        UIElementWrapperBase::initialize( aArguments );

        sal_Bool bPopupMode( sal_False );
        Reference< XWindow > xContentWindow;
        for ( sal_Int32 i = 0; i < aArguments.getLength(); i++ )
        {
            PropertyValue aPropValue;
            if ( aArguments[i] >>= aPropValue )
            {
                if ( aPropValue.Name.equalsAsciiL( "PopupMode", 9 ))
                    aPropValue.Value >>= bPopupMode;
                else if ( aPropValue.Name.equalsAsciiL( "ContentWindow", 13 ))
                    aPropValue.Value >>= xContentWindow;
            }
        }

        Reference< XFrame > xFrame( m_xWeakFrame );
        if ( xFrame.is() )
        {
            PanelWindow* pPanelWindow(0);
            Window*      pContentWindow(0);
            {
                vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
                Window* pWindow = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );
                pContentWindow  = VCLUnoHelper::GetWindow( xContentWindow );
                if ( pWindow )
                {
                    ULONG nStyles = WB_LINESPACING | WB_BORDER | WB_SCROLL | WB_MOVEABLE | WB_3DLOOK | WB_DOCKABLE | WB_SIZEABLE | WB_CLOSEABLE;

                    pPanelWindow = new PanelWindow( pWindow, nStyles );
                    m_xPanelWindow = VCLUnoHelper::GetInterface( pPanelWindow );
                    pPanelWindow->setResourceURL( m_aResourceURL );
                    pPanelWindow->setContentWindow( pContentWindow );
                }
            }

            try
            {
            }
            catch ( NoSuchElementException& )
            {
            }
        }
    }
}

// XEventListener
void SAL_CALL PanelWrapper::disposing( const ::com::sun::star::lang::EventObject& ) throw (::com::sun::star::uno::RuntimeException)
{
    // nothing todo
}

// XUpdatable
void SAL_CALL PanelWrapper::update() throw (::com::sun::star::uno::RuntimeException)
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();
}

// XUIElement interface
Reference< XInterface > SAL_CALL PanelWrapper::getRealInterface(  ) throw (::com::sun::star::uno::RuntimeException)
{
    ResetableGuard aLock( m_aLock );
    return m_xPanelWindow;
}

void SAL_CALL PanelWrapper::setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const com::sun::star::uno::Any&  aValue ) throw( com::sun::star::uno::Exception )
{
    ResetableGuard aLock( m_aLock );
    sal_Bool bNoClose( m_bNoClose );
    aLock.unlock();

    UIElementWrapperBase::setFastPropertyValue_NoBroadcast( nHandle, aValue );

    aLock.lock();

    sal_Bool bNewNoClose( m_bNoClose );
    if ( m_xPanelWindow.is() && !m_bDisposed && ( bNewNoClose != bNoClose ))
    {
        PanelWindow* pPanelWindow = dynamic_cast< PanelWindow* >( VCLUnoHelper::GetWindow( m_xPanelWindow ) );
        if ( pPanelWindow )
        {
            if ( bNewNoClose )
            {
                pPanelWindow->SetStyle( pPanelWindow->GetStyle() & ~WB_CLOSEABLE );
                pPanelWindow->SetFloatStyle( pPanelWindow->GetFloatStyle() & ~WB_CLOSEABLE );
            }
            else
            {
                pPanelWindow->SetStyle( pPanelWindow->GetStyle() | WB_CLOSEABLE );
                pPanelWindow->SetFloatStyle( pPanelWindow->GetFloatStyle() | WB_CLOSEABLE );
            }
        }
    }
}

} // namespace framework
<|endoftext|>