summaryrefslogtreecommitdiffstats
path: root/webkit/support/webkit_support.cc
blob: 51997ececc4706ee7102797575312c3be6e45c9a (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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
// Copyright (c) 2012 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 "webkit/support/webkit_support.h"

#include "base/at_exit.h"
#include "base/base64.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/debug/debugger.h"
#include "base/debug/stack_trace.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/i18n/icu_util.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/run_loop.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/strings/string_piece.h"
#include "base/strings/sys_string_conversions.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "cc/base/thread_impl.h"
#include "googleurl/src/url_util.h"
#include "grit/webkit_chromium_resources.h"
#include "media/base/filter_collection.h"
#include "media/base/media_log.h"
#include "net/base/escape.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebCache.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFileSystemCallbacks.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPluginParams.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "third_party/WebKit/public/platform/WebStorageNamespace.h"
#include "third_party/WebKit/public/platform/WebURLError.h"
#if defined(TOOLKIT_GTK)
#include "ui/base/keycodes/keyboard_code_conversion_gtk.h"
#endif
#include "ui/gl/gl_context.h"
#include "ui/gl/gl_implementation.h"
#include "ui/gl/gl_surface.h"
#include "webkit/base/file_path_string_conversions.h"
#include "webkit/browser/fileapi/isolated_context.h"
#include "webkit/common/gpu/test_context_provider_factory.h"
#include "webkit/common/gpu/webgraphicscontext3d_in_process_command_buffer_impl.h"
#include "webkit/common/user_agent/user_agent.h"
#include "webkit/common/user_agent/user_agent_util.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/webkitplatformsupport_impl.h"
#include "webkit/glue/webthread_impl.h"
#include "webkit/glue/weburlrequest_extradata_impl.h"
#include "webkit/plugins/npapi/plugin_list.h"
#include "webkit/plugins/npapi/webplugin_impl.h"
#include "webkit/plugins/npapi/webplugin_page_delegate.h"
#include "webkit/plugins/webplugininfo.h"
#include "webkit/renderer/appcache/web_application_cache_host_impl.h"
#include "webkit/renderer/compositor_bindings/web_compositor_support_impl.h"
#include "webkit/renderer/media/media_stream_client.h"
#include "webkit/renderer/media/webmediaplayer_impl.h"
#include "webkit/renderer/media/webmediaplayer_ms.h"
#include "webkit/renderer/media/webmediaplayer_params.h"
#include "webkit/support/platform_support.h"
#include "webkit/support/simple_appcache_system.h"
#include "webkit/support/simple_database_system.h"
#include "webkit/support/simple_dom_storage_system.h"
#include "webkit/support/simple_file_system.h"
#include "webkit/support/simple_resource_loader_bridge.h"
#include "webkit/support/test_webkit_platform_support.h"
#include "webkit/support/test_webplugin_page_delegate.h"
#include "webkit/support/web_layer_tree_view_impl_for_testing.h"

#if defined(OS_ANDROID)
#include "base/test/test_support_android.h"
#include "webkit/support/test_stream_texture_factory_android.h"
#endif

using WebKit::WebCString;
using WebKit::WebDevToolsAgentClient;
using WebKit::WebFileSystem;
using WebKit::WebFileSystemCallbacks;
using WebKit::WebFrame;
using WebKit::WebMediaPlayerClient;
using WebKit::WebPlugin;
using WebKit::WebPluginParams;
using WebKit::WebString;
using WebKit::WebURL;

namespace {

// All fatal log messages (e.g. DCHECK failures) imply unit test failures
void UnitTestAssertHandler(const std::string& str) {
  FAIL() << str;
}

void InitLogging() {
#if defined(OS_WIN)
  if (!::IsDebuggerPresent()) {
    UINT new_flags = SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX
        | SEM_NOGPFAULTERRORBOX;

    // Preserve existing error mode, as discussed at
    // http://blogs.msdn.com/oldnewthing/archive/2004/07/27/198410.aspx
    UINT existing_flags = SetErrorMode(new_flags);
    SetErrorMode(existing_flags | new_flags);

    // Don't pop up dialog on assertion failure, log to stdout instead.
    _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT);
  }
#endif

#if defined(OS_ANDROID)
  // On Android we expect the log to appear in logcat.
  base::InitAndroidTestLogging();
#else
  base::FilePath log_filename;
  PathService::Get(base::DIR_EXE, &log_filename);
  log_filename = log_filename.AppendASCII("DumpRenderTree.log");
  logging::InitLogging(
      log_filename.value().c_str(),
      // Only log to a file. This prevents debugging output from disrupting
      // whether or not we pass.
      logging::LOG_ONLY_TO_FILE,
      // We might have multiple DumpRenderTree processes going at once.
      logging::LOCK_LOG_FILE,
      logging::DELETE_OLD_LOG_FILE,
      logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);

  // We want process and thread IDs because we may have multiple processes.
  const bool kProcessId = true;
  const bool kThreadId = true;
  const bool kTimestamp = true;
  const bool kTickcount = true;
  logging::SetLogItems(kProcessId, kThreadId, !kTimestamp, kTickcount);
#endif  // else defined(OS_ANDROID)
}

class TestEnvironment {
 public:
#if defined(OS_ANDROID)
  // Android UI message loop goes through Java, so don't use it in tests.
  typedef base::MessageLoop MessageLoopType;
#else
  typedef base::MessageLoopForUI MessageLoopType;
#endif

  TestEnvironment(bool unit_test_mode,
                  base::AtExitManager* existing_at_exit_manager,
                  WebKit::Platform* shadow_platform_delegate) {
    if (unit_test_mode) {
      logging::SetLogAssertHandler(UnitTestAssertHandler);
    } else {
      // The existing_at_exit_manager must be not NULL.
      at_exit_manager_.reset(existing_at_exit_manager);
      InitLogging();
    }
    main_message_loop_.reset(new MessageLoopType);

    // TestWebKitPlatformSupport must be instantiated after MessageLoopType.
    webkit_platform_support_.reset(
        new TestWebKitPlatformSupport(unit_test_mode,
                                      shadow_platform_delegate));
  }

  ~TestEnvironment() {
    SimpleResourceLoaderBridge::Shutdown();
  }

  TestWebKitPlatformSupport* webkit_platform_support() const {
    return webkit_platform_support_.get();
  }

#if defined(OS_WIN) || defined(OS_MACOSX)
  void set_theme_engine(WebKit::WebThemeEngine* engine) {
    DCHECK(webkit_platform_support_ != 0);
    webkit_platform_support_->SetThemeEngine(engine);
  }

  WebKit::WebThemeEngine* theme_engine() const {
    return webkit_platform_support_->themeEngine();
  }
#endif

#if defined(OS_ANDROID)
  // On Android under layout test mode, we mock the current directory
  // in SetCurrentDirectoryForFileURL() and GetAbsoluteWebStringFromUTF8Path(),
  // as the directory might not exist on the device because we are using
  // file-over-http bridge.
  void set_mock_current_directory(const base::FilePath& directory) {
    mock_current_directory_ = directory;
  }

  base::FilePath mock_current_directory() const {
    return mock_current_directory_;
  }
#endif

  scoped_refptr<base::MessageLoopProxy> GetMediaThreadMessageLoopProxy() {
    if (!media_thread_) {
      media_thread_.reset(new base::Thread("Media"));
      CHECK(media_thread_->Start());
    }
    return media_thread_->message_loop_proxy();
  }

 private:
  // Data member at_exit_manager_ will take the ownership of the input
  // AtExitManager and manage its lifecycle.
  scoped_ptr<base::AtExitManager> at_exit_manager_;
  scoped_ptr<MessageLoopType> main_message_loop_;
  scoped_ptr<TestWebKitPlatformSupport> webkit_platform_support_;

  scoped_ptr<base::Thread> media_thread_;

#if defined(OS_ANDROID)
  base::FilePath mock_current_directory_;
#endif
};

class WebPluginImplWithPageDelegate
    : public webkit_support::TestWebPluginPageDelegate,
      public base::SupportsWeakPtr<WebPluginImplWithPageDelegate>,
      public webkit::npapi::WebPluginImpl {
 public:
  WebPluginImplWithPageDelegate(WebFrame* frame,
                                const WebPluginParams& params,
                                const base::FilePath& path)
      : webkit_support::TestWebPluginPageDelegate(),
        webkit::npapi::WebPluginImpl(frame, params, path, AsWeakPtr()) {}
  virtual ~WebPluginImplWithPageDelegate() {}
 private:
  DISALLOW_COPY_AND_ASSIGN(WebPluginImplWithPageDelegate);
};

base::FilePath GetWebKitRootDirFilePath() {
  base::FilePath basePath;
  PathService::Get(base::DIR_SOURCE_ROOT, &basePath);
  if (file_util::PathExists(
          basePath.Append(FILE_PATH_LITERAL("third_party/WebKit")))) {
    // We're in a WebKit-in-chrome checkout.
    basePath = basePath.Append(FILE_PATH_LITERAL("third_party/WebKit"));
  } else if (file_util::PathExists(
          basePath.Append(FILE_PATH_LITERAL("chromium")))) {
    // We're in a WebKit-only checkout on Windows.
    basePath = basePath.Append(FILE_PATH_LITERAL("../.."));
  } else if (file_util::PathExists(
          basePath.Append(FILE_PATH_LITERAL("webkit/support")))) {
    // We're in a WebKit-only/xcodebuild checkout on Mac
    basePath = basePath.Append(FILE_PATH_LITERAL("../../.."));
  }
  basePath = base::MakeAbsoluteFilePath(basePath);
  CHECK(!basePath.empty());
  // We're in a WebKit-only, make-build, so the DIR_SOURCE_ROOT is already the
  // WebKit root. That, or we have no idea where we are.
  return basePath;
}

class WebKitClientMessageLoopImpl
    : public WebDevToolsAgentClient::WebKitClientMessageLoop {
 public:
  WebKitClientMessageLoopImpl() : message_loop_(base::MessageLoop::current()) {}
  virtual ~WebKitClientMessageLoopImpl() { message_loop_ = NULL; }
  virtual void run() {
    base::MessageLoop::ScopedNestableTaskAllower allow(message_loop_);
    message_loop_->Run();
  }
  virtual void quitNow() {
    message_loop_->QuitNow();
  }
 private:
  base::MessageLoop* message_loop_;
};

TestEnvironment* test_environment;

void SetUpTestEnvironmentImpl(bool unit_test_mode,
                              WebKit::Platform* shadow_platform_delegate) {
  base::debug::EnableInProcessStackDumping();
  base::EnableTerminationOnHeapCorruption();

  // Initialize the singleton CommandLine with fixed values.  Some code refer to
  // CommandLine::ForCurrentProcess().  We don't use the actual command-line
  // arguments of DRT to avoid unexpected behavior change.
  //
  // webkit/glue/plugin/plugin_list_posix.cc checks --debug-plugin-loading.
  // webkit/glue/plugin/plugin_list_win.cc checks --old-wmp.
  // If DRT needs these flags, specify them in the following kFixedArguments.
  const char* kFixedArguments[] = {"DumpRenderTree"};
  CommandLine::Init(arraysize(kFixedArguments), kFixedArguments);

  // Explicitly initialize the GURL library before spawning any threads.
  // Otherwise crash may happend when different threads try to create a GURL
  // at same time.
  url_util::Initialize();
  base::AtExitManager* at_exit_manager = NULL;
  // In Android DumpRenderTree, AtExitManager is created in
  // testing/android/native_test_wrapper.cc before main() is called.
#if !defined(OS_ANDROID)
  // Some initialization code may use a AtExitManager before initializing
  // TestEnvironment, so we create a AtExitManager early and pass its ownership
  // to TestEnvironment.
  if (!unit_test_mode)
    at_exit_manager = new base::AtExitManager;
#endif
  webkit_support::BeforeInitialize(unit_test_mode);
  test_environment = new TestEnvironment(unit_test_mode, at_exit_manager,
                                         shadow_platform_delegate);
  webkit_support::AfterInitialize(unit_test_mode);
  if (!unit_test_mode) {
    // Load ICU data tables.  This has to run after TestEnvironment is created
    // because on Linux, we need base::AtExitManager.
    icu_util::Initialize();
  }
  webkit_glue::SetUserAgent(webkit_glue::BuildUserAgentFromProduct(
      "DumpRenderTree/0.0.0.0"), false);
}

}  // namespace

