summaryrefslogtreecommitdiffstats
path: root/src/core/devtools_frontend_qt.cpp
blob: ea2118b529f4623fbd0be1dd061ce2adff589bb0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

// based on content/shell/browser/shell_devtools_frontend.cc:
// 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 "devtools_frontend_qt.h"

#include "profile_adapter.h"
#include "profile_qt.h"
#include "web_contents_adapter.h"

#include "base/base64.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/json/string_escape.h"
#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/devtools/devtools_eye_dropper.h"
#include "chrome/browser/devtools/devtools_file_helper.h"
#include "chrome/common/url_constants.h"
#include "components/prefs/in_memory_pref_store.h"
#include "components/prefs/json_pref_store.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/devtools_frontend_host.h"
#include "content/public/browser/file_url_loader.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/shared_cors_origin_access_list.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_client.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/url_utils.h"
#include "ipc/ipc_channel.h"
#include "net/http/http_response_headers.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/cpp/simple_url_loader_stream_consumer.h"

using namespace QtWebEngineCore;

namespace {

constexpr char kScreencastEnabled[] = "screencastEnabled";

base::DictionaryValue CreateFileSystemValue(DevToolsFileHelper::FileSystem fileSystem)
{
    base::DictionaryValue fileSystemValue;
    fileSystemValue.SetStringKey("type", fileSystem.type);
    fileSystemValue.SetStringKey("fileSystemName", fileSystem.file_system_name);
    fileSystemValue.SetStringKey("rootURL", fileSystem.root_url);
    fileSystemValue.SetStringKey("fileSystemPath", fileSystem.file_system_path);
    return fileSystemValue;
}

base::DictionaryValue BuildObjectForResponse(const net::HttpResponseHeaders *rh, bool success,
                                             int netError)
{
    base::DictionaryValue response;
    int responseCode = 200;
    if (rh) {
        responseCode = rh->response_code();
    } else if (!success) {
        // In case of no headers, assume file:// URL and failed to load
        responseCode = 404;
    }
    response.SetInteger("statusCode", responseCode);
    response.SetInteger("netError", netError);
    response.SetString("netErrorName", net::ErrorToString(netError));

    auto headers = std::make_unique<base::DictionaryValue>();
    size_t iterator = 0;
    std::string name;
    std::string value;
    // TODO(caseq): this probably needs to handle duplicate header names
    // correctly by folding them.
    while (rh && rh->EnumerateHeaderLines(&iterator, &name, &value))
        headers->SetString(name, value);

    response.Set("headers", std::move(headers));
    return response;
}

static std::string GetFrontendURL()
{
    return "devtools://devtools/bundled/inspector.html";
}

}  // namespace

