<commit_before>#pragma once

#include <vector>

#include "acmacs-base/fmt.hh"
#include "acmacs-base/range-v3.hh"

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

namespace acmacs
{
    namespace detail
    {
        template <typename Key, typename Value> class map_base_t
        {
          public:
            using entry_type = std::pair<Key, Value>;
            using const_iterator = typename std::vector<entry_type>::const_iterator;

            // map_base_t() = default;
            virtual ~map_base_t() = default;

            bool empty() const noexcept { return data_.empty(); }
            constexpr const auto& data() const noexcept { return data_; }

            template <typename Range> void collect(Range&& rng, bool check_result = true)
            {
                data_ = rng | ranges::to<std::vector>;
                sorted_ = false;
                if (check_result && data_.size() > 1)
                    check();
            }

            template <typename EKey, typename EValue> auto& emplace(EKey&& key, EValue&& value)
            {
                sorted_ = false;
                return data_.emplace_back(std::forward<EKey>(key), std::forward<EValue>(value));
            }

          protected:
            constexpr auto& data() noexcept { return data_; }
            // constexpr bool sorted() const noexcept { return sorted_; }

            template <typename FindKey> const_iterator find_first(const FindKey& key) const noexcept
            {
                sort();
                return std::lower_bound(std::begin(data_), std::end(data_), key, [](const auto& e1, const auto& k2) { return e1.first < k2; });
            }

            virtual void check() const {}

            void sort() const noexcept
            {
                if (!sorted_) {
                    ranges::sort(data_, [](const auto& e1, const auto& e2) { return e1.first < e2.first; });
                    sorted_ = true;
                }
            }

          private:
            mutable std::vector<entry_type> data_;
            mutable bool sorted_{false};

        };
    } // namespace detail

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

    // see seqdb.cc Seqdb::hash_index() for sample usage
    template <typename Key, typename Value> class map_with_duplicating_keys_t : public detail::map_base_t<Key, Value>
    {
      public:
        using const_iterator = typename detail::map_base_t<Key, Value>::const_iterator;

        template <typename FindKey> std::pair<const_iterator, const_iterator> find(const FindKey& key) const noexcept
        {
            const auto first = this->find_first(key);
            // first may point to the wrong key, if key is not in the map
            return {first, std::find_if(first, std::end(this->data()), [&key](const auto& en) { return en.first != key; })};
        }

    };

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

    class map_with_unique_keys_error : public std::runtime_error
    {
      public:
        using std::runtime_error::runtime_error;
    };

    // see seqdb.cc Seqdb::seq_id_index() for sample usage
    template <typename Key, typename Value> class map_with_unique_keys_t : public detail::map_base_t<Key, Value>
    {
      public:
        using const_iterator = typename detail::map_base_t<Key, Value>::const_iterator;

        template <typename FindKey> const Value* find(const FindKey& key) const noexcept
        {
            if (const auto first = this->find_first(key); first->first == key)
                return &first->second;
            else
                return nullptr;
        }

      protected:
        void check() const override
        {
            this->sort();
            for (auto cur = std::next(std::begin(this->data())); cur != std::end(this->data()); ++cur) {
                if (cur->first == std::prev(cur)->first)
                    throw map_with_unique_keys_error{"duplicating keys within map_with_unique_keys_t"};
            }
        }

    };

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

    template <typename Key, typename Value> class small_map_with_unique_keys_t
    {
      public:
        using entry_type = std::pair<Key, Value>;
        using const_iterator = typename std::vector<entry_type>::const_iterator;

        small_map_with_unique_keys_t() = default;
        // template <typename Iter> small_map_with_unique_keys_t(Iter first, Iter last) : data_(first, last) {}
        small_map_with_unique_keys_t(std::initializer_list<entry_type> init) : data_{init} {}

        constexpr const auto& data() const noexcept { return data_; }
        auto begin() const noexcept { return data_.begin(); }
        auto end() const noexcept { return data_.end(); }
        auto empty() const noexcept { return data_.empty(); }
        auto size() const noexcept { return data_.size(); }

        template <typename K> auto find(const K& key) const noexcept
        {
            return std::find_if(std::begin(data_), std::end(data_), [&key](const auto& en) { return en.first == key; });
        }

        template <typename K> auto find(const K& key) noexcept
        {
            return std::find_if(std::begin(data_), std::end(data_), [&key](const auto& en) { return en.first == key; });
        }

        Value& at(const Key& key)
        {
            if (const auto found = find(key); found != std::end(data_))
                return found->second;
            throw std::out_of_range{fmt::format("acmacs::small_map_with_unique_keys_t::at(): no key: {}", key)};
        }

        const Value& at(const Key& key) const
        {
            if (const auto found = find(key); found != std::end(data_))
                return found->second;
            throw std::out_of_range{fmt::format("acmacs::small_map_with_unique_keys_t::at(): no key: {}", key)};
        }

        auto& emplace_or_replace(const Key& key, const Value& value)
        {
            if (auto found = find(key); found != end())
                return *found;
            else
                return data_.emplace_back(key, value);
        }

      private:
        std::vector<entry_type> data_;
    };

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

    template <typename Key, typename Value> class flat_map_t
    {
      public:
        using key_type = Key;
        using value_type = Value;
        using entry_type = std::pair<Key, Value>;

        flat_map_t() = default;
        template <typename Iter> flat_map_t(Iter first, Iter last) : data_(first, last) {}
        flat_map_t(std::initializer_list<entry_type> init) : data_{init} {}

        auto begin() const { return data_.begin(); }
        auto end() const { return data_.end(); }
        auto empty() const { return data_.empty(); }
        auto size() const { return data_.size(); }
        const auto& operator[](size_t index) const { return data_[index]; }
        const auto& back() const { return data_.back(); }
        auto& back() { return data_.back(); }
        void sort_by_key()
        {
            std::sort(std::begin(data_), std::end(data_), [](const auto& e1, const auto& e2) { return e1.first < e2.first; });
        }
        void sort_by_value()
        {
            std::sort(std::begin(data_), std::end(data_), [](const auto& e1, const auto& e2) { return e1.second < e2.second; });
        }
        void sort_by_value_reverse()
        {
            std::sort(std::begin(data_), std::end(data_), [](const auto& e1, const auto& e2) { return e1.second > e2.second; });
        }

        template <typename K> auto find(const K& key) const
        {
            return std::find_if(std::begin(data_), std::end(data_), [&key](const auto& en) { return en.first == key; });
        }

        template <typename K> auto find(const K& key)
        {
            return std::find_if(std::begin(data_), std::end(data_), [&key](const auto& en) { return en.first == key; });
        }
        template <typename K> bool exists(const K& key) const { return find(key) != std::end(data_); }

        Value& at(const Key& key)
        {
            if (const auto found = find(key); found != std::end(data_))
                return found->second;
            throw std::out_of_range{fmt::format("acmacs::flat_map_t::at(): no key: {}", key)};
        }

        const Value& at(const Key& key) const
        {
            if (const auto found = find(key); found != std::end(data_))
                return found->second;
            throw std::out_of_range{fmt::format("acmacs::flat_map_t::at(): no key: {}", key)};
        }

        const Value* at_ptr(const Key& key) const
        {
            if (const auto found = find(key); found != std::end(data_))
                return &found->second;
            else
                return nullptr;
        }

        auto& emplace(const Key& key, const Value& value) { return data_.emplace_back(key, value); }
        auto& emplace(Key&& key, Value&& value) { return data_.emplace_back(std::move(key), std::move(value)); }

        auto& emplace_or_replace(const Key& key, const Value& value)
        {
            if (auto found = find(key); found != std::end(data_)) {
                found->second = value;
                return *found;
            }
            else
                return emplace(key, value);
        }

        auto& emplace_not_replace(const Key& key, const Value& value)
        {
            if (auto found = find(key); found != std::end(data_))
                return *found;
            else
                return emplace(key, value);
        }

        auto& emplace_not_replace(const Key& key)
        {
            if (auto found = find(key); found != std::end(data_))
                return *found;
            else
                return emplace(key, Value{});
        }

        void reserve(size_t sz) { data_.reserve(sz); }

      private:
        std::vector<entry_type> data_;
    };

} // namespace acmacs

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>small_map_with_unique_keys_t improvements<commit_after>#pragma once

#include <vector>

#include "acmacs-base/fmt.hh"
#include "acmacs-base/range-v3.hh"

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

namespace acmacs
{
    namespace detail
    {
        template <typename Key, typename Value> class map_base_t
        {
          public:
            using entry_type = std::pair<Key, Value>;
            using const_iterator = typename std::vector<entry_type>::const_iterator;

            // map_base_t() = default;
            virtual ~map_base_t() = default;

            bool empty() const noexcept { return data_.empty(); }
            constexpr const auto& data() const noexcept { return data_; }

            template <typename Range> void collect(Range&& rng, bool check_result = true)
            {
                data_ = rng | ranges::to<std::vector>;
                sorted_ = false;
                if (check_result && data_.size() > 1)
                    check();
            }

            template <typename EKey, typename EValue> auto& emplace(EKey&& key, EValue&& value)
            {
                sorted_ = false;
                return data_.emplace_back(std::forward<EKey>(key), std::forward<EValue>(value));
            }

          protected:
            constexpr auto& data() noexcept { return data_; }
            // constexpr bool sorted() const noexcept { return sorted_; }

            template <typename FindKey> const_iterator find_first(const FindKey& key) const noexcept
            {
                sort();
                return std::lower_bound(std::begin(data_), std::end(data_), key, [](const auto& e1, const auto& k2) { return e1.first < k2; });
            }

            virtual void check() const {}

            void sort() const noexcept
            {
                if (!sorted_) {
                    ranges::sort(data_, [](const auto& e1, const auto& e2) { return e1.first < e2.first; });
                    sorted_ = true;
                }
            }

          private:
            mutable std::vector<entry_type> data_;
            mutable bool sorted_{false};

        };
    } // namespace detail

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

    // see seqdb.cc Seqdb::hash_index() for sample usage
    template <typename Key, typename Value> class map_with_duplicating_keys_t : public detail::map_base_t<Key, Value>
    {
      public:
        using const_iterator = typename detail::map_base_t<Key, Value>::const_iterator;

        template <typename FindKey> std::pair<const_iterator, const_iterator> find(const FindKey& key) const noexcept
        {
            const auto first = this->find_first(key);
            // first may point to the wrong key, if key is not in the map
            return {first, std::find_if(first, std::end(this->data()), [&key](const auto& en) { return en.first != key; })};
        }

    };

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

    class map_with_unique_keys_error : public std::runtime_error
    {
      public:
        using std::runtime_error::runtime_error;
    };

    // see seqdb.cc Seqdb::seq_id_index() for sample usage
    template <typename Key, typename Value> class map_with_unique_keys_t : public detail::map_base_t<Key, Value>
    {
      public:
        using const_iterator = typename detail::map_base_t<Key, Value>::const_iterator;

        template <typename FindKey> const Value* find(const FindKey& key) const noexcept
        {
            if (const auto first = this->find_first(key); first->first == key)
                return &first->second;
            else
                return nullptr;
        }

      protected:
        void check() const override
        {
            this->sort();
            for (auto cur = std::next(std::begin(this->data())); cur != std::end(this->data()); ++cur) {
                if (cur->first == std::prev(cur)->first)
                    throw map_with_unique_keys_error{"duplicating keys within map_with_unique_keys_t"};
            }
        }

    };

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