namespace webkit_support {

base::FilePath GetChromiumRootDirFilePath() {
  base::FilePath basePath;
  PathService::Get(base::DIR_SOURCE_ROOT, &basePath);
  if (file_util::PathExists(
          basePath.Append(FILE_PATH_LITERAL("third_party/WebKit")))) {
    // We're in a WebKit-in-chrome checkout.
    return basePath;
  }
  return GetWebKitRootDirFilePath()
         .Append(FILE_PATH_LITERAL("Source/WebKit/chromium"));
}

void SetUpTestEnvironment() {
  SetUpTestEnvironment(NULL);
}

void SetUpTestEnvironmentForUnitTests() {
  SetUpTestEnvironmentForUnitTests(NULL);
}

void SetUpTestEnvironment(WebKit::Platform* shadow_platform_delegate) {
  SetUpTestEnvironmentImpl(false, shadow_platform_delegate);
}

void SetUpTestEnvironmentForUnitTests(
    WebKit::Platform* shadow_platform_delegate) {
  SetUpTestEnvironmentImpl(true, shadow_platform_delegate);
}

void TearDownTestEnvironment() {
  // Flush any remaining messages before we kill ourselves.
  // http://code.google.com/p/chromium/issues/detail?id=9500
  base::RunLoop().RunUntilIdle();

  BeforeShutdown();
  if (RunningOnValgrind())
    WebKit::WebCache::clear();
  WebKit::shutdown();
  delete test_environment;
  test_environment = NULL;
  AfterShutdown();
  logging::CloseLogFile();
}

WebKit::Platform* GetWebKitPlatformSupport() {
  DCHECK(test_environment);
  return test_environment->webkit_platform_support();
}

WebPlugin* CreateWebPlugin(WebFrame* frame,
                           const WebPluginParams& params) {
  const bool kAllowWildcard = true;
  std::vector<webkit::WebPluginInfo> plugins;
  std::vector<std::string> mime_types;
  webkit::npapi::PluginList::Singleton()->GetPluginInfoArray(
      params.url, params.mimeType.utf8(), kAllowWildcard,
      NULL, &plugins, &mime_types);
  if (plugins.empty())
    return NULL;

  WebPluginParams new_params = params;
  new_params.mimeType = WebString::fromUTF8(mime_types.front());
  return new WebPluginImplWithPageDelegate(
      frame, new_params, plugins.front().path);
}

WebKit::WebMediaPlayer* CreateMediaPlayer(
    WebFrame* frame,
    const WebURL& url,
    WebMediaPlayerClient* client,
    webkit_media::MediaStreamClient* media_stream_client) {
  if (media_stream_client && media_stream_client->IsMediaStream(url)) {
    return new webkit_media::WebMediaPlayerMS(
        frame,
        client,
        base::WeakPtr<webkit_media::WebMediaPlayerDelegate>(),
        media_stream_client,
        new media::MediaLog());
  }

#if defined(OS_ANDROID)
  return NULL;
#else
  webkit_media::WebMediaPlayerParams params(
      test_environment->GetMediaThreadMessageLoopProxy(),
      NULL, NULL, new media::MediaLog());
  return new webkit_media::WebMediaPlayerImpl(
      frame,
      client,
      base::WeakPtr<webkit_media::WebMediaPlayerDelegate>(),
      params);
#endif
}

WebKit::WebMediaPlayer* CreateMediaPlayer(
    WebFrame* frame,
    const WebURL& url,
    WebMediaPlayerClient* client) {
  return CreateMediaPlayer(frame, url, client, NULL);
}

WebKit::WebApplicationCacheHost* CreateApplicationCacheHost(
    WebFrame*, WebKit::WebApplicationCacheHostClient* client) {
  return SimpleAppCacheSystem::CreateApplicationCacheHost(client);
}

WebKit::WebStorageNamespace* CreateSessionStorageNamespace(unsigned quota) {
  return SimpleDomStorageSystem::instance().CreateSessionStorageNamespace();
}

WebKit::WebString GetWebKitRootDir() {
  base::FilePath path = GetWebKitRootDirFilePath();
  std::string path_ascii = path.MaybeAsASCII();
  CHECK(!path_ascii.empty());
  return WebKit::WebString::fromUTF8(path_ascii.c_str());
}

void SetUpGLBindings(GLBindingPreferences bindingPref) {
  switch (bindingPref) {
    case GL_BINDING_DEFAULT:
      gfx::GLSurface::InitializeOneOff();
      break;
    case GL_BINDING_SOFTWARE_RENDERER:
      gfx::InitializeGLBindings(gfx::kGLImplementationOSMesaGL);
      break;
    default:
      NOTREACHED();
  }
}

WebKit::WebLayerTreeView* CreateLayerTreeView(
    LayerTreeViewType type,
    DRTLayerTreeViewClient* client,
    WebKit::WebThread* thread) {
  scoped_ptr<cc::Thread> compositor_thread;
  if (thread)
    compositor_thread = cc::ThreadImpl::CreateForDifferentThread(
        static_cast<webkit_glue::WebThreadImpl*>(thread)->
        message_loop()->message_loop_proxy());

  scoped_ptr<webkit::WebLayerTreeViewImplForTesting> view(
      new webkit::WebLayerTreeViewImplForTesting(type, client));

  if (!view->Initialize(compositor_thread.Pass()))
    return NULL;
  return view.release();
}

void SetThreadedCompositorEnabled(bool enabled) {
  test_environment->webkit_platform_support()->
      set_threaded_compositing_enabled(enabled);
}

void RegisterMockedURL(const WebKit::WebURL& url,
                     const WebKit::WebURLResponse& response,
                     const WebKit::WebString& file_path) {
  test_environment->webkit_platform_support()->url_loader_factory()->
      RegisterURL(url, response, file_path);
}

void RegisterMockedErrorURL(const WebKit::WebURL& url,
                            const WebKit::WebURLResponse& response,
                            const WebKit::WebURLError& error) {
  test_environment->webkit_platform_support()->url_loader_factory()->
      RegisterErrorURL(url, response, error);
}

void UnregisterMockedURL(const WebKit::WebURL& url) {
  test_environment->webkit_platform_support()->url_loader_factory()->
    UnregisterURL(url);
}

void UnregisterAllMockedURLs() {
  test_environment->webkit_platform_support()->url_loader_factory()->
    UnregisterAllURLs();
}

void ServeAsynchronousMockedRequests() {
  test_environment->webkit_platform_support()->url_loader_factory()->
      ServeAsynchronousRequests();
}

WebKit::WebURLRequest GetLastHandledAsynchronousMockedRequest() {
  return test_environment->webkit_platform_support()->url_loader_factory()->
      GetLastHandledAsynchronousRequest();
}

// Wrapper for debug_util
bool BeingDebugged() {
  return base::debug::BeingDebugged();
}

// Wrappers for MessageLoop

void RunMessageLoop() {
  base::MessageLoop::current()->Run();
}

void QuitMessageLoop() {
  base::MessageLoop::current()->Quit();
}

void QuitMessageLoopNow() {
  base::MessageLoop::current()->QuitNow();
}

void RunAllPendingMessages() {
  base::RunLoop().RunUntilIdle();
}

bool MessageLoopNestableTasksAllowed() {
  return base::MessageLoop::current()->NestableTasksAllowed();
}

void MessageLoopSetNestableTasksAllowed(bool allowed) {
  base::MessageLoop::current()->SetNestableTasksAllowed(allowed);
}

void DispatchMessageLoop() {
  base::MessageLoop* current = base::MessageLoop::current();
  base::MessageLoop::ScopedNestableTaskAllower allow(current);
  base::RunLoop().RunUntilIdle();
}

WebDevToolsAgentClient::WebKitClientMessageLoop* CreateDevToolsMessageLoop() {
  return new WebKitClientMessageLoopImpl();
}

void PostDelayedTask(void (*func)(void*), void* context, int64 delay_ms) {
  base::MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(func, context),
      base::TimeDelta::FromMilliseconds(delay_ms));
}

