build: remove duplicate devtools sources (#14522)

* build: remove duplicate devtools sources

* build: create separate target for chrome sources

* Move sources that are always depended on by electron,
  starting with security_state_tab_helper.{cc|h}
* Add //component/strings to pak for devtools security tab

* fix: allow specifying type of the added filesystem.

https://chromium-review.googlesource.com/c/chromium/src/+/729250

* fix: do not index excluded folders

https://chromium-review.googlesource.com/c/chromium/src/+/972579
This commit is contained in:
Robo 2018-09-12 19:15:08 +05:30 committed by Charles Kerr
parent 011c3b4326
commit 2cd03bf360
21 changed files with 122 additions and 1364 deletions

View file

@ -1,50 +0,0 @@
// Copyright 2014 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 "brightray/browser/devtools_contents_resizing_strategy.h"
#include <algorithm>
DevToolsContentsResizingStrategy::DevToolsContentsResizingStrategy()
: hide_inspected_contents_(false) {}
DevToolsContentsResizingStrategy::DevToolsContentsResizingStrategy(
const gfx::Rect& bounds)
: bounds_(bounds),
hide_inspected_contents_(bounds_.IsEmpty() && !bounds_.x() &&
!bounds_.y()) {}
void DevToolsContentsResizingStrategy::CopyFrom(
const DevToolsContentsResizingStrategy& strategy) {
bounds_ = strategy.bounds();
hide_inspected_contents_ = strategy.hide_inspected_contents();
}
bool DevToolsContentsResizingStrategy::Equals(
const DevToolsContentsResizingStrategy& strategy) {
return bounds_ == strategy.bounds() &&
hide_inspected_contents_ == strategy.hide_inspected_contents();
}
void ApplyDevToolsContentsResizingStrategy(
const DevToolsContentsResizingStrategy& strategy,
const gfx::Size& container_size,
gfx::Rect* new_devtools_bounds,
gfx::Rect* new_contents_bounds) {
new_devtools_bounds->SetRect(0, 0, container_size.width(),
container_size.height());
const gfx::Rect& bounds = strategy.bounds();
if (bounds.size().IsEmpty() && !strategy.hide_inspected_contents()) {
new_contents_bounds->SetRect(0, 0, container_size.width(),
container_size.height());
return;
}
int left = std::min(bounds.x(), container_size.width());
int top = std::min(bounds.y(), container_size.height());
int width = std::min(bounds.width(), container_size.width() - left);
int height = std::min(bounds.height(), container_size.height() - top);
new_contents_bounds->SetRect(left, top, width, height);
}

View file

@ -1,46 +0,0 @@
// Copyright 2014 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.
#ifndef BRIGHTRAY_BROWSER_DEVTOOLS_CONTENTS_RESIZING_STRATEGY_H_
#define BRIGHTRAY_BROWSER_DEVTOOLS_CONTENTS_RESIZING_STRATEGY_H_
#include "base/macros.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
// This class knows how to resize both DevTools and inspected WebContents
// inside a browser window hierarchy.
class DevToolsContentsResizingStrategy {
public:
DevToolsContentsResizingStrategy();
explicit DevToolsContentsResizingStrategy(const gfx::Rect& bounds);
void CopyFrom(const DevToolsContentsResizingStrategy& strategy);
bool Equals(const DevToolsContentsResizingStrategy& strategy);
const gfx::Rect& bounds() const { return bounds_; }
bool hide_inspected_contents() const { return hide_inspected_contents_; }
private:
// Contents bounds. When non-empty, used instead of insets.
gfx::Rect bounds_;
// Determines whether inspected contents is visible.
bool hide_inspected_contents_;
DISALLOW_COPY_AND_ASSIGN(DevToolsContentsResizingStrategy);
};
// Applies contents resizing strategy, producing bounds for devtools and
// page contents views. Generally, page contents view is placed atop of devtools
// inside a common parent view, which size should be passed in |container_size|.
// When unknown, providing empty rect as previous devtools and contents bounds
// is allowed.
void ApplyDevToolsContentsResizingStrategy(
const DevToolsContentsResizingStrategy& strategy,
const gfx::Size& container_size,
gfx::Rect* new_devtools_bounds,
gfx::Rect* new_contents_bounds);
#endif // BRIGHTRAY_BROWSER_DEVTOOLS_CONTENTS_RESIZING_STRATEGY_H_

View file

@ -1,218 +0,0 @@
// Copyright 2013 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-CHROMIUM file.
#include "brightray/browser/devtools_embedder_message_dispatcher.h"
#include "base/bind.h"
#include "base/values.h"
namespace brightray {
namespace {
using DispatchCallback = DevToolsEmbedderMessageDispatcher::DispatchCallback;
bool GetValue(const base::Value& value, std::string* result) {
return value.GetAsString(result);
}
bool GetValue(const base::Value& value, int* result) {
return value.GetAsInteger(result);
}
bool GetValue(const base::Value& value, bool* result) {
return value.GetAsBoolean(result);
}
bool GetValue(const base::Value& value, gfx::Rect* rect) {
const base::DictionaryValue* dict;
if (!value.GetAsDictionary(&dict))
return false;
int x = 0;
int y = 0;
int width = 0;
int height = 0;
if (!dict->GetInteger("x", &x) || !dict->GetInteger("y", &y) ||
!dict->GetInteger("width", &width) ||
!dict->GetInteger("height", &height))
return false;
rect->SetRect(x, y, width, height);
return true;
}
template <typename T>
struct StorageTraits {
using StorageType = T;
};
template <typename T>
struct StorageTraits<const T&> {
using StorageType = T;
};
template <typename... Ts>
struct ParamTuple {
bool Parse(const base::ListValue& list,
const base::ListValue::const_iterator& it) {
return it == list.end();
}
template <typename H, typename... As>
void Apply(const H& handler, As... args) {
handler.Run(args...);
}
};
template <typename T, typename... Ts>
struct ParamTuple<T, Ts...> {
bool Parse(const base::ListValue& list,
const base::ListValue::const_iterator& it) {
return it != list.end() && GetValue(*it, &head) && tail.Parse(list, it + 1);
}
template <typename H, typename... As>
void Apply(const H& handler, As... args) {
tail.template Apply<H, As..., T>(handler, args..., head);
}
typename StorageTraits<T>::StorageType head;
ParamTuple<Ts...> tail;
};
template <typename... As>
bool ParseAndHandle(const base::Callback<void(As...)>& handler,
const DispatchCallback& callback,
const base::ListValue& list) {
ParamTuple<As...> tuple;
if (!tuple.Parse(list, list.begin()))
return false;
tuple.Apply(handler);
return true;
}
template <typename... As>
bool ParseAndHandleWithCallback(
const base::Callback<void(const DispatchCallback&, As...)>& handler,
const DispatchCallback& callback,
const base::ListValue& list) {
ParamTuple<As...> tuple;
if (!tuple.Parse(list, list.begin()))
return false;
tuple.Apply(handler, callback);
return true;
}
} // namespace
/**
* Dispatcher for messages sent from the frontend running in an
* isolated renderer (chrome-devtools:// or chrome://inspect) to the embedder
* in the browser.
*
* The messages are sent via InspectorFrontendHost.sendMessageToEmbedder or
* chrome.send method accordingly.
*/
class DispatcherImpl : public DevToolsEmbedderMessageDispatcher {
public:
~DispatcherImpl() override {}
bool Dispatch(const DispatchCallback& callback,
const std::string& method,
const base::ListValue* params) override {
auto it = handlers_.find(method);
return it != handlers_.end() && it->second.Run(callback, *params);
}
template <typename... As>
void RegisterHandler(const std::string& method,
void (Delegate::*handler)(As...),
Delegate* delegate) {
handlers_[method] =
base::Bind(&ParseAndHandle<As...>,
base::Bind(handler, base::Unretained(delegate)));
}
template <typename... As>
void RegisterHandlerWithCallback(
const std::string& method,
void (Delegate::*handler)(const DispatchCallback&, As...),
Delegate* delegate) {
handlers_[method] =
base::Bind(&ParseAndHandleWithCallback<As...>,
base::Bind(handler, base::Unretained(delegate)));
}
private:
using Handler =
base::Callback<bool(const DispatchCallback&, const base::ListValue&)>;
using HandlerMap = std::map<std::string, Handler>;
HandlerMap handlers_;
};
// static
DevToolsEmbedderMessageDispatcher*
DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(
Delegate* delegate) {
auto* d = new DispatcherImpl();
d->RegisterHandler("bringToFront", &Delegate::ActivateWindow, delegate);
d->RegisterHandler("closeWindow", &Delegate::CloseWindow, delegate);
d->RegisterHandler("loadCompleted", &Delegate::LoadCompleted, delegate);
d->RegisterHandler("setInspectedPageBounds",
&Delegate::SetInspectedPageBounds, delegate);
d->RegisterHandler("inspectElementCompleted",
&Delegate::InspectElementCompleted, delegate);
d->RegisterHandler("inspectedURLChanged", &Delegate::InspectedURLChanged,
delegate);
d->RegisterHandlerWithCallback("setIsDocked", &Delegate::SetIsDocked,
delegate);
d->RegisterHandler("openInNewTab", &Delegate::OpenInNewTab, delegate);
d->RegisterHandler("showItemInFolder", &Delegate::ShowItemInFolder, delegate);
d->RegisterHandler("save", &Delegate::SaveToFile, delegate);
d->RegisterHandler("append", &Delegate::AppendToFile, delegate);
d->RegisterHandler("requestFileSystems", &Delegate::RequestFileSystems,
delegate);
d->RegisterHandler("addFileSystem", &Delegate::AddFileSystem, delegate);
d->RegisterHandler("removeFileSystem", &Delegate::RemoveFileSystem, delegate);
d->RegisterHandler("upgradeDraggedFileSystemPermissions",
&Delegate::UpgradeDraggedFileSystemPermissions, delegate);
d->RegisterHandler("indexPath", &Delegate::IndexPath, delegate);
d->RegisterHandlerWithCallback("loadNetworkResource",
&Delegate::LoadNetworkResource, delegate);
d->RegisterHandler("stopIndexing", &Delegate::StopIndexing, delegate);
d->RegisterHandler("searchInPath", &Delegate::SearchInPath, delegate);
d->RegisterHandler("setWhitelistedShortcuts",
&Delegate::SetWhitelistedShortcuts, delegate);
d->RegisterHandler("setEyeDropperActive", &Delegate::SetEyeDropperActive,
delegate);
d->RegisterHandler("showCertificateViewer", &Delegate::ShowCertificateViewer,
delegate);
d->RegisterHandler("zoomIn", &Delegate::ZoomIn, delegate);
d->RegisterHandler("zoomOut", &Delegate::ZoomOut, delegate);
d->RegisterHandler("resetZoom", &Delegate::ResetZoom, delegate);
d->RegisterHandler("setDevicesDiscoveryConfig",
&Delegate::SetDevicesDiscoveryConfig, delegate);
d->RegisterHandler("setDevicesUpdatesEnabled",
&Delegate::SetDevicesUpdatesEnabled, delegate);
d->RegisterHandler("performActionOnRemotePage",
&Delegate::PerformActionOnRemotePage, delegate);
d->RegisterHandler("openRemotePage", &Delegate::OpenRemotePage, delegate);
d->RegisterHandler("openNodeFrontend", &Delegate::OpenNodeFrontend, delegate);
d->RegisterHandler("dispatchProtocolMessage",
&Delegate::DispatchProtocolMessageFromDevToolsFrontend,
delegate);
d->RegisterHandlerWithCallback("sendJsonRequest", &Delegate::SendJsonRequest,
delegate);
d->RegisterHandlerWithCallback("getPreferences", &Delegate::GetPreferences,
delegate);
d->RegisterHandler("setPreference", &Delegate::SetPreference, delegate);
d->RegisterHandler("removePreference", &Delegate::RemovePreference, delegate);
d->RegisterHandler("clearPreferences", &Delegate::ClearPreferences, delegate);
d->RegisterHandler("connectionReady", &Delegate::ConnectionReady, delegate);
d->RegisterHandler("registerExtensionsAPI", &Delegate::RegisterExtensionsAPI,
delegate);
return d;
}
} // namespace brightray

View file

@ -1,113 +0,0 @@
// Copyright 2013 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-CHROMIUM file.
#ifndef BRIGHTRAY_BROWSER_DEVTOOLS_EMBEDDER_MESSAGE_DISPATCHER_H_
#define BRIGHTRAY_BROWSER_DEVTOOLS_EMBEDDER_MESSAGE_DISPATCHER_H_
#include <map>
#include <string>
#include "base/callback.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
namespace base {
class ListValue;
class Value;
} // namespace base
namespace brightray {
/**
* Dispatcher for messages sent from the DevTools frontend running in an
* isolated renderer (on chrome-devtools://) to the embedder in the browser.
*
* The messages are sent via InspectorFrontendHost.sendMessageToEmbedder method.
*/
class DevToolsEmbedderMessageDispatcher {
public:
class Delegate {
public:
using DispatchCallback = base::Callback<void(const base::Value*)>;
virtual ~Delegate() {}
virtual void ActivateWindow() = 0;
virtual void CloseWindow() = 0;
virtual void LoadCompleted() = 0;
virtual void SetInspectedPageBounds(const gfx::Rect& rect) = 0;
virtual void InspectElementCompleted() = 0;
virtual void InspectedURLChanged(const std::string& url) = 0;
virtual void SetIsDocked(const DispatchCallback& callback,
bool is_docked) = 0;
virtual void OpenInNewTab(const std::string& url) = 0;
virtual void ShowItemInFolder(const std::string& file_system_path) = 0;
virtual void SaveToFile(const std::string& url,
const std::string& content,
bool save_as) = 0;
virtual void AppendToFile(const std::string& url,
const std::string& content) = 0;
virtual void RequestFileSystems() = 0;
virtual void AddFileSystem(const std::string& file_system_path) = 0;
virtual void RemoveFileSystem(const std::string& file_system_path) = 0;
virtual void UpgradeDraggedFileSystemPermissions(
const std::string& file_system_url) = 0;
virtual void IndexPath(int index_request_id,
const std::string& file_system_path) = 0;
virtual void StopIndexing(int index_request_id) = 0;
virtual void LoadNetworkResource(const DispatchCallback& callback,
const std::string& url,
const std::string& headers,
int stream_id) = 0;
virtual void SearchInPath(int search_request_id,
const std::string& file_system_path,
const std::string& query) = 0;
virtual void SetWhitelistedShortcuts(const std::string& message) = 0;
virtual void SetEyeDropperActive(bool active) = 0;
virtual void ShowCertificateViewer(const std::string& cert_chain) = 0;
virtual void ZoomIn() = 0;
virtual void ZoomOut() = 0;
virtual void ResetZoom() = 0;
virtual void SetDevicesDiscoveryConfig(
bool discover_usb_devices,
bool port_forwarding_enabled,
const std::string& port_forwarding_config,
bool network_discovery_enabled,
const std::string& network_discovery_config) = 0;
virtual void SetDevicesUpdatesEnabled(bool enabled) = 0;
virtual void PerformActionOnRemotePage(const std::string& page_id,
const std::string& action) = 0;
virtual void OpenRemotePage(const std::string& browser_id,
const std::string& url) = 0;
virtual void OpenNodeFrontend() = 0;
virtual void DispatchProtocolMessageFromDevToolsFrontend(
const std::string& message) = 0;
virtual void SendJsonRequest(const DispatchCallback& callback,
const std::string& browser_id,
const std::string& url) = 0;
virtual void GetPreferences(const DispatchCallback& callback) = 0;
virtual void SetPreference(const std::string& name,
const std::string& value) = 0;
virtual void RemovePreference(const std::string& name) = 0;
virtual void ClearPreferences() = 0;
virtual void ConnectionReady() = 0;
virtual void RegisterExtensionsAPI(const std::string& origin,
const std::string& script) = 0;
};
using DispatchCallback = Delegate::DispatchCallback;
virtual ~DevToolsEmbedderMessageDispatcher() {}
virtual bool Dispatch(const DispatchCallback& callback,
const std::string& method,
const base::ListValue* params) = 0;
static DevToolsEmbedderMessageDispatcher* CreateForDevToolsFrontend(
Delegate* delegate);
};
} // namespace brightray
#endif // BRIGHTRAY_BROWSER_DEVTOOLS_EMBEDDER_MESSAGE_DISPATCHER_H_

View file

@ -1,485 +0,0 @@
// Copyright 2013 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 "brightray/browser/devtools_file_system_indexer.h"
#include <stddef.h>
#include <algorithm>
#include <iterator>
#include <set>
#include "base/bind.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_util.h"
#include "base/files/file_util_proxy.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/sequence_checker.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task_scheduler/lazy_task_runner.h"
#include "base/task_scheduler/post_task.h"
#include "content/public/browser/browser_thread.h"
using base::Bind;
using base::Callback;
using base::FileEnumerator;
using base::FilePath;
using base::Time;
using base::TimeDelta;
using base::TimeTicks;
using content::BrowserThread;
using std::map;
using std::string;
using std::vector;
namespace brightray {
namespace {
base::SequencedTaskRunner* impl_task_runner() {
constexpr base::TaskTraits kBlockingTraits = {base::MayBlock(),
base::TaskPriority::BACKGROUND};
static base::LazySequencedTaskRunner s_sequenced_task_task_runner =
LAZY_SEQUENCED_TASK_RUNNER_INITIALIZER(kBlockingTraits);
return s_sequenced_task_task_runner.Get().get();
}
typedef int32_t Trigram;
typedef char TrigramChar;
typedef uint16_t FileId;
const int kMinTimeoutBetweenWorkedNotification = 200;
// Trigram characters include all ASCII printable characters (32-126) except for
// the capital letters, because the index is case insensitive.
const size_t kTrigramCharacterCount = 126 - 'Z' - 1 + 'A' - ' ' + 1;
const size_t kTrigramCount =
kTrigramCharacterCount * kTrigramCharacterCount * kTrigramCharacterCount;
const int kMaxReadLength = 10 * 1024;
const TrigramChar kUndefinedTrigramChar = -1;
const TrigramChar kBinaryTrigramChar = -2;
const Trigram kUndefinedTrigram = -1;
class Index {
public:
Index();
// Index is only instantiated as a leak LazyInstance, so the destructor is
// never called.
~Index() = delete;
Time LastModifiedTimeForFile(const FilePath& file_path);
void SetTrigramsForFile(const FilePath& file_path,
const vector<Trigram>& index,
const Time& time);
vector<FilePath> Search(const string& query);
void NormalizeVectors();
void Reset();
void EnsureInitialized();
private:
FileId GetFileId(const FilePath& file_path);
typedef map<FilePath, FileId> FileIdsMap;
FileIdsMap file_ids_;
FileId last_file_id_;
// The index in this vector is the trigram id.
vector<vector<FileId>> index_;
typedef map<FilePath, Time> IndexedFilesMap;
IndexedFilesMap index_times_;
vector<bool> is_normalized_;
SEQUENCE_CHECKER(sequence_checker_);
DISALLOW_COPY_AND_ASSIGN(Index);
};
base::LazyInstance<Index>::Leaky g_trigram_index = LAZY_INSTANCE_INITIALIZER;
TrigramChar TrigramCharForChar(char c) {
static TrigramChar* trigram_chars = nullptr;
if (!trigram_chars) {
trigram_chars = new TrigramChar[256];
for (size_t i = 0; i < 256; ++i) {
if (i > 127) {
trigram_chars[i] = kUndefinedTrigramChar;
continue;
}
char ch = static_cast<char>(i);
if (ch == '\t')
ch = ' ';
if (base::IsAsciiUpper(ch))
ch = ch - 'A' + 'a';
bool is_binary_char = ch < 9 || (ch >= 14 && ch < 32) || ch == 127;
if (is_binary_char) {
trigram_chars[i] = kBinaryTrigramChar;
continue;
}
if (ch < ' ') {
trigram_chars[i] = kUndefinedTrigramChar;
continue;
}
if (ch >= 'Z')
ch = ch - 'Z' - 1 + 'A';
ch -= ' ';
char signed_trigram_count = static_cast<char>(kTrigramCharacterCount);
CHECK(ch >= 0 && ch < signed_trigram_count);
trigram_chars[i] = ch;
}
}
unsigned char uc = static_cast<unsigned char>(c);
return trigram_chars[uc];
}
Trigram TrigramAtIndex(const vector<TrigramChar>& trigram_chars, size_t index) {
static int kTrigramCharacterCountSquared =
kTrigramCharacterCount * kTrigramCharacterCount;
if (trigram_chars[index] == kUndefinedTrigramChar ||
trigram_chars[index + 1] == kUndefinedTrigramChar ||
trigram_chars[index + 2] == kUndefinedTrigramChar)
return kUndefinedTrigram;
Trigram trigram = kTrigramCharacterCountSquared * trigram_chars[index] +
kTrigramCharacterCount * trigram_chars[index + 1] +
trigram_chars[index + 2];
return trigram;
}
Index::Index() : last_file_id_(0) {
Reset();
}
void Index::Reset() {
file_ids_.clear();
index_.clear();
index_times_.clear();
is_normalized_.clear();
last_file_id_ = 0;
}
void Index::EnsureInitialized() {
if (index_.size() != 0)
return;
index_.resize(kTrigramCount);
is_normalized_.resize(kTrigramCount);
std::fill(is_normalized_.begin(), is_normalized_.end(), true);
}
Time Index::LastModifiedTimeForFile(const FilePath& file_path) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
EnsureInitialized();
Time last_modified_time;
if (index_times_.find(file_path) != index_times_.end())
last_modified_time = index_times_[file_path];
return last_modified_time;
}
void Index::SetTrigramsForFile(const FilePath& file_path,
const vector<Trigram>& index,
const Time& time) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
EnsureInitialized();
FileId file_id = GetFileId(file_path);
auto it = index.begin();
for (; it != index.end(); ++it) {
Trigram trigram = *it;
index_[trigram].push_back(file_id);
is_normalized_[trigram] = false;
}
index_times_[file_path] = time;
}
vector<FilePath> Index::Search(const string& query) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
EnsureInitialized();
const char* data = query.c_str();
vector<TrigramChar> trigram_chars;
trigram_chars.reserve(query.size());
for (size_t i = 0; i < query.size(); ++i) {
TrigramChar trigram_char = TrigramCharForChar(data[i]);
if (trigram_char == kBinaryTrigramChar)
trigram_char = kUndefinedTrigramChar;
trigram_chars.push_back(trigram_char);
}
vector<Trigram> trigrams;
for (size_t i = 0; i + 2 < query.size(); ++i) {
Trigram trigram = TrigramAtIndex(trigram_chars, i);
if (trigram != kUndefinedTrigram)
trigrams.push_back(trigram);
}
std::set<FileId> file_ids;
bool first = true;
vector<Trigram>::const_iterator it = trigrams.begin();
for (; it != trigrams.end(); ++it) {
Trigram trigram = *it;
if (first) {
std::copy(index_[trigram].begin(), index_[trigram].end(),
std::inserter(file_ids, file_ids.begin()));
first = false;
continue;
}
std::set<FileId> intersection =
base::STLSetIntersection<std::set<FileId>>(file_ids, index_[trigram]);
file_ids.swap(intersection);
}
vector<FilePath> result;
FileIdsMap::const_iterator ids_it = file_ids_.begin();
for (; ids_it != file_ids_.end(); ++ids_it) {
if (trigrams.empty() || file_ids.find(ids_it->second) != file_ids.end()) {
result.push_back(ids_it->first);
}
}
return result;
}
FileId Index::GetFileId(const FilePath& file_path) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
EnsureInitialized();
string file_path_str = file_path.AsUTF8Unsafe();
if (file_ids_.find(file_path) != file_ids_.end())
return file_ids_[file_path];
file_ids_[file_path] = ++last_file_id_;
return last_file_id_;
}
void Index::NormalizeVectors() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
EnsureInitialized();
for (size_t i = 0; i < kTrigramCount; ++i) {
if (!is_normalized_[i]) {
std::sort(index_[i].begin(), index_[i].end());
if (index_[i].capacity() > index_[i].size())
vector<FileId>(index_[i]).swap(index_[i]);
is_normalized_[i] = true;
}
}
}
typedef Callback<void(bool, const vector<bool>&)> IndexerCallback;
} // namespace
DevToolsFileSystemIndexer::FileSystemIndexingJob::FileSystemIndexingJob(
const FilePath& file_system_path,
const TotalWorkCallback& total_work_callback,
const WorkedCallback& worked_callback,
const DoneCallback& done_callback)
: file_system_path_(file_system_path),
total_work_callback_(total_work_callback),
worked_callback_(worked_callback),
done_callback_(done_callback),
files_indexed_(0),
stopped_(false) {
current_trigrams_set_.resize(kTrigramCount);
current_trigrams_.reserve(kTrigramCount);
}
DevToolsFileSystemIndexer::FileSystemIndexingJob::~FileSystemIndexingJob() {}
void DevToolsFileSystemIndexer::FileSystemIndexingJob::Start() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
impl_task_runner()->PostTask(
FROM_HERE, BindOnce(&FileSystemIndexingJob::CollectFilesToIndex, this));
}
void DevToolsFileSystemIndexer::FileSystemIndexingJob::Stop() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
impl_task_runner()->PostTask(
FROM_HERE, BindOnce(&FileSystemIndexingJob::StopOnImplSequence, this));
}
void DevToolsFileSystemIndexer::FileSystemIndexingJob::StopOnImplSequence() {
stopped_ = true;
}
void DevToolsFileSystemIndexer::FileSystemIndexingJob::CollectFilesToIndex() {
DCHECK(impl_task_runner()->RunsTasksInCurrentSequence());
if (stopped_)
return;
if (!file_enumerator_) {
file_enumerator_.reset(
new FileEnumerator(file_system_path_, true, FileEnumerator::FILES));
}
FilePath file_path = file_enumerator_->Next();
if (file_path.empty()) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
BindOnce(total_work_callback_, file_path_times_.size()));
indexing_it_ = file_path_times_.begin();
IndexFiles();
return;
}
Time saved_last_modified_time =
g_trigram_index.Get().LastModifiedTimeForFile(file_path);
FileEnumerator::FileInfo file_info = file_enumerator_->GetInfo();
Time current_last_modified_time = file_info.GetLastModifiedTime();
if (current_last_modified_time > saved_last_modified_time) {
file_path_times_[file_path] = current_last_modified_time;
}
impl_task_runner()->PostTask(
FROM_HERE, BindOnce(&FileSystemIndexingJob::CollectFilesToIndex, this));
}
void DevToolsFileSystemIndexer::FileSystemIndexingJob::IndexFiles() {
DCHECK(impl_task_runner()->RunsTasksInCurrentSequence());
if (stopped_)
return;
if (indexing_it_ == file_path_times_.end()) {
g_trigram_index.Get().NormalizeVectors();
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, done_callback_);
return;
}
FilePath file_path = indexing_it_->first;
current_file_.Initialize(file_path,
base::File::FLAG_OPEN | base::File::FLAG_READ);
if (!current_file_.IsValid()) {
FinishFileIndexing(false);
return;
}
current_file_offset_ = 0;
current_trigrams_.clear();
std::fill(current_trigrams_set_.begin(), current_trigrams_set_.end(), false);
ReadFromFile();
}
void DevToolsFileSystemIndexer::FileSystemIndexingJob::ReadFromFile() {
if (stopped_) {
CloseFile();
return;
}
std::unique_ptr<char[]> data_ptr(new char[kMaxReadLength]);
const char* const data = data_ptr.get();
int bytes_read =
current_file_.Read(current_file_offset_, data_ptr.get(), kMaxReadLength);
if (bytes_read < 0) {
FinishFileIndexing(false);
return;
}
if (bytes_read < 3) {
FinishFileIndexing(true);
return;
}
size_t size = static_cast<size_t>(bytes_read);
vector<TrigramChar> trigram_chars;
trigram_chars.reserve(size);
for (size_t i = 0; i < size; ++i) {
TrigramChar trigram_char = TrigramCharForChar(data[i]);
if (trigram_char == kBinaryTrigramChar) {
current_trigrams_.clear();
FinishFileIndexing(true);
return;
}
trigram_chars.push_back(trigram_char);
}
for (size_t i = 0; i + 2 < size; ++i) {
Trigram trigram = TrigramAtIndex(trigram_chars, i);
if ((trigram != kUndefinedTrigram) && !current_trigrams_set_[trigram]) {
current_trigrams_set_[trigram] = true;
current_trigrams_.push_back(trigram);
}
}
current_file_offset_ += bytes_read - 2;
impl_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&FileSystemIndexingJob::ReadFromFile, this));
}
void DevToolsFileSystemIndexer::FileSystemIndexingJob::FinishFileIndexing(
bool success) {
DCHECK(impl_task_runner()->RunsTasksInCurrentSequence());
CloseFile();
if (success) {
FilePath file_path = indexing_it_->first;
g_trigram_index.Get().SetTrigramsForFile(file_path, current_trigrams_,
file_path_times_[file_path]);
}
ReportWorked();
++indexing_it_;
impl_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&FileSystemIndexingJob::IndexFiles, this));
}
void DevToolsFileSystemIndexer::FileSystemIndexingJob::CloseFile() {
if (current_file_.IsValid())
current_file_.Close();
}
void DevToolsFileSystemIndexer::FileSystemIndexingJob::ReportWorked() {
TimeTicks current_time = TimeTicks::Now();
bool should_send_worked_nitification = true;
if (!last_worked_notification_time_.is_null()) {
TimeDelta delta = current_time - last_worked_notification_time_;
if (delta.InMilliseconds() < kMinTimeoutBetweenWorkedNotification)
should_send_worked_nitification = false;
}
++files_indexed_;
if (should_send_worked_nitification) {
last_worked_notification_time_ = current_time;
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
BindOnce(worked_callback_, files_indexed_));
files_indexed_ = 0;
}
}
static int g_instance_count = 0;
DevToolsFileSystemIndexer::DevToolsFileSystemIndexer() {
impl_task_runner()->PostTask(FROM_HERE,
base::BindOnce([]() { ++g_instance_count; }));
}
DevToolsFileSystemIndexer::~DevToolsFileSystemIndexer() {
impl_task_runner()->PostTask(FROM_HERE, base::BindOnce([]() {
--g_instance_count;
if (!g_instance_count)
g_trigram_index.Get().Reset();
}));
}
scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>
DevToolsFileSystemIndexer::IndexPath(
const string& file_system_path,
const TotalWorkCallback& total_work_callback,
const WorkedCallback& worked_callback,
const DoneCallback& done_callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
scoped_refptr<FileSystemIndexingJob> indexing_job = new FileSystemIndexingJob(
FilePath::FromUTF8Unsafe(file_system_path), total_work_callback,
worked_callback, done_callback);
indexing_job->Start();
return indexing_job;
}
void DevToolsFileSystemIndexer::SearchInPath(const string& file_system_path,
const string& query,
const SearchCallback& callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
impl_task_runner()->PostTask(
FROM_HERE,
BindOnce(&DevToolsFileSystemIndexer::SearchInPathOnImplSequence, this,
file_system_path, query, callback));
}
void DevToolsFileSystemIndexer::SearchInPathOnImplSequence(
const string& file_system_path,
const string& query,
const SearchCallback& callback) {
DCHECK(impl_task_runner()->RunsTasksInCurrentSequence());
vector<FilePath> file_paths = g_trigram_index.Get().Search(query);
vector<string> result;
FilePath path = FilePath::FromUTF8Unsafe(file_system_path);
vector<FilePath>::const_iterator it = file_paths.begin();
for (; it != file_paths.end(); ++it) {
if (path.IsParent(*it))
result.push_back(it->AsUTF8Unsafe());
}
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
BindOnce(callback, std::move(result)));
}
} // namespace brightray