    template <typename Key, typename Value> class small_map_with_unique_keys_t
    {
      public:
        using entry_type = std::pair<Key, Value>;
        using const_iterator = typename std::vector<entry_type>::const_iterator;

        small_map_with_unique_keys_t() = default;
        // template <typename Iter> small_map_with_unique_keys_t(Iter first, Iter last) : data_(first, last) {}
        small_map_with_unique_keys_t(std::initializer_list<entry_type> init) : data_{init} {}

        constexpr const auto& data() const noexcept { return data_; }
        auto begin() const noexcept { return data_.begin(); }
        auto end() const noexcept { return data_.end(); }
        auto empty() const noexcept { return data_.empty(); }
        auto size() const noexcept { return data_.size(); }

        template <typename K> auto find(const K& key) const noexcept
        {
            return std::find_if(std::begin(data_), std::end(data_), [&key](const auto& en) { return en.first == key; });
        }

        template <typename K> auto find(const K& key) noexcept
        {
            return std::find_if(std::begin(data_), std::end(data_), [&key](const auto& en) { return en.first == key; });
        }

        template <typename K, typename Callback> void find_then(const K& key, Callback callback) const noexcept
        {
            if (const auto& en = find(key); en != std::end(data_))
                callback(en->second);
        }

        template <typename K> Value& get(const K& key)
        {
            if (const auto found = find(key); found != std::end(data_))
                return found->second;
            throw std::out_of_range{fmt::format("acmacs::small_map_with_unique_keys_t::at(): no key: {}", key)};
        }

        template <typename K> const Value& get(const K& key) const
        {
            if (const auto found = find(key); found != std::end(data_))
                return found->second;
            throw std::out_of_range{fmt::format("acmacs::small_map_with_unique_keys_t::at(): no key: {}", key)};
        }

        template <typename K, typename V> const Value& get_or(const K& key, const V& dflt) const
        {
            if (const auto found = find(key); found != std::end(data_))
                return found->second;
            else
                return dflt;
        }

        template <typename K, typename V> auto& emplace_or_replace(const K& key, const V& value)
        {
            if (auto found = find(key); found != end()) {
                found->second = Value{value};
                return *found;
            }
            else
                return data_.emplace_back(Key{key}, Value{value});
        }

        template <typename K, typename V = Value> auto& emplace_not_replace(const K& key, const V& value = V{})
        {
            if (auto found = find(key); found != end())
                return *found;
            else
                return data_.emplace_back(Key{key}, Value{value});
        }

      private:
        std::vector<entry_type> data_;

    }; // small_map_with_unique_keys_t<Key, Value>

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

    template <typename Key, typename Value> class flat_map_t
    {
      public:
        using key_type = Key;
        using value_type = Value;
        using entry_type = std::pair<Key, Value>;

        flat_map_t() = default;
        template <typename Iter> flat_map_t(Iter first, Iter last) : data_(first, last) {}
        flat_map_t(std::initializer_list<entry_type> init) : data_{init} {}

        auto begin() const { return data_.begin(); }
        auto end() const { return data_.end(); }
        auto empty() const { return data_.empty(); }
        auto size() const { return data_.size(); }
        const auto& operator[](size_t index) const { return data_[index]; }
        const auto& back() const { return data_.back(); }
        auto& back() { return data_.back(); }
        void sort_by_key()
        {
            std::sort(std::begin(data_), std::end(data_), [](const auto& e1, const auto& e2) { return e1.first < e2.first; });
        }
        void sort_by_value()
        {
            std::sort(std::begin(data_), std::end(data_), [](const auto& e1, const auto& e2) { return e1.second < e2.second; });
        }
        void sort_by_value_reverse()
        {
            std::sort(std::begin(data_), std::end(data_), [](const auto& e1, const auto& e2) { return e1.second > e2.second; });
        }

        template <typename K> auto find(const K& key) const
        {
            return std::find_if(std::begin(data_), std::end(data_), [&key](const auto& en) { return en.first == key; });
        }

        template <typename K> auto find(const K& key)
        {
            return std::find_if(std::begin(data_), std::end(data_), [&key](const auto& en) { return en.first == key; });
        }
        template <typename K> bool exists(const K& key) const { return find(key) != std::end(data_); }

        Value& at(const Key& key)
        {
            if (const auto found = find(key); found != std::end(data_))
                return found->second;
            throw std::out_of_range{fmt::format("acmacs::flat_map_t::at(): no key: {}", key)};
        }

        const Value& at(const Key& key) const
        {
            if (const auto found = find(key); found != std::end(data_))
                return found->second;
            throw std::out_of_range{fmt::format("acmacs::flat_map_t::at(): no key: {}", key)};
        }

        const Value* at_ptr(const Key& key) const
        {
            if (const auto found = find(key); found != std::end(data_))
                return &found->second;
            else
                return nullptr;
        }

        auto& emplace(const Key& key, const Value& value) { return data_.emplace_back(key, value); }
        auto& emplace(Key&& key, Value&& value) { return data_.emplace_back(std::move(key), std::move(value)); }

        auto& emplace_or_replace(const Key& key, const Value& value)
        {
            if (auto found = find(key); found != std::end(data_)) {
                found->second = value;
                return *found;
            }
            else
                return emplace(key, value);
        }

        auto& emplace_not_replace(const Key& key, const Value& value)
        {
            if (auto found = find(key); found != std::end(data_))
                return *found;
            else
                return emplace(key, value);
        }

        auto& emplace_not_replace(const Key& key)
        {
            if (auto found = find(key); found != std::end(data_))
                return *found;
            else
                return emplace(key, Value{});
        }

        void reserve(size_t sz) { data_.reserve(sz); }

      private:
        std::vector<entry_type> data_;
    };

} // namespace acmacs

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


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

#include "config.h"

#include <string>

#include "Document.h"
#include "EventListener.h"
#include "InspectorController.h"
#include "InspectorFrontend.h"
#include "InspectorResource.h"
#include "Node.h"
#include "Page.h"
#include "PlatformString.h"
#include "ScriptObject.h"
#include "ScriptState.h"
#include "ScriptValue.h"
#include "V8Binding.h"
#include "V8Proxy.h"
#include <wtf/OwnPtr.h>
#undef LOG

#include "base/values.h"
#include "webkit/api/public/WebDataSource.h"
#include "webkit/api/public/WebURL.h"
#include "webkit/api/public/WebURLRequest.h"
#include "webkit/glue/devtools/bound_object.h"
#include "webkit/glue/devtools/debugger_agent_impl.h"
#include "webkit/glue/devtools/debugger_agent_manager.h"
#include "webkit/glue/devtools/dom_agent_impl.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webdevtoolsagent_delegate.h"
#include "webkit/glue/webdevtoolsagent_impl.h"
#include "webkit/glue/webview_impl.h"

using WebCore::Document;
using WebCore::InspectorController;
using WebCore::InspectorFrontend;
using WebCore::InspectorResource;
using WebCore::Node;
using WebCore::Page;
using WebCore::ScriptObject;
using WebCore::ScriptState;
using WebCore::ScriptValue;
using WebCore::String;
using WebCore::V8ClassIndex;
using WebCore::V8DOMWrapper;
using WebCore::V8Proxy;
using WebKit::WebDataSource;
using WebKit::WebFrame;
using WebKit::WebURLRequest;

WebDevToolsAgentImpl::WebDevToolsAgentImpl(
    WebViewImpl* web_view_impl,
    WebDevToolsAgentDelegate* delegate)
    : host_id_(delegate->GetHostId()),
      delegate_(delegate),
      web_view_impl_(web_view_impl),
      document_(NULL),
      attached_(false) {
  debugger_agent_delegate_stub_.set(new DebuggerAgentDelegateStub(this));
  dom_agent_delegate_stub_.set(new DomAgentDelegateStub(this));
  tools_agent_delegate_stub_.set(new ToolsAgentDelegateStub(this));
  tools_agent_native_delegate_stub_.set(new ToolsAgentNativeDelegateStub(this));
}

WebDevToolsAgentImpl::~WebDevToolsAgentImpl() {
  DebuggerAgentManager::OnWebViewClosed(web_view_impl_);
  DisposeUtilityContext();
}

void WebDevToolsAgentImpl::DisposeUtilityContext() {
  if (!utility_context_.IsEmpty()) {
    utility_context_.Dispose();
    utility_context_.Clear();
  }
}

void WebDevToolsAgentImpl::Attach() {
  if (attached_) {
    return;
  }
  debugger_agent_impl_.set(
      new DebuggerAgentImpl(web_view_impl_,
                            debugger_agent_delegate_stub_.get(),
                            this));
  Page* page = web_view_impl_->page();
  dom_agent_impl_.set(new DomAgentImpl(dom_agent_delegate_stub_.get()));

  // We are potentially attaching to the running page -> init agents with
  // Document if any.
  Document* doc = page->mainFrame()->document();
  if (doc) {
    // Reuse existing context in case detached/attached.
    if (utility_context_.IsEmpty()) {
      debugger_agent_impl_->ResetUtilityContext(doc, &utility_context_);
      InitDevToolsAgentHost();
    }

    dom_agent_impl_->SetDocument(doc);

    InspectorController* ic = web_view_impl_->page()->inspectorController();
    // Unhide resources panel if necessary.
    tools_agent_delegate_stub_->SetResourcesPanelEnabled(
        ic->resourceTrackingEnabled());
    v8::HandleScope scope;
    ScriptState* state = scriptStateFromPage(web_view_impl_->page());
    ic->setFrontendProxyObject(
        state,
        ScriptObject(state, utility_context_->Global()));
    // Allow controller to send messages to the frontend.
    ic->setWindowVisible(true, false);
  }
  attached_ = true;
}

void WebDevToolsAgentImpl::Detach() {
  // Prevent controller from sending messages to the frontend.
  InspectorController* ic = web_view_impl_->page()->inspectorController();
  ic->setWindowVisible(false, false);
  HideDOMNodeHighlight();
  devtools_agent_host_.set(NULL);
  debugger_agent_impl_.set(NULL);
  dom_agent_impl_.set(NULL);
  attached_ = false;
}

void WebDevToolsAgentImpl::OnNavigate() {
  DebuggerAgentManager::OnNavigate();
}

void WebDevToolsAgentImpl::SetMainFrameDocumentReady(bool ready) {
  if (!attached_) {
    return;
  }

  // We were attached prior to the page load -> init agents with Document.
  Document* doc;
  if (ready) {
    Page* page = web_view_impl_->page();
    doc = page->mainFrame()->document();
  } else {
    doc = NULL;
  }
  if (doc) {
    debugger_agent_impl_->ResetUtilityContext(doc, &utility_context_);
    InitDevToolsAgentHost();
  }
  dom_agent_impl_->SetDocument(doc);
}