void PostDelayedTask(TaskAdaptor* task, int64 delay_ms) {
  base::MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&TaskAdaptor::Run, base::Owned(task)),
      base::TimeDelta::FromMilliseconds(delay_ms));
}

// Wrappers for FilePath and file_util

WebString GetAbsoluteWebStringFromUTF8Path(const std::string& utf8_path) {
  // WebKit is happy with a relative path if the absolute path doesn't exist,
  // so we need to check the result of MakeAbsoluteFilePath().
#if defined(OS_WIN)
  base::FilePath orig_path(UTF8ToWide(utf8_path));
  base::FilePath path = base::MakeAbsoluteFilePath(orig_path);
  return WebString(path.empty() ? orig_path.value() : path.value());
#else
  base::FilePath orig_path(
      base::SysWideToNativeMB(base::SysUTF8ToWide(utf8_path)));
  base::FilePath path;
#if defined(OS_ANDROID)
  if (WebKit::layoutTestMode()) {
    // See comment of TestEnvironment::set_mock_current_directory().
    if (!orig_path.IsAbsolute()) {
      // Not using FilePath::Append() because it can't handle '..' in orig_path.
      DCHECK(test_environment);
      GURL base_url = net::FilePathToFileURL(
          test_environment->mock_current_directory()
              .Append(FILE_PATH_LITERAL("foo")));
      net::FileURLToFilePath(base_url.Resolve(orig_path.value()), &path);
    }
  } else {
    path = base::MakeAbsoluteFilePath(orig_path);
    if (path.empty())
      path = orig_path;
  }
#else
  path = base::MakeAbsoluteFilePath(orig_path);
  if (path.empty())
    path = orig_path;
#endif  // else defined(OS_ANDROID)
  return WideToUTF16(base::SysNativeMBToWide(path.value()));
#endif  // else defined(OS_WIN)
}