namespace QtWebEngineCore {

class DevToolsFrontendQt::NetworkResourceLoader
        : public network::SimpleURLLoaderStreamConsumer {
public:
    NetworkResourceLoader(int stream_id,
                          int request_id,
                          DevToolsFrontendQt *bindings,
                          std::unique_ptr<network::SimpleURLLoader> loader,
                          network::mojom::URLLoaderFactory *url_loader_factory)
        : stream_id_(stream_id),
          request_id_(request_id),
          bindings_(bindings),
          loader_(std::move(loader))
    {
        loader_->SetOnResponseStartedCallback(base::BindOnce(
                                                  &NetworkResourceLoader::OnResponseStarted, base::Unretained(this)));
        loader_->DownloadAsStream(url_loader_factory, this);
    }

private:
    void OnResponseStarted(const GURL &final_url,
                           const network::mojom::URLResponseHead &response_head)
    {
        response_headers_ = response_head.headers;
    }

    void OnDataReceived(base::StringPiece chunk, base::OnceClosure resume) override
    {
        base::Value chunkValue;

        bool encoded = !base::IsStringUTF8(chunk);
        if (encoded) {
            std::string encoded_string;
            base::Base64Encode(chunk, &encoded_string);
            chunkValue = base::Value(std::move(encoded_string));
        } else {
            chunkValue = base::Value(chunk);
        }
        base::Value id(stream_id_);
        base::Value encodedValue(encoded);

        bindings_->CallClientFunction("DevToolsAPI", "streamWrite", std::move(id), std::move(chunkValue), std::move(encodedValue));
        std::move(resume).Run();
    }

    void OnComplete(bool success) override
    {
        auto response = BuildObjectForResponse(response_headers_.get(), success, loader_->NetError());
        bindings_->SendMessageAck(request_id_, std::move(response));
        bindings_->m_loaders.erase(bindings_->m_loaders.find(this));
    }

    void OnRetry(base::OnceClosure start_retry) override { NOTREACHED(); }

    const int stream_id_;
    const int request_id_;
    DevToolsFrontendQt *const bindings_;
    std::unique_ptr<network::SimpleURLLoader> loader_;
    scoped_refptr<net::HttpResponseHeaders> response_headers_;
};

// This constant should be in sync with
// the constant at devtools_ui_bindings.cc.
const size_t kMaxMessageChunkSize = IPC::Channel::kMaximumMessageSize / 4;

// static
DevToolsFrontendQt *DevToolsFrontendQt::Show(QSharedPointer<WebContentsAdapter> frontendAdapter, content::WebContents *inspectedContents)
{
    DCHECK(frontendAdapter);
    DCHECK(inspectedContents);

    if (!frontendAdapter->isInitialized()) {
        scoped_refptr<content::SiteInstance> site =
            content::SiteInstance::CreateForURL(frontendAdapter->profile(), GURL(GetFrontendURL()));
        frontendAdapter->initialize(site.get());
    }

    frontendAdapter->setInspector(true);

    content::WebContents *contents = frontendAdapter->webContents();
    if (contents == inspectedContents) {
        LOG(WARNING) << "You can not inspect yourself";
        return nullptr;
    }

    DevToolsFrontendQt *devtoolsFrontend = new DevToolsFrontendQt(frontendAdapter, inspectedContents);

    if (contents->GetURL() == GURL(GetFrontendURL())) {
        contents->GetController().Reload(content::ReloadType::ORIGINAL_REQUEST_URL, false);
    }  else {
        content::NavigationController::LoadURLParams loadParams((GURL(GetFrontendURL())));
        loadParams.transition_type = ui::PageTransitionFromInt(ui::PAGE_TRANSITION_AUTO_TOPLEVEL | ui::PAGE_TRANSITION_FROM_API);
        contents->GetController().LoadURLWithParams(loadParams);
    }

    return devtoolsFrontend;
}

DevToolsFrontendQt::DevToolsFrontendQt(QSharedPointer<WebContentsAdapter> webContentsAdapter,
                                       content::WebContents *inspectedContents)
    : content::WebContentsObserver(webContentsAdapter->webContents())
    , m_frontendAdapter(webContentsAdapter)
    , m_inspectedAdapter(static_cast<WebContentsDelegateQt *>(inspectedContents->GetDelegate())
                                 ->webContentsAdapter())
    , m_inspectedContents(inspectedContents)
    , m_inspect_element_at_x(-1)
    , m_inspect_element_at_y(-1)
    , m_prefStore(nullptr)
    , m_weakFactory(this)
{
    // We use a separate prefstore than one in ProfileQt, because that one is in-memory only, and this
    // needs to be stored or it will show introduction text on every load.
    if (webContentsAdapter->profileAdapter()->isOffTheRecord())
        m_prefStore = scoped_refptr<PersistentPrefStore>(new InMemoryPrefStore());
    else
        CreateJsonPreferences(false);

    m_frontendDelegate = static_cast<WebContentsDelegateQt *>(webContentsAdapter->webContents()->GetDelegate());
    m_fileHelper = std::make_unique<DevToolsFileHelper>(
            webContentsAdapter->webContents(),
            static_cast<Profile *>(webContentsAdapter->webContents()->GetBrowserContext()), this);
}

DevToolsFrontendQt::~DevToolsFrontendQt()
{
    if (QSharedPointer<WebContentsAdapter> p = m_frontendAdapter)
        p->setInspector(false);
}

void DevToolsFrontendQt::Activate()
{
    m_frontendDelegate->ActivateContents(web_contents());
}

void DevToolsFrontendQt::Focus()
{
    web_contents()->Focus();
}

void DevToolsFrontendQt::InspectElementAt(int x, int y)
{
    if (m_agentHost)
        m_agentHost->InspectElement(m_inspectedContents->GetFocusedFrame(), x, y);
    else {
        m_inspect_element_at_x = x;
        m_inspect_element_at_y = y;
    }
}

void DevToolsFrontendQt::Close()
{
    // Don't close the webContents, it might be reused, but pretend it was
    WebContentsDestroyed();
}

void DevToolsFrontendQt::DisconnectFromTarget()
{
    if (!m_agentHost)
        return;
    m_agentHost->DetachClient(this);
    m_agentHost = nullptr;
}

void DevToolsFrontendQt::ReadyToCommitNavigation(content::NavigationHandle *navigationHandle)
{
    // ShellDevToolsFrontend does this in RenderViewCreated,
    // but that doesn't work for us for some reason.
    content::RenderFrameHost *frame = navigationHandle->GetRenderFrameHost();
    if (navigationHandle->IsInMainFrame()) {
        // If the frontend for some reason goes to some place other than devtools, stop the bindings
        if (navigationHandle->GetURL() != GetFrontendURL())
            m_frontendHost.reset(nullptr);
        else if (!m_frontendHost)
            m_frontendHost = content::DevToolsFrontendHost::Create(
                        frame,
                        base::BindRepeating(&DevToolsFrontendQt::HandleMessageFromDevToolsFrontend,
                                            base::Unretained(this)));
    }
}

void DevToolsFrontendQt::DocumentOnLoadCompletedInPrimaryMainFrame()
{
    if (!m_inspectedContents)
        return;
    // Don't call AttachClient multiple times for the same DevToolsAgentHost.
    // Otherwise it will call AgentHostClosed which closes the DevTools window.
    // This may happen in cases where the DevTools content fails to load.
    scoped_refptr<content::DevToolsAgentHost> agent_host =
            content::DevToolsAgentHost::GetOrCreateFor(m_inspectedContents);
    if (agent_host != m_agentHost) {
        if (m_agentHost)
            m_agentHost->DetachClient(this);
        m_agentHost = agent_host;
        m_agentHost->AttachClient(this);
        if (m_inspect_element_at_x != -1) {
            m_agentHost->InspectElement(m_inspectedContents->GetFocusedFrame(), m_inspect_element_at_x, m_inspect_element_at_y);
            m_inspect_element_at_x = -1;
            m_inspect_element_at_y = -1;
        }
    }
}

void DevToolsFrontendQt::WebContentsDestroyed()
{
    if (m_inspectedAdapter)
        m_inspectedAdapter->devToolsFrontendDestroyed(this);

    if (m_agentHost) {
        m_agentHost->DetachClient(this);
        m_agentHost = nullptr;
    }
    delete this;
}

void DevToolsFrontendQt::SetPreference(const std::string &name, const std::string &value)
{
    DCHECK(m_prefStore);
    m_prefStore->SetValue(name, base::WrapUnique(new base::Value(value)), 0);
}

void DevToolsFrontendQt::RemovePreference(const std::string &name)
{
    DCHECK(m_prefStore);
    m_prefStore->RemoveValue(name, 0);
}

void DevToolsFrontendQt::ClearPreferences()
{
    ProfileQt *profile = static_cast<ProfileQt *>(web_contents()->GetBrowserContext());
    if (profile->IsOffTheRecord() || profile->profileAdapter()->storageName().isEmpty())
        m_prefStore = scoped_refptr<PersistentPrefStore>(new InMemoryPrefStore());
    else
        CreateJsonPreferences(true);
}

void DevToolsFrontendQt::CreateJsonPreferences(bool clear)
{
    content::BrowserContext *browserContext = web_contents()->GetBrowserContext();
    DCHECK(!browserContext->IsOffTheRecord());
    JsonPrefStore *jsonPrefStore = new JsonPrefStore(
                browserContext->GetPath().Append(FILE_PATH_LITERAL("devtoolsprefs.json")));
    // We effectively clear the preferences by not calling ReadPrefs
    base::ScopedAllowBlockingForTesting allowBlocking;
    if (!clear)
        jsonPrefStore->ReadPrefs();

    m_prefStore = scoped_refptr<PersistentPrefStore>(jsonPrefStore);
}

void DevToolsFrontendQt::HandleMessageFromDevToolsFrontend(base::Value message)
{
    const std::string *method_ptr = nullptr;
    base::Value *params_value = nullptr;
    if (message.is_dict()) {
        method_ptr = message.FindStringKey("method");
        params_value = message.FindKey("params");
    }
    if (!method_ptr || (params_value && !params_value->is_list())) {
        LOG(ERROR) << "Invalid message was sent to embedder: " << message;
        return;
    }
    base::Value empty_params(base::Value::Type::LIST);
    if (!params_value)
        params_value = &empty_params;

    int request_id = message.FindIntKey("id").value_or(0);
    const std::string &method = *method_ptr;
    base::Value::List *paramsPtr;
    if (params_value)
        paramsPtr = params_value->GetIfList();
    base::Value::List &params = *paramsPtr;

    if (method == "dispatchProtocolMessage" && params.size() == 1) {
        const std::string *protocol_message = params[0].GetIfString();
        if (!protocol_message)
            return;
        if (m_agentHost)
            m_agentHost->DispatchProtocolMessage(this, base::as_bytes(base::make_span(*protocol_message)));
    } else if (method == "loadCompleted") {
        web_contents()->GetMainFrame()->ExecuteJavaScript(u"DevToolsAPI.setUseSoftMenu(true);",
                                                          base::NullCallback());
    } else if (method == "loadNetworkResource" && params.size() == 3) {
        // TODO(pfeldman): handle some of the embedder messages in content.
        const std::string *url = params[0].GetIfString();
        const std::string *headers = params[1].GetIfString();
        absl::optional<int> stream_id = params[2].GetIfInt();
        if (!url || !headers || !stream_id.has_value()) {
            return;
        }

        GURL gurl(*url);
        if (!gurl.is_valid()) {
            base::DictionaryValue response;
            response.SetInteger("statusCode", 404);
            response.SetBoolean("urlValid", false);
            SendMessageAck(request_id, std::move(response));
            return;
        }

        net::NetworkTrafficAnnotationTag traffic_annotation =
            net::DefineNetworkTrafficAnnotation(
                "devtools_handle_front_end_messages", R"(
                semantics {
                  sender: "Developer Tools"
                  description:
                    "When user opens Developer Tools, the browser may fetch "
                    "additional resources from the network to enrich the debugging "
                    "experience (e.g. source map resources)."
                  trigger: "User opens Developer Tools to debug a web page."
                  data: "Any resources requested by Developer Tools."
                  destination: OTHER
                }
                policy {
                  cookies_allowed: YES
                  cookies_store: "user"
                  setting:
                    "It's not possible to disable this feature from settings."
                  chrome_policy {
                    DeveloperToolsAvailability {
                      policy_options {mode: MANDATORY}
                      DeveloperToolsAvailability: 2
                    }
                  }
                })");
        auto resource_request = std::make_unique<network::ResourceRequest>();
        resource_request->url = gurl;
        // TODO(caseq): this preserves behavior of URLFetcher-based implementation.
        // We really need to pass proper first party origin from the front-end.
        resource_request->site_for_cookies = net::SiteForCookies::FromUrl(gurl);
        resource_request->headers.AddHeadersFromString(*headers);

        mojo::Remote<network::mojom::URLLoaderFactory> file_url_loader_factory;
        scoped_refptr<network::SharedURLLoaderFactory> network_url_loader_factory;
        network::mojom::URLLoaderFactory *url_loader_factory;
        if (gurl.SchemeIsFile()) {
            file_url_loader_factory.Bind(content::CreateFileURLLoaderFactory(base::FilePath(), nullptr));
            url_loader_factory = file_url_loader_factory.get();
        } else if (content::HasWebUIScheme(gurl)) {
            base::DictionaryValue response;
            response.SetInteger("statusCode", 403);
            SendMessageAck(request_id, std::move(response));
            return;
        } else {
            auto *partition = web_contents()->GetBrowserContext()->GetStoragePartitionForUrl(gurl);
            network_url_loader_factory = partition->GetURLLoaderFactoryForBrowserProcess();
            url_loader_factory = network_url_loader_factory.get();
        }
        auto simple_url_loader = network::SimpleURLLoader::Create(
                    std::move(resource_request), traffic_annotation);
        auto resource_loader = std::make_unique<NetworkResourceLoader>(
                    *stream_id, request_id, this, std::move(simple_url_loader),
                    url_loader_factory);
        m_loaders.insert(std::move(resource_loader));
        return;
    } else if (method == "getPreferences") {
        // Screencast is enabled by default if it's not present in the preference store.
        if (!m_prefStore->GetValue(kScreencastEnabled, NULL))
            SetPreference(kScreencastEnabled, "false");

        m_preferences = std::move(*m_prefStore->GetValues());
        SendMessageAck(request_id, m_preferences.Clone());
        return;
    } else if (method == "setPreference" && params.size() >= 2) {
        const std::string *name = params[0].GetIfString();
        const std::string *value = params[1].GetIfString();
        if (!name || !value)
            return;
        SetPreference(*name, *value);
    } else if (method == "removePreference" && params.size() >= 1) {
        const std::string *name = params[0].GetIfString();
        if (!name)
            return;
        RemovePreference(*name);
    } else if (method == "clearPreferences") {
        ClearPreferences();
    } else if (method == "requestFileSystems") {
        base::ListValue fileSystemsValue;
        for (auto const &fileSystem : m_fileHelper->GetFileSystems())
            fileSystemsValue.Append(CreateFileSystemValue(fileSystem));
        CallClientFunction("DevToolsAPI", "fileSystemsLoaded", std::move(fileSystemsValue));
    } else if (method == "reattach") {
        if (!m_agentHost)
            return;
        m_agentHost->DetachClient(this);
        m_agentHost->AttachClient(this);
    } else if (method == "inspectedURLChanged" && params.size() >= 1) {
        const std::string *url = params[0].GetIfString();
        if (!url)
            return;
        const std::string kHttpPrefix = "http://";
        const std::string kHttpsPrefix = "https://";
        const std::string simplified_url =
            base::StartsWith(*url, kHttpsPrefix, base::CompareCase::SENSITIVE)
                ? url->substr(kHttpsPrefix.length())
                : base::StartsWith(*url, kHttpPrefix, base::CompareCase::SENSITIVE)
                      ? url->substr(kHttpPrefix.length())
                      : *url;
        // DevTools UI is not localized.
        web_contents()->UpdateTitleForEntry(web_contents()->GetController().GetActiveEntry(),
                                            base::UTF8ToUTF16(
                                                base::StringPrintf("DevTools - %s", simplified_url.c_str())));
    } else if (method == "openInNewTab" && params.size() >= 1) {
        const std::string *urlString = params[0].GetIfString();
        if (!urlString)
            return;
        GURL url(*urlString);
        if (!url.is_valid())
            return;
        content::OpenURLParams openParams(GURL(url),
                                          content::Referrer(),
                                          WindowOpenDisposition::NEW_FOREGROUND_TAB,
                                          ui::PAGE_TRANSITION_LINK,
                                          false);
        // OpenURL will (via WebContentsDelegateQt::OpenURLFromTab) call
        // application code, which may decide to close this devtools view (see
        // quicknanobrowser for example).
        //
        // Chromium always calls SendMessageAck through a callback bound to a
        // WeakPtr, we do the same here, except without the callback.
        base::WeakPtr<DevToolsFrontendQt> weakThis = m_weakFactory.GetWeakPtr();
        web_contents()->OpenURL(openParams);
        if (!weakThis)
            return;
    } else if (method == "bringToFront") {
        Activate();
    } else if (method == "closeWindow") {
        web_contents()->Close();
    } else if (method == "setEyeDropperActive" && params.size() == 1) {
        absl::optional<bool> active = params[0].GetIfBool();
        if (!active)
            return;
        SetEyeDropperActive(*active);
    } else if (method == "save" && params.size() == 3) {
        const std::string *url = params[0].GetIfString();
        const std::string *content = params[1].GetIfString();
        absl::optional<bool> saveAs = params[2].GetIfBool();
        if (!url || !content || !saveAs)
            return;
        SaveToFile(*url, *content, *saveAs);
    } else if (method == "append" && params.size() == 2) {
        const std::string *url = params[0].GetIfString();
        const std::string *content = params[1].GetIfString();
        if (!url || !content)
            return;
        AppendToFile(*url, *content);
    } else if (method == "addFileSystem" && params.size() == 1) {
        const std::string *type = params[0].GetIfString();
        if (!type)
            return;
        AddFileSystem(*type);
    } else if (method == "removeFileSystem" && params.size() == 1) {
        const std::string *fileSystemPath = params[0].GetIfString();
        if (!fileSystemPath)
            return;
        RemoveFileSystem(*fileSystemPath);
    } else if (method == "upgradeDraggedFileSystemPermissions" && params.size() == 1) {
        const std::string *fileSystemUrl = params[0].GetIfString();
        if (!fileSystemUrl)
            return;
        UpgradeDraggedFileSystemPermissions(*fileSystemUrl);
    } else {
        VLOG(1) << "Unimplemented devtools method: " << message;
        return;
    }

    if (request_id)
        SendMessageAck(request_id, base::Value());
}

void DevToolsFrontendQt::SetEyeDropperActive(bool active)
{
    if (!m_inspectedContents)
        return;
    if (active) {
        m_eyeDropper.reset(new DevToolsEyeDropper(
                               m_inspectedContents,
                               base::BindRepeating(&DevToolsFrontendQt::ColorPickedInEyeDropper,
                                                   base::Unretained(this))));
    } else {
        m_eyeDropper.reset();
    }
}

void DevToolsFrontendQt::ColorPickedInEyeDropper(int r, int g, int b, int a)
{
    base::DictionaryValue color;
    color.SetInteger("r", r);
    color.SetInteger("g", g);
    color.SetInteger("b", b);
    color.SetInteger("a", a);
    CallClientFunction("DevToolsAPI", "eyeDropperPickedColor", std::move(color));
}

void DevToolsFrontendQt::DispatchProtocolMessage(content::DevToolsAgentHost *agentHost, base::span<const uint8_t> message)
{
    Q_UNUSED(agentHost);
    base::StringPiece str_message(reinterpret_cast<const char*>(message.data()), message.size());

    if (str_message.length() < kMaxMessageChunkSize) {
        CallClientFunction("DevToolsAPI", "dispatchMessage",
                           base::Value(std::string(str_message)));
    } else {
        size_t total_size = str_message.length();
        for (size_t pos = 0; pos < str_message.length(); pos += kMaxMessageChunkSize) {
            base::StringPiece str_message_chunk = str_message.substr(pos, kMaxMessageChunkSize);

            CallClientFunction("DevToolsAPI", "dispatchMessageChunk",
                               base::Value(std::string(str_message_chunk)),
                               base::Value(base::NumberToString(pos ? 0 : total_size)));
        }
    }
}

void DevToolsFrontendQt::CallClientFunction(const std::string &object_name,
                                            const std::string &method_name,
                                            base::Value arg1, base::Value arg2, base::Value arg3,
                                            base::OnceCallback<void(base::Value)> cb)

{
    base::Value::List arguments;
    if (!arg1.is_none()) {
        arguments.Append(std::move(arg1));
        if (!arg2.is_none()) {
            arguments.Append(std::move(arg2));
            if (!arg3.is_none()) {
                arguments.Append(std::move(arg3));
            }
        }
    }
    web_contents()->GetMainFrame()->ExecuteJavaScriptMethod(base::ASCIIToUTF16(object_name),
                                                            base::ASCIIToUTF16(method_name),
                                                            std::move(arguments),
                                                            std::move(cb));

}

// static
bool DevToolsFrontendQt::IsValidFrontendURL(const GURL &url)
{
    // NOTE: the inspector app does not change the frontend url.
    // If we bring back the devtools_app, the url must be sanitized
    // according to chrome/browser/devtools/devtools_ui_bindings.cc.
    return url.spec() == GetFrontendURL();
}

void DevToolsFrontendQt::SendMessageAck(int request_id, base::Value arg)
{
    base::Value id_value(request_id);
    CallClientFunction("DevToolsAPI", "embedderMessageAck", std::move(id_value), std::move(arg));
}

void DevToolsFrontendQt::AgentHostClosed(content::DevToolsAgentHost *agentHost)
{
    DCHECK(agentHost == m_agentHost.get());
    m_agentHost = nullptr;
    m_inspectedContents = nullptr;
    m_inspectedAdapter = nullptr;
    Close();
}

void DevToolsFrontendQt::SaveToFile(const std::string &url, const std::string &content, bool saveAs)
{
    m_fileHelper->Save(
            url, content, saveAs,
            base::BindOnce(&DevToolsFrontendQt::FileSavedAs, m_weakFactory.GetWeakPtr(), url),
            base::BindOnce(&DevToolsFrontendQt::CanceledFileSaveAs, m_weakFactory.GetWeakPtr(),
                           url));
}

void DevToolsFrontendQt::FileSavedAs(const std::string &url, const std::string &fileSystemPath)
{
    CallClientFunction("DevToolsAPI", "savedURL", base::Value(url), base::Value(fileSystemPath));
}

void DevToolsFrontendQt::CanceledFileSaveAs(const std::string &url)
{
    CallClientFunction("DevToolsAPI", "canceledSaveURL", base::Value(url));
}

void DevToolsFrontendQt::AppendToFile(const std::string &url, const std::string &content)
{
    m_fileHelper->Append(
            url, content,
            base::BindOnce(&DevToolsFrontendQt::AppendedTo, m_weakFactory.GetWeakPtr(), url));
}

void DevToolsFrontendQt::AppendedTo(const std::string &url)
{
    CallClientFunction("DevToolsAPI", "appendedToURL", base::Value(url));
}

void DevToolsFrontendQt::AddFileSystem(const std::string &type)
{
    CHECK(IsValidFrontendURL(web_contents()->GetLastCommittedURL()) && m_frontendHost);
    m_fileHelper->AddFileSystem(type, base::NullCallback());
}

void DevToolsFrontendQt::UpgradeDraggedFileSystemPermissions(const std::string &fileSystemUrl)
{
    CHECK(IsValidFrontendURL(web_contents()->GetLastCommittedURL()) && m_frontendHost);
    m_fileHelper->UpgradeDraggedFileSystemPermissions(fileSystemUrl, base::NullCallback());
}

void DevToolsFrontendQt::RemoveFileSystem(const std::string &fileSystemPath)
{
    CHECK(IsValidFrontendURL(web_contents()->GetLastCommittedURL()) && m_frontendHost);
    m_fileHelper->RemoveFileSystem(fileSystemPath);
}

// DevToolsFileHelper::Delegate implementation
// based on chrome/browser/devtools/devtools_ui_bindings.cc
void DevToolsFrontendQt::FileSystemAdded(const std::string &error,
                                         const DevToolsFileHelper::FileSystem *file_system)
{
    if (file_system) {
        CallClientFunction("DevToolsAPI", "fileSystemAdded", base::Value(error),
                           CreateFileSystemValue(*file_system));
    } else {
        CallClientFunction("DevToolsAPI", "fileSystemAdded", base::Value(error));
    }
}

void DevToolsFrontendQt::FileSystemRemoved(const std::string &file_system_path)
{
    CallClientFunction("DevToolsAPI", "fileSystemRemoved", base::Value(file_system_path));
}

void DevToolsFrontendQt::FilePathsChanged(const std::vector<std::string> &changed_paths,
                                          const std::vector<std::string> &added_paths,
                                          const std::vector<std::string> &removed_paths)
{
    const int kMaxPathsPerMessage = 1000;
    size_t changed_index = 0;
    size_t added_index = 0;
    size_t removed_index = 0;
    // Dispatch limited amount of file paths in a time to avoid
    // IPC max message size limit. See https://crbug.com/797817.
    while (changed_index < changed_paths.size() || added_index < added_paths.size()
           || removed_index < removed_paths.size()) {
        int budget = kMaxPathsPerMessage;
        base::ListValue changed, added, removed;
        while (budget > 0 && changed_index < changed_paths.size()) {
            changed.Append(changed_paths[changed_index++]);
            --budget;
        }
        while (budget > 0 && added_index < added_paths.size()) {
            added.Append(added_paths[added_index++]);
            --budget;
        }
        while (budget > 0 && removed_index < removed_paths.size()) {
            removed.Append(removed_paths[removed_index++]);
            --budget;
        }
        CallClientFunction("DevToolsAPI", "fileSystemFilesChangedAddedRemoved", std::move(changed),
                           std::move(added), std::move(removed));
    }
}

} // namespace QtWebEngineCore