void WebDevToolsAgentImpl::DidCommitLoadForFrame(
    WebViewImpl* webview,
    WebFrame* frame,
    bool is_new_navigation) {
  if (!attached_) {
    DisposeUtilityContext();
    return;
  }
  WebDataSource* ds = frame->dataSource();
  const WebURLRequest& request = ds->request();
  GURL url = ds->hasUnreachableURL() ?
      ds->unreachableURL() :
      request.url();
  if (webview->GetMainFrame() == frame) {
    tools_agent_delegate_stub_->FrameNavigate(
        url.possibly_invalid_spec());
  }
  InspectorController* ic = webview->page()->inspectorController();
  // Unhide resources panel if necessary.
  tools_agent_delegate_stub_->SetResourcesPanelEnabled(
      ic->resourceTrackingEnabled());
}

void WebDevToolsAgentImpl::WindowObjectCleared(WebFrameImpl* webframe) {
  DebuggerAgentManager::SetHostId(webframe, host_id_);
  if (attached_) {
    // Push context id into the client if it is already attached.
    debugger_agent_delegate_stub_->SetContextId(host_id_);
  }
}

void WebDevToolsAgentImpl::ForceRepaint() {
  delegate_->ForceRepaint();
}

void WebDevToolsAgentImpl::HighlightDOMNode(int node_id) {
  if (!attached_) {
    return;
  }
  Node* node = dom_agent_impl_->GetNodeForId(node_id);
  if (!node) {
    return;
  }
  Page* page = web_view_impl_->page();
  page->inspectorController()->highlight(node);
}

void WebDevToolsAgentImpl::HideDOMNodeHighlight() {
  Page* page = web_view_impl_->page();
  if (page) {
    page->inspectorController()->hideHighlight();
  }
}

void WebDevToolsAgentImpl::ExecuteUtilityFunction(
      int call_id,
      const String& function_name,
      const String& json_args) {
  String result;
  String exception;
  result = debugger_agent_impl_->ExecuteUtilityFunction(utility_context_,
      function_name, json_args, &exception);
  tools_agent_delegate_stub_->DidExecuteUtilityFunction(call_id,
      result, exception);
}

void WebDevToolsAgentImpl::EvaluateJavaScript(
    int call_id,
    const WebCore::String& source) {
  String exception;
  String result = debugger_agent_impl_->EvaluateJavaScript(utility_context_,
      source, &exception);
  tools_agent_delegate_stub_->DidEvaluateJavaScript(call_id, result, exception);
}

void WebDevToolsAgentImpl::ClearConsoleMessages() {
  Page* page = web_view_impl_->page();
  if (page) {
    page->inspectorController()->clearConsoleMessages();
  }
}

void WebDevToolsAgentImpl::GetResourceContent(
    int call_id,
    int identifier) {
  String content;
  Page* page = web_view_impl_->page();
  if (page) {
    RefPtr<InspectorResource> resource =
        page->inspectorController()->resources().get(identifier);
    if (resource.get()) {
      content = resource->sourceString();
    }
  }
  tools_agent_native_delegate_stub_->DidGetResourceContent(call_id, content);
}

void WebDevToolsAgentImpl::SetResourceTrackingEnabled(
    bool enabled,
    bool always) {
  // Hide / unhide resources panel if necessary.
  tools_agent_delegate_stub_->SetResourcesPanelEnabled(enabled);

  InspectorController* ic = web_view_impl_->page()->inspectorController();
  if (enabled) {
    ic->enableResourceTracking(always);
  } else {
    ic->disableResourceTracking(always);
  }
}

void WebDevToolsAgentImpl::DispatchMessageFromClient(
    const std::string& class_name,
    const std::string& method_name,
    const std::string& raw_msg) {
  OwnPtr<ListValue> message(
      static_cast<ListValue*>(DevToolsRpc::ParseMessage(raw_msg)));
  if (ToolsAgentDispatch::Dispatch(
      this, class_name, method_name, *message.get())) {
    return;
  }

  if (!attached_) {
    return;
  }

  if (debugger_agent_impl_.get() &&
      DebuggerAgentDispatch::Dispatch(
          debugger_agent_impl_.get(), class_name, method_name,
          *message.get())) {
    return;
  }

  if (DomAgentDispatch::Dispatch(
      dom_agent_impl_.get(), class_name, method_name, *message.get())) {
    return;
  }
}

void WebDevToolsAgentImpl::InspectElement(int x, int y) {
  Node* node = web_view_impl_->GetNodeForWindowPos(x, y);
  if (!node) {
    return;
  }

  int node_id = dom_agent_impl_->PushNodePathToClient(node);
  tools_agent_delegate_stub_->UpdateFocusedNode(node_id);
}

void WebDevToolsAgentImpl::SendRpcMessage(
    const std::string& class_name,
    const std::string& method_name,
    const std::string& raw_msg) {
  delegate_->SendMessageToClient(class_name, method_name, raw_msg);
}

void WebDevToolsAgentImpl::InitDevToolsAgentHost() {
  devtools_agent_host_.set(
      new BoundObject(utility_context_, this, "DevToolsAgentHost"));
  devtools_agent_host_->AddProtoFunction(
      "dispatch",
      WebDevToolsAgentImpl::JsDispatchOnClient);
  devtools_agent_host_->AddProtoFunction(
      "getNodeForId",
      WebDevToolsAgentImpl::JsGetNodeForId);
  devtools_agent_host_->Build();

  v8::HandleScope scope;
  v8::Context::Scope utility_scope(utility_context_);
  InspectorController* ic = web_view_impl_->page()->inspectorController();
  utility_context_->Global()->Set(
      v8::String::New("InspectorController"),
      V8DOMWrapper::convertToV8Object(V8ClassIndex::INSPECTORBACKEND,
                                      ic->inspectorBackend()));
}

// static
v8::Handle<v8::Value> WebDevToolsAgentImpl::JsDispatchOnClient(
    const v8::Arguments& args) {
  v8::TryCatch exception_catcher;
  String message = WebCore::toWebCoreStringWithNullCheck(args[0]);
  if (message.isEmpty() || exception_catcher.HasCaught()) {
    return v8::Undefined();
  }
  WebDevToolsAgentImpl* agent = static_cast<WebDevToolsAgentImpl*>(
      v8::External::Cast(*args.Data())->Value());
  agent->tools_agent_delegate_stub_->DispatchOnClient(message);
  return v8::Undefined();
}

// static
v8::Handle<v8::Value> WebDevToolsAgentImpl::JsGetNodeForId(
    const v8::Arguments& args) {
  int node_id = static_cast<int>(args[0]->NumberValue());
  WebDevToolsAgentImpl* agent = static_cast<WebDevToolsAgentImpl*>(
      v8::External::Cast(*args.Data())->Value());
  Node* node = agent->dom_agent_impl_->GetNodeForId(node_id);
  return V8DOMWrapper::convertToV8Object(V8ClassIndex::NODE, node);
}

// static
void WebDevToolsAgent::ExecuteDebuggerCommand(
    const std::string& command,
    int caller_id) {
  DebuggerAgentManager::ExecuteDebuggerCommand(command, caller_id);
}

// static
void WebDevToolsAgent::SetMessageLoopDispatchHandler(
    MessageLoopDispatchHandler handler) {
  DebuggerAgentManager::SetMessageLoopDispatchHandler(handler);
}
<commit_msg>Fix Chromium canary^h^h^h^H parrot build: remove InspectorController::clearConsole call.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"

#include <string>

#include "Document.h"
#include "EventListener.h"
#include "InspectorController.h"
#include "InspectorFrontend.h"
#include "InspectorResource.h"
#include "Node.h"
#include "Page.h"
#include "PlatformString.h"
#include "ScriptObject.h"
#include "ScriptState.h"
#include "ScriptValue.h"
#include "V8Binding.h"
#include "V8Proxy.h"
#include <wtf/OwnPtr.h>
#undef LOG

#include "base/values.h"
#include "webkit/api/public/WebDataSource.h"
#include "webkit/api/public/WebURL.h"
#include "webkit/api/public/WebURLRequest.h"
#include "webkit/glue/devtools/bound_object.h"
#include "webkit/glue/devtools/debugger_agent_impl.h"
#include "webkit/glue/devtools/debugger_agent_manager.h"
#include "webkit/glue/devtools/dom_agent_impl.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webdevtoolsagent_delegate.h"
#include "webkit/glue/webdevtoolsagent_impl.h"
#include "webkit/glue/webview_impl.h"

using WebCore::Document;
using WebCore::InspectorController;
using WebCore::InspectorFrontend;
using WebCore::InspectorResource;
using WebCore::Node;
using WebCore::Page;
using WebCore::ScriptObject;
using WebCore::ScriptState;
using WebCore::ScriptValue;
using WebCore::String;
using WebCore::V8ClassIndex;
using WebCore::V8DOMWrapper;
using WebCore::V8Proxy;
using WebKit::WebDataSource;
using WebKit::WebFrame;
using WebKit::WebURLRequest;

WebDevToolsAgentImpl::WebDevToolsAgentImpl(
    WebViewImpl* web_view_impl,
    WebDevToolsAgentDelegate* delegate)
    : host_id_(delegate->GetHostId()),
      delegate_(delegate),
      web_view_impl_(web_view_impl),
      document_(NULL),
      attached_(false) {
  debugger_agent_delegate_stub_.set(new DebuggerAgentDelegateStub(this));
  dom_agent_delegate_stub_.set(new DomAgentDelegateStub(this));
  tools_agent_delegate_stub_.set(new ToolsAgentDelegateStub(this));
  tools_agent_native_delegate_stub_.set(new ToolsAgentNativeDelegateStub(this));
}

WebDevToolsAgentImpl::~WebDevToolsAgentImpl() {
  DebuggerAgentManager::OnWebViewClosed(web_view_impl_);
  DisposeUtilityContext();
}

void WebDevToolsAgentImpl::DisposeUtilityContext() {
  if (!utility_context_.IsEmpty()) {
    utility_context_.Dispose();
    utility_context_.Clear();
  }
}

void WebDevToolsAgentImpl::Attach() {
  if (attached_) {
    return;
  }
  debugger_agent_impl_.set(
      new DebuggerAgentImpl(web_view_impl_,
                            debugger_agent_delegate_stub_.get(),
                            this));
  Page* page = web_view_impl_->page();
  dom_agent_impl_.set(new DomAgentImpl(dom_agent_delegate_stub_.get()));

  // We are potentially attaching to the running page -> init agents with
  // Document if any.
  Document* doc = page->mainFrame()->document();
  if (doc) {
    // Reuse existing context in case detached/attached.
    if (utility_context_.IsEmpty()) {
      debugger_agent_impl_->ResetUtilityContext(doc, &utility_context_);
      InitDevToolsAgentHost();
    }

    dom_agent_impl_->SetDocument(doc);

    InspectorController* ic = web_view_impl_->page()->inspectorController();
    // Unhide resources panel if necessary.
    tools_agent_delegate_stub_->SetResourcesPanelEnabled(
        ic->resourceTrackingEnabled());
    v8::HandleScope scope;
    ScriptState* state = scriptStateFromPage(web_view_impl_->page());
    ic->setFrontendProxyObject(
        state,
        ScriptObject(state, utility_context_->Global()));
    // Allow controller to send messages to the frontend.
    ic->setWindowVisible(true, false);
  }
  attached_ = true;
}