WebURL CreateURLForPathOrURL(const std::string& path_or_url_in_nativemb) {
  // NativeMB to UTF-8
  std::wstring wide_path_or_url
      = base::SysNativeMBToWide(path_or_url_in_nativemb);
  std::string path_or_url_in_utf8 = WideToUTF8(wide_path_or_url);

  GURL url(path_or_url_in_utf8);
  if (url.is_valid() && url.has_scheme())
    return WebURL(url);
#if defined(OS_WIN)
  base::FilePath path(wide_path_or_url);
#else
  base::FilePath path(path_or_url_in_nativemb);
#endif
  return net::FilePathToFileURL(base::MakeAbsoluteFilePath(path));
}

WebURL RewriteLayoutTestsURL(const std::string& utf8_url) {
  const char kPrefix[] = "file:///tmp/LayoutTests/";
  const int kPrefixLen = arraysize(kPrefix) - 1;

  if (utf8_url.compare(0, kPrefixLen, kPrefix, kPrefixLen))
    return WebURL(GURL(utf8_url));

  base::FilePath replacePath =
      GetWebKitRootDirFilePath().Append(FILE_PATH_LITERAL("LayoutTests/"));

  // On Android, the file is actually accessed through file-over-http. Disable
  // the following CHECK because the file is unlikely to exist on the device.
#if !defined(OS_ANDROID)
  CHECK(file_util::PathExists(replacePath)) << replacePath.value() <<
      " (re-written from " << utf8_url << ") does not exit";
#endif

#if defined(OS_WIN)
  std::string utf8_path = WideToUTF8(replacePath.value());
#else
  std::string utf8_path
      = WideToUTF8(base::SysNativeMBToWide(replacePath.value()));
#endif
  std::string newUrl = std::string("file://") + utf8_path
      + utf8_url.substr(kPrefixLen);
  return WebURL(GURL(newUrl));
}