View file

@ -1,108 +0,0 @@
// Copyright 2013 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.
#ifndef BRIGHTRAY_BROWSER_DEVTOOLS_FILE_SYSTEM_INDEXER_H_
#define BRIGHTRAY_BROWSER_DEVTOOLS_FILE_SYSTEM_INDEXER_H_
#include <stdint.h>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "base/callback.h"
#include "base/files/file.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
namespace base {
class FilePath;
class FileEnumerator;
class Time;
} // namespace base
namespace brightray {
class DevToolsFileSystemIndexer
: public base::RefCountedThreadSafe<DevToolsFileSystemIndexer> {
public:
typedef base::Callback<void(int)> TotalWorkCallback;
typedef base::Callback<void(int)> WorkedCallback;
typedef base::Callback<void()> DoneCallback;
typedef base::Callback<void(const std::vector<std::string>&)> SearchCallback;
class FileSystemIndexingJob
: public base::RefCountedThreadSafe<FileSystemIndexingJob> {
public:
void Stop();
private:
friend class base::RefCountedThreadSafe<FileSystemIndexingJob>;
friend class DevToolsFileSystemIndexer;
FileSystemIndexingJob(const base::FilePath& file_system_path,
const TotalWorkCallback& total_work_callback,
const WorkedCallback& worked_callback,
const DoneCallback& done_callback);
virtual ~FileSystemIndexingJob();
void Start();
void StopOnImplSequence();
void CollectFilesToIndex();
void IndexFiles();
void ReadFromFile();
void OnRead(base::File::Error error, const char* data, int bytes_read);
void FinishFileIndexing(bool success);
void CloseFile();
void ReportWorked();
base::FilePath file_system_path_;
TotalWorkCallback total_work_callback_;
WorkedCallback worked_callback_;
DoneCallback done_callback_;
std::unique_ptr<base::FileEnumerator> file_enumerator_;
typedef std::map<base::FilePath, base::Time> FilePathTimesMap;
FilePathTimesMap file_path_times_;
FilePathTimesMap::const_iterator indexing_it_;
base::File current_file_;
int64_t current_file_offset_;
typedef int32_t Trigram;
std::vector<Trigram> current_trigrams_;
// The index in this vector is the trigram id.
std::vector<bool> current_trigrams_set_;
base::TimeTicks last_worked_notification_time_;
int files_indexed_;
bool stopped_;
};
DevToolsFileSystemIndexer();
// Performs file system indexing for given |file_system_path| and sends
// progress callbacks.
scoped_refptr<FileSystemIndexingJob> IndexPath(
const std::string& file_system_path,
const TotalWorkCallback& total_work_callback,
const WorkedCallback& worked_callback,
const DoneCallback& done_callback);
// Performs trigram search for given |query| in |file_system_path|.
void SearchInPath(const std::string& file_system_path,
const std::string& query,
const SearchCallback& callback);
private:
friend class base::RefCountedThreadSafe<DevToolsFileSystemIndexer>;
virtual ~DevToolsFileSystemIndexer();
void SearchInPathOnImplSequence(const std::string& file_system_path,
const std::string& query,
const SearchCallback& callback);
DISALLOW_COPY_AND_ASSIGN(DevToolsFileSystemIndexer);
};
} // namespace brightray
#endif // BRIGHTRAY_BROWSER_DEVTOOLS_FILE_SYSTEM_INDEXER_H_