void WebDevToolsAgentImpl::Detach() {
  // Prevent controller from sending messages to the frontend.
  InspectorController* ic = web_view_impl_->page()->inspectorController();
  ic->setWindowVisible(false, false);
  HideDOMNodeHighlight();
  devtools_agent_host_.set(NULL);
  debugger_agent_impl_.set(NULL);
  dom_agent_impl_.set(NULL);
  attached_ = false;
}

void WebDevToolsAgentImpl::OnNavigate() {
  DebuggerAgentManager::OnNavigate();
}

void WebDevToolsAgentImpl::SetMainFrameDocumentReady(bool ready) {
  if (!attached_) {
    return;
  }

  // We were attached prior to the page load -> init agents with Document.
  Document* doc;
  if (ready) {
    Page* page = web_view_impl_->page();
    doc = page->mainFrame()->document();
  } else {
    doc = NULL;
  }
  if (doc) {
    debugger_agent_impl_->ResetUtilityContext(doc, &utility_context_);
    InitDevToolsAgentHost();
  }
  dom_agent_impl_->SetDocument(doc);
}

void WebDevToolsAgentImpl::DidCommitLoadForFrame(
    WebViewImpl* webview,
    WebFrame* frame,
    bool is_new_navigation) {
  if (!attached_) {
    DisposeUtilityContext();
    return;
  }
  WebDataSource* ds = frame->dataSource();
  const WebURLRequest& request = ds->request();
  GURL url = ds->hasUnreachableURL() ?
      ds->unreachableURL() :
      request.url();
  if (webview->GetMainFrame() == frame) {
    tools_agent_delegate_stub_->FrameNavigate(
        url.possibly_invalid_spec());
  }
  InspectorController* ic = webview->page()->inspectorController();
  // Unhide resources panel if necessary.
  tools_agent_delegate_stub_->SetResourcesPanelEnabled(
      ic->resourceTrackingEnabled());
}

void WebDevToolsAgentImpl::WindowObjectCleared(WebFrameImpl* webframe) {
  DebuggerAgentManager::SetHostId(webframe, host_id_);
  if (attached_) {
    // Push context id into the client if it is already attached.
    debugger_agent_delegate_stub_->SetContextId(host_id_);
  }
}

void WebDevToolsAgentImpl::ForceRepaint() {
  delegate_->ForceRepaint();
}

void WebDevToolsAgentImpl::HighlightDOMNode(int node_id) {
  if (!attached_) {
    return;
  }
  Node* node = dom_agent_impl_->GetNodeForId(node_id);
  if (!node) {
    return;
  }
  Page* page = web_view_impl_->page();
  page->inspectorController()->highlight(node);
}

void WebDevToolsAgentImpl::HideDOMNodeHighlight() {
  Page* page = web_view_impl_->page();
  if (page) {
    page->inspectorController()->hideHighlight();
  }
}

void WebDevToolsAgentImpl::ExecuteUtilityFunction(
      int call_id,
      const String& function_name,
      const String& json_args) {
  String result;
  String exception;
  result = debugger_agent_impl_->ExecuteUtilityFunction(utility_context_,
      function_name, json_args, &exception);
  tools_agent_delegate_stub_->DidExecuteUtilityFunction(call_id,
      result, exception);
}

void WebDevToolsAgentImpl::EvaluateJavaScript(
    int call_id,
    const WebCore::String& source) {
  String exception;
  String result = debugger_agent_impl_->EvaluateJavaScript(utility_context_,
      source, &exception);
  tools_agent_delegate_stub_->DidEvaluateJavaScript(call_id, result, exception);
}

void WebDevToolsAgentImpl::ClearConsoleMessages() {
// TODO(pfeldman): restore once migrated to DOMAgent.
//  Page* page = web_view_impl_->page();
//  if (page) {
//    page->inspectorController()->clearConsoleMessages();
//  }
}

void WebDevToolsAgentImpl::GetResourceContent(
    int call_id,
    int identifier) {
  String content;
  Page* page = web_view_impl_->page();
  if (page) {
    RefPtr<InspectorResource> resource =
        page->inspectorController()->resources().get(identifier);
    if (resource.get()) {
      content = resource->sourceString();
    }
  }
  tools_agent_native_delegate_stub_->DidGetResourceContent(call_id, content);
}

void WebDevToolsAgentImpl::SetResourceTrackingEnabled(
    bool enabled,
    bool always) {
  // Hide / unhide resources panel if necessary.
  tools_agent_delegate_stub_->SetResourcesPanelEnabled(enabled);

  InspectorController* ic = web_view_impl_->page()->inspectorController();
  if (enabled) {
    ic->enableResourceTracking(always);
  } else {
    ic->disableResourceTracking(always);
  }
}

void WebDevToolsAgentImpl::DispatchMessageFromClient(
    const std::string& class_name,
    const std::string& method_name,
    const std::string& raw_msg) {
  OwnPtr<ListValue> message(
      static_cast<ListValue*>(DevToolsRpc::ParseMessage(raw_msg)));
  if (ToolsAgentDispatch::Dispatch(
      this, class_name, method_name, *message.get())) {
    return;
  }

  if (!attached_) {
    return;
  }

  if (debugger_agent_impl_.get() &&
      DebuggerAgentDispatch::Dispatch(
          debugger_agent_impl_.get(), class_name, method_name,
          *message.get())) {
    return;
  }

  if (DomAgentDispatch::Dispatch(
      dom_agent_impl_.get(), class_name, method_name, *message.get())) {
    return;
  }
}

void WebDevToolsAgentImpl::InspectElement(int x, int y) {
  Node* node = web_view_impl_->GetNodeForWindowPos(x, y);
  if (!node) {
    return;
  }

  int node_id = dom_agent_impl_->PushNodePathToClient(node);
  tools_agent_delegate_stub_->UpdateFocusedNode(node_id);
}

void WebDevToolsAgentImpl::SendRpcMessage(
    const std::string& class_name,
    const std::string& method_name,
    const std::string& raw_msg) {
  delegate_->SendMessageToClient(class_name, method_name, raw_msg);
}

void WebDevToolsAgentImpl::InitDevToolsAgentHost() {
  devtools_agent_host_.set(
      new BoundObject(utility_context_, this, "DevToolsAgentHost"));
  devtools_agent_host_->AddProtoFunction(
      "dispatch",
      WebDevToolsAgentImpl::JsDispatchOnClient);
  devtools_agent_host_->AddProtoFunction(
      "getNodeForId",
      WebDevToolsAgentImpl::JsGetNodeForId);
  devtools_agent_host_->Build();

  v8::HandleScope scope;
  v8::Context::Scope utility_scope(utility_context_);
  InspectorController* ic = web_view_impl_->page()->inspectorController();
  utility_context_->Global()->Set(
      v8::String::New("InspectorController"),
      V8DOMWrapper::convertToV8Object(V8ClassIndex::INSPECTORBACKEND,
                                      ic->inspectorBackend()));
}

// static
v8::Handle<v8::Value> WebDevToolsAgentImpl::JsDispatchOnClient(
    const v8::Arguments& args) {
  v8::TryCatch exception_catcher;
  String message = WebCore::toWebCoreStringWithNullCheck(args[0]);
  if (message.isEmpty() || exception_catcher.HasCaught()) {
    return v8::Undefined();
  }
  WebDevToolsAgentImpl* agent = static_cast<WebDevToolsAgentImpl*>(
      v8::External::Cast(*args.Data())->Value());
  agent->tools_agent_delegate_stub_->DispatchOnClient(message);
  return v8::Undefined();
}

// static
v8::Handle<v8::Value> WebDevToolsAgentImpl::JsGetNodeForId(
    const v8::Arguments& args) {
  int node_id = static_cast<int>(args[0]->NumberValue());
  WebDevToolsAgentImpl* agent = static_cast<WebDevToolsAgentImpl*>(
      v8::External::Cast(*args.Data())->Value());
  Node* node = agent->dom_agent_impl_->GetNodeForId(node_id);
  return V8DOMWrapper::convertToV8Object(V8ClassIndex::NODE, node);
}

// static
void WebDevToolsAgent::ExecuteDebuggerCommand(
    const std::string& command,
    int caller_id) {
  DebuggerAgentManager::ExecuteDebuggerCommand(command, caller_id);
}

// static
void WebDevToolsAgent::SetMessageLoopDispatchHandler(
    MessageLoopDispatchHandler handler) {
  DebuggerAgentManager::SetMessageLoopDispatchHandler(handler);
}
<|endoftext|>


<commit_before>#pragma once

#include "acmacs-base/fmt.hh"
#include "acmacs-base/rjson.hh"
#include "acmacs-base/flat-map.hh"

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

namespace acmacs::settings::inline v2
{
    class error : public std::runtime_error
    {
        using std::runtime_error::runtime_error;
    };

    class Settings
    {
      public:
        Settings() = default;
        Settings(const std::vector<std::string_view>& filenames) { load(filenames); }
        virtual ~Settings() = default;

        // read settings from files, upon reading each file apply "init" in it (if found)
        void load(const std::vector<std::string_view>& filenames)
        {
            for (const auto& filename : filenames)
                load(filename);
        }
        void load(std::string_view filename);

        // substitute vars in name, find name in environment or in data_ or in built-in and apply it
        // if name starts with ? do nothing
        // if name not found, throw
        virtual void apply(std::string_view name = "main") const;
        void apply(const char* name) const { apply(std::string_view{name}); }

        // substitute vars in name, find name in the top of data_ and apply it
        // do nothing if name starts with ? or if it is not found in top of data_
        virtual void apply_top(std::string_view name) const;

        virtual bool apply_built_in(std::string_view name) const; // returns true if built-in command with that name found and applied

        void setenv_from_string(std::string_view key, std::string_view value);
        template <typename T> void setenv(std::string_view key, T&& value) { setenv(key, rjson::value{std::forward<T>(value)}); }

        const rjson::value& getenv(std::string_view key) const { return environment_.get(static_cast<std::string>(environment_.substitute(key))); }
        template <typename T> T getenv(std::string_view key, T&& a_default) const
        {
            if (const auto& val = environment_.get(static_cast<std::string>(environment_.substitute(key))); val.is_string()) {
                auto orig = static_cast<std::string>(val);
                for (size_t num_subst = 0; num_subst < 10; ++num_subst) {
                    const auto substituted = environment_.substitute(std::string_view{orig});
                    if (substituted.is_string() && orig != static_cast<std::string>(substituted))
                        orig = substituted;
                    else
                        return static_cast<T>(substituted);
                }
                throw error(fmt::format("Settings::getenv: too many substitutions in {}", val));
            }
            else if (!val.is_const_null())
                return static_cast<T>(val);
            else
                return std::move(a_default);
        }

        std::string getenv(std::string_view key, const char* a_default) const { return getenv(key, std::string{a_default}); }
        void printenv() const { environment_.print(); }

      protected:
        template <typename... Key> const rjson::value& get(Key&&... keys) const;
        void apply(const rjson::value& entry) const;

      private:
        class Environment
        {
          public:
            Environment() { push(); }