bool SetCurrentDirectoryForFileURL(const WebKit::WebURL& fileUrl) {
  base::FilePath local_path;
  if (!net::FileURLToFilePath(fileUrl, &local_path))
    return false;
#if defined(OS_ANDROID)
  if (WebKit::layoutTestMode()) {
    // See comment of TestEnvironment::set_mock_current_directory().
    DCHECK(test_environment);
    base::FilePath directory = local_path.DirName();
    test_environment->set_mock_current_directory(directory);
    // Still try to actually change the directory, but ignore any error.
    // For a few tests that need to access resources directly as files
    // (e.g. blob tests) we still push the resources and need to chdir there.
    file_util::SetCurrentDirectory(directory);
    return true;
  }
#endif
  return file_util::SetCurrentDirectory(local_path.DirName());
}

WebURL LocalFileToDataURL(const WebURL& fileUrl) {
  base::FilePath local_path;
  if (!net::FileURLToFilePath(fileUrl, &local_path))
    return WebURL();

  std::string contents;
  if (!file_util::ReadFileToString(local_path, &contents))
    return WebURL();

  std::string contents_base64;
  if (!base::Base64Encode(contents, &contents_base64))
    return WebURL();

  const char kDataUrlPrefix[] = "data:text/css;charset=utf-8;base64,";
  return WebURL(GURL(kDataUrlPrefix + contents_base64));
}