View file

@ -3,6 +3,8 @@
#include <string>
#include "base/files/file_path.h"
namespace brightray {
class InspectableWebContentsDelegate {
@ -17,11 +19,13 @@ class InspectableWebContentsDelegate {
virtual void DevToolsAppendToFile(const std::string& url,
const std::string& content) {}
virtual void DevToolsRequestFileSystems() {}
virtual void DevToolsAddFileSystem(const base::FilePath& file_system_path) {}
virtual void DevToolsAddFileSystem(const std::string& type,
const base::FilePath& file_system_path) {}
virtual void DevToolsRemoveFileSystem(
const base::FilePath& file_system_path) {}
virtual void DevToolsIndexPath(int request_id,
const std::string& file_system_path) {}
const std::string& file_system_path,
const std::string& excluded_folders) {}
virtual void DevToolsStopIndexing(int request_id) {}
virtual void DevToolsSearchInPath(int request_id,
const std::string& file_system_path,

View file

@ -271,7 +271,7 @@ content::WebContents* InspectableWebContentsImpl::GetDevToolsWebContents()
}
void InspectableWebContentsImpl::InspectElement(int x, int y) {
if (agent_host_.get())
if (agent_host_)
agent_host_->InspectElement(web_contents_->GetMainFrame(), x, y);
}
@ -354,19 +354,27 @@ bool InspectableWebContentsImpl::IsDevToolsViewShowing() {
void InspectableWebContentsImpl::AttachTo(
scoped_refptr<content::DevToolsAgentHost> host) {
if (agent_host_.get())
Detach();
Detach();
agent_host_ = std::move(host);
// Terminate existing debugging connections and start debugging.
agent_host_->ForceAttachClient(this);
// We could use ForceAttachClient here if problem arises with
// devtools multiple session support.
agent_host_->AttachClient(this);
}
void InspectableWebContentsImpl::Detach() {
if (agent_host_.get())
if (agent_host_)
agent_host_->DetachClient(this);
agent_host_ = nullptr;
}
void InspectableWebContentsImpl::Reattach(const DispatchCallback& callback) {
if (agent_host_) {
agent_host_->DetachClient(this);
agent_host_->AttachClient(this);
}
callback.Run(nullptr);
}
void InspectableWebContentsImpl::CallClientFunction(
const std::string& function_name,
const base::Value* arg1,
@ -528,11 +536,9 @@ void InspectableWebContentsImpl::RequestFileSystems() {
delegate_->DevToolsRequestFileSystems();
}
void InspectableWebContentsImpl::AddFileSystem(
const std::string& file_system_path) {
void InspectableWebContentsImpl::AddFileSystem(const std::string& type) {
if (delegate_)
delegate_->DevToolsAddFileSystem(
base::FilePath::FromUTF8Unsafe(file_system_path));
delegate_->DevToolsAddFileSystem(type, base::FilePath());
}
void InspectableWebContentsImpl::RemoveFileSystem(
@ -547,9 +553,11 @@ void InspectableWebContentsImpl::UpgradeDraggedFileSystemPermissions(
void InspectableWebContentsImpl::IndexPath(
int request_id,
const std::string& file_system_path) {
const std::string& file_system_path,
const std::string& excluded_folders) {
if (delegate_)
delegate_->DevToolsIndexPath(request_id, file_system_path);
delegate_->DevToolsIndexPath(request_id, file_system_path,
excluded_folders);
}
void InspectableWebContentsImpl::StopIndexing(int request_id) {
@ -620,7 +628,7 @@ void InspectableWebContentsImpl::DispatchProtocolMessageFromDevToolsFrontend(
return;
}
if (agent_host_.get())
if (agent_host_)
agent_host_->DispatchProtocolMessage(this, message);
}

View file

@ -11,9 +11,9 @@
#include <vector>
#include "base/memory/weak_ptr.h"
#include "brightray/browser/devtools_contents_resizing_strategy.h"
#include "brightray/browser/devtools_embedder_message_dispatcher.h"
#include "brightray/browser/inspectable_web_contents.h"
#include "chrome/browser/devtools/devtools_contents_resizing_strategy.h"
#include "chrome/browser/devtools/devtools_embedder_message_dispatcher.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/devtools_frontend_host.h"
#include "content/public/browser/web_contents_delegate.h"
@ -92,12 +92,13 @@ class InspectableWebContentsImpl
void AppendToFile(const std::string& url,
const std::string& content) override;
void RequestFileSystems() override;
void AddFileSystem(const std::string& file_system_path) override;
void AddFileSystem(const std::string& type) override;
void RemoveFileSystem(const std::string& file_system_path) override;
void UpgradeDraggedFileSystemPermissions(
const std::string& file_system_url) override;
void IndexPath(int index_request_id,
const std::string& file_system_path) override;
const std::string& file_system_path,
const std::string& excluded_folders) override;
void StopIndexing(int index_request_id) override;
void SearchInPath(int search_request_id,
const std::string& file_system_path,
@ -133,6 +134,12 @@ class InspectableWebContentsImpl
void ConnectionReady() override;
void RegisterExtensionsAPI(const std::string& origin,
const std::string& script) override;
void Reattach(const DispatchCallback& callback) override;
void RecordEnumeratedHistogram(const std::string& name,
int sample,
int boundary_value) override {}
void ReadyForTest() override {}
void SetOpenNewWindowForPopups(bool value) override {}
// content::DevToolsFrontendHostDelegate:
void HandleMessageFromDevToolsFrontend(const std::string& message);

View file

@ -1,7 +1,7 @@
#import <AppKit/AppKit.h>
#include "base/mac/scoped_nsobject.h"
#include "brightray/browser/devtools_contents_resizing_strategy.h"
#include "chrome/browser/devtools/devtools_contents_resizing_strategy.h"
#include "ui/base/cocoa/base_view.h"
namespace brightray {

View file

@ -2,8 +2,8 @@
#define BRIGHTRAY_BROWSER_VIEWS_INSPECTABLE_WEB_CONTENTS_VIEW_VIEWS_H_
#include "base/compiler_specific.h"
#include "brightray/browser/devtools_contents_resizing_strategy.h"
#include "brightray/browser/inspectable_web_contents_view.h"
#include "chrome/browser/devtools/devtools_contents_resizing_strategy.h"
#include "ui/views/view.h"
namespace views {