            const rjson::value& get(std::string_view key) const;
            void push() { data_.emplace_back(); }
            void pop() { data_.erase(std::prev(std::end(data_))); }
            size_t size() const { return data_.size(); }
            void add(std::string_view key, const rjson::value& val) { data_.rbegin()->emplace_or_replace(std::string{key}, val); }
            void add(std::string_view key, rjson::value&& val) { data_.rbegin()->emplace_or_replace(std::string{key}, std::move(val)); }
            void print() const;
            void print_key_value() const;

            rjson::value substitute(std::string_view source) const;

          private:
            std::vector<acmacs::flat_map_t<std::string, rjson::value>> data_;

            rjson::value substitute(const rjson::value& source) const;
        };

        std::vector<rjson::value> data_;
        mutable Environment environment_;

        void push_and_apply(const rjson::object& entry) const;

        friend class Subenvironment;
    };
} // namespace acmacs::settings::inline v2

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

namespace acmacs::settings::inline v2
{
    template <typename... Key> const rjson::value& Settings::get(Key && ... keys) const
    {
        for (auto it = data_.rbegin(); it != data_.rend(); ++it) {
            if (const auto& val = it->get(std::forward<Key>(keys)...); !val.is_const_null())
                return val;
        }
        return rjson::ConstNull;

    } // acmacs::settings::v2::Settings::get

    template <> inline void Settings::setenv(std::string_view key, const rjson::value& value) { environment_.add(key, value); }
    template <> inline void Settings::setenv(std::string_view key, rjson::value && value) { environment_.add(key, std::move(value)); }

} // namespace acmacs::settings::inline v2

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>settings-v2<commit_after>#pragma once

#include "acmacs-base/fmt.hh"
#include "acmacs-base/rjson.hh"
#include "acmacs-base/flat-map.hh"

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

namespace acmacs::settings::inline v2
{
    class error : public std::runtime_error
    {
        using std::runtime_error::runtime_error;
    };

    class Settings
    {
      public:
        Settings() = default;
        Settings(const std::vector<std::string_view>& filenames) { load(filenames); }
        virtual ~Settings() = default;

        // read settings from files, upon reading each file apply "init" in it (if found)
        void load(const std::vector<std::string_view>& filenames)
        {
            for (const auto& filename : filenames)
                load(filename);
        }
        void load(std::string_view filename);

        // substitute vars in name, find name in environment or in data_ or in built-in and apply it
        // if name starts with ? do nothing
        // if name not found, throw
        virtual void apply(std::string_view name = "main") const;
        void apply(const char* name) const { apply(std::string_view{name}); }

        // substitute vars in name, find name in the top of data_ and apply it
        // do nothing if name starts with ? or if it is not found in top of data_
        virtual void apply_top(std::string_view name) const;

        virtual bool apply_built_in(std::string_view name) const; // returns true if built-in command with that name found and applied

        void setenv_from_string(std::string_view key, std::string_view value);
        template <typename T> void setenv(std::string_view key, T&& value) { setenv(key, rjson::value{std::forward<T>(value)}); }

        const rjson::value& getenv(std::string_view key) const { return environment_.get(static_cast<std::string>(environment_.substitute(key))); }
        template <typename T> T getenv(std::string_view key, T&& a_default) const
        {
            if (const auto& val = environment_.get(static_cast<std::string>(environment_.substitute(key))); val.is_string()) {
                auto orig = static_cast<std::string>(val);
                for (size_t num_subst = 0; num_subst < 10; ++num_subst) {
                    const auto substituted = environment_.substitute(std::string_view{orig});
                    if (substituted.is_string() && orig != static_cast<std::string>(substituted))
                        orig = substituted;
                    else if (substituted.is_const_null()) // substitutions lead to const-null
                        return std::move(a_default);
                    else
                        return static_cast<T>(substituted);
                }
                throw error(fmt::format("Settings::getenv: too many substitutions in {}", val));
            }
            else if (!val.is_const_null())
                return static_cast<T>(val);
            else
                return std::move(a_default);
        }

        std::string getenv(std::string_view key, const char* a_default) const { return getenv(key, std::string{a_default}); }
        void printenv() const { environment_.print(); }

      protected:
        template <typename... Key> const rjson::value& get(Key&&... keys) const;
        void apply(const rjson::value& entry) const;

      private:
        class Environment
        {
          public:
            Environment() { push(); }

            const rjson::value& get(std::string_view key) const;
            void push() { data_.emplace_back(); }
            void pop() { data_.erase(std::prev(std::end(data_))); }
            size_t size() const { return data_.size(); }
            void add(std::string_view key, const rjson::value& val) { data_.rbegin()->emplace_or_replace(std::string{key}, val); }
            void add(std::string_view key, rjson::value&& val) { data_.rbegin()->emplace_or_replace(std::string{key}, std::move(val)); }
            void print() const;
            void print_key_value() const;

            rjson::value substitute(std::string_view source) const;

          private:
            std::vector<acmacs::flat_map_t<std::string, rjson::value>> data_;

            rjson::value substitute(const rjson::value& source) const;
        };

        std::vector<rjson::value> data_;
        mutable Environment environment_;

        void push_and_apply(const rjson::object& entry) const;

        friend class Subenvironment;
    };
} // namespace acmacs::settings::inline v2

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

namespace acmacs::settings::inline v2
{
    template <typename... Key> const rjson::value& Settings::get(Key && ... keys) const
    {
        for (auto it = data_.rbegin(); it != data_.rend(); ++it) {
            if (const auto& val = it->get(std::forward<Key>(keys)...); !val.is_const_null())
                return val;
        }
        return rjson::ConstNull;

    } // acmacs::settings::v2::Settings::get

    template <> inline void Settings::setenv(std::string_view key, const rjson::value& value) { environment_.add(key, value); }
    template <> inline void Settings::setenv(std::string_view key, rjson::value && value) { environment_.add(key, std::move(value)); }

} // namespace acmacs::settings::inline v2

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------

#include "cling/Interpreter/ValuePrinter.h"

#include "cling/Interpreter/CValuePrinter.h"
#include "cling/Interpreter/ValuePrinterInfo.h"
#include "cling/Interpreter/StoredValueRef.h"
#include "cling/Interpreter/Value.h"

#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Expr.h"
#include "clang/AST/Type.h"

#include "llvm/Support/raw_ostream.h"

#include <string>

// Implements the CValuePrinter interface.
extern "C" void cling_PrintValue(void* /*clang::Expr**/ E,
                      void* /*clang::ASTContext**/ C,
                      const void* value) {
  clang::Expr* Exp = (clang::Expr*)E;
  clang::ASTContext* Context = (clang::ASTContext*)C;
  cling::ValuePrinterInfo VPI(Exp, Context);
  cling::printValuePublic(llvm::outs(), value, value, VPI);

  cling::flushOStream(llvm::outs());
}

static void StreamChar(llvm::raw_ostream& o, const char v,
                       const char* Sep = "\n") {
  o << '"' << v << "\"" << Sep;
}

static void StreamCharPtr(llvm::raw_ostream& o, const char* const v,
                          const char* Sep = "\n") {
  o << '"';
  const char* p = v;
  for (;*p && p - v < 128; ++p) {
    o << *p;
  }
  if (*p) o << "\"..." << Sep;
  else o << "\"" << Sep;
}

static void StreamRef(llvm::raw_ostream& o, const void* v,
                      const char* Sep = "\n") {
  o <<"&" << v << Sep;
}

static void StreamPtr(llvm::raw_ostream& o, const void* v,
                      const char* Sep = "\n") {
  o << v << Sep;
}

static void StreamValue(llvm::raw_ostream& o, const void* const p,
                        const cling::ValuePrinterInfo& VPI,
                        clang::QualType Ty,
                        const char* Sep = "\n");

static void StreamArr(llvm::raw_ostream& o, const void* p,
                      const cling::ValuePrinterInfo& VPI,
                      clang::QualType Ty,
                      const char* Sep = "\n") {
  const clang::ASTContext& C = *VPI.getASTContext();
  const clang::ArrayType* ArrTy = Ty->getAsArrayTypeUnsafe();
  clang::QualType ElementTy = ArrTy->getElementType();
  if (ElementTy->isCharType())
    StreamCharPtr(o, (const char*)p);
  else if (Ty->isConstantArrayType()) {
    // Stream a constant array by streaming up to 5 elements.
    const clang::ConstantArrayType* CArrTy
      = C.getAsConstantArrayType(Ty);
    const llvm::APInt& APSize = CArrTy->getSize();
    size_t ElBytes = C.getTypeSize(ElementTy) / C.getCharWidth();
    size_t Size = (size_t)APSize.getZExtValue();
    o << "{ ";
    for (size_t i = 0; i < Size; ++i) {
      StreamValue(o, ((char*)p) + i * ElBytes, VPI, ElementTy, " ");
      if (i + 1 < Size) {
        if (i == 4) {
          o << "...";
          break;
        }
        else o << ", ";
      }
    }
    o << " }" << Sep;
  } else
    StreamPtr(o, p, Sep);
}

static void StreamObj(llvm::raw_ostream& o, const void* v,
                      const cling::ValuePrinterInfo& VPI,
                      clang::QualType QTy,
                      const char* Sep = "\n") {
  const clang::Type* Ty = QTy.getTypePtr();
  if (clang::CXXRecordDecl* CXXRD = Ty->getAsCXXRecordDecl()) {
    const cling::Value* value = 0;
    if (CXXRD->getQualifiedNameAsString().compare("cling::StoredValueRef") == 0){
      const cling::StoredValueRef* VR = (const cling::StoredValueRef*)v;
      if (VR->isValid()) {
        value = &VR->get();
      } else {
        o << "<<<invalid>>> ";
      }
    } else if (CXXRD->getQualifiedNameAsString().compare("cling::Value") == 0) {
      value = (const cling::Value*)v;
    }
    if (value) {
      if (value->isValid()) {
        o << "boxes [";
        const clang::ASTContext& C = *VPI.getASTContext();
        o <<
          "(" <<
          value->type.getAsString(C.getPrintingPolicy()) <<
          ") ";
        clang::QualType valType = value->type.getDesugaredType(C);
        if (valType->isFloatingType())
          o << value->value.DoubleVal;
        else if (valType->isIntegerType())
          o << value->value.IntVal.getSExtValue();
        else if (valType->isBooleanType())
          o << value->value.IntVal.getBoolValue();
        else
          StreamValue(o, value->value.PointerVal, VPI, valType, "");
        o << "]" << Sep;

        return;
      } else
        o << "<<<invalid>>> ";
    }
  } // if CXXRecordDecl

  // TODO: Print the object members.
  o << "@" << v << Sep;
}