// A wrapper object for exporting base::ScopedTempDir to be used
// by webkit layout tests.
class ScopedTempDirectoryInternal : public ScopedTempDirectory {
 public:
  virtual bool CreateUniqueTempDir() OVERRIDE {
    return tempDirectory_.CreateUniqueTempDir();
  }

  virtual std::string path() const OVERRIDE {
    return tempDirectory_.path().MaybeAsASCII();
  }

 private:
  base::ScopedTempDir tempDirectory_;
};

ScopedTempDirectory* CreateScopedTempDirectory() {
  return new ScopedTempDirectoryInternal();
}

int64 GetCurrentTimeInMillisecond() {
  return base::TimeDelta(base::Time::Now() -
                         base::Time::UnixEpoch()).ToInternalValue() /
         base::Time::kMicrosecondsPerMillisecond;
}

std::string EscapePath(const std::string& path) {
  return net::EscapePath(path);
}

std::string MakeURLErrorDescription(const WebKit::WebURLError& error) {
  std::string domain = error.domain.utf8();
  int code = error.reason;

  if (domain == net::kErrorDomain) {
    domain = "NSURLErrorDomain";
    switch (error.reason) {
    case net::ERR_ABORTED:
      code = -999;  // NSURLErrorCancelled
      break;
    case net::ERR_UNSAFE_PORT:
      // Our unsafe port checking happens at the network stack level, but we
      // make this translation here to match the behavior of stock WebKit.
      domain = "WebKitErrorDomain";
      code = 103;
      break;
    case net::ERR_ADDRESS_INVALID:
    case net::ERR_ADDRESS_UNREACHABLE:
    case net::ERR_NETWORK_ACCESS_DENIED:
      code = -1004;  // NSURLErrorCannotConnectToHost
      break;
    }
  } else {
    DLOG(WARNING) << "Unknown error domain";
  }

  return base::StringPrintf("<NSError domain %s, code %d, failing URL \"%s\">",
      domain.c_str(), code, error.unreachableURL.spec().data());
}