static void StreamValue(llvm::raw_ostream& o, const void* const p,
                        const cling::ValuePrinterInfo& VPI,
                        clang::QualType Ty,
                        const char* Sep /*= "\n"*/) {
  const clang::ASTContext& C = *VPI.getASTContext();
  Ty = Ty.getDesugaredType(C);
  if (const clang::BuiltinType *BT
           = llvm::dyn_cast<clang::BuiltinType>(Ty.getCanonicalType())) {
    switch (BT->getKind()) {
    case clang::BuiltinType::Bool:
      if (*(const bool*)p) o << "true" << Sep;
      else o << "false" << Sep; break;
    case clang::BuiltinType::Char_U:
    case clang::BuiltinType::UChar:
    case clang::BuiltinType::Char_S:
    case clang::BuiltinType::SChar:  StreamChar(o, *(const char*)p); break;
    case clang::BuiltinType::Short:  o << *(const short*)p << Sep; break;
    case clang::BuiltinType::UShort:
      o << *(const unsigned short*)p << Sep;
      break;
    case clang::BuiltinType::Int:    o << *(const int*)p << Sep; break;
    case clang::BuiltinType::UInt:
      o << *(const unsigned int*)p << Sep;
      break;
    case clang::BuiltinType::Long:   o << *(const long*)p << Sep; break;
    case clang::BuiltinType::ULong:
      o << *(const unsigned long*)p << Sep;
      break;
    case clang::BuiltinType::LongLong:
      o << *(const long long*)p << Sep;
      break;
    case clang::BuiltinType::ULongLong:
      o << *(const unsigned long long*)p << Sep;
      break;
    case clang::BuiltinType::Float:  o << *(const float*)p << Sep; break;
    case clang::BuiltinType::Double: o << *(const double*)p << Sep; break;
    default:
      StreamObj(o, p, VPI, Ty, Sep);
    }
  }
  else if (Ty.getAsString().compare("class std::basic_string<char>") == 0) {
    StreamObj(o, p, VPI, Ty, Sep);
    o <<"c_str: ";
    StreamCharPtr(o, ((const char*) (*(const std::string*)p).c_str()), Sep);
  }
  else if (Ty->isEnumeralType()) {
    StreamObj(o, p, VPI, Ty, Sep);
    clang::EnumDecl* ED = Ty->getAs<clang::EnumType>()->getDecl();
    uint64_t value = *(const uint64_t*)p;
    bool IsFirst = true;
    llvm::APSInt ValAsAPSInt = C.MakeIntValue(value, Ty);
    for (clang::EnumDecl::enumerator_iterator I = ED->enumerator_begin(),
           E = ED->enumerator_end(); I != E; ++I) {
      if (I->getInitVal() == ValAsAPSInt) {
        if (!IsFirst) {
          o << " ? ";
        }
        o << "(" << I->getQualifiedNameAsString() << ")";
        IsFirst = false;
      }
    }
    o << " : (int) " << ValAsAPSInt.toString(/*Radix = */10) << Sep;
  }
  else if (Ty->isReferenceType())
    StreamRef(o, p, Sep);
  else if (Ty->isPointerType()) {
    clang::QualType PointeeTy = Ty->getPointeeType();
    if (PointeeTy->isCharType())
      StreamCharPtr(o, (const char*)p, Sep);
    else
      StreamPtr(o, p, Sep);
  }
  else if (Ty->isArrayType())
    StreamArr(o, p, VPI, Ty, Sep);
  else
    StreamObj(o, p, VPI, Ty, Sep);
}

namespace cling {
  void printValuePublicDefault(llvm::raw_ostream& o, const void* const p,
                               const ValuePrinterInfo& VPI) {
    const clang::Expr* E = VPI.getExpr();
    o << "(";
    o << E->getType().getAsString();
    o << ") ";
    StreamValue(o, p, VPI, VPI.getExpr()->getType());
  }

  void flushOStream(llvm::raw_ostream& o) {
    o.flush();
  }

} // end namespace cling
<commit_msg>Const correctness.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------

#include "cling/Interpreter/ValuePrinter.h"

#include "cling/Interpreter/CValuePrinter.h"
#include "cling/Interpreter/ValuePrinterInfo.h"
#include "cling/Interpreter/StoredValueRef.h"
#include "cling/Interpreter/Value.h"

#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Expr.h"
#include "clang/AST/Type.h"

#include "llvm/Support/raw_ostream.h"

#include <string>

// Implements the CValuePrinter interface.
extern "C" void cling_PrintValue(void* /*clang::Expr**/ E,
                      void* /*clang::ASTContext**/ C,
                      const void* value) {
  clang::Expr* Exp = (clang::Expr*)E;
  clang::ASTContext* Context = (clang::ASTContext*)C;
  cling::ValuePrinterInfo VPI(Exp, Context);
  cling::printValuePublic(llvm::outs(), value, value, VPI);

  cling::flushOStream(llvm::outs());
}

static void StreamChar(llvm::raw_ostream& o, const char v,
                       const char* Sep = "\n") {
  o << '"' << v << "\"" << Sep;
}

static void StreamCharPtr(llvm::raw_ostream& o, const char* const v,
                          const char* Sep = "\n") {
  o << '"';
  const char* p = v;
  for (;*p && p - v < 128; ++p) {
    o << *p;
  }
  if (*p) o << "\"..." << Sep;
  else o << "\"" << Sep;
}

static void StreamRef(llvm::raw_ostream& o, const void* v,
                      const char* Sep = "\n") {
  o <<"&" << v << Sep;
}

static void StreamPtr(llvm::raw_ostream& o, const void* v,
                      const char* Sep = "\n") {
  o << v << Sep;
}

static void StreamValue(llvm::raw_ostream& o, const void* const p,
                        const cling::ValuePrinterInfo& VPI,
                        clang::QualType Ty,
                        const char* Sep = "\n");

static void StreamArr(llvm::raw_ostream& o, const void* p,
                      const cling::ValuePrinterInfo& VPI,
                      clang::QualType Ty,
                      const char* Sep = "\n") {
  const clang::ASTContext& C = *VPI.getASTContext();
  const clang::ArrayType* ArrTy = Ty->getAsArrayTypeUnsafe();
  clang::QualType ElementTy = ArrTy->getElementType();
  if (ElementTy->isCharType())
    StreamCharPtr(o, (const char*)p);
  else if (Ty->isConstantArrayType()) {
    // Stream a constant array by streaming up to 5 elements.
    const clang::ConstantArrayType* CArrTy
      = C.getAsConstantArrayType(Ty);
    const llvm::APInt& APSize = CArrTy->getSize();
    size_t ElBytes = C.getTypeSize(ElementTy) / C.getCharWidth();
    size_t Size = (size_t)APSize.getZExtValue();
    o << "{ ";
    for (size_t i = 0; i < Size; ++i) {
      StreamValue(o, ((const char*)p) + i * ElBytes, VPI, ElementTy, " ");
      if (i + 1 < Size) {
        if (i == 4) {
          o << "...";
          break;
        }
        else o << ", ";
      }
    }
    o << " }" << Sep;
  } else
    StreamPtr(o, p, Sep);
}

static void StreamObj(llvm::raw_ostream& o, const void* v,
                      const cling::ValuePrinterInfo& VPI,
                      clang::QualType QTy,
                      const char* Sep = "\n") {
  const clang::Type* Ty = QTy.getTypePtr();
  if (clang::CXXRecordDecl* CXXRD = Ty->getAsCXXRecordDecl()) {
    const cling::Value* value = 0;
    if (CXXRD->getQualifiedNameAsString().compare("cling::StoredValueRef") == 0){
      const cling::StoredValueRef* VR = (const cling::StoredValueRef*)v;
      if (VR->isValid()) {
        value = &VR->get();
      } else {
        o << "<<<invalid>>> ";
      }
    } else if (CXXRD->getQualifiedNameAsString().compare("cling::Value") == 0) {
      value = (const cling::Value*)v;
    }
    if (value) {
      if (value->isValid()) {
        o << "boxes [";
        const clang::ASTContext& C = *VPI.getASTContext();
        o <<
          "(" <<
          value->type.getAsString(C.getPrintingPolicy()) <<
          ") ";
        clang::QualType valType = value->type.getDesugaredType(C);
        if (valType->isFloatingType())
          o << value->value.DoubleVal;
        else if (valType->isIntegerType())
          o << value->value.IntVal.getSExtValue();
        else if (valType->isBooleanType())
          o << value->value.IntVal.getBoolValue();
        else
          StreamValue(o, value->value.PointerVal, VPI, valType, "");
        o << "]" << Sep;

        return;
      } else
        o << "<<<invalid>>> ";
    }
  } // if CXXRecordDecl

  // TODO: Print the object members.
  o << "@" << v << Sep;
}

static void StreamValue(llvm::raw_ostream& o, const void* const p,
                        const cling::ValuePrinterInfo& VPI,
                        clang::QualType Ty,
                        const char* Sep /*= "\n"*/) {
  const clang::ASTContext& C = *VPI.getASTContext();
  Ty = Ty.getDesugaredType(C);
  if (const clang::BuiltinType *BT
           = llvm::dyn_cast<clang::BuiltinType>(Ty.getCanonicalType())) {
    switch (BT->getKind()) {
    case clang::BuiltinType::Bool:
      if (*(const bool*)p) o << "true" << Sep;
      else o << "false" << Sep; break;
    case clang::BuiltinType::Char_U:
    case clang::BuiltinType::UChar:
    case clang::BuiltinType::Char_S:
    case clang::BuiltinType::SChar:  StreamChar(o, *(const char*)p); break;
    case clang::BuiltinType::Short:  o << *(const short*)p << Sep; break;
    case clang::BuiltinType::UShort:
      o << *(const unsigned short*)p << Sep;
      break;
    case clang::BuiltinType::Int:    o << *(const int*)p << Sep; break;
    case clang::BuiltinType::UInt:
      o << *(const unsigned int*)p << Sep;
      break;
    case clang::BuiltinType::Long:   o << *(const long*)p << Sep; break;
    case clang::BuiltinType::ULong:
      o << *(const unsigned long*)p << Sep;
      break;
    case clang::BuiltinType::LongLong:
      o << *(const long long*)p << Sep;
      break;
    case clang::BuiltinType::ULongLong:
      o << *(const unsigned long long*)p << Sep;
      break;
    case clang::BuiltinType::Float:  o << *(const float*)p << Sep; break;
    case clang::BuiltinType::Double: o << *(const double*)p << Sep; break;
    default:
      StreamObj(o, p, VPI, Ty, Sep);
    }
  }
  else if (Ty.getAsString().compare("class std::basic_string<char>") == 0) {
    StreamObj(o, p, VPI, Ty, Sep);
    o <<"c_str: ";
    StreamCharPtr(o, ((const char*) (*(const std::string*)p).c_str()), Sep);
  }
  else if (Ty->isEnumeralType()) {
    StreamObj(o, p, VPI, Ty, Sep);
    clang::EnumDecl* ED = Ty->getAs<clang::EnumType>()->getDecl();
    uint64_t value = *(const uint64_t*)p;
    bool IsFirst = true;
    llvm::APSInt ValAsAPSInt = C.MakeIntValue(value, Ty);
    for (clang::EnumDecl::enumerator_iterator I = ED->enumerator_begin(),
           E = ED->enumerator_end(); I != E; ++I) {
      if (I->getInitVal() == ValAsAPSInt) {
        if (!IsFirst) {
          o << " ? ";
        }
        o << "(" << I->getQualifiedNameAsString() << ")";
        IsFirst = false;
      }
    }
    o << " : (int) " << ValAsAPSInt.toString(/*Radix = */10) << Sep;
  }
  else if (Ty->isReferenceType())
    StreamRef(o, p, Sep);
  else if (Ty->isPointerType()) {
    clang::QualType PointeeTy = Ty->getPointeeType();
    if (PointeeTy->isCharType())
      StreamCharPtr(o, (const char*)p, Sep);
    else
      StreamPtr(o, p, Sep);
  }
  else if (Ty->isArrayType())
    StreamArr(o, p, VPI, Ty, Sep);
  else
    StreamObj(o, p, VPI, Ty, Sep);
}

namespace cling {
  void printValuePublicDefault(llvm::raw_ostream& o, const void* const p,
                               const ValuePrinterInfo& VPI) {
    const clang::Expr* E = VPI.getExpr();
    o << "(";
    o << E->getType().getAsString();
    o << ") ";
    StreamValue(o, p, VPI, VPI.getExpr()->getType());
  }

  void flushOStream(llvm::raw_ostream& o) {
    o.flush();
  }

} // end namespace cling
<|endoftext|>


<commit_before>// Time:  O(n)
// Space: O(logn)

/**
 * Definition of SegmentTreeNode:
 * class SegmentTreeNode {
 * public:
 *     int start, end;
 *     SegmentTreeNode *left, *right;
 *     SegmentTreeNode(int start, int end) {
 *         this->start = start, this->end = end;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     *@param start, end: Denote an segment / interval
     *@return: The root of Segment Tree
     */
    SegmentTreeNode * build(int start, int end) {
        if (start > end) {
            return nullptr;
        }

        // The root's start and end is given by build method.
        SegmentTreeNode *root = new SegmentTreeNode(start, end);

        // If start equals to end, there will be no children for this node.
        if (start == end) {
            return root;
        }

        // Left child: start=A.left, end=(A.left + A.right) / 2.
        root->left = build(start, (start + end) / 2);

        // Right child: start=(A.left + A.right) / 2 + 1, end=A.right.
        root->right = build((start + end) / 2 + 1, end);

        return root;
    }
};
<commit_msg>Update segment-tree-build.cpp<commit_after>// Time:  O(n)
// Space: O(h) = O(logn)

/**
 * Definition of SegmentTreeNode:
 * class SegmentTreeNode {
 * public:
 *     int start, end;
 *     SegmentTreeNode *left, *right;
 *     SegmentTreeNode(int start, int end) {
 *         this->start = start, this->end = end;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     *@param start, end: Denote an segment / interval
     *@return: The root of Segment Tree
     */
    SegmentTreeNode * build(int start, int end) {
        if (start > end) {
            return nullptr;
        }

        // The root's start and end is given by build method.
        SegmentTreeNode *root = new SegmentTreeNode(start, end);

        // If start equals to end, there will be no children for this node.
        if (start == end) {
            return root;
        }

        // Left child: start=A.left, end=(A.left + A.right) / 2.
        root->left = build(start, (start + end) / 2);

        // Right child: start=(A.left + A.right) / 2 + 1, end=A.right.
        root->right = build((start + end) / 2 + 1, end);

        return root;
    }
};
<|endoftext|>


<commit_before>/*****************************************************************************
 * Help.cpp : Help and About dialogs
 ****************************************************************************
 * Copyright (C) 2007 the VideoLAN team
 * $Id$
 *
 * Authors: Jean-Baptiste Kempf <jb (at) videolan.org>
 *          Rémi Duraffort <ivoire (at) via.ecp.fr>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

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

#include <vlc_common.h>

#include "dialogs/help.hpp"
#include <vlc_about.h>

#ifdef UPDATE_CHECK
#include <vlc_update.h>
#endif

#include "dialogs_provider.hpp"

#include <vlc_intf_strings.h>

#include <QTextBrowser>
#include <QTabWidget>
#include <QFile>
#include <QLabel>
#include <QString>
#include <QDialogButtonBox>
#include <QEvent>
#include <QFileDialog>
#include <QDate>

HelpDialog *HelpDialog::instance = NULL;

HelpDialog::HelpDialog( intf_thread_t *_p_intf ) : QVLCFrame( _p_intf )

{
    setWindowTitle( qtr( "Help" ) );
    setMinimumSize( 250, 300 );

    QGridLayout *layout = new QGridLayout( this );
    QTextBrowser *helpBrowser = new QTextBrowser( this );
    helpBrowser->setOpenExternalLinks( true );
    helpBrowser->setHtml( I_LONGHELP );
    QPushButton *closeButton = new QPushButton( qtr( "&Close" ) );
    closeButton->setDefault( true );

    layout->addWidget( helpBrowser, 0, 0, 1, 0 );
    layout->addWidget( closeButton, 1, 3 );

    BUTTONACT( closeButton, close() );
    readSettings( "Help", QSize( 400, 450 ) );
}

HelpDialog::~HelpDialog()
{
    writeSettings( "Help" );
}

void HelpDialog::close()
{
    toggleVisible();
}

AboutDialog *AboutDialog::instance = NULL;

AboutDialog::AboutDialog( QWidget *parent, intf_thread_t *_p_intf)
            : QVLCDialog( parent, _p_intf )
{
    setWindowTitle( qtr( "About" ) );
    resize( 600, 500 );
    setMinimumSize( 600, 500 );

    QGridLayout *layout = new QGridLayout( this );
    QTabWidget *tab = new QTabWidget( this );

    QPushButton *closeButton = new QPushButton( qtr( "&Close" ) );
    closeButton->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );
    closeButton->setDefault( true );

    QLabel *introduction = new QLabel(
            qtr( "VLC media player" " " VERSION_MESSAGE ) );
    QLabel *iconVLC = new QLabel;
    if( QDate::currentDate().dayOfYear() >= 354 )
        iconVLC->setPixmap( QPixmap( ":/vlc48-christmas.png" ) );
    else
        iconVLC->setPixmap( QPixmap( ":/vlc48.png" ) );
    layout->addWidget( iconVLC, 0, 0, 1, 1 );
    layout->addWidget( introduction, 0, 1, 1, 7 );
    layout->addWidget( tab, 1, 0, 1, 8 );
    layout->addWidget( closeButton, 2, 6, 1, 2 );

    /* Main Introduction */
    QWidget *infoWidget = new QWidget( this );
    QHBoxLayout *infoLayout = new QHBoxLayout( infoWidget );
    QLabel *infoLabel = new QLabel(
            qtr( "VLC media player is a free media player, "
                "encoder and streamer that can read from files, "
                "CDs, DVDs, network streams, capture cards and even more!\n"
                "Also, VLC works on essentially every popular platform.\n\n" )
            + qtr( "This version of VLC was compiled by:\n " )
            + qfu( VLC_CompileBy() )+ "@" + qfu( VLC_CompileHost() ) + "."
            + qfu( VLC_CompileDomain() ) + ".\n"
            + "Compiler: " + qfu( VLC_Compiler() ) + ".\n"
            + qtr( "Based on Git commit: " ) + qfu( VLC_Changeset() ) + ".\n"
            + qtr( "You are using the Qt4 Interface.\n\n" )
            + qtr( "Copyright © " COPYRIGHT_YEARS " by the VideoLAN Team.\n" )
            + "vlc@videolan.org, http://www.videolan.org" );
    infoLabel->setWordWrap( infoLabel );

    QLabel *iconVLC2 = new QLabel;
    if( QDate::currentDate().dayOfYear() >= 354 )
        iconVLC2->setPixmap( QPixmap( ":/vlc128-christmas.png" ) );
    else
        iconVLC2->setPixmap( QPixmap( ":/vlc128.png" ) );
    infoLayout->addWidget( iconVLC2 );
    infoLayout->addWidget( infoLabel );

    /* GPL License */
    QTextEdit *licenseEdit = new QTextEdit( this );
    licenseEdit->setText( qfu( psz_license ) );
    licenseEdit->setReadOnly( true );

    /* People who helped */
    QWidget *thanksWidget = new QWidget( this );
    QVBoxLayout *thanksLayout = new QVBoxLayout( thanksWidget );

    QLabel *thanksLabel = new QLabel( qtr( "We would like to thank the whole "
                "community, the testers, our users and the following people "
                "(and the missing ones...) for their collaboration to "
                "provide the best software." ) );
    thanksLabel->setWordWrap( true );
    thanksLayout->addWidget( thanksLabel );
    QTextEdit *thanksEdit = new QTextEdit( this );
    thanksEdit->setText( qfu( psz_thanks ) );
    thanksEdit->setReadOnly( true );
    thanksLayout->addWidget( thanksEdit );

    /* People who wrote the software */
    QTextEdit *authorsEdit = new QTextEdit( this );
    authorsEdit->setText( qfu( psz_authors ) );
    authorsEdit->setReadOnly( true );

    /* add the tabs to the Tabwidget */
    tab->addTab( infoWidget, qtr( "About" ) );
    tab->addTab( authorsEdit, qtr( "Authors" ) );
    tab->addTab( thanksWidget, qtr("Thanks") );
    tab->addTab( licenseEdit, qtr("License") );

    BUTTONACT( closeButton, close() );
}

AboutDialog::~AboutDialog()
{
}

void AboutDialog::close()
{
    toggleVisible();
}

#ifdef UPDATE_CHECK

/*****************************************************************************
 * UpdateDialog
 *****************************************************************************/
/* callback to get information from the core */
static void UpdateCallback( void *data, bool b_ret )
{
    UpdateDialog* UDialog = (UpdateDialog *)data;
    QEvent* event;

    if( b_ret )
        event = new QEvent( (QEvent::Type)UDOkEvent );
    else
        event = new QEvent( (QEvent::Type)UDErrorEvent );

    QApplication::postEvent( UDialog, event );
}

UpdateDialog *UpdateDialog::instance = NULL;

UpdateDialog::UpdateDialog( intf_thread_t *_p_intf ) : QVLCFrame( _p_intf )
{
    setWindowTitle( qtr( "Update" ) );

    QGridLayout *layout = new QGridLayout( this );

    QPushButton *closeButton = new QPushButton( qtr( "&Close" ) );
    updateButton = new QPushButton( qtr( "&Update List" ) );
    updateButton->setDefault( true );
    QDialogButtonBox *buttonBox = new QDialogButtonBox( Qt::Horizontal );
    buttonBox->addButton( updateButton, QDialogButtonBox::ActionRole );
    buttonBox->addButton( closeButton, QDialogButtonBox::AcceptRole );

    updateLabel = new QLabel( qtr( "Checking for an update..." ) );
    updateLabel->setWordWrap( true );

    layout->addWidget( updateLabel, 0, 0 );
    layout->addWidget( buttonBox, 1, 0 );

    BUTTONACT( updateButton, UpdateOrDownload() );
    BUTTONACT( closeButton, close() );

    /* Create the update structure */
    p_update = update_New( p_intf );
    b_checked = false;

    readSettings( "Update", QSize( 120, 80 ) );

    /* Check for updates */
    UpdateOrDownload();
}

UpdateDialog::~UpdateDialog()
{
    update_Delete( p_update );
    writeSettings( "Update" );
}

void UpdateDialog::close()
{
    toggleVisible();
}