WebKit::WebURLError CreateCancelledError(const WebKit::WebURLRequest& request) {
  WebKit::WebURLError error;
  error.domain = WebKit::WebString::fromUTF8(net::kErrorDomain);
  error.reason = net::ERR_ABORTED;
  error.unreachableURL = request.url();
  return error;
}

WebKit::WebURLRequest::ExtraData* CreateWebURLRequestExtraData(
    WebKit::WebReferrerPolicy referrer_policy) {
  return new webkit_glue::WebURLRequestExtraDataImpl(referrer_policy,
                                                     WebKit::WebString());
}

// Bridge for SimpleDatabaseSystem

void SetDatabaseQuota(int quota) {
  SimpleDatabaseSystem::GetInstance()->SetDatabaseQuota(quota);
}

void ClearAllDatabases() {
  SimpleDatabaseSystem::GetInstance()->ClearAllDatabases();
}

// Bridge for SimpleResourceLoaderBridge

void SetAcceptAllCookies(bool accept) {
  SimpleResourceLoaderBridge::SetAcceptAllCookies(accept);
}

// Theme engine
#if defined(OS_WIN) || defined(OS_MACOSX)

void SetThemeEngine(WebKit::WebThemeEngine* engine) {
  DCHECK(test_environment);
  test_environment->set_theme_engine(engine);
}