/* Check for updates */
void UpdateDialog::UpdateOrDownload()
{
    if( !b_checked )
    {
        updateButton->setEnabled( false );
        msg_Dbg( p_intf, "Launching an update request" );
        update_Check( p_update, UpdateCallback, this );
    }
    else
    {
        updateButton->setEnabled( false );
        QString dest_dir = QFileDialog::getExistingDirectory( this,
                                 qtr( "Select a directory ..." ),
                                 qfu( config_GetHomeDir() ) );

        if( dest_dir != "" )
        {
            toggleVisible();
            update_Download( p_update, qtu( dest_dir ) );
        }
        else
            updateButton->setEnabled( true );
    }
}

/* Handle the events */
void UpdateDialog::customEvent( QEvent *event )
{
    if( event->type() == UDOkEvent )
        updateNotify( true );
    else
        updateNotify( false );
}

/* Notify the end of the update_Check */
void UpdateDialog::updateNotify( bool b_result )
{
    /* The update finish without errors */
    if( b_result )
    {
        if( update_NeedUpgrade( p_update ) )
        {
            update_release_t *p_release = update_GetRelease( p_update );
            assert( p_release );
            b_checked = true;
            updateButton->setText( "Download" );
            updateLabel->setText( qtr( "There is a new version of VLC :\n" )
                                + qfu( p_release->psz_desc )  );
        }
        else
            updateLabel->setText( qtr( "You have the latest version of VLC" ) );
    }
    else
        updateLabel->setText(
                        qtr( "An error occurred while checking for updates" ) );

    adjustSize();
    updateButton->setEnabled( true );
}

#endif

<commit_msg>Stick to ASCII in gettext messages<commit_after>/*****************************************************************************
 * Help.cpp : Help and About dialogs
 ****************************************************************************
 * Copyright (C) 2007 the VideoLAN team
 * $Id$
 *
 * Authors: Jean-Baptiste Kempf <jb (at) videolan.org>
 *          Rémi Duraffort <ivoire (at) via.ecp.fr>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

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

#include <vlc_common.h>

#include "dialogs/help.hpp"
#include <vlc_about.h>

#ifdef UPDATE_CHECK
#include <vlc_update.h>
#endif

#include "dialogs_provider.hpp"

#include <vlc_intf_strings.h>

#include <QTextBrowser>
#include <QTabWidget>
#include <QFile>
#include <QLabel>
#include <QString>
#include <QDialogButtonBox>
#include <QEvent>
#include <QFileDialog>
#include <QDate>

HelpDialog *HelpDialog::instance = NULL;

HelpDialog::HelpDialog( intf_thread_t *_p_intf ) : QVLCFrame( _p_intf )

{
    setWindowTitle( qtr( "Help" ) );
    setMinimumSize( 250, 300 );

    QGridLayout *layout = new QGridLayout( this );
    QTextBrowser *helpBrowser = new QTextBrowser( this );
    helpBrowser->setOpenExternalLinks( true );
    helpBrowser->setHtml( I_LONGHELP );
    QPushButton *closeButton = new QPushButton( qtr( "&Close" ) );
    closeButton->setDefault( true );

    layout->addWidget( helpBrowser, 0, 0, 1, 0 );
    layout->addWidget( closeButton, 1, 3 );

    BUTTONACT( closeButton, close() );
    readSettings( "Help", QSize( 400, 450 ) );
}

HelpDialog::~HelpDialog()
{
    writeSettings( "Help" );
}

void HelpDialog::close()
{
    toggleVisible();
}

AboutDialog *AboutDialog::instance = NULL;

AboutDialog::AboutDialog( QWidget *parent, intf_thread_t *_p_intf)
            : QVLCDialog( parent, _p_intf )
{
    setWindowTitle( qtr( "About" ) );
    resize( 600, 500 );
    setMinimumSize( 600, 500 );

    QGridLayout *layout = new QGridLayout( this );
    QTabWidget *tab = new QTabWidget( this );

    QPushButton *closeButton = new QPushButton( qtr( "&Close" ) );
    closeButton->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );
    closeButton->setDefault( true );

    QLabel *introduction = new QLabel(
            qtr( "VLC media player" " " VERSION_MESSAGE ) );
    QLabel *iconVLC = new QLabel;
    if( QDate::currentDate().dayOfYear() >= 354 )
        iconVLC->setPixmap( QPixmap( ":/vlc48-christmas.png" ) );
    else
        iconVLC->setPixmap( QPixmap( ":/vlc48.png" ) );
    layout->addWidget( iconVLC, 0, 0, 1, 1 );
    layout->addWidget( introduction, 0, 1, 1, 7 );
    layout->addWidget( tab, 1, 0, 1, 8 );
    layout->addWidget( closeButton, 2, 6, 1, 2 );

    /* Main Introduction */
    QWidget *infoWidget = new QWidget( this );
    QHBoxLayout *infoLayout = new QHBoxLayout( infoWidget );
    QLabel *infoLabel = new QLabel(
            qtr( "VLC media player is a free media player, "
                "encoder and streamer that can read from files, "
                "CDs, DVDs, network streams, capture cards and even more!\n"
                "Also, VLC works on essentially every popular platform.\n\n" )
            + qtr( "This version of VLC was compiled by:\n " )
            + qfu( VLC_CompileBy() )+ "@" + qfu( VLC_CompileHost() ) + "."
            + qfu( VLC_CompileDomain() ) + ".\n"
            + "Compiler: " + qfu( VLC_Compiler() ) + ".\n"
            + qtr( "Based on Git commit: " ) + qfu( VLC_Changeset() ) + ".\n"
            + qtr( "You are using the Qt4 Interface.\n\n" )
            + qtr( "Copyright (C) " COPYRIGHT_YEARS " by the VideoLAN Team.\n" )
            + "vlc@videolan.org, http://www.videolan.org" );
    infoLabel->setWordWrap( infoLabel );

    QLabel *iconVLC2 = new QLabel;
    if( QDate::currentDate().dayOfYear() >= 354 )
        iconVLC2->setPixmap( QPixmap( ":/vlc128-christmas.png" ) );
    else
        iconVLC2->setPixmap( QPixmap( ":/vlc128.png" ) );
    infoLayout->addWidget( iconVLC2 );
    infoLayout->addWidget( infoLabel );

    /* GPL License */
    QTextEdit *licenseEdit = new QTextEdit( this );
    licenseEdit->setText( qfu( psz_license ) );
    licenseEdit->setReadOnly( true );

    /* People who helped */
    QWidget *thanksWidget = new QWidget( this );
    QVBoxLayout *thanksLayout = new QVBoxLayout( thanksWidget );

    QLabel *thanksLabel = new QLabel( qtr( "We would like to thank the whole "
                "community, the testers, our users and the following people "
                "(and the missing ones...) for their collaboration to "
                "provide the best software." ) );
    thanksLabel->setWordWrap( true );
    thanksLayout->addWidget( thanksLabel );
    QTextEdit *thanksEdit = new QTextEdit( this );
    thanksEdit->setText( qfu( psz_thanks ) );
    thanksEdit->setReadOnly( true );
    thanksLayout->addWidget( thanksEdit );

    /* People who wrote the software */
    QTextEdit *authorsEdit = new QTextEdit( this );
    authorsEdit->setText( qfu( psz_authors ) );
    authorsEdit->setReadOnly( true );

    /* add the tabs to the Tabwidget */
    tab->addTab( infoWidget, qtr( "About" ) );
    tab->addTab( authorsEdit, qtr( "Authors" ) );
    tab->addTab( thanksWidget, qtr("Thanks") );
    tab->addTab( licenseEdit, qtr("License") );

    BUTTONACT( closeButton, close() );
}

AboutDialog::~AboutDialog()
{
}

void AboutDialog::close()
{
    toggleVisible();
}

#ifdef UPDATE_CHECK

/*****************************************************************************
 * UpdateDialog
 *****************************************************************************/
/* callback to get information from the core */
static void UpdateCallback( void *data, bool b_ret )
{
    UpdateDialog* UDialog = (UpdateDialog *)data;
    QEvent* event;

    if( b_ret )
        event = new QEvent( (QEvent::Type)UDOkEvent );
    else
        event = new QEvent( (QEvent::Type)UDErrorEvent );

    QApplication::postEvent( UDialog, event );
}

UpdateDialog *UpdateDialog::instance = NULL;

UpdateDialog::UpdateDialog( intf_thread_t *_p_intf ) : QVLCFrame( _p_intf )
{
    setWindowTitle( qtr( "Update" ) );

    QGridLayout *layout = new QGridLayout( this );

    QPushButton *closeButton = new QPushButton( qtr( "&Close" ) );
    updateButton = new QPushButton( qtr( "&Update List" ) );
    updateButton->setDefault( true );
    QDialogButtonBox *buttonBox = new QDialogButtonBox( Qt::Horizontal );
    buttonBox->addButton( updateButton, QDialogButtonBox::ActionRole );
    buttonBox->addButton( closeButton, QDialogButtonBox::AcceptRole );

    updateLabel = new QLabel( qtr( "Checking for an update..." ) );
    updateLabel->setWordWrap( true );

    layout->addWidget( updateLabel, 0, 0 );
    layout->addWidget( buttonBox, 1, 0 );

    BUTTONACT( updateButton, UpdateOrDownload() );
    BUTTONACT( closeButton, close() );

    /* Create the update structure */
    p_update = update_New( p_intf );
    b_checked = false;

    readSettings( "Update", QSize( 120, 80 ) );

    /* Check for updates */
    UpdateOrDownload();
}

UpdateDialog::~UpdateDialog()
{
    update_Delete( p_update );
    writeSettings( "Update" );
}

void UpdateDialog::close()
{
    toggleVisible();
}

/* Check for updates */
void UpdateDialog::UpdateOrDownload()
{
    if( !b_checked )
    {
        updateButton->setEnabled( false );
        msg_Dbg( p_intf, "Launching an update request" );
        update_Check( p_update, UpdateCallback, this );
    }
    else
    {
        updateButton->setEnabled( false );
        QString dest_dir = QFileDialog::getExistingDirectory( this,
                                 qtr( "Select a directory ..." ),
                                 qfu( config_GetHomeDir() ) );

        if( dest_dir != "" )
        {
            toggleVisible();
            update_Download( p_update, qtu( dest_dir ) );
        }
        else
            updateButton->setEnabled( true );
    }
}

/* Handle the events */
void UpdateDialog::customEvent( QEvent *event )
{
    if( event->type() == UDOkEvent )
        updateNotify( true );
    else
        updateNotify( false );
}

/* Notify the end of the update_Check */
void UpdateDialog::updateNotify( bool b_result )
{
    /* The update finish without errors */
    if( b_result )
    {
        if( update_NeedUpgrade( p_update ) )
        {
            update_release_t *p_release = update_GetRelease( p_update );
            assert( p_release );
            b_checked = true;
            updateButton->setText( "Download" );
            updateLabel->setText( qtr( "There is a new version of VLC :\n" )
                                + qfu( p_release->psz_desc )  );
        }
        else
            updateLabel->setText( qtr( "You have the latest version of VLC" ) );
    }
    else
        updateLabel->setText(
                        qtr( "An error occurred while checking for updates" ) );

    adjustSize();
    updateButton->setEnabled( true );
}

#endif

<|endoftext|>