WebKit::WebThemeEngine* GetThemeEngine() {
  DCHECK(test_environment);
  return test_environment->theme_engine();
}

#endif

// DevTools frontend path for inspector LayoutTests.
WebURL GetDevToolsPathAsURL() {
  base::FilePath dirExe;
  if (!PathService::Get(base::DIR_EXE, &dirExe)) {
      DCHECK(false);
      return WebURL();
  }
#if defined(OS_MACOSX)
  dirExe = dirExe.AppendASCII("../../..");
#endif
  base::FilePath devToolsPath = dirExe.AppendASCII(
      "resources/inspector/devtools.html");
  return net::FilePathToFileURL(devToolsPath);
}

// FileSystem
void OpenFileSystem(WebFrame* frame,
    WebKit::WebFileSystemType type,
    long long size, bool create, WebFileSystemCallbacks* callbacks) {
  SimpleFileSystem* fileSystem = static_cast<SimpleFileSystem*>(
      test_environment->webkit_platform_support()->fileSystem());
  fileSystem->OpenFileSystem(frame, type, size, create, callbacks);
}

void DeleteFileSystem(WebFrame* frame,
                      WebKit::WebFileSystemType type,
                      WebFileSystemCallbacks* callbacks) {
  SimpleFileSystem* fileSystem = static_cast<SimpleFileSystem*>(
      test_environment->webkit_platform_support()->fileSystem());
  fileSystem->DeleteFileSystem(frame, type, callbacks);
}

WebKit::WebString RegisterIsolatedFileSystem(
    const WebKit::WebVector<WebKit::WebString>& filenames) {
  fileapi::IsolatedContext::FileInfoSet files;
  for (size_t i = 0; i < filenames.size(); ++i) {
    base::FilePath path = webkit_base::WebStringToFilePath(filenames[i]);
    files.AddPath(path, NULL);
  }
  std::string filesystemId =
      fileapi::IsolatedContext::GetInstance()->RegisterDraggedFileSystem(files);
  return UTF8ToUTF16(filesystemId);
}

// Keyboard code
#if defined(TOOLKIT_GTK)
int NativeKeyCodeForWindowsKeyCode(int keycode, bool shift) {
  ui::KeyboardCode code = static_cast<ui::KeyboardCode>(keycode);
  return ui::GdkNativeKeyCodeForWindowsKeyCode(code, shift);
}
#endif

// Logging
void EnableWebCoreLogChannels(const std::string& channels) {
  webkit_glue::EnableWebCoreLogChannels(channels);
}

void SetGamepadData(const WebKit::WebGamepads& pads) {
  test_environment->webkit_platform_support()->setGamepadData(pads);
}

}  // namespace webkit_support