diff --git a/.gitignore b/.gitignore index 2831dd298f80b..c495fce1e1be6 100644 --- a/.gitignore +++ b/.gitignore @@ -302,3 +302,5 @@ vs-chromium-project.txt /win8/metro_driver/metro_driver_version_resources.xml /x86-generic_out/ /xcodebuild +/content/nw + diff --git a/BUILD.gn b/BUILD.gn index 94297185edddf..54656cd9781be 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -94,6 +94,7 @@ group("gn_all") { if (!is_ios && !is_android && !is_chromecast && !is_fuchsia) { deps += [ + "//content/nw:nwjs", "//chrome", "//chrome/test:browser_tests", "//chrome/test:interactive_ui_tests", diff --git a/DEPS b/DEPS index eb3d9ca3828ba..53a5165a80ac8 100644 --- a/DEPS +++ b/DEPS @@ -17,6 +17,8 @@ vars = { '6226d6cd80aaf2e5295ed460cf73ef6a582e4d78', 'freetype_revision': '7819aeb622a94be0d89caf8382f290d0266c4aed', + 'nwjs_git': + 'https://github.com/nwjs', 'google_toolbox_for_mac_revision': '038a2399b20e67ab17685e23ee873a66811fa107', 'libfuzzer_revision': @@ -183,8 +185,13 @@ deps = { (Var("chromium_git")) + '/chromium/deps/acid3.git@6be0a66a1ebd7ebc5abc1b2f405a945f6d871521', 'src/tools/swarming_client': (Var("chromium_git")) + '/external/swarming.client.git@a941a089ff1000403078b74cb628eb430f07d271', - 'src/v8': - (Var("chromium_git")) + '/v8/v8.git@7e9b79ac823001bdd0966adb7c2ac8630d4f5e9b' + #'src/v8': + # (Var("chromium_git")) + '/v8/v8.git@7e9b79ac823001bdd0966adb7c2ac8630d4f5e9b' + # (Var("nwjs_git")) + '/v8.git@origin/nw16', + #'src/content/nw': + # (Var("nwjs_git")) + '/nw.js.git@origin/nw16', + #'src/third_party/node': + # (Var("nwjs_git")) + '/node.git@origin/nw16', } deps_os = { @@ -690,6 +697,17 @@ hooks = [ 'name': 'wasm_asmjs_fuzzer' }, + { + 'action': [ + 'python', + 'src/content/nw/tools/patcher.py', + '--patch-config', 'src/content/nw/patch/patch.cfg' + ], + 'pattern': + '.', + 'name': + 'nw_patch' + }, { 'action': [ 'python', diff --git a/apps/app_lifetime_monitor.cc b/apps/app_lifetime_monitor.cc index 0e2169e2fc628..532f79df0b3fd 100644 --- a/apps/app_lifetime_monitor.cc +++ b/apps/app_lifetime_monitor.cc @@ -77,8 +77,10 @@ void AppLifetimeMonitor::OnAppWindowRemoved(AppWindow* app_window) { } void AppLifetimeMonitor::OnAppWindowHidden(AppWindow* app_window) { +#if 0 if (!HasOtherVisibleAppWindows(app_window)) NotifyAppDeactivated(app_window->extension_id()); +#endif } void AppLifetimeMonitor::OnAppWindowShown(AppWindow* app_window, diff --git a/apps/launcher.cc b/apps/launcher.cc index d1925112dd938..fb50a14125999 100644 --- a/apps/launcher.cc +++ b/apps/launcher.cc @@ -101,7 +101,10 @@ class PlatformAppPathLauncher extension_id(app->id()), entry_paths_(entry_paths), mime_type_collector_(context), - is_directory_collector_(context) {} + is_directory_collector_(context) { + if (app->is_nwjs_app()) //NWJS#5097 + entry_paths_.clear(); + } PlatformAppPathLauncher(content::BrowserContext* context, const Extension* app, @@ -110,7 +113,7 @@ class PlatformAppPathLauncher extension_id(app->id()), mime_type_collector_(context), is_directory_collector_(context) { - if (!file_path.empty()) + if (!file_path.empty() && !app->is_nwjs_app()) //NWJS#5097 entry_paths_.push_back(file_path); } diff --git a/base/BUILD.gn b/base/BUILD.gn index 19fe0bc0f6ce6..f13c5e4d097df 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn @@ -539,6 +539,8 @@ component("base") { "message_loop/message_pump_libevent.h", "message_loop/message_pump_mac.h", "message_loop/message_pump_mac.mm", + "message_loop/message_pump_uv.cc", + "message_loop/message_pump_uv.h", "message_loop/message_pump_win.cc", "message_loop/message_pump_win.h", "message_loop/timer_slack.h", diff --git a/base/base_switches.cc b/base/base_switches.cc index daa05c2eb86c4..6a373ea75aea2 100644 --- a/base/base_switches.cc +++ b/base/base_switches.cc @@ -121,4 +121,5 @@ const char kEnableCrashReporterForTesting[] = "enable-crash-reporter-for-testing"; #endif +const char kNWJS[] = "nwjs"; } // namespace switches diff --git a/base/base_switches.h b/base/base_switches.h index 8ba05a68e44d0..803f04c0e714b 100644 --- a/base/base_switches.h +++ b/base/base_switches.h @@ -41,6 +41,7 @@ extern const char kDisableUsbKeyboardDetect[]; extern const char kEnableCrashReporterForTesting[]; #endif +extern const char kNWJS[]; } // namespace switches #endif // BASE_BASE_SWITCHES_H_ diff --git a/base/command_line.cc b/base/command_line.cc index 873da81348365..81787129c7a77 100644 --- a/base/command_line.cc +++ b/base/command_line.cc @@ -152,43 +152,84 @@ string16 QuoteForCommandLineToArgvW(const string16& arg, CommandLine::CommandLine(NoProgram no_program) : argv_(1), - begin_args_(1) { + begin_args_(1), + argc0_(0), argv0_(NULL) { } CommandLine::CommandLine(const FilePath& program) : argv_(1), - begin_args_(1) { + begin_args_(1), + argc0_(0), argv0_(NULL) { SetProgram(program); } CommandLine::CommandLine(int argc, const CommandLine::CharType* const* argv) : argv_(1), - begin_args_(1) { + begin_args_(1), + argc0_(0), argv0_(NULL) { InitFromArgv(argc, argv); } CommandLine::CommandLine(const StringVector& argv) : argv_(1), - begin_args_(1) { + begin_args_(1), + argc0_(0), argv0_(NULL) { InitFromArgv(argv); } CommandLine::CommandLine(const CommandLine& other) : argv_(other.argv_), + original_argv_(other.original_argv_), switches_(other.switches_), - begin_args_(other.begin_args_) { + begin_args_(other.begin_args_), + argc0_(other.argc0_), argv0_(NULL) { + +#if defined(OS_WIN) + if (other.argv0_) { + argv0_ = new char*[argc0_ + 1]; + for (int i = 0; i < argc0_; ++i) { + argv0_[i] = new char[strlen(other.argv0_[i]) + 1]; + strcpy(argv0_[i], other.argv0_[i]); + } + argv0_[argc0_] = NULL; + } +#else + argv0_ = other.argv0_; +#endif ResetStringPieces(); } CommandLine& CommandLine::operator=(const CommandLine& other) { argv_ = other.argv_; + original_argv_ = other.original_argv_; switches_ = other.switches_; begin_args_ = other.begin_args_; +#if defined(OS_WIN) + if (other.argv0_) { + argc0_ = other.argc0_; + argv0_ = new char*[argc0_ + 1]; + for (int i = 0; i < argc0_; ++i) { + argv0_[i] = new char[strlen(other.argv0_[i]) + 1]; + strcpy(argv0_[i], other.argv0_[i]); + } + argv0_[argc0_] = NULL; + } +#else + argv0_ = other.argv0_; +#endif ResetStringPieces(); return *this; } CommandLine::~CommandLine() { +#if defined(OS_WIN) + if (!argv0_) + return; + for (int i = 0; i < argc0_; i++) { + delete[] argv0_[i]; + } + delete[] argv0_; +#endif } #if defined(OS_WIN) @@ -260,12 +301,34 @@ CommandLine CommandLine::FromString(const string16& command_line) { void CommandLine::InitFromArgv(int argc, const CommandLine::CharType* const* argv) { StringVector new_argv; + argc0_ = argc; +#if !defined(OS_WIN) + argv0_ = (char**)argv; +#else + argv0_ = new char*[argc + 1]; + for (int i = 0; i < argc; ++i) { + std::string str(base::WideToUTF8(argv[i])); + argv0_[i] = new char[str.length() + 1]; + strcpy(argv0_[i], str.c_str()); + } + argv0_[argc] = NULL; +#endif for (int i = 0; i < argc; ++i) new_argv.push_back(argv[i]); InitFromArgv(new_argv); } void CommandLine::InitFromArgv(const StringVector& argv) { +#if !defined(OS_MACOSX) + original_argv_ = argv; +#else + for (size_t index = 0; index < argv.size(); ++index) { + if (argv[index].compare(0, strlen("--psn_"), "--psn_") != 0 && + argv[index].compare(0, strlen("-psn_"), "-psn_") != 0) { + original_argv_.push_back(argv[index]); + } + } +#endif argv_ = StringVector(1); switches_.clear(); switches_by_stringpiece_.clear(); @@ -402,6 +465,12 @@ void CommandLine::AppendArgNative(const CommandLine::StringType& value) { argv_.push_back(value); } +#if defined(OS_MACOSX) +void CommandLine::FixOrigArgv4Finder(const CommandLine::StringType& value) { + original_argv_.push_back(value); +} +#endif + void CommandLine::AppendArguments(const CommandLine& other, bool include_program) { if (include_program) diff --git a/base/command_line.h b/base/command_line.h index 3d29f8fee7fbb..f72a7139d5a6f 100644 --- a/base/command_line.h +++ b/base/command_line.h @@ -150,6 +150,11 @@ class BASE_EXPORT CommandLine { // Returns the original command line string as a vector of strings. const StringVector& argv() const { return argv_; } + int argc0() { return argc0_; } + char** argv0() { return argv0_; } + + // Returns the original command line string as a vector of strings (keeps precedence). + const StringVector& original_argv() const { return original_argv_; } // Get and Set the program part of the command line string (the first item). FilePath GetProgram() const; @@ -200,6 +205,10 @@ class BASE_EXPORT CommandLine { void AppendArgPath(const FilePath& value); void AppendArgNative(const StringType& value); +#if defined(OS_MACOSX) + void FixOrigArgv4Finder(const StringType& value); +#endif + // Append the switches and arguments from another command line to this one. // If |include_program| is true, include |other|'s program as well. void AppendArguments(const CommandLine& other, bool include_program); @@ -241,6 +250,9 @@ class BASE_EXPORT CommandLine { // The argv array: { program, [(--|-|/)switch[=value]]*, [--], [argument]* } StringVector argv_; + // The argv array (precedence not messed). + StringVector original_argv_; + // Parsed-out switch keys and values. SwitchMap switches_; @@ -252,6 +264,9 @@ class BASE_EXPORT CommandLine { // The index after the program and switches, any arguments start here. size_t begin_args_; + + int argc0_; + char** argv0_; }; } // namespace base diff --git a/base/files/file_util_posix.cc b/base/files/file_util_posix.cc index 7efac54e5303b..8a51a9b899331 100644 --- a/base/files/file_util_posix.cc +++ b/base/files/file_util_posix.cc @@ -133,7 +133,7 @@ std::string TempFileName() { #if defined(GOOGLE_CHROME_BUILD) return std::string(".com.google.Chrome.XXXXXX"); #else - return std::string(".org.chromium.Chromium.XXXXXX"); + return std::string(".io.nwjs.XXXXXX"); #endif } diff --git a/base/message_loop/message_loop.cc b/base/message_loop/message_loop.cc index d72602babf6e8..d9c186f23052a 100644 --- a/base/message_loop/message_loop.cc +++ b/base/message_loop/message_loop.cc @@ -202,6 +202,9 @@ std::unique_ptr MessageLoop::CreateMessagePumpForType(Type type) { return std::unique_ptr(new MessagePumpForUI()); #endif + if (type == MessageLoop::TYPE_NODE) + return std::unique_ptr(new MessagePumpUV()); + DCHECK_EQ(MessageLoop::TYPE_DEFAULT, type); return MESSAGE_PUMP_DEFAULT; } diff --git a/base/message_loop/message_loop.h b/base/message_loop/message_loop.h index fa25e78f6d38d..97c89bb38de88 100644 --- a/base/message_loop/message_loop.h +++ b/base/message_loop/message_loop.h @@ -45,6 +45,8 @@ class JavaMessageHandlerFactory; } // namespace base #endif // defined(OS_ANDROID) +#include "base/message_loop/message_pump_uv.h" + namespace base { class ThreadTaskRunnerHandle; @@ -107,6 +109,9 @@ class BASE_EXPORT MessageLoop : public MessagePump::Delegate, // TYPE_CUSTOM // MessagePump was supplied to constructor. // + // TYPE_NODE + // For integration with NodeJS/libuv in the renderer thread + enum Type { TYPE_DEFAULT, TYPE_UI, @@ -114,7 +119,8 @@ class BASE_EXPORT MessageLoop : public MessagePump::Delegate, TYPE_IO, #if defined(OS_ANDROID) TYPE_JAVA, -#endif // defined(OS_ANDROID) +#endif // defined(OS_ANDROID) + TYPE_NODE }; // Normally, it is not necessary to instantiate a MessageLoop. Instead, it @@ -594,6 +600,43 @@ class BASE_EXPORT MessageLoopForIO : public MessageLoop { static_assert(sizeof(MessageLoop) == sizeof(MessageLoopForIO), "MessageLoopForIO should not have extra member variables"); +#if !defined(OS_MACOSX) + +//----------------------------------------------------------------------------- +// MessageLoopForUV extends MessageLoop with methods that are particular to a +// MessageLoop instantiated with TYPE_NODE. +// +// This class is typically used like so: +// MessageLoopForUV::current()->...call some method... +// + +class BASE_EXPORT MessageLoopForUV : public MessageLoop { + public: + + MessageLoopForUV() : MessageLoop(TYPE_NODE) { + } + + // Returns the MessageLoopForUV of the current thread. + static MessageLoopForUV* current() { + MessageLoop* loop = MessageLoop::current(); + //DCHECK_EQ(MessageLoop::TYPE_NODE, loop->type()); + return static_cast(loop); + } + + base::MessagePumpUV* pump_uv() { + return static_cast(pump_.get()); + } + +}; + +// Do not add any member variables to MessageLoopForUV! This is important b/c +// MessageLoopForUV is often allocated via MessageLoop(TYPE_IO). Any extra +// data that you need should be stored on the MessageLoop's pump_ instance. +static_assert(sizeof(MessageLoop) == sizeof(MessageLoopForUV), + "MessageLoopForUV should not have extra member variables"); + +#endif + } // namespace base #endif // BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_ diff --git a/base/message_loop/message_pump_mac.h b/base/message_loop/message_pump_mac.h index 763c6b4868d43..f968734746b1c 100644 --- a/base/message_loop/message_pump_mac.h +++ b/base/message_loop/message_pump_mac.h @@ -119,9 +119,16 @@ class BASE_EXPORT MessagePumpCFRunLoopBase : public MessagePump { // Invokes function(run_loop_, arg, mode) for all the modes in |mode_mask_|. template - void InvokeForEnabledModes(void function(CFRunLoopRef, Argument, CFStringRef), - Argument argument); - + void InvokeForEnabledModes(void method(CFRunLoopRef, Argument, CFStringRef), + Argument argument) { + for (size_t i = 0; i < nAllModes; ++i) { + if (mode_mask_ & (0x1 << i)) + method(run_loop_, argument, kAllModes[i]); + } + } + + static const CFStringRef kAllModes[]; + static const size_t nAllModes; private: // Marking timers as invalid at the right time helps significantly reduce // power use (see the comment in RunDelayedWorkTimer()), however there is no @@ -148,7 +155,8 @@ class BASE_EXPORT MessagePumpCFRunLoopBase : public MessagePump { // the instance method; the instance method returns true if it resignalled // work_source_ to be called again from the loop. static void RunWorkSource(void* info); - bool RunWork(); + protected: + virtual bool RunWork(); // Perform idle-priority work. This is normally called by PreWaitObserver, // but is also associated with idle_work_source_. When this function @@ -156,7 +164,8 @@ class BASE_EXPORT MessagePumpCFRunLoopBase : public MessagePump { // static method calls the instance method; the instance method returns // true if idle work was done. static void RunIdleWorkSource(void* info); - bool RunIdleWork(); + virtual bool RunIdleWork(); + virtual void PreWaitObserverHook(); // Perform work that may have been deferred because it was not runnable // within a nested run loop. This is associated with diff --git a/base/message_loop/message_pump_mac.mm b/base/message_loop/message_pump_mac.mm index 71cb00b80a113..4529c819d55b6 100644 --- a/base/message_loop/message_pump_mac.mm +++ b/base/message_loop/message_pump_mac.mm @@ -23,15 +23,7 @@ namespace base { -namespace { - -// AppKit RunLoop modes observed to potentially run tasks posted to Chrome's -// main thread task runner. Some are internal to AppKit but must be observed to -// keep Chrome's UI responsive. Others that may be interesting, but are not -// watched: -// - com.apple.hitoolbox.windows.transitionmode -// - com.apple.hitoolbox.windows.flushmode -const CFStringRef kAllModes[] = { +const CFStringRef MessagePumpCFRunLoopBase::kAllModes[] = { kCFRunLoopCommonModes, // Mode that only sees Chrome work sources. @@ -43,6 +35,15 @@ // Process work when AppKit is highlighting an item on the main menubar. CFSTR("NSUnhighlightMenuRunLoopMode"), }; +const size_t MessagePumpCFRunLoopBase::nAllModes = arraysize(MessagePumpCFRunLoopBase::kAllModes); +namespace { + +// AppKit RunLoop modes observed to potentially run tasks posted to Chrome's +// main thread task runner. Some are internal to AppKit but must be observed to +// keep Chrome's UI responsive. Others that may be interesting, but are not +// watched: +// - com.apple.hitoolbox.windows.transitionmode +// - com.apple.hitoolbox.windows.flushmode // Mask that determines which modes in |kAllModes| to use. enum { kCommonModeMask = 0x1, kAllModesMask = ~0 }; @@ -297,17 +298,6 @@ explicit MessagePumpScopedAutoreleasePool(MessagePumpCFRunLoopBase* pump) : return [[NSAutoreleasePool alloc] init]; } -template -void MessagePumpCFRunLoopBase::InvokeForEnabledModes(void method(CFRunLoopRef, - Argument, - CFStringRef), - Argument argument) { - for (size_t i = 0; i < arraysize(kAllModes); ++i) { - if (mode_mask_ & (0x1 << i)) - method(run_loop_, argument, kAllModes[i]); - } -} - #if !defined(OS_IOS) // This function uses private API to modify a test timer's valid state and // uses public API to confirm that the private API changed the correct bit. @@ -549,9 +539,13 @@ explicit MessagePumpScopedAutoreleasePool(MessagePumpCFRunLoopBase* pump) : // nesting-deferred work may have accumulated. Schedule it for processing // if appropriate. self->MaybeScheduleNestingDeferredWork(); + self->PreWaitObserverHook(); }); } +void MessagePumpCFRunLoopBase::PreWaitObserverHook() { +} + // Called from the run loop. // static void MessagePumpCFRunLoopBase::PreSourceObserver(CFRunLoopObserverRef observer, diff --git a/base/message_loop/message_pump_uv.cc b/base/message_loop/message_pump_uv.cc new file mode 100644 index 0000000000000..eef24ed23c84f --- /dev/null +++ b/base/message_loop/message_pump_uv.cc @@ -0,0 +1,184 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/message_loop/message_pump_uv.h" + +#include "base/logging.h" +#include "base/command_line.h" +#include "v8/include/v8.h" +//#include "third_party/node/src/node.h" +#undef CHECK +#undef CHECK_EQ +#undef CHECK_GE +#undef CHECK_GT +#undef CHECK_NE +#undef CHECK_LT +#undef CHECK_LE +#undef CHECK_OP +#undef DISALLOW_COPY_AND_ASSIGN +#include "third_party/node-nw/src/node_webkit.h" + +#define NW_HOOK_MAP(type, sym, fn) extern type fn; +#define NW_HOOK_INIT(type, sym, fn) BASE_EXPORT type fn = nullptr; +#define NODE_HOOK_INIT(type, sym, fn) BASE_EXPORT type fn = nullptr; +#include "content/nw/src/common/node_hooks.h" +#undef NODE_HOOK_INIT +#undef NW_HOOK_INIT +#undef NW_HOOK_MAP + +namespace base { + +MessagePumpUV::MessagePumpUV() + : keep_running_(true), + nesting_level_(0) { + // wakeup_event_ = new uv_async_t; + // uv_async_init(uv_default_loop(), wakeup_event_, wakeup_callback); + // node::g_nw_uv_run = uv_run; + const base::CommandLine& command_line = + *base::CommandLine::ForCurrentProcess(); + int worker_support = command_line.HasSwitch("enable-node-worker") ? 1 : 0; //kEnableNodeWorker + g_msg_pump_ctor_fn(&wakeup_event_, worker_support); +} + +MessagePumpUV::~MessagePumpUV() { + // delete wakeup_event_; + // wakeup_event_ = NULL; + g_msg_pump_dtor_fn(&wakeup_event_); +} + +void MessagePumpUV::Run(Delegate* delegate) { + + ++nesting_level_; + DCHECK(keep_running_) << "Quit must have been called outside of Run!"; + + msg_pump_context_t ctx; + memset(&ctx, 0, sizeof(msg_pump_context_t)); + + // Poll external loop in nested message loop, so node.js's events will be + // paused in nested loop. + // uv_loop_t* loop = uv_default_loop(); + ctx.loop = g_uv_default_loop_fn(); + ctx.wakeup_event = wakeup_event_; + ctx.wakeup_events = &wakeup_events_; + + if (nesting_level_ > 1) { + g_msg_pump_nest_enter_fn(&ctx); + wakeup_event_ = ctx.wakeup_event; + // loop = uv_loop_new(); + + // wakeup_events_.push_back(wakeup_event_); + // wakeup_event_ = new uv_async_t; + // uv_async_init(loop, wakeup_event_, wakeup_callback); + } + + // // Create handles for the loop. + // uv_idle_t idle_handle; + // uv_idle_init(loop, &idle_handle); + + // uv_timer_t delay_timer; + // delay_timer.data = &idle_handle; + // uv_timer_init(loop, &delay_timer); + + g_msg_pump_pre_loop_fn(&ctx); + // Enter Loop + for (;;) { + bool did_work = delegate->DoWork(); + if (!keep_running_) + break; + + did_work |= delegate->DoDelayedWork(&delayed_work_time_); + if (!keep_running_) + break; + + if (did_work) { + // // call tick callback after done work in V8, + // // in the same way node upstream handle this in MakeCallBack, + // // or the tick callback is blocked in some cases + // if (node::g_env) { + // v8::Isolate* isolate = node::g_env->isolate(); + // v8::HandleScope handleScope(isolate); + // (*node::g_nw_uv_run)(loop, UV_RUN_NOWAIT); + // node::CallNWTickCallback(node::g_env, v8::Undefined(isolate)); + // } + g_msg_pump_did_work_fn(&ctx); + continue; + } + + did_work = delegate->DoIdleWork(); + if (!keep_running_) + break; + + if (did_work) { + g_msg_pump_did_work_fn(&ctx); + continue; + } + + if (delayed_work_time_.is_null()) { + // (*node::g_nw_uv_run)(loop, UV_RUN_ONCE); + g_msg_pump_need_work_fn(&ctx); + } else { + TimeDelta delay = delayed_work_time_ - TimeTicks::Now(); + if (delay > TimeDelta()) { + // uv_timer_start(&delay_timer, timer_callback, + // delay.InMilliseconds(), 0); + // (*node::g_nw_uv_run)(loop, UV_RUN_ONCE); + // uv_idle_stop(&idle_handle); + // uv_timer_stop(&delay_timer); + g_msg_pump_delay_work_fn(&ctx, delay.InMilliseconds()); + } else { + // It looks like delayed_work_time_ indicates a time in the past, so we + // need to call DoDelayedWork now. + delayed_work_time_ = TimeTicks(); + } + } + // Since event_ is auto-reset, we don't need to do anything special here + // other than service each delegate method. + } + + // should be called before g_msg_pump_nest_leave_fn() or there will + // be heap overrun in nest loop case like NWJS#5742 + g_msg_pump_clean_ctx_fn(&ctx); + + if (nesting_level_ > 1) { + // uv_close((uv_handle_t*)wakeup_event_, NULL); + // // Delete external loop. + // uv_loop_close(loop); + // free(loop); + + // // Restore previous async handle. + // delete wakeup_event_; + // wakeup_event_ = wakeup_events_.back(); + // wakeup_events_.pop_back(); + g_msg_pump_nest_leave_fn(&ctx); + wakeup_event_ = ctx.wakeup_event; + } + + keep_running_ = true; + --nesting_level_; +} + +void MessagePumpUV::Quit() { + keep_running_ = false; +} + +void MessagePumpUV::ScheduleWork() { +// // Since this can be called on any thread, we need to ensure that our Run +// // loop wakes up. +// #if defined(OS_WIN) +// uv_async_send_nw(wakeup_event_); +// #else +// uv_async_send(wakeup_event_); +// #endif + g_msg_pump_sched_work_fn(wakeup_event_); +} + +void MessagePumpUV::ScheduleDelayedWork( + const TimeTicks& delayed_work_time) { + // We know that we can't be blocked on Wait right now since this method can + // only be called on the same thread as Run, so we only need to update our + // record of how long to sleep when we do sleep. + delayed_work_time_ = delayed_work_time; +} + +} // namespace base diff --git a/base/message_loop/message_pump_uv.h b/base/message_loop/message_pump_uv.h new file mode 100644 index 0000000000000..a464e2a9963b7 --- /dev/null +++ b/base/message_loop/message_pump_uv.h @@ -0,0 +1,50 @@ +// Copyright (c) 2011 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 BASE_MESSAGE_PUMP_UV_H_ +#define BASE_MESSAGE_PUMP_UV_H_ +#pragma once + +#include "base/message_loop/message_pump.h" +#include "base/time/time.h" +#include "content/common/content_export.h" + +#include + +//#include "third_party/node/deps/uv/include/uv.h" + +typedef struct uv_async_s uv_async_t; +namespace base { + +class BASE_EXPORT MessagePumpUV : public MessagePump { + public: + MessagePumpUV(); + + // MessagePump methods: + void Run(Delegate* delegate) override; + void Quit() override; + void ScheduleWork() override; + void ScheduleDelayedWork(const TimeTicks& delayed_work_time) override; + + private: + ~MessagePumpUV() override; + + // This flag is set to false when Run should return. + bool keep_running_; + + // Nested loop level. + int nesting_level_; + + // Handle to wake up loop. + std::vector wakeup_events_; + void* wakeup_event_; + + TimeTicks delayed_work_time_; + + DISALLOW_COPY_AND_ASSIGN(MessagePumpUV); +}; + +} // namespace base + +#endif // BASE_MESSAGE_PUMP_UV_H_ diff --git a/base/message_loop/message_pumpuv_mac.h b/base/message_loop/message_pumpuv_mac.h new file mode 100644 index 0000000000000..c82ce5ede6db6 --- /dev/null +++ b/base/message_loop/message_pumpuv_mac.h @@ -0,0 +1,95 @@ +// 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. + +// The basis for all native run loops on the Mac is the CFRunLoop. It can be +// used directly, it can be used as the driving force behind the similar +// Foundation NSRunLoop, and it can be used to implement higher-level event +// loops such as the NSApplication event loop. +// +// This file introduces a basic CFRunLoop-based implementation of the +// MessagePump interface called CFRunLoopBase. CFRunLoopBase contains all +// of the machinery necessary to dispatch events to a delegate, but does not +// implement the specific run loop. Concrete subclasses must provide their +// own DoRun and Quit implementations. +// +// A concrete subclass that just runs a CFRunLoop loop is provided in +// MessagePumpCFRunLoop. For an NSRunLoop, the similar MessagePumpNSRunLoop +// is provided. +// +// For the application's event loop, an implementation based on AppKit's +// NSApplication event system is provided in MessagePumpNSApplication. +// +// Typically, MessagePumpNSApplication only makes sense on a Cocoa +// application's main thread. If a CFRunLoop-based message pump is needed on +// any other thread, one of the other concrete subclasses is preferrable. +// MessagePumpMac::Create is defined, which returns a new NSApplication-based +// or NSRunLoop-based MessagePump subclass depending on which thread it is +// called on. + +#ifndef BASE_MESSAGE_LOOP_MESSAGE_PUMPUV_MAC_H_ +#define BASE_MESSAGE_LOOP_MESSAGE_PUMPUV_MAC_H_ + +#include "base/message_loop/message_pump.h" + +#include +#include "v8.h" +#include "third_party/node-nw/src/node_webkit.h" + +#include "base/memory/weak_ptr.h" +#include "base/message_loop/timer_slack.h" + +#include "base/message_loop/message_pump_mac.h" + +#if defined(__OBJC__) +#if defined(OS_IOS) +#import +#else +#import + +#endif // !defined(OS_IOS) +#endif // defined(__OBJC__) + +namespace base { + +class RunLoop; +class TimeTicks; + +class BASE_EXPORT MessagePumpUVNSRunLoop : public MessagePumpCFRunLoopBase { + public: + MessagePumpUVNSRunLoop(); + ~MessagePumpUVNSRunLoop() override; + + void DoRun(Delegate* delegate) override; + void Quit() override; + + protected: + bool RunWork() override; + bool RunIdleWork() override; + void PreWaitObserverHook() override; + + private: + // A source that doesn't do anything but provide something signalable + // attached to the run loop. This source will be signalled when Quit + // is called, to cause the loop to wake up so that it can stop. + CFRunLoopSourceRef quit_source_; + + // Thread to poll uv events. + static void EmbedThreadRunner(void *arg); + + // False after Quit is called. + bool keep_running_; + // Flag to pause the libuv loop. + bool pause_uv_; + + msg_pump_context_t ctx_; + // Whether we're done. + int embed_closed_; + int nw_nesting_level_; + + DISALLOW_COPY_AND_ASSIGN(MessagePumpUVNSRunLoop); +}; + +} // namespace base + +#endif // BASE_MESSAGE_LOOP_MESSAGE_PUMPUV_MAC_H_ diff --git a/base/message_loop/message_pumpuv_mac.mm b/base/message_loop/message_pumpuv_mac.mm new file mode 100644 index 0000000000000..6822094d65a1b --- /dev/null +++ b/base/message_loop/message_pumpuv_mac.mm @@ -0,0 +1,376 @@ +// 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. +// Copyright Plask, (c) Dean McNamee , 2011. BSD license + + +#import "base/message_loop/message_pump_mac.h" +#import "base/message_loop/message_pumpuv_mac.h" + +#include +#import + +#include + +#include + +#include "base/logging.h" +#include "base/mac/scoped_cftyperef.h" +#include "base/message_loop/timer_slack.h" +#include "base/command_line.h" +#include "base/run_loop.h" +#include "base/time/time.h" +#include "v8/include/v8.h" + +#if !defined(OS_IOS) +#import +#endif // !defined(OS_IOS) + +#include +#include +#include + +#include +#include "third_party/node-nw/src/node_webkit.h" +#include "content/nw/src/nw_content.h" + +#define EVENTLOOP_DEBUG 0 + +#if EVENTLOOP_DEBUG +#define EVENTLOOP_DEBUG_C(x) x +#else +#define EVENTLOOP_DEBUG_C(x) do { } while(0) +#endif + + +//static bool g_should_quit = false; +static int g_kqueue_fd = 0; +static int g_main_thread_pipe_fd = 0; +static int g_kqueue_thread_pipe_fd = 0; + +#define NW_HOOK_MAP(type, sym, fn) extern type fn; +#include "content/nw/src/common/node_hooks.h" +#undef NW_HOOK_MAP + +int kevent_hook(int kq, const struct kevent *changelist, int nchanges, + struct kevent *eventlist, int nevents, + const struct timespec *timeout) { + int res; + + EVENTLOOP_DEBUG_C((printf("KQUEUE--- fd: %d changes: %d\n", kq, nchanges))); + +#if 0 //EVENTLOOP_DEBUG + for (int i = 0; i < nchanges; ++i) { + dump_kevent(&changelist[i]); + } +#endif + +#if EVENTLOOP_BYPASS_CUSTOM + int res = kevent(kq, changelist, nchanges, eventlist, nevents, timeout); + printf("---> results: %d\n", res); + for (int i = 0; i < res; ++i) { + dump_kevent(&eventlist[i]); + } + return res; +#endif + + if (eventlist == NULL) // Just updating the state. + return kevent(kq, changelist, nchanges, eventlist, nevents, timeout); + + struct timespec zerotimeout; + memset(&zerotimeout, 0, sizeof(zerotimeout)); + + // Going for a poll. A bit less optimial but we break it into two system + // calls to make sure that the kqueue state is up to date. We might as well + // also peek since we basically get it for free w/ the same call. + EVENTLOOP_DEBUG_C((printf("-- Updating kqueue state and peek\n"))); + res = kevent(kq, changelist, nchanges, eventlist, nevents, &zerotimeout); + if (res != 0) return res; + + /* + printf("kevent() blocking\n"); + res = kevent(kq, NULL, 0, eventlist, nevents, timeout); + if (res != 0) return res; + return res; + */ + + /* + printf("Going for it...\n"); + res = kevent(kq, changelist, nchanges, eventlist, nevents, timeout); + printf("<- %d\n", res); + return res; + */ + + double ts = 9999; // Timeout in seconds. Default to some "future". + if (timeout != NULL) + ts = timeout->tv_sec + (timeout->tv_nsec / 1000000000.0); + + // NOTE(deanm): We only ever make a single pass, because we need to make + // sure that any user code (which could update timers, etc) is reflected + // and we have a proper timeout value. Since user code can run in response + // to [NSApp sendEvent] (mouse movement, keypress, etc, etc), we wind down + // and go back through the uv loop again to make sure to update everything. + + EVENTLOOP_DEBUG_C((printf("-> Running NSApp iteration: timeout %f\n", ts))); + + // Have the helper thread start select()ing on the kqueue. + write(g_main_thread_pipe_fd, "~", 1); + + [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode + beforeDate:[NSDate dateWithTimeIntervalSinceNow:ts]]; + + // Stop the helper thread if it hasn't already woken up (in which case it + // would have already stopped itself). + write(g_main_thread_pipe_fd, "!", 1); + + EVENTLOOP_DEBUG_C((printf("<- Finished NSApp iteration\n"))); + + // Do the actual kqueue call now (ignore the timeout, don't block). + return kevent(kq, NULL, 0, eventlist, nevents, &zerotimeout); +} + +namespace base { + +namespace { + +// static +#if 0 +const CFStringRef kMessageLoopExclusiveRunLoopMode = + CFSTR("kMessageLoopExclusiveRunLoopMode"); + +void CFRunLoopAddSourceToAllModes(CFRunLoopRef rl, CFRunLoopSourceRef source) { + CFRunLoopAddSource(rl, source, kCFRunLoopCommonModes); + CFRunLoopAddSource(rl, source, kMessageLoopExclusiveRunLoopMode); +} + +void CFRunLoopRemoveSourceFromAllModes(CFRunLoopRef rl, + CFRunLoopSourceRef source) { + CFRunLoopRemoveSource(rl, source, kCFRunLoopCommonModes); + CFRunLoopRemoveSource(rl, source, kMessageLoopExclusiveRunLoopMode); +} +#endif + +void NoOp(void* info) { +} + +#if 0 +void UvNoOp(void* handle) { +} +#endif + +} // namespace + +// A scoper for autorelease pools created from message pump run loops. +// Avoids dirtying up the ScopedNSAutoreleasePool interface for the rare +// case where an autorelease pool needs to be passed in. +class MessagePumpScopedAutoreleasePool { + public: + explicit MessagePumpScopedAutoreleasePool(MessagePumpCFRunLoopBase* pump) : + pool_(pump->CreateAutoreleasePool()) { + } + ~MessagePumpScopedAutoreleasePool() { + [pool_ drain]; + } + + private: + NSAutoreleasePool* pool_; + DISALLOW_COPY_AND_ASSIGN(MessagePumpScopedAutoreleasePool); +}; + +bool MessagePumpUVNSRunLoop::RunWork() { + if (!delegate_) { + // This point can be reached with a NULL delegate_ if Run is not on the + // stack but foreign code is spinning the CFRunLoop. Arrange to come back + // here when a delegate is available. + delegateless_work_ = true; + return false; + } + + // The NSApplication-based run loop only drains the autorelease pool at each + // UI event (NSEvent). The autorelease pool is not drained for each + // CFRunLoopSource target that's run. Use a local pool for any autoreleased + // objects if the app is not currently handling a UI event to ensure they're + // released promptly even in the absence of UI events. + MessagePumpScopedAutoreleasePool autorelease_pool(this); + + // Call DoWork and DoDelayedWork once, and if something was done, arrange to + // come back here again as long as the loop is still running. + bool did_work = delegate_->DoWork(); + bool resignal_work_source = did_work; + + TimeTicks next_time; + delegate_->DoDelayedWork(&next_time); + if (!did_work) { + // Determine whether there's more delayed work, and if so, if it needs to + // be done at some point in the future or if it's already time to do it. + // Only do these checks if did_work is false. If did_work is true, this + // function, and therefore any additional delayed work, will get another + // chance to run before the loop goes to sleep. + bool more_delayed_work = !next_time.is_null(); + if (more_delayed_work) { + TimeDelta delay = next_time - TimeTicks::Now(); + if (delay > TimeDelta()) { + // There's more delayed work to be done in the future. + ScheduleDelayedWork(next_time); + } else { + // There's more delayed work to be done, and its time is in the past. + // Arrange to come back here directly as long as the loop is still + // running. + resignal_work_source = true; + } + } + } + + if (resignal_work_source) { + CFRunLoopSourceSignal(work_source_); + } + + return resignal_work_source; +} + +bool MessagePumpUVNSRunLoop::RunIdleWork() { + if (!delegate_) { + // This point can be reached with a NULL delegate_ if Run is not on the + // stack but foreign code is spinning the CFRunLoop. Arrange to come back + // here when a delegate is available. + delegateless_idle_work_ = true; + return false; + } + + // The NSApplication-based run loop only drains the autorelease pool at each + // UI event (NSEvent). The autorelease pool is not drained for each + // CFRunLoopSource target that's run. Use a local pool for any autoreleased + // objects if the app is not currently handling a UI event to ensure they're + // released promptly even in the absence of UI events. + MessagePumpScopedAutoreleasePool autorelease_pool(this); + + // Call DoIdleWork once, and if something was done, arrange to come back here + // again as long as the loop is still running. + bool did_work = delegate_->DoIdleWork(); + if (did_work) { + CFRunLoopSourceSignal(idle_work_source_); + } + + return did_work; +} + +void MessagePumpUVNSRunLoop::PreWaitObserverHook() { + // call tick callback before sleep in mach port + // in the same way node upstream handle this in MakeCallBack, + // or the tick callback is blocked in some cases + nw::KickNextTick(); +} + +MessagePumpUVNSRunLoop::MessagePumpUVNSRunLoop() + : MessagePumpCFRunLoopBase(0x1 /*kCommonModeMask*/), keep_running_(true) { + CFRunLoopSourceContext source_context = CFRunLoopSourceContext(); + source_context.perform = NoOp; + quit_source_ = CFRunLoopSourceCreate(NULL, // allocator + 0, // priority + &source_context); + InvokeForEnabledModes(&CFRunLoopAddSource, quit_source_); + + embed_closed_ = 0; + nw_nesting_level_ = 0; + int pipefds[2]; + if (pipe(pipefds) != 0) abort(); + + const base::CommandLine& command_line = + *base::CommandLine::ForCurrentProcess(); + int worker_support = command_line.HasSwitch("enable-node-worker") ? 1 : 0; //kEnableNodeWorker + + g_uv_init_nw_fn(worker_support); + g_uv_default_loop_fn(); + + g_kqueue_thread_pipe_fd = pipefds[0]; + g_main_thread_pipe_fd = pipefds[1]; + g_kqueue_fd = g_uv_backend_fd_fn(); + + g_msg_pump_ctor_osx_fn(&ctx_, (void*)EmbedThreadRunner, (void*)kevent_hook, this, worker_support); +} + +MessagePumpUVNSRunLoop::~MessagePumpUVNSRunLoop() { + InvokeForEnabledModes(&CFRunLoopRemoveSource, quit_source_); + CFRelease(quit_source_); + // Clear uv. + embed_closed_ = 1; + g_msg_pump_dtor_osx_fn(&ctx_); +} + +void MessagePumpUVNSRunLoop::DoRun(Delegate* delegate) { + + nw_nesting_level_++; + // Pause uv in nested loop. + if (nw_nesting_level_ > 1) { + pause_uv_ = true; + while (keep_running_) { + // NSRunLoop manages autorelease pools itself. + [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode + beforeDate:[NSDate distantFuture]]; + } + } else { + while (keep_running_) { + g_uv_runloop_once_fn(); + } + } + + keep_running_ = true; + // Resume uv. + if (nw_nesting_level_ > 1) { + pause_uv_ = false; + } + nw_nesting_level_--; +} + +void MessagePumpUVNSRunLoop::Quit() { + keep_running_ = false; + CFRunLoopSourceSignal(quit_source_); + CFRunLoopWakeUp(run_loop()); + if (nw_nesting_level_ < 2) // NWJS#5020 + write(g_main_thread_pipe_fd, "q", 1); +} + +void MessagePumpUVNSRunLoop::EmbedThreadRunner(void *arg) { + bool check_kqueue = false; + + base::MessagePumpUVNSRunLoop* message_pump = static_cast(arg); + + NSAutoreleasePool* pool = [NSAutoreleasePool new]; // To avoid the warning. + + while (true) { + int nfds = g_kqueue_thread_pipe_fd + 1; + fd_set fds; + FD_ZERO(&fds); + FD_SET(g_kqueue_thread_pipe_fd, &fds); + if (check_kqueue) { + FD_SET(g_kqueue_fd, &fds); + if (g_kqueue_fd + 1 > nfds) nfds = g_kqueue_fd + 1; + } + + EVENTLOOP_DEBUG_C((printf("Calling select: %d\n", check_kqueue))); + int res = select(nfds, &fds, NULL, NULL, NULL); + if (res <= 0) abort(); // TODO(deanm): Handle signals, etc. + + if (FD_ISSET(g_kqueue_fd, &fds)) { + EVENTLOOP_DEBUG_C((printf("postEvent\n"))); + message_pump->ScheduleWork(); + check_kqueue = false; + } + + if (FD_ISSET(g_kqueue_thread_pipe_fd, &fds)) { + char msg; + ssize_t amt = read(g_kqueue_thread_pipe_fd, &msg, 1); + if (amt != 1) abort(); // TODO(deanm): Handle errors. + if (msg == 'q') { // quit. + EVENTLOOP_DEBUG_C((printf("quitting kqueue helper\n"))); + break; + } + check_kqueue = msg == '~'; // ~ - start, ! - stop. + } + } + + [pool drain]; + +} + +} // namespace base diff --git a/base/native_library_posix.cc b/base/native_library_posix.cc index 3459716af1c68..68d6abe1a0594 100644 --- a/base/native_library_posix.cc +++ b/base/native_library_posix.cc @@ -29,7 +29,7 @@ NativeLibrary LoadNativeLibraryWithOptions(const FilePath& library_path, // please refer to the bug tracker. Some useful bug reports to read include: // http://crbug.com/17943, http://crbug.com/17557, http://crbug.com/36892, // and http://crbug.com/40794. - int flags = RTLD_LAZY; + int flags = RTLD_LAZY | RTLD_GLOBAL; #if defined(OS_ANDROID) || !defined(RTLD_DEEPBIND) // Certain platforms don't define RTLD_DEEPBIND. Android dlopen() requires // further investigation, as it might vary across versions. Crash here to diff --git a/base/native_library_win.cc b/base/native_library_win.cc index 68ff3d1f95d53..6dd0f15b528f5 100644 --- a/base/native_library_win.cc +++ b/base/native_library_win.cc @@ -3,6 +3,7 @@ // found in the LICENSE file. #include "base/native_library.h" +#include "base/path_service.h" #include @@ -12,6 +13,8 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" +#include "base/win/iat_patch_function.h" +#include "chrome/common/chrome_paths.h" namespace base { @@ -79,6 +82,74 @@ LoadLibraryResult GetLoadLibraryResult(bool are_search_flags_available, return result; } +base::win::IATPatchFunction* FlashCreateProcessProxy = nullptr; + +BOOL WINAPI CreateProcessAForFlash( + _In_opt_ LPCSTR lpApplicationName, + _Inout_opt_ LPSTR lpCommandLine, + _In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes, + _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes, + _In_ BOOL bInheritHandles, + _In_ DWORD dwCreationFlags, + _In_opt_ LPVOID lpEnvironment, + _In_opt_ LPCSTR lpCurrentDirectory, + _In_ LPSTARTUPINFOA lpStartupInfo, + _Out_ LPPROCESS_INFORMATION lpProcessInformation) { + bool unhook = false; + if (FlashCreateProcessProxy != nullptr && + strstr(lpCommandLine, "cmd.exe /c echo NOT SANDBOXED") != NULL) { + unhook = true; + dwCreationFlags |= CREATE_NO_WINDOW; + } + + typedef BOOL(WINAPI *CREATE_PROC) ( + LPCSTR, + LPSTR, + LPSECURITY_ATTRIBUTES, + LPSECURITY_ATTRIBUTES, + BOOL, + DWORD, + LPVOID, + LPCSTR, + LPSTARTUPINFOA, + LPPROCESS_INFORMATION + ); + + if (FlashCreateProcessProxy != nullptr) { + CREATE_PROC createProc = (CREATE_PROC)FlashCreateProcessProxy->original_function(); + BOOL retVal = createProc( + lpApplicationName, + lpCommandLine, + lpProcessAttributes, + lpThreadAttributes, + bInheritHandles, + dwCreationFlags, + lpEnvironment, + lpCurrentDirectory, + lpStartupInfo, + lpProcessInformation + ); + + if (unhook) { + DWORD lastError = GetLastError(); + delete FlashCreateProcessProxy; + FlashCreateProcessProxy = nullptr; + SetLastError(lastError); + } + return retVal; + } + return FALSE; +} + +bool IsFlash(const FilePath& library_path) { + base::FilePath flash_filename; + if (!PathService::Get(chrome::FILE_PEPPER_FLASH_SYSTEM_PLUGIN, + &flash_filename)) + return false; + + return flash_filename == library_path; +} + NativeLibrary LoadNativeLibraryHelper(const FilePath& library_path, NativeLibraryLoadError* error) { // LoadLibrary() opens the file off disk. @@ -135,6 +206,20 @@ NativeLibrary LoadNativeLibraryHelper(const FilePath& library_path, if (!module && error) error->code = GetLastError(); + if (module) { + if (IsFlash(library_path)) { + FlashCreateProcessProxy = new base::win::IATPatchFunction; + if (NO_ERROR != + FlashCreateProcessProxy->Patch(library_path.value().c_str(), + "kernel32.dll", + "CreateProcessA", + CreateProcessAForFlash)) { + delete FlashCreateProcessProxy; + FlashCreateProcessProxy = nullptr; + } + } + } + if (restore_directory) SetCurrentDirectory(current_directory); diff --git a/base/process/launch_posix.cc b/base/process/launch_posix.cc index b841dee3276ea..f52ae6853e689 100644 --- a/base/process/launch_posix.cc +++ b/base/process/launch_posix.cc @@ -480,6 +480,7 @@ Process LaunchProcess(const std::vector& argv, #ifndef PR_SET_NO_NEW_PRIVS #define PR_SET_NO_NEW_PRIVS 38 #endif +#if 0 if (!options.allow_new_privs) { if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) && errno != EINVAL) { // Only log if the error is not EINVAL (i.e. not supported). @@ -493,6 +494,7 @@ Process LaunchProcess(const std::vector& argv, _exit(127); } } +#endif #endif if (current_directory != nullptr) { diff --git a/base/threading/thread_restrictions.h b/base/threading/thread_restrictions.h index e9f801778ea0e..ca23fc518e9b8 100644 --- a/base/threading/thread_restrictions.h +++ b/base/threading/thread_restrictions.h @@ -18,6 +18,11 @@ class AwFormDatabaseService; class CookieManager; } +namespace extensions { +class NwAppSetProxyConfigFunction; +class ContentVerifier; +} + namespace cc { class CompletionEvent; class SingleThreadTaskGraphRunner; @@ -216,6 +221,9 @@ class BASE_EXPORT ThreadRestrictions { friend class ui::CommandBufferLocal; friend class ui::GpuState; + friend class extensions::NwAppSetProxyConfigFunction; + friend class extensions::ContentVerifier; + // END ALLOWED USAGE. // BEGIN USAGE THAT NEEDS TO BE FIXED. friend class ::chromeos::BlockingMethodCaller; // http://crbug.com/125360 diff --git a/build/compiler_version.py b/build/compiler_version.py index 8db0108110963..8d80f0cbcbb02 100755 --- a/build/compiler_version.py +++ b/build/compiler_version.py @@ -54,7 +54,7 @@ def GetVersion(compiler, tool): try: # Note that compiler could be something tricky like "distcc g++". if tool == "assembler": - compiler = compiler + " -Xassembler --version -x assembler -c /dev/null" + compiler = compiler + " --version -Xassembler -x assembler -c /dev/null" # Unmodified: GNU assembler (GNU Binutils) 2.24 # Ubuntu: GNU assembler (GNU Binutils for Ubuntu) 2.22 # Fedora: GNU assembler version 2.23.2 diff --git a/build/config/BUILD.gn b/build/config/BUILD.gn index aff0e3d9d360a..c6e9307ce65b0 100644 --- a/build/config/BUILD.gn +++ b/build/config/BUILD.gn @@ -125,6 +125,9 @@ config("feature_flags") { if (is_official_build) { defines += [ "OFFICIAL_BUILD" ] } + if (nwjs_sdk) { + defines += [ "NWJS_SDK" ] + } if (is_chrome_branded) { defines += [ "GOOGLE_CHROME_BUILD" ] } else { diff --git a/build/config/BUILDCONFIG.gn b/build/config/BUILDCONFIG.gn index fa4ec72c87c2f..bc154d8650f8e 100644 --- a/build/config/BUILDCONFIG.gn +++ b/build/config/BUILDCONFIG.gn @@ -130,6 +130,8 @@ declare_args() { # separate flags. is_official_build = false + nwjs_sdk = true + # Whether we're a traditional desktop unix. is_desktop_linux = current_os == "linux" diff --git a/build/config/allocator.gni b/build/config/allocator.gni index a08a1430e2385..1e3f5782b6e50 100644 --- a/build/config/allocator.gni +++ b/build/config/allocator.gni @@ -10,7 +10,7 @@ if (is_android || current_cpu == "mipsel" || is_mac || is_ios || is_asan || (is_linux && target_cpu == "arm64")) { _default_allocator = "none" } else { - _default_allocator = "tcmalloc" + _default_allocator = "none" } # The debug CRT on Windows has some debug features that are incompatible with diff --git a/build/config/chrome_build.gni b/build/config/chrome_build.gni index c649018a7a0ae..7b527b6bd5638 100644 --- a/build/config/chrome_build.gni +++ b/build/config/chrome_build.gni @@ -10,7 +10,7 @@ declare_args() { # Break chrome.dll into multple pieces based on process type. Only available # on Windows. - is_multi_dll_chrome = is_win && !is_component_build + is_multi_dll_chrome = false #is_win && !is_component_build } # Refers to the subdirectory for branding in various places including diff --git a/build/config/compiler/BUILD.gn b/build/config/compiler/BUILD.gn index 6e3ddbdc7e1eb..803d5ca278178 100644 --- a/build/config/compiler/BUILD.gn +++ b/build/config/compiler/BUILD.gn @@ -70,8 +70,8 @@ declare_args() { # Omit unwind support in official builds to save space. # We can use breakpad for these builds. - exclude_unwind_tables = (is_chrome_branded && is_official_build) || - (is_chromecast && !is_cast_desktop_build && !is_debug) + exclude_unwind_tables = true #(is_chrome_branded && is_official_build) || + #(is_chromecast && !is_cast_desktop_build && !is_debug) # If true, optimize for size. Does not affect windows builds. # Linux & Mac favor speed over size. @@ -410,7 +410,9 @@ config("compiler") { # still have a buggy gold. # The bug only affects x86 and x64, so we can still use ICF when targeting # other architectures. - if ((!is_android && linux_use_bundled_binutils) || + if ((is_linux || is_android) && current_cpu == "x86") { + ldflags += [ "-Wl,--icf=none" ] + } else if ((!is_android && linux_use_bundled_binutils) || !(current_cpu == "x86" || current_cpu == "x64")) { ldflags += [ "-Wl,--icf=all" ] } @@ -976,6 +978,7 @@ config("default_warnings") { "/wd4457", "/wd4458", "/wd4459", + "/wd4275", ] cflags_cc += [ diff --git a/build/config/features.gni b/build/config/features.gni index d143dac4b89ce..c99cc4fd84c56 100644 --- a/build/config/features.gni +++ b/build/config/features.gni @@ -24,8 +24,7 @@ declare_args() { # Enables Native Client support. # Temporarily disable nacl on arm64 linux to get rid of compilation errors. # TODO(mcgrathr): When mipsel-nacl-clang is available, drop the exclusion. - enable_nacl = !is_ios && !is_android && !is_chromecast && - current_cpu != "mipsel" && !(is_linux && target_cpu == "arm64") + enable_nacl = false # Non-SFI is not yet supported on mipsel enable_nacl_nonsfi = current_cpu != "mipsel" @@ -35,7 +34,7 @@ declare_args() { # # Note: this flag is used by WebRTC which is DEPSed into Chrome. Moving it # out of //build will require using the build_overrides directory. - proprietary_codecs = is_chrome_branded || is_chromecast + proprietary_codecs = true # Variable safe_browsing is used to control the build time configuration for # safe browsing feature. Safe browsing can be compiled in 3 different levels: @@ -46,7 +45,7 @@ declare_args() { } else if (is_android) { safe_browsing_mode = 2 } else { - safe_browsing_mode = 1 + safe_browsing_mode = 0 } # Set to true make a build that disables activation of field trial tests diff --git a/build/config/nacl/rules.gni b/build/config/nacl/rules.gni index c8956b4e6dae2..614a887042eeb 100644 --- a/build/config/nacl/rules.gni +++ b/build/config/nacl/rules.gni @@ -74,7 +74,11 @@ template("generate_nmf") { # Starts empty so the code below can use += everywhere. data = [] - nmfflags += [ "--library-path=" + rebase_path(root_out_dir) ] + if (target_os == "linux") { + nmfflags += [ "--library-path=" + rebase_path("${root_out_dir}/lib") ] + } else { + nmfflags += [ "--library-path=" + rebase_path("${root_out_dir}") ] + } # NOTE: There is no explicit dependency for the lib directory # (lib32 and lib64 for x86/x64) created in the product directory. diff --git a/build/dotfile_settings.gni b/build/dotfile_settings.gni index f39a196be649e..eb47a77de81d9 100644 --- a/build/dotfile_settings.gni +++ b/build/dotfile_settings.gni @@ -7,6 +7,7 @@ build_dotfile_settings = { exec_script_whitelist = [ + "//content/nw/BUILD.gn", "//build/config/android/config.gni", "//build/config/android/internal_rules.gni", "//build/config/android/rules.gni", diff --git a/build/gyp_chromium.py b/build/gyp_chromium.py index ab2e470dce305..6deea0fa762da 100644 --- a/build/gyp_chromium.py +++ b/build/gyp_chromium.py @@ -61,7 +61,6 @@ def main(): sys.exit(gyp.main(sys.argv[1:] + [ '--check', '--no-circular-check', - '-I', os.path.join(script_dir, 'common.gypi'), '-D', 'gyp_output_dir=out'])) if __name__ == '__main__': diff --git a/build/toolchain/toolchain.gni b/build/toolchain/toolchain.gni index 1746bda9ff2c1..c5f1f09fe04fe 100644 --- a/build/toolchain/toolchain.gni +++ b/build/toolchain/toolchain.gni @@ -78,7 +78,11 @@ assert(!use_xcode_clang || target_os == "ios", # TODO(agrieve): GYP sets this to "lib" for Linux & Android, but this won't work # in GN until support for loadable_module() is added. # See: https://codereview.chromium.org/1236503002/ -shlib_subdir = "." +if (is_linux) { + shlib_subdir = "lib" +} else { + shlib_subdir = "." +} # Root out dir for shared library files. root_shlib_dir = root_out_dir diff --git a/build/util/version.gypi b/build/util/version.gypi new file mode 100644 index 0000000000000..327a5c2e5f596 --- /dev/null +++ b/build/util/version.gypi @@ -0,0 +1,20 @@ +# 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. + +{ + 'variables': { + 'variables': { + 'version_py_path': '<(DEPTH)/build/util/version.py', + 'version_path': '<(DEPTH)/chrome/VERSION', + 'lastchange_path': '<(DEPTH)/build/util/LASTCHANGE', + }, + 'version_py_path': '<(version_py_path)', + 'version_path': '<(version_path)', + 'lastchange_path': '<(lastchange_path)', + 'version_full': + ' -o -a ' parser = optparse.OptionParser(usage=usage) - parser.add_option('-i', '--input', help='reorder chrome.exe in DIR', + parser.add_option('-i', '--input', help='reorder nw.exe in DIR', metavar='DIR') - parser.add_option('-o', '--output', help='write new chrome.exe to DIR', + parser.add_option('-o', '--output', help='write new nw.exe to DIR', metavar='DIR') parser.add_option('-a', '--arch', help='architecture of build (optional)', default='ia32') diff --git a/chrome/BUILD.gn b/chrome/BUILD.gn index 070d7c6008b1d..b63740c1c8e39 100644 --- a/chrome/BUILD.gn +++ b/chrome/BUILD.gn @@ -48,11 +48,11 @@ if (is_win) { # See comment in chrome_dll.gypi in the hardlink_to_output # target for why this cannot be 'initial' like the DLL. inputs = [ - "$root_out_dir/initialexe/chrome.exe", + "$root_out_dir/initialexe/nw.exe", ] outputs = [ - "$root_out_dir/chrome.exe", - "$root_out_dir/chrome.exe.pdb", + "$root_out_dir/nw.exe", + "$root_out_dir/nw.exe.pdb", ] args = [ "-i", @@ -128,9 +128,9 @@ if (!is_android && !is_mac) { executable("chrome_initial") { if (is_win) { - output_name = "initialexe/chrome" + output_name = "initialexe/nw" } else { - output_name = "chrome" + output_name = "nw" } if (!is_win || is_clang) { @@ -161,7 +161,7 @@ if (!is_android && !is_mac) { ] if (is_linux || is_win) { data += [ - "$root_out_dir/chrome_100_percent.pak", + "$root_out_dir/nw_100_percent.pak", "$root_out_dir/locales/en-US.pak", "$root_out_dir/locales/fr.pak", ] @@ -242,13 +242,24 @@ if (!is_android && !is_mac) { } if (is_linux) { - sources += [ - "app/chrome_dll_resource.h", - "app/chrome_main.cc", - "app/chrome_main_delegate.cc", - "app/chrome_main_delegate.h", - ] + if (!is_component_build) { + # Set rpath to find our own libfreetype even in a non-component build. + configs += [ "//build/config/gcc:rpath_for_built_shared_libraries" ] + } + + # NWJS: we use upstream like config in component build, but put everything in + # main dll in static build, as we did before GN migration + if (is_component_build) { + sources += [ + "app/chrome_dll_resource.h", + "app/chrome_main.cc", + "app/chrome_main_delegate.cc", + "app/chrome_main_delegate.h", + ] + } + + if (is_component_build) { deps += [ # On Linux, link the dependencies (libraries) that make up actual # Chromium functionality directly into the executable. @@ -265,11 +276,19 @@ if (!is_android && !is_mac) { "//headless:headless_shell_lib", "//services/service_manager/embedder", ] + } else { + deps += [ + ":chrome_dll", + ":main_dll", + ] + } + if (is_component_build) { public_deps = [ ":xdg_mime", # Needs to be public for installer to consume files. "//chrome/common:features", ] + } ldflags = [ "-pie" ] @@ -279,10 +298,12 @@ if (!is_android && !is_mac) { ldflags += [ "-Wl,--long-plt" ] } + if (is_component_build) { if (use_pango || use_cairo) { # Needed for chrome_main.cc initialization of libraries. configs += [ "//build/config/linux/pangocairo" ] } + } if (use_x11) { configs += [ @@ -305,6 +326,14 @@ if (!is_android && !is_mac) { if (is_chromeos) { deps += [ "//third_party/adobe/flash:flapper_binaries" ] } + deps += [ + "//content/nw:nw_base", + ] + if (is_component_build) { + deps += [ + "//components/startup_metric_utils/browser:lib", + ] + } data_deps += [ "//third_party/widevine/cdm:widevinecdmadapter" ] @@ -315,7 +344,7 @@ if (!is_android && !is_mac) { } } # !is_android && !is_mac -if (is_win) { +if (is_win || (is_linux && !is_component_build)) { # This target is a forwarding target to compile the necessary DLLs used # by Chrome. group("chrome_dll") { @@ -330,6 +359,7 @@ if (is_win) { shared_library("main_dll") { configs += [ "//build/config/compiler:wexit_time_destructors" ] defines = [] + ldflags = [] sources = [ "//base/win/dllmain.cc", @@ -340,36 +370,41 @@ if (is_win) { "app/chrome_main_mac.mm", ] - output_name = "chrome" + output_name = "nw" deps = [ ":browser_dependencies", - ":chrome_dll_manifest", - ":chrome_dll_version", - "//base/trace_event/etw_manifest:chrome_events_win", "//build/config:exe_and_shlib_deps", "//chrome/app:chrome_dll_resources", "//chrome/app:command_ids", - "//chrome/app/theme:chrome_unscaled_resources", "//chrome/common:features", - "//chrome/install_static:install_static_util", - "//chrome/install_static:secondary_module", - "//chrome_elf", - "//components/crash/content/app", - "//components/policy:generated", - "//content/app/resources", - "//content/public/common:service_names", - "//crypto", - "//headless:headless_shell_browser_lib", - "//net:net_resources", - "//ppapi/features", - "//services/service_manager/embedder", - "//third_party/cld", - "//third_party/wtl", - "//ui/views", + #"//third_party/cld", ] - ldflags = [ + # reverts commit a2052ac9b6ec749735f3d8e269bf5a5600935914 + if (is_win) { + deps += [ + ":chrome_dll_manifest", + ":chrome_dll_version", + "//base/trace_event/etw_manifest:chrome_events_win", + "//chrome/app/theme:chrome_unscaled_resources", + "//chrome/install_static:install_static_util", + "//chrome/install_static:secondary_module", + "//chrome_elf", + "//components/crash/content/app", + "//components/policy:generated", + "//content/app/resources", + "//content/public/common:service_names", + "//crypto", + "//headless:headless_shell_browser_lib", + "//net:net_resources", + "//ppapi/features", + "//services/service_manager/embedder", + "//third_party/wtl", + "//ui/views", + ] + + ldflags += [ "/DELAYLOAD:comdlg32.dll", "/DELAYLOAD:crypt32.dll", "/DELAYLOAD:cryptui.dll", @@ -394,6 +429,7 @@ if (is_win) { configs += [ "//build/config/win:default_large_module_incremental_linking" ] } + } #is_win if (use_aura) { deps += [ "//ui/compositor" ] @@ -413,6 +449,9 @@ if (is_win) { ":child_dependencies", "//content/public/app:both", ] + if (is_linux || is_win) { + deps += [ "//headless:headless_shell_lib", ] + } } if (enable_package_mash_services) { @@ -446,9 +485,6 @@ if (is_win) { "//build/config:exe_and_shlib_deps", "//chrome/browser/policy:path_parser", "//chrome/common:features", - "//chrome/install_static:install_static_util", - "//chrome/install_static:secondary_module", - "//chrome_elf", "//components/browser_watcher:browser_watcher_client", "//components/crash/content/app", "//content/public/app:child", @@ -457,6 +493,12 @@ if (is_win) { "//services/service_manager/embedder", ] + if (is_win) { + deps += [ + "//chrome/install_static:install_static_util", + "//chrome/install_static:secondary_module", + "//chrome_elf", + ] ldflags = [ "/DELAYLOAD:d3d11.dll", "/DELAYLOAD:d3d9.dll", @@ -474,8 +516,10 @@ if (is_win) { configs += [ "//build/config/win:no_incremental_linking" ] } configs += [ "//build/config/compiler/pgo:default_pgo_flags" ] + } #is_win } } + if (is_win) { copy("copy_first_run") { sources = [ "app/firstRun", @@ -484,6 +528,7 @@ if (is_win) { "$root_out_dir/First Run", ] } + } } else if (is_mac) { chrome_helper_name = chrome_product_full_name + " Helper" chrome_framework_name = chrome_product_full_name + " Framework" @@ -568,7 +613,7 @@ if (is_win) { # Remove the default strip configuration (which strips all symbols) so that # a saves file can be specified. - if (enable_stripping) { + if (false) { remove_configs = [ "//build/config/mac:strip_all" ] ldflags = @@ -761,7 +806,7 @@ if (is_win) { # Remove the default strip configuration (which strips all symbols) so that # a saves file can be specified. - if (enable_stripping) { + if (false) { remove_configs = [ "//build/config/mac:strip_all" ] ldflags += @@ -886,7 +931,8 @@ if (is_win) { } else if (current_cpu == "x64") { sources += [ "$root_out_dir/nacl_irt_x86_64.nexe" ] } - public_deps += [ "//ppapi/native_client:irt" ] + sources += [ "$root_out_dir/pnacl" ] + public_deps += [ "//ppapi/native_client:irt", "//ppapi/native_client/src/untrusted/pnacl_support_extension:pnacl_support_extension" ] } } } else { @@ -1091,6 +1137,8 @@ if (is_win) { ":chrome_framework_shared_library", ] + output_name = "nw" + sources = [ "app/chrome_crash_reporter_client.cc", "app/chrome_crash_reporter_client.h", @@ -1114,7 +1162,8 @@ if (is_win) { "//content/public/common:service_names", "//headless:headless_shell_lib", "//services/service_manager/embedder", - "//third_party/cld", + #"//third_party/cld", + "//ui/events:dom_keycode_converter", ] if (is_component_build) { @@ -1199,7 +1248,7 @@ if (is_win) { ldflags += [ "-rpath", "@loader_path/../../../../..", - "-Wl,-reexport_library,libchrome_dll.dylib", + "-Wl,-reexport_library,libnw.dylib", ] data_deps = [ @@ -1218,7 +1267,7 @@ if (is_win) { assert(_framework_binary_path != "", "Ignore configuration-dependent unused variable warning") - if (!is_asan && !is_component_build) { + if (!is_asan && !is_component_build && false) { action("verify_chrome_framework_order") { script = "//chrome/tools/build/mac/run_verify_order.py" stamp_file = "$target_out_dir/run_$target_name.stamp" @@ -1281,6 +1330,7 @@ if (is_win) { # Use an absolute path to dump_syms in case a user has it in their path. args = rebase_path(outputs, root_out_dir) + [ rebase_path("$root_out_dir/dump_syms"), + "-a", "x86_64", "-g", rebase_path( "$root_out_dir/{{source_name_part}}.dSYM/Contents/Resources/DWARF/{{source_name_part}}", @@ -1298,6 +1348,37 @@ if (is_win) { ] } + action("nw_sym_archive") { + script = "//content/nw/tools/archive_symbols.py" + + _syms = [ + "$root_out_dir/$chrome_framework_name-$chrome_version_full.breakpad", + "$root_out_dir/$chrome_helper_name-$chrome_version_full.breakpad", + "$root_out_dir/$chrome_product_full_name-$chrome_version_full.breakpad", + "$root_out_dir/crashpad_handler-$chrome_version_full.breakpad", + ] + + sources = _chrome_symbols_sources + + _output = "$root_out_dir/nwjs.breakpad.tar" + + outputs = [ + _output, + ] + + args = [ rebase_path(_output, root_out_dir) ] + + rebase_path(_syms, root_out_dir) + + deps = [ + ":chrome_app", + ":chrome_dump_syms", + ":chrome_framework", + ":chrome_helper_app", + "//chrome/browser/ui/cocoa/notifications:alert_notification_xpc_service", + "//third_party/crashpad/crashpad/handler:crashpad_handler", + ] + } + action("chrome_dsym_archive") { script = "//chrome/tools/build/mac/archive_symbols.py" @@ -1738,7 +1819,7 @@ if (is_linux) { dump_syms_binary = get_label_info(dump_syms_label, "root_out_dir") + "/" + "dump_syms" - chrome_binary = "$root_out_dir/chrome" + chrome_binary = "$root_out_dir/nw" if (current_cpu == "x86") { # GYP used "ia32" so keep that naming for back-compat. symbol_file = "$root_out_dir/chrome.breakpad.ia32" diff --git a/chrome/app/app-Info.plist b/chrome/app/app-Info.plist index c5939d4d093fb..03ac630d3e501 100644 --- a/chrome/app/app-Info.plist +++ b/chrome/app/app-Info.plist @@ -336,7 +336,7 @@ public.data UTTypeDescription - Chromium Extra + NWJS Extra UTTypeIdentifier org.chromium.extension UTTypeTagSpecification diff --git a/chrome/app/chrome_crash_reporter_client.cc b/chrome/app/chrome_crash_reporter_client.cc index b113ba1b7d631..fd4bccfe4709b 100644 --- a/chrome/app/chrome_crash_reporter_client.cc +++ b/chrome/app/chrome_crash_reporter_client.cc @@ -50,7 +50,7 @@ void ChromeCrashReporterClient::SetCrashReporterClientIdFromGUID( } #endif -#if defined(OS_POSIX) && !defined(OS_MACOSX) +#if defined(OS_POSIX) void ChromeCrashReporterClient::GetProductNameAndVersion( const char** product_name, const char** version) { @@ -62,19 +62,21 @@ void ChromeCrashReporterClient::GetProductNameAndVersion( *product_name = "Chrome_ChromeOS"; #else // OS_LINUX #if !defined(ADDRESS_SANITIZER) - *product_name = "Chrome_Linux"; + *product_name = product_name_.c_str(); #else *product_name = "Chrome_Linux_ASan"; #endif #endif - *version = PRODUCT_VERSION; + *version = product_version_.c_str(); } +#if !defined(OS_MACOSX) base::FilePath ChromeCrashReporterClient::GetReporterLogFilename() { return base::FilePath(CrashUploadList::kReporterLogFilename); } #endif +#endif bool ChromeCrashReporterClient::GetCrashDumpLocation( base::FilePath* crash_dir) { @@ -95,11 +97,14 @@ size_t ChromeCrashReporterClient::RegisterCrashKeys() { } bool ChromeCrashReporterClient::IsRunningUnattended() { - std::unique_ptr env(base::Environment::Create()); - return env->HasVar(env_vars::kHeadless); + // std::unique_ptr env(base::Environment::Create()); + // return env->HasVar(env_vars::kHeadless); + return !enable_upload_; } bool ChromeCrashReporterClient::GetCollectStatsConsent() { + return true; +#if 0 #if defined(GOOGLE_CHROME_BUILD) bool is_official_chrome_build = true; #else @@ -125,6 +130,7 @@ bool ChromeCrashReporterClient::GetCollectStatsConsent() { return is_official_chrome_build && GoogleUpdateSettings::GetCollectStatsConsent(); #endif // defined(OS_ANDROID) +#endif // 0 } #if defined(OS_ANDROID) diff --git a/chrome/app/chrome_crash_reporter_client.h b/chrome/app/chrome_crash_reporter_client.h index a266aa1e72dff..a9a3287fd9de7 100644 --- a/chrome/app/chrome_crash_reporter_client.h +++ b/chrome/app/chrome_crash_reporter_client.h @@ -26,11 +26,12 @@ class ChromeCrashReporterClient : public crash_reporter::CrashReporterClient { void SetCrashReporterClientIdFromGUID( const std::string& client_guid) override; #endif - -#if defined(OS_POSIX) && !defined(OS_MACOSX) +#if defined(OS_POSIX) void GetProductNameAndVersion(const char** product_name, const char** version) override; +#if !defined(OS_MACOSX) base::FilePath GetReporterLogFilename() override; +#endif #endif bool GetCrashDumpLocation(base::FilePath* crash_dir) override; diff --git a/chrome/app/chrome_crash_reporter_client_win.cc b/chrome/app/chrome_crash_reporter_client_win.cc index 166a13df213ba..8744a13bb6435 100644 --- a/chrome/app/chrome_crash_reporter_client_win.cc +++ b/chrome/app/chrome_crash_reporter_client_win.cc @@ -35,6 +35,7 @@ namespace { // RegisterCrashKeys function in the crash_keys::CrashReporterClient interface // and the snprintf function defined here. constexpr char kActiveURL[] = "url-chunk"; +constexpr char kNWJSURL[] = "url-nwjs"; constexpr char kFontKeyName[] = "font_key_name"; // Installed extensions. |kExtensionID| should be formatted with an integer, @@ -101,6 +102,7 @@ size_t RegisterCrashKeysHelper() { {kMetricsClientId, kSmallSize}, {kChannel, kSmallSize}, {kActiveURL, kLargeSize}, + {kNWJSURL, kLargeSize}, {kNumVariations, kSmallSize}, {kVariations, kHugeSize}, {kNumExtensionsCount, kSmallSize}, @@ -240,10 +242,12 @@ void ChromeCrashReporterClient::InitializeCrashReportingForProcess() { std::wstring process_type = install_static::GetSwitchValueFromCommandLine( ::GetCommandLine(), install_static::kProcessType); + std::wstring disable_crash_handler = install_static::GetSwitchValueFromCommandLine( + ::GetCommandLine(), L"disable-crash-handler"); // Don't set up Crashpad crash reporting in the Crashpad handler itself, nor // in the fallback crash handler for the Crashpad handler process. if (process_type != install_static::kCrashpadHandler && - process_type != install_static::kFallbackHandler) { + process_type != install_static::kFallbackHandler && disable_crash_handler != L"true") { crash_reporter::SetCrashReporterClient(instance); crash_reporter::InitializeCrashpadWithEmbeddedHandler( process_type.empty(), install_static::UTF16ToUTF8(process_type)); @@ -370,11 +374,11 @@ size_t ChromeCrashReporterClient::RegisterCrashKeys() { } bool ChromeCrashReporterClient::IsRunningUnattended() { - return install_static::HasEnvironmentVariable16(install_static::kHeadless); + return !enable_upload_; } bool ChromeCrashReporterClient::GetCollectStatsConsent() { - return install_static::GetCollectStatsConsent(); + return true; // install_static::GetCollectStatsConsent(); } bool ChromeCrashReporterClient::GetCollectStatsInSample() { diff --git a/chrome/app/chrome_dll.ver b/chrome/app/chrome_dll.ver index 910fca21d178a..fccabec864571 100644 --- a/chrome/app/chrome_dll.ver +++ b/chrome/app/chrome_dll.ver @@ -1,2 +1,2 @@ -INTERNAL_NAME=chrome_dll -ORIGINAL_FILENAME=chrome.dll +INTERNAL_NAME=nw_dll +ORIGINAL_FILENAME=nw.dll diff --git a/chrome/app/chrome_exe.ver b/chrome/app/chrome_exe.ver index a2d39013f5a5d..17bb91f1806de 100644 --- a/chrome/app/chrome_exe.ver +++ b/chrome/app/chrome_exe.ver @@ -1,2 +1,2 @@ -INTERNAL_NAME=chrome_exe -ORIGINAL_FILENAME=chrome.exe +INTERNAL_NAME=nw_exe +ORIGINAL_FILENAME=nw.exe diff --git a/chrome/app/chrome_exe_main_mac.cc b/chrome/app/chrome_exe_main_mac.cc index b8595246a42d7..56c567eba33bd 100644 --- a/chrome/app/chrome_exe_main_mac.cc +++ b/chrome/app/chrome_exe_main_mac.cc @@ -70,7 +70,7 @@ __attribute__((visibility("default"))) int main(int argc, char* argv[]) { } snprintf(framework_path, framework_path_size, "%s/%s", parent_dir, rel_path); - void* library = dlopen(framework_path, RTLD_LAZY | RTLD_LOCAL | RTLD_FIRST); + void* library = dlopen(framework_path, RTLD_LAZY | RTLD_FIRST); if (!library) { fprintf(stderr, "dlopen %s: %s\n", framework_path, dlerror()); abort(); diff --git a/chrome/app/chrome_exe_main_win.cc b/chrome/app/chrome_exe_main_win.cc index b1095fb081dd4..501f709503f4a 100644 --- a/chrome/app/chrome_exe_main_win.cc +++ b/chrome/app/chrome_exe_main_win.cc @@ -225,7 +225,6 @@ int main() { HINSTANCE instance = GetModuleHandle(nullptr); #endif install_static::InitializeFromPrimaryModule(); - SignalInitializeCrashReporting(); // Initialize the CommandLine singleton from the environment. base::CommandLine::Init(0, nullptr); @@ -243,6 +242,12 @@ int main() { HasValidWindowsPrefetchArgument(*command_line)); if (process_type == crash_reporter::switches::kCrashpadHandler) { + // HACK: Let Windows know that we have started. This is needed to suppress + // the IDC_APPSTARTING cursor from being displayed for a prolonged period + // while a subprocess is starting. NWJS#4685 + PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0); + MSG msg; + PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); crash_reporter::SetupFallbackCrashHandling(*command_line); return crash_reporter::RunAsCrashpadHandler( *base::CommandLine::ForCurrentProcess(), switches::kProcessType); @@ -260,8 +265,10 @@ int main() { EnableHighDPISupport(); +#if 0 //FIXME(nwjs) if (AttemptFastNotify(*command_line)) return 0; +#endif RemoveAppCompatFlagsEntry(); diff --git a/chrome/app/chrome_main.cc b/chrome/app/chrome_main.cc index aec129c9bd1b7..0680fa561fae4 100644 --- a/chrome/app/chrome_main.cc +++ b/chrome/app/chrome_main.cc @@ -64,7 +64,7 @@ int ChromeMain(int argc, const char** argv) { #if defined(OS_WIN) // The process should crash when going through abnormal termination. - base::win::SetShouldCrashOnProcessDetach(true); + base::win::SetShouldCrashOnProcessDetach(false); base::win::SetAbortBehaviorForCrashReporting(); params.instance = instance; params.sandbox_info = sandbox_info; diff --git a/chrome/app/chrome_main_delegate.cc b/chrome/app/chrome_main_delegate.cc index 12bde04bb9841..555486633ab1e 100644 --- a/chrome/app/chrome_main_delegate.cc +++ b/chrome/app/chrome_main_delegate.cc @@ -4,6 +4,8 @@ #include "chrome/app/chrome_main_delegate.h" +#include "chrome_elf/chrome_elf_main.h" + #include #include @@ -62,6 +64,7 @@ #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_switches.h" +#include "content/nw/src/nw_base.h" #if defined(OS_WIN) #include #include @@ -169,6 +172,16 @@ #if !defined(CHROME_MULTIPLE_DLL_BROWSER) #include "chrome/child/pdf_child_init.h" +#include "third_party/node-nw/src/node_webkit.h" +#include "third_party/zlib/google/zip_reader.h" +#include "base/native_library.h" +#include "base/strings/utf_string_conversions.h" +#if defined(OS_MACOSX) +#include "base/mac/bundle_locations.h" +#include "base/strings/sys_string_conversions.h" +#endif + + base::LazyInstance::DestructorAtExit g_chrome_content_gpu_client = LAZY_INSTANCE_INITIALIZER; base::LazyInstance::DestructorAtExit @@ -190,6 +203,13 @@ base::LazyInstance::Leaky g_chrome_crash_client = extern int NaClMain(const content::MainFunctionParams&); extern int CloudPrintServiceProcessMain(const content::MainFunctionParams&); +#if defined(COMPONENT_BUILD) +CONTENT_EXPORT NodeStartFn g_node_start_fn; +#else +extern NodeStartFn g_node_start_fn; +#endif +SetBlobPathFn g_set_blob_path_fn = nullptr; + namespace { #if defined(OS_WIN) @@ -385,7 +405,7 @@ struct MainFunction { // Initializes the user data dir. Must be called before InitializeLocalState(). void InitializeUserDataDir(base::CommandLine* command_line) { -#if defined(OS_WIN) +#if 0 wchar_t user_data_dir_buf[MAX_PATH], invalid_user_data_dir_buf[MAX_PATH]; using GetUserDataDirectoryThunkFunction = @@ -437,10 +457,15 @@ void InitializeUserDataDir(base::CommandLine* command_line) { } } #endif // OS_LINUX -#if defined(OS_MACOSX) +#if defined(OS_MACOSX) || defined(OS_WIN) policy::path_parser::CheckUserDataDirPolicy(&user_data_dir); #endif // OS_MAC + // On Windows, trailing separators leave Chrome in a bad state. + // See crbug.com/464616. + if (user_data_dir.EndsWithSeparator()) + user_data_dir = user_data_dir.StripTrailingSeparators(); + const bool specified_directory_was_invalid = !user_data_dir.empty() && !PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA, user_data_dir, false, true); @@ -470,7 +495,7 @@ void InitializeUserDataDir(base::CommandLine* command_line) { // Append the fallback user data directory to the commandline. Otherwise, // child or service processes will attempt to use the invalid directory. - if (specified_directory_was_invalid) + //if (specified_directory_was_invalid) command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir); #endif // OS_WIN } @@ -532,7 +557,7 @@ bool ChromeMainDelegate::BasicStartupComplete(int* exit_code) { chromeos::BootTimesRecorder::Get()->SaveChromeMainStats(); #endif - const base::CommandLine& command_line = + base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); #if defined(OS_WIN) @@ -557,6 +582,37 @@ bool ChromeMainDelegate::BasicStartupComplete(int* exit_code) { #if !defined(CHROME_MULTIPLE_DLL_BROWSER) ChildProfiling::ProcessStarted(); #endif + + const base::CommandLine::StringVector& args = command_line.GetArgs(); + if (args.size() > 0) { + zip::ZipReader reader; + base::FilePath fp(args[0]); + LOG(WARNING) << "final extension: " << fp.FinalExtension(); + if (!command_line.HasSwitch(switches::kProcessType) && fp.FinalExtension() == FILE_PATH_LITERAL(".js") && + base::PathExists(fp) && !base::DirectoryExists(fp) && !reader.Open(fp)) { + base::NativeLibraryLoadError error; +#if defined(OS_MACOSX) + base::FilePath node_dll_path = base::mac::FrameworkBundlePath().Append(base::FilePath::FromUTF8Unsafe(base::GetNativeLibraryName("node"))); + base::ScopedCFTypeRef natives_file_name(base::SysUTF8ToCFStringRef("natives_blob.bin")); + std::string blob_path = base::mac::PathForFrameworkBundleResource(natives_file_name).AsUTF8Unsafe(); +#else + base::FilePath node_dll_path = base::FilePath::FromUTF8Unsafe(base::GetNativeLibraryName("node")); +#endif + base::NativeLibrary node_dll = base::LoadNativeLibrary(node_dll_path, &error); + if(!node_dll) + LOG(FATAL) << "Failed to load node library (error: " << error.ToString() << ")"; + else { +#if defined(OS_MACOSX) + g_set_blob_path_fn = (SetBlobPathFn)base::GetFunctionPointerFromNativeLibrary(node_dll, "g_set_blob_path"); + g_set_blob_path_fn(blob_path.c_str()); +#endif + g_node_start_fn = (NodeStartFn)base::GetFunctionPointerFromNativeLibrary(node_dll, "g_node_start"); + *exit_code = g_node_start_fn(command_line.argc0(), command_line.argv0()); + } + return true; + } + } + Profiling::ProcessStarted(); base::trace_event::TraceLog::GetInstance()->SetArgumentFilterPredicate( @@ -711,6 +767,22 @@ bool ChromeMainDelegate::BasicStartupComplete(int* exit_code) { metrics::LeakDetector::InitTLSSlot(); #endif + std::wstring product_name, product_version; + std::string report_url; + + nw::InitNWPackage(); + std::string name = nw::package()->GetName(); + std::string version; + product_name = std::wstring(name.begin(), name.end()); + nw::package()->root()->GetString("version", &version); + product_version = std::wstring(version.begin(), version.end()); +#if defined(OS_WIN) + SignalInitializeCrashReporting(&product_name, &product_version); + if (nw::package()->root()->GetString("crash_report_url", &report_url)) { + crash_reporter::CrashReporterClient* client = (crash_reporter::CrashReporterClient*)ElfGetReporterClient(); + client->SetUploadDump(true); + } +#endif return false; } @@ -783,13 +855,31 @@ void ChromeMainDelegate::PreSandboxStartup() { crash_reporter::SetCrashReporterClient(g_chrome_crash_client.Pointer()); #endif + std::string report_url; + if (nw::package()->root()->GetString("crash_report_url", &report_url)) { +#if !defined(OS_WIN) + crash_reporter::CrashReporterClient* client = crash_reporter::GetCrashReporterClient(); + client->SetUploadDump(true); + client->product_name_ = nw::package()->GetName(); + nw::package()->root()->GetString("version", &client->product_version_); +#endif + } + #if defined(OS_MACOSX) // On the Mac, the child executable lives at a predefined location within // the app bundle's versioned directory. + std::string product_string; + if (nw::package()->root()->GetString("product_string", &product_string)) { + std::string helperProcessExecutablePath = (product_string + " Helper.app/Contents/MacOS/" + product_string + " Helper"); + PathService::Override(content::CHILD_PROCESS_EXE, + chrome::GetVersionedDirectory(). + Append(helperProcessExecutablePath)); + }else{ PathService::Override(content::CHILD_PROCESS_EXE, chrome::GetVersionedDirectory(). Append(chrome::kHelperProcessExecutablePath)); + } InitMacCrashReporter(command_line, process_type); SetUpInstallerPreferences(command_line); #endif @@ -806,7 +896,7 @@ void ChromeMainDelegate::PreSandboxStartup() { // Initialize the user data dir for any process type that needs it. if (chrome::ProcessNeedsProfileDir(process_type)) { InitializeUserDataDir(base::CommandLine::ForCurrentProcess()); -#if defined(OS_WIN) && !defined(CHROME_MULTIPLE_DLL_CHILD) +#if 0 if (downgrade::IsMSIInstall()) { downgrade::MoveUserDataForFirstRunAfterDowngrade(); base::FilePath user_data_dir; @@ -816,11 +906,13 @@ void ChromeMainDelegate::PreSandboxStartup() { #endif } +#if 0 // Register component_updater PathProvider after DIR_USER_DATA overidden by // command line flags. Maybe move the chrome PathProvider down here also? component_updater::RegisterPathProvider(chrome::DIR_COMPONENTS, chrome::DIR_INTERNAL_PLUGINS, chrome::DIR_USER_DATA); +#endif #if !defined(OS_ANDROID) && !defined(OS_WIN) // Android does InitLogging when library is loaded. Skip here. @@ -929,6 +1021,12 @@ void ChromeMainDelegate::PreSandboxStartup() { // After all the platform Breakpads have been initialized, store the command // line for crash reporting. crash_keys::SetCrashKeysFromCommandLine(command_line); +#if 1 //!defined(OS_WIN) + if (!report_url.empty()) { + GURL url(report_url); + chrome_content_client_.SetNWReportURL(url); + } +#endif } void ChromeMainDelegate::SandboxInitialized(const std::string& process_type) { diff --git a/chrome/app/chrome_version.rc.version b/chrome/app/chrome_version.rc.version index 0ec74bdd42dd5..588068457adbf 100644 --- a/chrome/app/chrome_version.rc.version +++ b/chrome/app/chrome_version.rc.version @@ -10,8 +10,6 @@ // VS_VERSION_INFO VERSIONINFO - FILEVERSION @MAJOR@,@MINOR@,@BUILD@,@PATCH@ - PRODUCTVERSION @MAJOR@,@MINOR@,@BUILD@,@PATCH@ FILEFLAGSMASK 0x17L #ifdef _DEBUG FILEFLAGS 0x1L @@ -28,16 +26,13 @@ BEGIN BEGIN VALUE "CompanyName", "@COMPANY_FULLNAME@" VALUE "FileDescription", "@PRODUCT_FULLNAME@" - VALUE "FileVersion", "@MAJOR@.@MINOR@.@BUILD@.@PATCH@" VALUE "InternalName", "@INTERNAL_NAME@" VALUE "LegalCopyright", "@COPYRIGHT@" VALUE "OriginalFilename", "@ORIGINAL_FILENAME@" VALUE "ProductName", "@PRODUCT_FULLNAME@" - VALUE "ProductVersion", "@MAJOR@.@MINOR@.@BUILD@.@PATCH@" VALUE "CompanyShortName", "@COMPANY_SHORTNAME@" VALUE "ProductShortName", "@PRODUCT_SHORTNAME@" VALUE "LastChange", "@LASTCHANGE@" - VALUE "Official Build", "@OFFICIAL_BUILD@" END END BLOCK "VarFileInfo" diff --git a/chrome/app/chromium_strings.grd b/chrome/app/chromium_strings.grd index 0a1609831b696..87fb56405c002 100644 --- a/chrome/app/chromium_strings.grd +++ b/chrome/app/chromium_strings.grd @@ -130,10 +130,10 @@ If you update this file, be sure also to update google_chrome_strings.grd. --> Disconnecting $1someone@example.com will clear your history, bookmarks, settings, and other Chromium data stored on this device. Data stored in your Google Account will not be cleared and can be managed on <a target="_blank" href="$2">Google Dashboard</a>. - Chromium + nwjs - Chromium + nwjs @@ -143,7 +143,7 @@ If you update this file, be sure also to update google_chrome_strings.grd. --> - Chromium is a web browser that runs webpages and applications with lightning speed. It's fast, stable, and easy to use. Browse the web more safely with malware and phishing protection built into Chromium. + nwjs runtime enables writing native application with Web technologies. @@ -197,7 +197,7 @@ If you update this file, be sure also to update google_chrome_strings.grd. --> The Chromium Authors - Copyright {0,date,y}2016 The Chromium Authors. All rights reserved. + Copyright {0,date,y}2016 The Chromium Authors, NW.js contributors, Node.js. All rights reserved. @@ -680,13 +680,13 @@ Chromium is unable to recover your settings. - Chromium + nwjs - Chromium Helper + nwjs Helper - Chromium Helper + nwjs Helper diff --git a/chrome/app/framework.order b/chrome/app/framework.order index 4f8a71752dc76..55c4c16742e2a 100644 --- a/chrome/app/framework.order +++ b/chrome/app/framework.order @@ -18,6 +18,267 @@ # Provided by build/sanitizers/sanitizer_options.cc in ASan builds. ___asan_default_options +__ZN4node14ErrnoExceptionEPN2v87IsolateEiPKcS4_S4_ +__ZN4node11UVExceptionEPN2v87IsolateEiPKcS4_S4_ +__ZN4node11UVExceptionEPN2v87IsolateEiPKcS4_S4_S4_ +__ZN4node16CallTickCallbackEPNS_11EnvironmentEN2v86HandleINS2_5ValueEEE +__ZN4node12MakeCallbackEPN2v87IsolateENS0_6HandleINS0_6ObjectEEEPKciPNS3_INS0_5ValueEEE +__ZN4node12MakeCallbackEPN2v87IsolateENS0_6HandleINS0_6ObjectEEENS3_INS0_6StringEEEiPNS3_INS0_5ValueEEE +__ZN4node12MakeCallbackEPN2v87IsolateENS0_6HandleINS0_6ObjectEEENS3_INS0_8FunctionEEEiPNS3_INS0_5ValueEEE +__ZN4node6EncodeEPN2v87IsolateEPKcmNS_8encodingE +__ZN4node6EncodeEPN2v87IsolateEPKtm +__ZN4node11DecodeBytesEPN2v87IsolateENS0_6HandleINS0_5ValueEEENS_8encodingE +__ZN4node11DecodeWriteEPN2v87IsolateEPcmNS0_6HandleINS0_5ValueEEENS_8encodingE +_node_module_register +__ZN4node14FatalExceptionEPN2v87IsolateERKNS0_8TryCatchE +__ZN4node9OnMessageEN2v86HandleINS0_7MessageEEENS1_INS0_5ValueEEE +__ZN4node15LoadEnvironmentEPNS_11EnvironmentE +__ZN4node4InitEPiPPKcS0_PS3_ +__ZN4node9RunAtExitEPNS_11EnvironmentE +__ZN4node6AtExitEPFvPvES0_ +__ZN4node14EmitBeforeExitEPNS_11EnvironmentE +__ZN4node8EmitExitEPNS_11EnvironmentE +__ZN4node17CreateEnvironmentEPN2v87IsolateENS0_6HandleINS0_7ContextEEEiPKPKciS9_ +__ZN4node17CreateEnvironmentEPN2v87IsolateEP9uv_loop_sNS0_6HandleINS0_7ContextEEEiPKPKciSB_ +__ZN4node5StartEiPPc +__ZN4node11SetupNWNodeEiPPc +__ZN4node15StartNWInstanceEiPPcN2v86HandleINS2_7ContextEEE +__ZN4node17SetNWTickCallbackEPFN2v86HandleINS0_5ValueEEEPNS_11EnvironmentES3_E +__ZN4node18CallNWTickCallbackEPNS_11EnvironmentEN2v86HandleINS2_5ValueEEE +__ZN4node6Buffer11HasInstanceEN2v86HandleINS1_5ValueEEE +__ZN4node6Buffer11HasInstanceEN2v86HandleINS1_6ObjectEEE +__ZN4node6Buffer4DataEN2v86HandleINS1_5ValueEEE +__ZN4node6Buffer4DataEN2v86HandleINS1_6ObjectEEE +__ZN4node6Buffer6LengthEN2v86HandleINS1_5ValueEEE +__ZN4node6Buffer6LengthEN2v86HandleINS1_6ObjectEEE +__ZN4node6Buffer3NewEPN2v87IsolateENS1_6HandleINS1_6StringEEENS_8encodingE +__ZN4node6Buffer3NewEPN2v87IsolateEm +__ZN4node6Buffer3NewEPN2v87IsolateEPKcm +__ZN4node6Buffer3NewEPN2v87IsolateEPcmPFvS4_PvES5_ +__ZN4node6Buffer3UseEPN2v87IsolateEPcj +__ZN4node4i18n22InitializeICUDirectoryEPKc +__ZN4node7smalloc17ExternalArraySizeEN2v817ExternalArrayTypeE +__ZN4node7smalloc5AllocEPN2v87IsolateENS1_6HandleINS1_6ObjectEEEmNS1_17ExternalArrayTypeE +__ZN4node7smalloc5AllocEPN2v87IsolateENS1_6HandleINS1_6ObjectEEEPcmNS1_17ExternalArrayTypeE +__ZN4node7smalloc5AllocEPN2v87IsolateENS1_6HandleINS1_6ObjectEEEmPFvPcPvES8_NS1_17ExternalArrayTypeE +__ZN4node7smalloc5AllocEPN2v87IsolateENS1_6HandleINS1_6ObjectEEEPcmPFvS7_PvES8_NS1_17ExternalArrayTypeE +__ZN4node7smalloc12AllocDisposeEPN2v87IsolateENS1_6HandleINS1_6ObjectEEE +__ZN4node7smalloc15HasExternalDataEPN2v87IsolateENS1_5LocalINS1_6ObjectEEE +_uv_fs_poll_init +_uv_fs_poll_start +_uv_fs_poll_stop +_uv_fs_poll_getpath +_uv_inet_ntop +_uv_inet_pton +_uv_queue_work +_uv_cancel +_uv_handle_size +_uv_req_size +_uv_loop_size +_uv_buf_init +_uv_err_name +_uv_strerror +_uv_ip4_addr +_uv_ip6_addr +_uv_ip4_name +_uv_ip6_name +_uv_tcp_bind +_uv_udp_bind +_uv_tcp_connect +_uv_udp_send +_uv_udp_try_send +_uv_udp_recv_start +_uv_udp_recv_stop +_uv_walk +_uv_ref +_uv_unref +_uv_has_ref +_uv_stop +_uv_now +_uv_recv_buffer_size +_uv_send_buffer_size +_uv_fs_event_getpath +_uv_fs_scandir_next +_uv_loop_configure +_uv_default_loop +_uv_loop_new +_uv_loop_close +_uv_loop_delete +_uv_version +_uv_version_string +_uv_async_init +_uv_async_send +_uv_hrtime +_uv_close +_uv_is_closing +_uv_backend_fd +_uv_backend_timeout +_uv_loop_alive +_uv_run +_uv_update_time +_uv_is_active +_uv_cwd +_uv_chdir +_uv_disable_stdio_inheritance +_uv_fileno +_uv_getrusage +_uv_dlopen +_uv_dlclose +_uv_dlsym +_uv_dlerror +_uv_fs_access +_uv_fs_chmod +_uv_fs_chown +_uv_fs_close +_uv_fs_fchmod +_uv_fs_fchown +_uv_fs_fdatasync +_uv_fs_fstat +_uv_fs_fsync +_uv_fs_ftruncate +_uv_fs_futime +_uv_fs_lstat +_uv_fs_link +_uv_fs_mkdir +_uv_fs_mkdtemp +_uv_fs_open +_uv_fs_read +_uv_fs_scandir +_uv_fs_readlink +_uv_fs_rename +_uv_fs_rmdir +_uv_fs_sendfile +_uv_fs_stat +_uv_fs_symlink +_uv_fs_unlink +_uv_fs_utime +_uv_fs_write +_uv_fs_req_cleanup +_uv_getaddrinfo +_uv_freeaddrinfo +_uv_getnameinfo +_uv_loop_init +_uv_prepare_init +_uv_prepare_start +_uv_prepare_stop +_uv_check_init +_uv_check_start +_uv_check_stop +_uv_idle_init +_uv_idle_start +_uv_idle_stop +_uv_pipe_init +_uv_pipe_bind +_uv_pipe_open +_uv_pipe_connect +_uv_pipe_getsockname +_uv_pipe_getpeername +_uv_pipe_pending_instances +_uv_pipe_pending_count +_uv_pipe_pending_type +_uv_poll_init +_uv_poll_init_socket +_uv_poll_stop +_uv_poll_start +_uv_spawn +_uv_process_kill +_uv_kill +_uv_signal_init +_uv_signal_start +_uv_signal_stop +_uv_accept +_uv_listen +_uv_shutdown +_uv_write2 +_uv_write +_uv_try_write +_uv_read_start +_uv_read_stop +_uv_is_readable +_uv_is_writable +_uv_stream_set_blocking +_uv_tcp_init +_uv_tcp_open +_uv_tcp_getsockname +_uv_tcp_getpeername +_uv_tcp_nodelay +_uv_tcp_keepalive +_uv_tcp_simultaneous_accepts +_uv_thread_create +_uv_thread_self +_uv_thread_join +_uv_thread_equal +_uv_mutex_init +_uv_mutex_destroy +_uv_mutex_lock +_uv_mutex_trylock +_uv_mutex_unlock +_uv_rwlock_init +_uv_rwlock_destroy +_uv_rwlock_rdlock +_uv_rwlock_tryrdlock +_uv_rwlock_rdunlock +_uv_rwlock_wrlock +_uv_rwlock_trywrlock +_uv_rwlock_wrunlock +_uv_once +_uv_sem_init +_uv_sem_destroy +_uv_sem_post +_uv_sem_wait +_uv_sem_trywait +_uv_cond_init +_uv_cond_destroy +_uv_cond_signal +_uv_cond_broadcast +_uv_cond_wait +_uv_cond_timedwait +_uv_barrier_init +_uv_barrier_destroy +_uv_barrier_wait +_uv_key_create +_uv_key_delete +_uv_key_get +_uv_key_set +_uv_timer_init +_uv_timer_start +_uv_timer_stop +_uv_timer_again +_uv_timer_set_repeat +_uv_timer_get_repeat +_uv_tty_init +_uv_tty_set_mode +_uv_tty_get_winsize +_uv_guess_handle +_uv_tty_reset_mode +_uv_udp_init +_uv_udp_open +_uv_udp_set_membership +_uv_udp_set_broadcast +_uv_udp_set_ttl +_uv_udp_set_multicast_ttl +_uv_udp_set_multicast_loop +_uv_udp_set_multicast_interface +_uv_udp_getsockname +_uv_setup_args +_uv_set_process_title +_uv_get_process_title +_uv_exepath +_uv_get_free_memory +_uv_get_total_memory +_uv_loadavg +_uv_resident_set_memory +_uv_uptime +_uv_cpu_info +_uv_free_cpu_info +_uv_interface_addresses +_uv_free_interface_addresses +_uv_fs_event_init +_uv_fs_event_start +_uv_fs_event_stop + + + # Entry point from the app mode loader. _ChromeAppModeStart_v4 diff --git a/chrome/app/main_dll_loader_win.cc b/chrome/app/main_dll_loader_win.cc index 589e62d98c47e..8323c2ec2ae3f 100644 --- a/chrome/app/main_dll_loader_win.cc +++ b/chrome/app/main_dll_loader_win.cc @@ -51,13 +51,24 @@ typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*, int64_t); typedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)(); +#define BUFSIZE MAX_PATH + // Loads |module| after setting the CWD to |module|'s directory. Returns a // reference to the loaded module on success, or null on error. HMODULE LoadModuleWithDirectory(const base::FilePath& module) { + bool restore_directory = false; + TCHAR Buffer[BUFSIZE]; + if (::GetCurrentDirectoryW(BUFSIZE, Buffer)) { + restore_directory = true; + } ::SetCurrentDirectoryW(module.DirName().value().c_str()); PreReadFile(module); - return ::LoadLibraryExW(module.value().c_str(), nullptr, + HMODULE ret = ::LoadLibraryExW(module.value().c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH); + if (restore_directory) + ::SetCurrentDirectory(Buffer); + + return ret; } void RecordDidRun(const base::FilePath& dll_path) { @@ -134,7 +145,7 @@ HMODULE MainDllLoader::Load(base::FilePath* module) { } HMODULE dll = LoadModuleWithDirectory(*module); if (!dll) { - PLOG(ERROR) << "Failed to load Chrome DLL from " << module->value(); + PLOG(ERROR) << "Failed to load NW DLL from " << module->value(); return nullptr; } diff --git a/chrome/app/nibs/MainMenu.xib b/chrome/app/nibs/MainMenu.xib index eb05d828eb233..7de16d66f511f 100644 --- a/chrome/app/nibs/MainMenu.xib +++ b/chrome/app/nibs/MainMenu.xib @@ -1,581 +1,792 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -CA - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + 1050 + 14B25 + 7702 + 1343.16 + 755.00 + + com.apple.InterfaceBuilder.CocoaPlugin + 7702 + + + NSCustomObject + NSMenu + NSMenuItem + + + com.apple.InterfaceBuilder.CocoaPlugin + + + PluginDependencyRecalculationVersion + + + + + BrowserCrApplication + + + FirstResponder + + + BrowserCrApplication + + + NSFontManager + + + AMainMenu + + + + ^IDS_APP_MENU_PRODUCT_NAME + + 2147483647 + + NSImage + NSMenuCheckmark + + + NSImage + NSMenuMixedState + + submenuAction: + 44002 + + + ^IDS_APP_MENU_PRODUCT_NAME + + + + ^IDS_ABOUT_MAC$IDS_PRODUCT_NAME + + 2147483647 + + + 40018 + + + + ^IDS_HIDE_APP_MAC$IDS_PRODUCT_NAME + h + 1048576 + 2147483647 + + + 44003 + + + + ^IDS_HIDE_OTHERS_MAC + h + 1572864 + 2147483647 + + + + + + ^IDS_SHOW_ALL_MAC + + 2147483647 + + + + + + YES + YES + + + 2147483647 + + + + + + ^IDS_CONFIRM_TO_QUIT_OPTION + + 2147483647 + + + + + + YES + YES + + + 2147483647 + + + + + + ^IDS_EXIT_MAC$IDS_PRODUCT_NAME + q + 1048576 + 2147483647 + + + 34031 + + + _NSAppleMenu + + + + + ^IDS_EDIT_MENU_MAC + + 2147483647 + + + submenuAction: + 36004 + + + ^IDS_EDIT_MENU_MAC + + + + ^IDS_EDIT_UNDO_MAC + z + 1048576 + 2147483647 + + + 50144 + + + + ^IDS_EDIT_REDO_MAC + Z + 1179648 + 2147483647 + + + 50145 + + + + YES + YES + + + 2147483647 + + + + + + ^IDS_CUT_MAC + x + 1048576 + 2147483647 + + + 50141 + + + + ^IDS_COPY_MAC + c + 1048576 + 2147483647 + + + 50140 + + + + ^IDS_PASTE_MAC + v + 1048576 + 2147483647 + + + 50142 + + + + ^IDS_PASTE_MATCH_STYLE_MAC + V + 1048576 + 2147483647 + + + 50147 + + + + YES + ^IDS_PASTE_MATCH_STYLE_MAC + V + 1572864 + 2147483647 + + + + + + ^IDS_EDIT_DELETE_MAC + + 2147483647 + + + 50143 + + + + ^IDS_EDIT_SELECT_ALL_MAC + a + 1048576 + 2147483647 + + + 50146 + + + + + + + ^IDS_WINDOW_MENU_MAC + + 2147483647 + + + submenuAction: + 34045 + + + ^IDS_WINDOW_MENU_MAC + + + + ^IDS_MINIMIZE_WINDOW_MAC + m + 1048576 + 2147483647 + + + 34046 + + + + ^IDS_ZOOM_WINDOW_MAC + + 2147483647 + + + 34047 + + + + ^IDS_ALL_WINDOWS_FRONT_MAC + + 2147483647 + + + 34048 + + + _NSWindowsMenu + + + + _NSMainMenu + + + ChromeUILocalizer + + + AppController + + + + NO + + + + delegate + + + + 485 + + + + terminate: + + + + 647 + + + + hide: + + + + 369 + + + + hideOtherApplications: + + + + 370 + + + + unhideAllApplications: + + + + 372 + + + + undo: + + + + 223 + + + + redo: + + + + 231 + + + + cut: + + + + 228 + + + + copy: + + + + 224 + + + + paste: + + + + 226 + + + + pasteAndMatchStyle: + + + + 696 + + + + pasteAndMatchStyle: + + + + 697 + + + + delete: + + + + 235 + + + + selectAll: + + + + 232 + + + + performMiniaturize: + + + + 37 + + + + performZoom: + + + + 240 + + + + arrangeInFront: + + + + 39 + + + + orderFrontStandardAboutPanel: + + + + 644 + + + + toggleConfirmToQuit: + + + + 688 + + + + owner_ + + + + 642 + + + + + + 0 + + + + + + -2 + + + File's Owner + + + -1 + + + First Responder + + + -3 + + + Application + + + 373 + + + + + 29 + + + + + + + + Main Menu + + + 56 + + + + + + + + 57 + + + + + + + + + + + + + + + 58 + + + + + 134 + + + + + 145 + + + + + 150 + + + + + 149 + + + + + 687 + + + + + 686 + + + + + 136 + + + + + 217 + + + + + + + + 205 + + + + + + + + + + + + + + + + + 207 + + + + + 215 + + + + + 206 + + + + + 199 + + + + + 197 + + + + + 203 + + + + + 658 + + + + + 689 + + + + + 202 + + + + + 198 + + + + + 19 + + + + + + + + 24 + + + + + + + + + + 23 + + + + + 239 + + + + + 5 + + + + + 641 + + + + + 483 + + + + + + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + + + + + + + + 0 + IBCocoaFramework + NO + + com.apple.InterfaceBuilder.CocoaPlugin.macosx + + + + com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3 + + + YES + 3 + + {12, 12} + {10, 2} + + + + diff --git a/chrome/app/nw.dll.manifest b/chrome/app/nw.dll.manifest new file mode 100644 index 0000000000000..d068c1366cec5 --- /dev/null +++ b/chrome/app/nw.dll.manifest @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/chrome/app/nw.exe.manifest b/chrome/app/nw.exe.manifest new file mode 100644 index 0000000000000..d36f084b65946 --- /dev/null +++ b/chrome/app/nw.exe.manifest @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/chrome/app/theme/chromium/BRANDING b/chrome/app/theme/chromium/BRANDING index 6a6bc265f7eeb..0b950e39cb0be 100644 --- a/chrome/app/theme/chromium/BRANDING +++ b/chrome/app/theme/chromium/BRANDING @@ -1,9 +1,9 @@ -COMPANY_FULLNAME=The Chromium Authors -COMPANY_SHORTNAME=The Chromium Authors -PRODUCT_FULLNAME=Chromium -PRODUCT_SHORTNAME=Chromium -PRODUCT_INSTALLER_FULLNAME=Chromium Installer -PRODUCT_INSTALLER_SHORTNAME=Chromium Installer +COMPANY_FULLNAME=The NWJS Community +COMPANY_SHORTNAME=nwjs.io +PRODUCT_FULLNAME=nwjs +PRODUCT_SHORTNAME=nwjs +PRODUCT_INSTALLER_FULLNAME=NWJS Installer +PRODUCT_INSTALLER_SHORTNAME=NWJS Installer COPYRIGHT=Copyright 2016 The Chromium Authors. All rights reserved. -MAC_BUNDLE_ID=org.chromium.Chromium -MAC_CREATOR_CODE=Cr24 +MAC_BUNDLE_ID=io.nwjs.nwjs +MAC_CREATOR_CODE=NWJS \ No newline at end of file diff --git a/chrome/app/theme/chromium/mac/app.icns b/chrome/app/theme/chromium/mac/app.icns index 54ee532d7934d..1a03ae29c16fa 100644 Binary files a/chrome/app/theme/chromium/mac/app.icns and b/chrome/app/theme/chromium/mac/app.icns differ diff --git a/chrome/app/theme/chromium/mac/document.icns b/chrome/app/theme/chromium/mac/document.icns index 73fd43dfb87b0..1a03ae29c16fa 100644 Binary files a/chrome/app/theme/chromium/mac/document.icns and b/chrome/app/theme/chromium/mac/document.icns differ diff --git a/chrome/app/theme/chromium/product_logo_128.png b/chrome/app/theme/chromium/product_logo_128.png index 9f88fb10a2b4a..7e63ba7f8c2b1 100644 Binary files a/chrome/app/theme/chromium/product_logo_128.png and b/chrome/app/theme/chromium/product_logo_128.png differ diff --git a/chrome/app/theme/chromium/product_logo_22.png b/chrome/app/theme/chromium/product_logo_22.png index 33c2256e6d042..1207110f2c59a 100644 Binary files a/chrome/app/theme/chromium/product_logo_22.png and b/chrome/app/theme/chromium/product_logo_22.png differ diff --git a/chrome/app/theme/chromium/product_logo_22_mono.png b/chrome/app/theme/chromium/product_logo_22_mono.png index dc970053fa029..1207110f2c59a 100644 Binary files a/chrome/app/theme/chromium/product_logo_22_mono.png and b/chrome/app/theme/chromium/product_logo_22_mono.png differ diff --git a/chrome/app/theme/chromium/product_logo_24.png b/chrome/app/theme/chromium/product_logo_24.png index e6d9e56fe8bb3..543bff73b3ed1 100644 Binary files a/chrome/app/theme/chromium/product_logo_24.png and b/chrome/app/theme/chromium/product_logo_24.png differ diff --git a/chrome/app/theme/chromium/product_logo_256.png b/chrome/app/theme/chromium/product_logo_256.png index 96ee2307fc7d3..00664f9ecac42 100644 Binary files a/chrome/app/theme/chromium/product_logo_256.png and b/chrome/app/theme/chromium/product_logo_256.png differ diff --git a/chrome/app/theme/chromium/product_logo_32.xpm b/chrome/app/theme/chromium/product_logo_32.xpm new file mode 100644 index 0000000000000..71ab1b52f1637 --- /dev/null +++ b/chrome/app/theme/chromium/product_logo_32.xpm @@ -0,0 +1,563 @@ +/* XPM */ +static char * nwjs_logo_32_xpm[] = { +"32 32 528 2", +" c None", +". c #C2C2C7", +"+ c #B0B0B4", +"@ c #B8B8BC", +"# c #5F5F69", +"$ c #5E5E67", +"% c #B7B7BA", +"& c #B1B1B5", +"* c #B2B2B8", +"= c #C2C2C6", +"- c #5E5E66", +"; c #1A1D2A", +"> c #222634", +", c #222835", +"' c #1A1D29", +") c #5C5C64", +"! c #C1C1C3", +"~ c #B2B3B7", +"{ c #B1B2B9", +"] c #BEBFC2", +"^ c #909094", +"/ c #1B1C28", +"( c #2A303D", +"_ c #3A4050", +": c #444B5B", +"< c #444B5A", +"[ c #3A4151", +"} c #1A1B28", +"| c #8A8A90", +"1 c #BFBFC2", +"2 c #B1B1B9", +"3 c #BEBEC1", +"4 c #AEAEB3", +"5 c #32323B", +"6 c #1F2431", +"7 c #343A49", +"8 c #474D5E", +"9 c #515869", +"0 c #545B6C", +"a c #545C6D", +"b c #525869", +"c c #484F60", +"d c #343B4B", +"e c #1F2430", +"f c #2E2F38", +"g c #A9A9AF", +"h c #BDBDC0", +"i c #BABAC0", +"j c #BCBCC0", +"k c #57575E", +"l c #10141E", +"m c #282E3B", +"n c #3D4352", +"o c #4C5364", +"p c #565D6E", +"q c #5C6376", +"r c #61687B", +"s c #60677B", +"t c #5D6477", +"u c #585E6F", +"v c #4E5566", +"w c #3F4655", +"x c #292F3D", +"y c #525259", +"z c #BCBDC2", +"A c #A7A7AF", +"B c #C2C2C4", +"C c #85858C", +"D c #161820", +"E c #1C222D", +"F c #2F3542", +"G c #3E4553", +"H c #49505F", +"I c #555B6D", +"J c #5F6579", +"K c #686F83", +"L c #6D748A", +"M c #6C7287", +"N c #697085", +"O c #61677B", +"P c #565D6F", +"Q c #4B5262", +"R c #3F4654", +"S c #303643", +"T c #1D232F", +"U c #16171F", +"V c #7B7B81", +"W c #BEBEC2", +"X c #A6A7AE", +"Y c #9B9BA0", +"Z c #A8A8AE", +"` c #2F2F36", +" . c #11161F", +".. c #222934", +"+. c #303641", +"@. c #373D4A", +"#. c #414755", +"$. c #4E5565", +"%. c #5D6475", +"&. c #697084", +"*. c #747B90", +"=. c #757C92", +"-. c #777E94", +";. c #747C91", +">. c #6B7287", +",. c #5F6578", +"'. c #515868", +"). c #424957", +"!. c #383E4A", +"~. c #313642", +"{. c #232934", +"]. c #111520", +"^. c #2B2C33", +"/. c #A2A2A7", +"(. c #75757D", +"_. c #ABABB0", +":. c #14151D", +"<. c #1D232D", +"[. c #2B303B", +"}. c #313742", +"|. c #323844", +"1. c #353B48", +"2. c #404654", +"3. c #4E5464", +"4. c #6E768A", +"5. c #7D859A", +"6. c #7C849A", +"7. c #7E869C", +"8. c #7E879C", +"9. c #70778B", +"0. c #5F6779", +"a. c #505667", +"b. c #424856", +"c. c #383D4A", +"d. c #2C323F", +"e. c #11141C", +"f. c #A8A9AD", +"g. c #696970", +"h. c #84858B", +"i. c #5A5A61", +"j. c #1C212C", +"k. c #30343F", +"l. c #333844", +"m. c #333945", +"n. c #353B47", +"o. c #393F4B", +"p. c #404553", +"q. c #484F5D", +"r. c #5B6275", +"s. c #6E778B", +"t. c #80879D", +"u. c #80889E", +"v. c #71798E", +"w. c #5D6577", +"x. c #535A6C", +"y. c #4A515F", +"z. c #3A404C", +"A. c #363B47", +"B. c #343741", +"C. c #313A4A", +"D. c #2E3847", +"E. c #212530", +"F. c #62636A", +"G. c #87888E", +"H. c #8E8E95", +"I. c #3E3F47", +"J. c #2A2F3A", +"K. c #313640", +"L. c #333843", +"M. c #3A3F4A", +"N. c #3E4551", +"O. c #464B59", +"P. c #4C5161", +"Q. c #52596A", +"R. c #53596B", +"S. c #565F70", +"T. c #4D5363", +"U. c #474D5B", +"V. c #3E4756", +"W. c #3B3E49", +"X. c #393A46", +"Y. c #1E63B5", +"Z. c #1D4C87", +"`. c #2E3644", +" + c #2B313C", +".+ c #505158", +"++ c #919197", +"@+ c #939398", +"#+ c #393A41", +"$+ c #2A2F39", +"%+ c #2F343E", +"&+ c #303440", +"*+ c #333742", +"=+ c #393E4A", +"-+ c #3D4350", +";+ c #3B414E", +">+ c #424857", +",+ c #414654", +"'+ c #454C5A", +")+ c #434B5B", +"!+ c #41454F", +"~+ c #3E3F48", +"{+ c #33557F", +"]+ c #1F70C2", +"^+ c #0B88FF", +"/+ c #1A4373", +"(+ c #2B2A2F", +"_+ c #2E333D", +":+ c #2B303A", +"<+ c #4C4D54", +"[+ c #94959C", +"}+ c #95959B", +"|+ c #393A42", +"1+ c #292E38", +"2+ c #2F333D", +"3+ c #30353F", +"4+ c #323742", +"5+ c #353A45", +"6+ c #373C48", +"7+ c #3A404D", +"8+ c #3C4250", +"9+ c #3D4250", +"0+ c #3C414E", +"a+ c #3D424F", +"b+ c #363D4D", +"c+ c #275A96", +"d+ c #0F81F7", +"e+ c #0B85FB", +"f+ c #0B71E9", +"g+ c #1A2536", +"h+ c #282E3A", +"i+ c #2F343D", +"j+ c #2F333E", +"k+ c #2A2E39", +"l+ c #4D4E54", +"m+ c #96969D", +"n+ c #96969C", +"o+ c #393B42", +"p+ c #292D37", +"q+ c #2D323C", +"r+ c #333944", +"s+ c #353945", +"t+ c #353A46", +"u+ c #353A48", +"v+ c #3A3536", +"w+ c #30476C", +"x+ c #1860C3", +"y+ c #0D76F3", +"z+ c #0981FF", +"A+ c #0A6FF1", +"B+ c #0B49AA", +"C+ c #1B1F29", +"D+ c #2C313E", +"E+ c #30353D", +"F+ c #2E323D", +"G+ c #2A2F38", +"H+ c #98989E", +"I+ c #96969B", +"J+ c #3B3C43", +"K+ c #282D36", +"L+ c #2D313B", +"M+ c #2E333C", +"N+ c #30343D", +"O+ c #2F353F", +"P+ c #2C313C", +"Q+ c #313641", +"R+ c #2D333F", +"S+ c #545358", +"T+ c #2F7BC6", +"U+ c #1A6CDE", +"V+ c #0A78FA", +"W+ c #0A67EA", +"X+ c #0951DF", +"Y+ c #082D79", +"Z+ c #1C1E23", +"`+ c #2E3441", +" @ c #30343E", +".@ c #2E313B", +"+@ c #4E4F56", +"@@ c #3C3D44", +"#@ c #282D37", +"$@ c #2B313B", +"%@ c #252A33", +"&@ c #272C35", +"*@ c #292F39", +"=@ c #2F333F", +"-@ c #55575E", +";@ c #818183", +">@ c #9297A1", +",@ c #898988", +"'@ c #0540C3", +")@ c #0840CF", +"!@ c #0C1E46", +"~@ c #1A1F2A", +"{@ c #262B34", +"]@ c #272B35", +"^@ c #292E37", +"/@ c #2C313A", +"(@ c #4F5156", +"_@ c #97979E", +":@ c #292D36", +"<@ c #2B3038", +"[@ c #2B3039", +"}@ c #2B313A", +"|@ c #2A3039", +"1@ c #252B35", +"2@ c #67696D", +"3@ c #A2A2A2", +"4@ c #A3A3A5", +"5@ c #868B92", +"6@ c #818793", +"7@ c #0433BC", +"8@ c #0F1934", +"9@ c #272D37", +"0@ c #2C3039", +"a@ c #2C3038", +"b@ c #2A2E37", +"c@ c #4F5056", +"d@ c #96979D", +"e@ c #939399", +"f@ c #3B3D43", +"g@ c #282C36", +"h@ c #2B2F38", +"i@ c #2C2F39", +"j@ c #2B2F3A", +"k@ c #7E7F82", +"l@ c #A9A9AA", +"m@ c #A7A7A8", +"n@ c #8A8A8B", +"o@ c #5B5B5D", +"p@ c #232C48", +"q@ c #11161E", +"r@ c #2A313D", +"s@ c #292E3A", +"t@ c #2D323D", +"u@ c #282E36", +"v@ c #4D4E55", +"w@ c #95959C", +"x@ c #909096", +"y@ c #2B2F37", +"z@ c #373B44", +"A@ c #969696", +"B@ c #A5A5A6", +"C@ c #8E8E8F", +"D@ c #69696D", +"E@ c #1F222C", +"F@ c #0F1421", +"G@ c #1E232F", +"H@ c #2D323E", +"I@ c #272D38", +"J@ c #2C303A", +"K@ c #2A2F37", +"L@ c #4E4F55", +"M@ c #93939A", +"N@ c #8E8E93", +"O@ c #3B3D44", +"P@ c #232831", +"Q@ c #53565B", +"R@ c #9F9E9D", +"S@ c #8B8B8B", +"T@ c #45474C", +"U@ c #161822", +"V@ c #060C18", +"W@ c #1F2531", +"X@ c #2C313F", +"Y@ c #272D39", +"Z@ c #262C36", +"`@ c #29303B", +" # c #2A2E38", +".# c #8E8F96", +"+# c #3D3E46", +"@# c #262A33", +"## c #696A6D", +"$# c #757678", +"%# c #33373E", +"&# c #060B18", +"*# c #161C29", +"=# c #29303D", +"-# c #272F3B", +";# c #212833", +"># c #242A36", +",# c #2A303E", +"'# c #2B303E", +")# c #2B323F", +"!# c #282F3B", +"~# c #282E38", +"{# c #4C4E55", +"]# c #88888F", +"^# c #7E7E85", +"/# c #43444C", +"(# c #262B35", +"_# c #2F333B", +":# c #4C4E51", +"<# c #21272F", +"[# c #141924", +"}# c #1D222D", +"|# c #292E39", +"1# c #2B313F", +"2# c #262D38", +"3# c #2B313E", +"4# c #2B303C", +"5# c #292F38", +"6# c #52535A", +"7# c #808087", +"8# c #6F7076", +"9# c #5D5D66", +"0# c #252B34", +"a# c #1E222D", +"b# c #242832", +"c# c #272E37", +"d# c #2A303C", +"e# c #2B313D", +"f# c #2C3340", +"g# c #272E3B", +"h# c #2B3340", +"i# c #68696F", +"j# c #707178", +"k# c #9F9FA4", +"l# c #2A2D37", +"m# c #2B323B", +"n# c #2D333E", +"o# c #2F3440", +"p# c #2C323D", +"q# c #2B323D", +"r# c #2C313D", +"s# c #2B303D", +"t# c #282D3A", +"u# c #282D3B", +"v# c #2C323C", +"w# c #2E343E", +"x# c #2F3441", +"y# c #2F3540", +"z# c #2A303A", +"A# c #9B9CA1", +"B# c #4E4E56", +"C# c #72737B", +"D# c #A2A3A7", +"E# c #4C4E57", +"F# c #262C35", +"G# c #303642", +"H# c #313743", +"I# c #2F3642", +"J# c #2F3644", +"K# c #2F3643", +"L# c #2F3543", +"M# c #2D3341", +"N# c #2D3340", +"O# c #303743", +"P# c #2F3640", +"Q# c #50525A", +"R# c #9F9FA5", +"S# c #6A6A73", +"T# c #62626C", +"U# c #9F9FA7", +"V# c #8A8A92", +"W# c #363942", +"X# c #232932", +"Y# c #2F343F", +"Z# c #313744", +"`# c #343C4A", +" $ c #363F52", +".$ c #394258", +"+$ c #3A455D", +"@$ c #39435B", +"#$ c #394358", +"$$ c #373F52", +"%$ c #343B4A", +"&$ c #323744", +"*$ c #222730", +"=$ c #3C3F47", +"-$ c #909198", +";$ c #9D9DA6", +">$ c #61616C", +",$ c #7D7E88", +"'$ c #ACACB5", +")$ c #717179", +"!$ c #2A2E36", +"~$ c #29303A", +"{$ c #323949", +"]$ c #353D4F", +"^$ c #3A4256", +"/$ c #394256", +"($ c #373F53", +"_$ c #353D4E", +":$ c #333A49", +"<$ c #272B33", +"[$ c #75767D", +"}$ c #A8A8B0", +"|$ c #787984", +"1$ c #8B8B95", +"2$ c #A1A1A9", +"3$ c #575861", +"4$ c #1F252E", +"5$ c #303847", +"6$ c #313948", +"7$ c #313846", +"8$ c #303742", +"9$ c #1F252F", +"0$ c #5B5C64", +"a$ c #A6A6AD", +"b$ c #8A8A94", +"c$ c #6A6A75", +"d$ c #93949D", +"e$ c #8F8F98", +"f$ c #3E414A", +"g$ c #242932", +"h$ c #2E333E", +"i$ c #2E323E", +"j$ c #2D333D", +"k$ c #3C3E47", +"l$ c #8F8F97", +"m$ c #90909A", +"n$ c #666672", +"o$ c #6A6B76", +"p$ c #73747D", +"q$ c #292D35", +"r$ c #75767E", +"s$ c #92929B", +"t$ c #696A75", +"u$ c #686974", +"v$ c #82828D", +"w$ c #6B6C76", +"x$ c #6A6C75", +"y$ c #81808B", +"z$ c #666773", +"A$ c #474855", +"B$ c #5E5F6A", +"C$ c #5F606C", +" . . ", +" + @ # $ % & ", +" * = - ; > , ' ) ! ~ ", +" { ] ^ / ( _ : < [ ( } | 1 2 ", +" 3 4 5 6 7 8 9 0 a b c d e f g h ", +" i j k l m n o p q r s t u v w x l y @ z ", +" A B C D E F G H I J K L M N O P Q R S T U V W X ", +" Y Z ` ...+.@.#.$.%.&.*.=.-.;.>.,.'.).!.~.{.].^./.Y ", +" (._.:.<.[.}.|.1.2.3.q 4.5.6.7.8.9.0.a.b.c.|.}.d.<.e.f.g. ", +" h.i.j.k.l.m.n.o.p.q.9 r.s.t.u.v.w.x.y.#.z.A.B.C.D.E.F.G. ", +" H.I.J.K.+.L.A.M.N.O.P.Q.P R.b S.R.T.U.V.W.X.Y.Z.`. +.+++ ", +" @+#+$+%+&+*+A.=+-+;+2.>+,+'+'+b.)+!+~+{+]+^+/+(+_+:+<+[+ ", +" }+|+1+2+3+4+5+6+M.7+n.c.8+9+0+a+b+c+d+e+f+g+h+i+j+k+l+m+ ", +" n+o+p+q+i+K.4+r+s+l.~.t+u+v+w+x+y+z+A+B+C+D+K.E+F+G+l+H+ ", +" I+J+K+L+M+N+O+k.%+P+Q+R+S+T+U+V+W+X+Y+Z+`+k. @2+.@1++@H+ ", +" }+@@#@$@:+p+%@&@#@*@=@-@;@>@,@'@)@!@~@{@]@%@^@:+/@G+(@_@ ", +" }+@@:@<@[@[@}@$+|@1@2@3@4@5@6@7@8@K+{@9@$+[.:+0@a@b@c@d@ ", +" e@f@g@h@h@i@j@ +&+k@l@m@n@o@p@q@r@s@:+t@ +j@[@h@h@u@v@w@ ", +" x@@@]@h@y@<@[@z@A@B@C@D@E@F@G@t@H@I@D+ +J@$+h@K@h@:@L@M@ ", +" N@O@{@p+h@P@Q@R@S@T@U@V@W@X@X@h+Y@Z@`@[.j@G+h@ #^@&@+@.# ", +" G.+#@##@}@##$#%#&#*#=#X@-#;#>#,#'#)#!# +J.:+$+^@~#]@{#]# ", +" ^#/#(#_#:#<#[#}#|#D+D+1#( 2#2#3#1#D+D+4#$@J.5# #^@]@6#7# ", +" 8#9#0#|#a#b#c#d#e#e#d.d.f#m g#h#d.3#e#e#[.|@:+[.P+$+i#j# ", +" 6#k#l#m#n#o#n#p#q#r#e#s#3#t#u#e#s#r#v#e#p#w#x#y#z#h@A#B# ", +" C#D#E#F#}.G#S H#I#J#K#L#M#N#F L#J#S O#H#G#P#b#Q#R#S# ", +" T#U#V#W#X#%+Y#Z#`# $.$+$@$#$$$%$&$Y#%+*$=$-$;$>$ ", +" ,$'$)$!$~$I#{$]$$$^$/$($_$:$L#*@<$[$}$|$ ", +" 1$2$3$4$+.K#5$6$6$7$K#8$9$0$a$b$ ", +" c$d$e$f$g$h$i$H@j$P@k$l$m$n$ ", +" o$e$p$q$/@/@!$r$s$t$ ", +" u$v$w$x$y$z$ ", +" A$B$C$ "}; diff --git a/chrome/app/theme/chromium/product_logo_64.png b/chrome/app/theme/chromium/product_logo_64.png index c8f9c190c8e97..8358e5d2e0a32 100644 Binary files a/chrome/app/theme/chromium/product_logo_64.png and b/chrome/app/theme/chromium/product_logo_64.png differ diff --git a/chrome/app/theme/chromium/win/chromium.ico b/chrome/app/theme/chromium/win/chromium.ico index c2e434a028b53..173a8f4e8f8aa 100644 Binary files a/chrome/app/theme/chromium/win/chromium.ico and b/chrome/app/theme/chromium/win/chromium.ico differ diff --git a/chrome/app/version_assembly/BUILD.gn b/chrome/app/version_assembly/BUILD.gn index f9336e7c6803e..608fb1a197e4a 100644 --- a/chrome/app/version_assembly/BUILD.gn +++ b/chrome/app/version_assembly/BUILD.gn @@ -24,8 +24,7 @@ windows_manifest("chrome_exe_manifest") { sources = [ as_invoker_manifest, common_controls_manifest, - default_compatibility_manifest, - version_assembly_output_file, + default_compatibility_manifest ] type = "exe" diff --git a/chrome/app/version_assembly/version_assembly_manifest.template b/chrome/app/version_assembly/version_assembly_manifest.template index 9bd1fc58f9fb1..8478d639e0689 100644 --- a/chrome/app/version_assembly/version_assembly_manifest.template +++ b/chrome/app/version_assembly/version_assembly_manifest.template @@ -4,5 +4,5 @@ name='@MAJOR@.@MINOR@.@BUILD@.@PATCH@' version='@MAJOR@.@MINOR@.@BUILD@.@PATCH@' type='win32'/> - + diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index c79b28b3776c9..afbaa469c47a9 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn @@ -1392,20 +1392,20 @@ split_static_library("browser") { "tracing/crash_service_uploader.h", "tracing/navigation_tracing.cc", "tracing/navigation_tracing.h", - "translate/android/translate_utils.cc", - "translate/android/translate_utils.h", - "translate/chrome_translate_client.cc", - "translate/chrome_translate_client.h", + #"translate/android/translate_utils.cc", + #"translate/android/translate_utils.h", + #"translate/chrome_translate_client.cc", + #"translate/chrome_translate_client.h", "translate/language_model_factory.cc", "translate/language_model_factory.h", - "translate/translate_accept_languages_factory.cc", - "translate/translate_accept_languages_factory.h", - "translate/translate_ranker_factory.cc", - "translate/translate_ranker_factory.h", - "translate/translate_ranker_metrics_provider.cc", - "translate/translate_ranker_metrics_provider.h", - "translate/translate_service.cc", - "translate/translate_service.h", + #"translate/translate_accept_languages_factory.cc", + #"translate/translate_accept_languages_factory.h", + #"translate/translate_ranker_factory.cc", + #"translate/translate_ranker_factory.h", + #"translate/translate_ranker_metrics_provider.cc", + #"translate/translate_ranker_metrics_provider.h", + #"translate/translate_service.cc", + #"translate/translate_service.h", "undo/bookmark_undo_service_factory.cc", "undo/bookmark_undo_service_factory.h", "update_client/chrome_update_query_params_delegate.cc", @@ -1476,6 +1476,7 @@ split_static_library("browser") { deps = [ ":resource_prefetch_predictor_proto", "//cc", + "//content/nw:nw_browser", "//chrome:extra_resources", "//chrome:resources", "//chrome:strings", @@ -1505,7 +1506,7 @@ split_static_library("browser") { "//components/chrome_cleaner/public/constants", "//components/chrome_cleaner/public/interfaces", "//components/cloud_devices/common", - "//components/component_updater", + #"//components/component_updater", "//components/content_settings/core/browser", "//components/content_settings/core/common", "//components/contextual_search:browser", @@ -1573,11 +1574,11 @@ split_static_library("browser") { "//components/profile_metrics", "//components/proxy_config", "//components/query_parser", - "//components/rappor", - "//components/rappor:rappor_recorder", + #"//components/rappor", + #"//components/rappor:rappor_recorder", "//components/renderer_context_menu", "//components/resources", - "//components/safe_browsing_db", + #"//components/safe_browsing_db", "//components/safe_json", "//components/search", "//components/search_engines", @@ -4382,8 +4383,11 @@ proto_library("resource_prefetch_predictor_proto") { } grit("resources") { - source = "browser_resources.grd" - + if (nwjs_sdk) { + source = "browser_resources.grd" + } else { + source = "nwjs_resources.grd" + } defines = chrome_grit_defines if (enable_hangout_services_extension) { defines += [ "enable_hangout_services_extension" ] diff --git a/chrome/browser/app_controller_mac.mm b/chrome/browser/app_controller_mac.mm index a7c2bfb9d87dc..51b37b0beafb9 100644 --- a/chrome/browser/app_controller_mac.mm +++ b/chrome/browser/app_controller_mac.mm @@ -102,6 +102,8 @@ #include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/l10n_util_mac.h" +#include "content/nw/src/nw_content.h" + using apps::AppShimHandler; using apps::ExtensionAppShimHandler; using base::UserMetricsAction; @@ -143,7 +145,7 @@ } Browser* browser = chrome::GetLastActiveBrowser(); - CHECK(browser); + //CHECK(browser); return browser; } @@ -343,6 +345,7 @@ - (void)awakeFromNib { [self initMenuState]; // Initialize the Profile menu. +#if 0 [self initProfileMenu]; // If the OSX version supports this method, the system will automatically @@ -356,6 +359,7 @@ - (void)awakeFromNib { if (customizeItem) [viewMenu removeItem:customizeItem]; } +#endif } - (void)unregisterEventHandlers { @@ -465,6 +469,9 @@ - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app { return NSTerminateNow; } + if (!AppWindowRegistryUtil::CloseAllAppWindows(true)) + return NSTerminateCancel; + // Check if the preference is turned on. const PrefService* prefs = g_browser_process->local_state(); if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) { @@ -646,7 +653,11 @@ - (void)setUpdateCheckInterval { - (void)openStartupUrls { DCHECK(startupComplete_); - [self openUrlsReplacingNTP:startupUrls_]; + if (startupUrls_.size()) { + base::CommandLine::ForCurrentProcess()->AppendArg(startupUrls_[0].spec()); + base::CommandLine::ForCurrentProcess()->FixOrigArgv4Finder(startupUrls_[0].spec()); + } + //[self openUrlsReplacingNTP:startupUrls_]; startupUrls_.clear(); } @@ -709,7 +720,7 @@ - (void)applicationDidFinishLaunching:(NSNotification*)notify { // If enabled, keep Chrome alive when apps are open instead of quitting all // apps. - quitWithAppsController_ = new QuitWithAppsController(); + // quitWithAppsController_ = new QuitWithAppsController(); // Dynamically update shortcuts for "Close Window" and "Close Tab" menu items. [[closeTabMenuItem_ menu] setDelegate:self]; @@ -1091,6 +1102,8 @@ - (void)commandDispatchUsingKeyModifiers:(id)sender { // browser windows. - (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows { + return nw::ApplicationShouldHandleReopenHook(hasVisibleWindows) ? YES : NO; +#if 0 // If the browser is currently trying to quit, don't do anything and return NO // to prevent AppKit from doing anything. // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved. @@ -1180,6 +1193,7 @@ - (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication // We've handled the reopen event, so return NO to tell AppKit not // to do anything. return NO; +#endif } - (void)initMenuState { @@ -1288,6 +1302,9 @@ - (void)openUrls:(const std::vector&)urls { return; } + nw::OSXOpenURLsHook(urls); + +#if 0 Browser* browser = chrome::GetLastActiveBrowser(); // if no browser window exists then create one with no tabs to be filled in if (!browser) { @@ -1301,6 +1318,7 @@ - (void)openUrls:(const std::vector&)urls { chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN; StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run); launch.OpenURLsInBrowser(browser, false, urls); +#endif } - (void)getUrl:(NSAppleEventDescriptor*)event @@ -1384,6 +1402,7 @@ - (NSMenu*)applicationDockMenu:(NSApplication*)sender { if (profilesAdded) [dockMenu addItem:[NSMenuItem separatorItem]]; +#if 0 NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC); base::scoped_nsobject item( [[NSMenuItem alloc] initWithTitle:titleStr @@ -1408,6 +1427,7 @@ - (NSMenu*)applicationDockMenu:(NSApplication*)sender { [item setEnabled:[self validateUserInterfaceItem:item]]; [dockMenu addItem:item]; } +#endif // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit // tests which use the mock in place of the profile-initialized model. diff --git a/chrome/browser/apps/app_load_service.cc b/chrome/browser/apps/app_load_service.cc index cbf6cdc553733..67dea8d919251 100644 --- a/chrome/browser/apps/app_load_service.cc +++ b/chrome/browser/apps/app_load_service.cc @@ -4,6 +4,8 @@ #include "chrome/browser/apps/app_load_service.h" +#include "content/nw/src/nw_content.h" + #include "apps/app_restore_service.h" #include "apps/launcher.h" #include "chrome/browser/apps/app_load_service_factory.h" @@ -71,6 +73,8 @@ bool AppLoadService::LoadAndLaunch(const base::FilePath& extension_path, return false; } + nw::SetMainExtensionId(extension_id); + // Schedule the app to be launched once loaded. PostReloadAction& action = post_reload_actions_[extension_id]; action.action_type = LAUNCH_FOR_LOAD_AND_LAUNCH; diff --git a/chrome/browser/apps/app_shim/app_shim_handler_mac.cc b/chrome/browser/apps/app_shim/app_shim_handler_mac.cc index e8d0a9128a1a3..755623f4e1230 100644 --- a/chrome/browser/apps/app_shim/app_shim_handler_mac.cc +++ b/chrome/browser/apps/app_shim/app_shim_handler_mac.cc @@ -21,13 +21,15 @@ #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" +#include "content/nw/src/nw_content.h" + namespace apps { namespace { void TerminateIfNoAppWindows() { bool app_windows_left = - AppWindowRegistryUtil::IsAppWindowVisibleInAnyProfile(0); + AppWindowRegistryUtil::IsAppWindowVisibleInAnyProfile(0, false); if (!app_windows_left && !AppListService::Get()->IsAppListVisible()) { chrome::AttemptExit(); } @@ -63,7 +65,8 @@ class AppShimHandlerRegistry : public content::NotificationObserver { } void MaybeTerminate() { - if (!browser_session_running_) { + if (!nw::IsReloadingApp()) { + //NW: #4164. browser_session_running_ never set to false // Post this to give AppWindows a chance to remove themselves from the // registry. base::ThreadTaskRunnerHandle::Get()->PostTask( diff --git a/chrome/browser/apps/app_shim/extension_app_shim_handler_mac.cc b/chrome/browser/apps/app_shim/extension_app_shim_handler_mac.cc index 03d55d7daaa28..0a8640132fa27 100644 --- a/chrome/browser/apps/app_shim/extension_app_shim_handler_mac.cc +++ b/chrome/browser/apps/app_shim/extension_app_shim_handler_mac.cc @@ -323,7 +323,7 @@ const Extension* ExtensionAppShimHandler::MaybeGetAppForBrowser( } // static -void ExtensionAppShimHandler::QuitAppForWindow(AppWindow* app_window) { +void ExtensionAppShimHandler::QuitAppForWindow(AppWindow* app_window, bool user_force) { ExtensionAppShimHandler* handler = GetInstance(); Host* host = handler->FindHost( Profile::FromBrowserContext(app_window->browser_context()), @@ -334,7 +334,7 @@ void ExtensionAppShimHandler::QuitAppForWindow(AppWindow* app_window) { // App shims might be disabled or the shim is still starting up. AppWindowRegistry::Get( Profile::FromBrowserContext(app_window->browser_context())) - ->CloseAllAppWindowsForApp(app_window->extension_id()); + ->CloseAllAppWindowsForApp(app_window->extension_id(), user_force); } } @@ -639,7 +639,8 @@ void ExtensionAppShimHandler::OnShimQuit(Host* host) { const AppWindowList windows = delegate_->GetWindows(profile, app_id); for (AppWindowRegistry::const_iterator it = windows.begin(); it != windows.end(); ++it) { - (*it)->GetBaseWindow()->Close(); + if ((*it)->NWCanClose()) + (*it)->GetBaseWindow()->Close(); } } // Once the last window closes, flow will end up in OnAppDeactivated via diff --git a/chrome/browser/apps/app_shim/extension_app_shim_handler_mac.h b/chrome/browser/apps/app_shim/extension_app_shim_handler_mac.h index 1b3efd15765d1..23067efba9b6e 100644 --- a/chrome/browser/apps/app_shim/extension_app_shim_handler_mac.h +++ b/chrome/browser/apps/app_shim/extension_app_shim_handler_mac.h @@ -93,7 +93,7 @@ class ExtensionAppShimHandler : public AppShimHandler, static const extensions::Extension* MaybeGetAppForBrowser(Browser* browser); - static void QuitAppForWindow(extensions::AppWindow* app_window); + static void QuitAppForWindow(extensions::AppWindow* app_window, bool user_force = false); static void QuitHostedAppForWindow(Profile* profile, const std::string& app_id); diff --git a/chrome/browser/apps/app_window_registry_util.cc b/chrome/browser/apps/app_window_registry_util.cc index d8702debf325e..571bee28832f3 100644 --- a/chrome/browser/apps/app_window_registry_util.cc +++ b/chrome/browser/apps/app_window_registry_util.cc @@ -43,7 +43,7 @@ AppWindow* AppWindowRegistryUtil::GetAppWindowForNativeWindowAnyProfile( // static bool AppWindowRegistryUtil::IsAppWindowVisibleInAnyProfile( - int window_type_mask) { + int window_type_mask, bool check_visible) { std::vector profiles = g_browser_process->profile_manager()->GetLoadedProfiles(); for (std::vector::const_iterator i = profiles.begin(); @@ -59,7 +59,7 @@ bool AppWindowRegistryUtil::IsAppWindowVisibleInAnyProfile( continue; for (const AppWindow* window : app_windows) { - if (!window->is_hidden() && + if ((!window->is_hidden() || !check_visible )&& (window_type_mask == 0 || (window->window_type() & window_type_mask))) return true; @@ -70,7 +70,7 @@ bool AppWindowRegistryUtil::IsAppWindowVisibleInAnyProfile( } // static -void AppWindowRegistryUtil::CloseAllAppWindows() { +bool AppWindowRegistryUtil::CloseAllAppWindows(bool user_force) { std::vector profiles = g_browser_process->profile_manager()->GetLoadedProfiles(); for (std::vector::const_iterator i = profiles.begin(); @@ -86,8 +86,13 @@ void AppWindowRegistryUtil::CloseAllAppWindows() { AppWindowList window_list_copy(registry->app_windows()); for (auto* window : window_list_copy) { // Ensure window is still valid. - if (base::ContainsValue(registry->app_windows(), window)) - window->GetBaseWindow()->Close(); + if (base::ContainsValue(registry->app_windows(), window)) { + if (window->NWCanClose(user_force)) + window->GetBaseWindow()->Close(); + else + return false; + } } } + return true; } diff --git a/chrome/browser/apps/app_window_registry_util.h b/chrome/browser/apps/app_window_registry_util.h index 8fd6b358cc8ca..5dcf02ecd612d 100644 --- a/chrome/browser/apps/app_window_registry_util.h +++ b/chrome/browser/apps/app_window_registry_util.h @@ -21,10 +21,10 @@ class AppWindowRegistryUtil { // Returns true if the number of visible app windows registered across all // browser contexts is non-zero. |window_type_mask| is a bitwise OR filter of // AppWindow::WindowType, or 0 for any window type. - static bool IsAppWindowVisibleInAnyProfile(int window_type_mask); + static bool IsAppWindowVisibleInAnyProfile(int window_type_mask, bool check_visible = true); // Close all app windows in all profiles. - static void CloseAllAppWindows(); + static bool CloseAllAppWindows(bool user_force = false); }; #endif // CHROME_BROWSER_APPS_APP_WINDOW_REGISTRY_UTIL_H_ diff --git a/chrome/browser/apps/browser_context_keyed_service_factories.cc b/chrome/browser/apps/browser_context_keyed_service_factories.cc index 73955307fb649..e1144eace4e1f 100644 --- a/chrome/browser/apps/browser_context_keyed_service_factories.cc +++ b/chrome/browser/apps/browser_context_keyed_service_factories.cc @@ -13,7 +13,7 @@ namespace chrome_apps { void EnsureBrowserContextKeyedServiceFactoriesBuilt() { apps::EnsureBrowserContextKeyedServiceFactoriesBuilt(); - AppShortcutManagerFactory::GetInstance(); + //AppShortcutManagerFactory::GetInstance(); apps::AppLoadServiceFactory::GetInstance(); } diff --git a/chrome/browser/background/background_application_list_model.cc b/chrome/browser/background/background_application_list_model.cc index 7c6bef10ec23e..820c00531505e 100644 --- a/chrome/browser/background/background_application_list_model.cc +++ b/chrome/browser/background/background_application_list_model.cc @@ -251,8 +251,10 @@ bool BackgroundApplicationListModel::IsBackgroundApp( // manifest. // Not a background app if we don't have the background permission. + // NWJS: nwjs_default_app is listed as background app and prevents + // quit so we need to disable it here if (!extension.permissions_data()->HasAPIPermission( - APIPermission::kBackground)) { + APIPermission::kBackground, true)) { return false; } diff --git a/chrome/browser/background/background_contents_service.cc b/chrome/browser/background/background_contents_service.cc index 5e79600f38635..b41df0570da30 100644 --- a/chrome/browser/background/background_contents_service.cc +++ b/chrome/browser/background/background_contents_service.cc @@ -417,6 +417,7 @@ void BackgroundContentsService::Observe( } case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: case chrome::NOTIFICATION_BACKGROUND_CONTENTS_TERMINATED: { +#if 0 Profile* profile = content::Source(source).ptr(); const Extension* extension = NULL; if (type == chrome::NOTIFICATION_BACKGROUND_CONTENTS_TERMINATED) { @@ -451,6 +452,7 @@ void BackgroundContentsService::Observe( // Restart the extension. RestartForceInstalledExtensionOnCrash(extension, profile); } +#endif break; } diff --git a/chrome/browser/browser_process.h b/chrome/browser/browser_process.h index 96d26749b40db..1ffab3f542a5c 100644 --- a/chrome/browser/browser_process.h +++ b/chrome/browser/browser_process.h @@ -255,6 +255,7 @@ class BrowserProcess { virtual net_log::ChromeNetLog* net_log() = 0; +#if 0 virtual component_updater::ComponentUpdateService* component_updater() = 0; virtual CRLSetFetcher* crl_set_fetcher() = 0; @@ -264,7 +265,7 @@ class BrowserProcess { virtual component_updater::SupervisedUserWhitelistInstaller* supervised_user_whitelist_installer() = 0; - +#endif virtual MediaFileSystemRegistry* media_file_system_registry() = 0; virtual bool created_local_state() const = 0; diff --git a/chrome/browser/browser_process_impl.cc b/chrome/browser/browser_process_impl.cc index fca71f7f0bc86..0085727853cbb 100644 --- a/chrome/browser/browser_process_impl.cc +++ b/chrome/browser/browser_process_impl.cc @@ -306,8 +306,10 @@ void BrowserProcessImpl::StartTearDown() { // that URLFetcher operation before going away.) metrics_services_manager_.reset(); intranet_redirect_detector_.reset(); +#if 0 if (safe_browsing_service_.get()) safe_browsing_service()->ShutDown(); +#endif network_time_tracker_.reset(); #if BUILDFLAG(ENABLE_PLUGINS) plugins_resource_service_.reset(); @@ -944,6 +946,7 @@ net_log::ChromeNetLog* BrowserProcessImpl::net_log() { return net_log_.get(); } +#if 0 component_updater::ComponentUpdateService* BrowserProcessImpl::component_updater() { if (component_updater_) @@ -960,13 +963,16 @@ BrowserProcessImpl::component_updater() { return component_updater_.get(); } +#endif +#if 0 CRLSetFetcher* BrowserProcessImpl::crl_set_fetcher() { if (!crl_set_fetcher_) crl_set_fetcher_ = new CRLSetFetcher(); return crl_set_fetcher_.get(); } + component_updater::PnaclComponentInstaller* BrowserProcessImpl::pnacl_component_installer() { #if !defined(DISABLE_NACL) @@ -991,6 +997,7 @@ BrowserProcessImpl::supervised_user_whitelist_installer() { } return supervised_user_whitelist_installer_.get(); } +#endif void BrowserProcessImpl::ResourceDispatcherHostCreated() { resource_dispatcher_host_delegate_.reset( @@ -1079,8 +1086,11 @@ void BrowserProcessImpl::PreCreateThreads() { #if BUILDFLAG(ENABLE_EXTENSIONS) // chrome-extension:// URLs are safe to request anywhere, but may only // commit (including in iframes) in extension processes. - ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeIsolatedScheme( - extensions::kExtensionScheme, true); + // NWJS: Upstream: Remove command line/field trial support for + // disabling Isolate + // Extensions. https://codereview.chromium.org/2850793005 + ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme( + extensions::kExtensionScheme); #endif io_thread_.reset( @@ -1209,9 +1219,11 @@ void BrowserProcessImpl::CreateSafeBrowsingService() { // Set this flag to true so that we don't retry indefinitely to // create the service class if there was an error. created_safe_browsing_service_ = true; +#if 0 safe_browsing_service_ = safe_browsing::SafeBrowsingService::CreateSafeBrowsingService(); safe_browsing_service_->Initialize(); +#endif } void BrowserProcessImpl::CreateSubresourceFilterRulesetService() { @@ -1303,7 +1315,7 @@ void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() { } void BrowserProcessImpl::ApplyMetricsReportingPolicy() { -#if !defined(OS_ANDROID) +#if 0 CHECK(BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::BindOnce( @@ -1313,11 +1325,13 @@ void BrowserProcessImpl::ApplyMetricsReportingPolicy() { } void BrowserProcessImpl::CacheDefaultWebClientState() { +#if 0 #if defined(OS_CHROMEOS) cached_default_web_client_state_ = shell_integration::IS_DEFAULT; #elif !defined(OS_ANDROID) cached_default_web_client_state_ = shell_integration::GetDefaultBrowser(); #endif +#endif } void BrowserProcessImpl::Pin() { diff --git a/chrome/browser/browser_process_impl.h b/chrome/browser/browser_process_impl.h index ac66b067e7eae..50b09fada66bc 100644 --- a/chrome/browser/browser_process_impl.h +++ b/chrome/browser/browser_process_impl.h @@ -142,12 +142,14 @@ class BrowserProcessImpl : public BrowserProcess, #endif net_log::ChromeNetLog* net_log() override; +#if 0 component_updater::ComponentUpdateService* component_updater() override; CRLSetFetcher* crl_set_fetcher() override; component_updater::PnaclComponentInstaller* pnacl_component_installer() override; component_updater::SupervisedUserWhitelistInstaller* supervised_user_whitelist_installer() override; +#endif MediaFileSystemRegistry* media_file_system_registry() override; bool created_local_state() const override; #if BUILDFLAG(ENABLE_WEBRTC) diff --git a/chrome/browser/browser_resources.grd b/chrome/browser/browser_resources.grd index 77382fa27d849..4bb5f02336162 100644 --- a/chrome/browser/browser_resources.grd +++ b/chrome/browser/browser_resources.grd @@ -93,6 +93,7 @@ + diff --git a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc index 601de50127851..ec930141a4036 100644 --- a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc +++ b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc @@ -139,6 +139,7 @@ base::Closure UIThreadTrampoline(const base::Closure& callback) { return base::Bind(&UIThreadTrampolineHelper, callback); } + template void IgnoreArgumentHelper(const base::Closure& callback, T unused_argument) { callback.Run(); @@ -185,6 +186,7 @@ void ClearPnaclCacheOnIOThread(base::Time begin, } #endif +#if 0 void ClearCookiesOnIOThread(base::Time delete_begin, base::Time delete_end, net::URLRequestContextGetter* rq_context, @@ -208,6 +210,7 @@ void ClearCookiesWithPredicateOnIOThread( cookie_store->DeleteAllCreatedBetweenWithPredicateAsync( delete_begin, delete_end, predicate, IgnoreArgument(callback)); } +#endif void ClearNetworkPredictorOnIOThread(chrome_browser_net::Predictor* predictor) { DCHECK_CURRENTLY_ON(BrowserThread::IO); @@ -693,6 +696,7 @@ void ChromeBrowsingDataRemoverDelegate::RemoveEmbedderData( // hours/days to the safebrowsing cookies since they aren't the result of // any user action. if (delete_begin_ == base::Time()) { +#if 0 safe_browsing::SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service(); if (sb_service) { @@ -720,6 +724,7 @@ void ChromeBrowsingDataRemoverDelegate::RemoveEmbedderData( weak_ptr_factory_.GetWeakPtr())))); } } +#endif } MediaDeviceIDSalt::Reset(profile_->GetPrefs()); diff --git a/chrome/browser/chrome_browser_main.cc b/chrome/browser/chrome_browser_main.cc index f786c546e9a5d..f349e5f65891a 100644 --- a/chrome/browser/chrome_browser_main.cc +++ b/chrome/browser/chrome_browser_main.cc @@ -12,6 +12,11 @@ #include #include + +#include "content/nw/src/browser/nw_chrome_browser_hooks.h" +#include "content/nw/src/browser/nw_content_browser_hooks.h" + + #include "base/at_exit.h" #include "base/base_switches.h" #include "base/bind.h" @@ -468,6 +473,7 @@ OSStatus KeychainCallback(SecKeychainEvent keychain_event, } #endif // defined(OS_MACOSX) +#if 0 void RegisterComponentsForUpdate() { auto* const cus = g_browser_process->component_updater(); @@ -535,6 +541,7 @@ void RegisterComponentsForUpdate() { #endif // defined(GOOGLE_CHROME_BUILD) #endif // defined(OS_WIN) } +#endif // disable component updater #if !defined(OS_ANDROID) bool ProcessSingletonNotificationCallback( @@ -544,6 +551,9 @@ bool ProcessSingletonNotificationCallback( if (!g_browser_process || g_browser_process->IsShuttingDown()) return false; + if (!nw::ProcessSingletonNotificationCallbackHook(command_line, current_directory)) + return false; + if (command_line.HasSwitch(switches::kOriginalProcessStartTime)) { std::string start_time_string = command_line.GetSwitchValueASCII(switches::kOriginalProcessStartTime); @@ -808,7 +818,7 @@ void ChromeBrowserMainParts::StartMetricsRecording() { group_name); } - g_browser_process->GetMetricsServicesManager()->UpdateUploadPermissions(true); + g_browser_process->GetMetricsServicesManager()->UpdateUploadPermissions(false); } void ChromeBrowserMainParts::RecordBrowserStartupTime() { @@ -948,9 +958,13 @@ int ChromeBrowserMainParts::PreCreateThreads() { // should be deferred to PreMainMessageLoopRunImpl. TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads"); + result_code_ = PreCreateThreadsImpl(); if (result_code_ == content::RESULT_CODE_NORMAL_EXIT) { + result_code_ = nw::MainPartsPreCreateThreadsHook(); + if (result_code_ != content::RESULT_CODE_NORMAL_EXIT) + return result_code_; #if !defined(OS_ANDROID) // These members must be initialized before exiting this function normally. DCHECK(master_prefs_.get()); @@ -1247,6 +1261,8 @@ void ChromeBrowserMainParts::PreMainMessageLoopRun() { result_code_ = PreMainMessageLoopRunImpl(); + nw::MainPartsPreMainMessageLoopRunHook(); + for (size_t i = 0; i < chrome_extra_parts_.size(); ++i) chrome_extra_parts_[i]->PreMainMessageLoopRun(); } @@ -1640,7 +1656,7 @@ int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() { #endif // BUILDFLAG(ENABLE_BACKGROUND) // Post-profile init --------------------------------------------------------- - TranslateService::Initialize(); + //TranslateService::Initialize(); // Needs to be done before PostProfileInit, since login manager on CrOS is // called inside PostProfileInit. @@ -1658,7 +1674,7 @@ int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() { // (requires supporting early exit). PostProfileInit(); -#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) +#if 0 //!defined(OS_ANDROID) && !defined(OS_CHROMEOS) // Execute first run specific code after the PrefService has been initialized // and preferences have been registered since some of the import code depends // on preferences. @@ -1815,9 +1831,10 @@ int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() { // http://crbug.com/105065. browser_process_->notification_ui_manager(); +#if 0 if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate)) RegisterComponentsForUpdate(); - +#endif #if defined(OS_ANDROID) variations::VariationsService* variations_service = browser_process_->variations_service(); @@ -1991,7 +2008,7 @@ void ChromeBrowserMainParts::PostMainMessageLoopRun() { // Some tests don't set parameters.ui_task, so they started translate // language fetch that was never completed so we need to cleanup here // otherwise it will be done by the destructor in a wrong thread. - TranslateService::Shutdown(parameters().ui_task == NULL); + //TranslateService::Shutdown(parameters().ui_task == NULL); if (notify_result_ == ProcessSingleton::PROCESS_NONE) process_singleton_->Cleanup(); @@ -2056,6 +2073,7 @@ void ChromeBrowserMainParts::PostDestroyThreads() { process_singleton_.reset(); device_event_log::Shutdown(); + nw::MainPartsPostDestroyThreadsHook(); // We need to do this check as late as possible, but due to modularity, this // may be the last point in Chrome. This would be more effective if done at // a higher level on the stack, so that it is impossible for an early return diff --git a/chrome/browser/chrome_browser_main_mac.mm b/chrome/browser/chrome_browser_main_mac.mm index 31016d66d6769..071d7684c18bc 100644 --- a/chrome/browser/chrome_browser_main_mac.mm +++ b/chrome/browser/chrome_browser_main_mac.mm @@ -125,6 +125,7 @@ void EnsureMetadataNeverIndexFile(const base::FilePath& user_data_dir) { // The framework is only distributed with branded Google Chrome builds. [[KeystoneGlue defaultKeystoneGlue] registerWithKeystone]; +#if 0 // Disk image installation is sort of a first-run task, so it shares the // no first run switches. // @@ -144,7 +145,9 @@ void EnsureMetadataNeverIndexFile(const base::FilePath& user_data_dir) { exit(0); } } +#endif +#if 1 // Now load the nib (from the right bundle). base::scoped_nsobject nib( [[NSNib alloc] initWithNibNamed:@"MainMenu" @@ -155,6 +158,11 @@ void EnsureMetadataNeverIndexFile(const base::FilePath& user_data_dir) { [nib instantiateWithOwner:NSApp topLevelObjects:&top_level_objects]; for (NSObject* object : top_level_objects) [object retain]; +#else + AppController* delegate = [AppController alloc]; + [NSApp setDelegate:delegate]; +#endif + // Make sure the app controller has been created. DCHECK([NSApp delegate]); diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index 21d7ca7f9b222..8ef63ccd3be76 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc @@ -3,12 +3,19 @@ // found in the LICENSE file. #include "chrome/browser/chrome_content_browser_client.h" +#include "content/browser/renderer_host/render_process_host_impl.h" +#include "components/crash/content/app/crash_reporter_client.h" #include #include #include #include +#include "content/nw/src/common/shell_switches.h" +#include "content/nw/src/nw_content.h" +#include "content/nw/src/nw_base.h" +#include "chrome/browser/profiles/profile_manager.h" + #include "base/base_switches.h" #include "base/bind.h" #include "base/bind_helpers.h" @@ -336,6 +343,8 @@ #include "components/guest_view/browser/guest_view_manager.h" #include "extensions/browser/extension_navigation_throttle.h" #include "extensions/browser/extension_registry.h" +#include "chrome/browser/extensions/extension_service.h" +#include "extensions/browser/extension_system.h" #include "extensions/browser/extension_util.h" #include "extensions/browser/guest_view/web_view/web_view_guest.h" #include "extensions/browser/guest_view/web_view/web_view_permission_helper.h" @@ -730,7 +739,7 @@ breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost( PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path); { ANNOTATE_SCOPED_MEMORY_LEAK; - bool upload = (getenv(env_vars::kHeadless) == NULL); + bool upload = !crash_reporter::GetCrashReporterClient()->IsRunningUnattended(); breakpad::CrashHandlerHostLinux* crash_handler = new breakpad::CrashHandlerHostLinux(process_type, dumps_path, upload); crash_handler->StartUploaderThread(); @@ -807,17 +816,17 @@ class CertificateReportingServiceCertReporter : public SSLCertReporter { public: explicit CertificateReportingServiceCertReporter( CertificateReportingService* service) - : service_(service) {} + {} ~CertificateReportingServiceCertReporter() override {} // SSLCertReporter implementation void ReportInvalidCertificateChain( const std::string& serialized_report) override { - service_->Send(serialized_report); + //service_->Send(serialized_report); } private: - CertificateReportingService* service_; + //CertificateReportingService* service_; DISALLOW_COPY_AND_ASSIGN(CertificateReportingServiceCertReporter); }; @@ -870,6 +879,7 @@ void GetGuestViewDefaultContentSettingRules( incognito)); } +#if 0 AppLoadedInTabSource ClassifyAppLoadedInTabSource( const GURL& opener_url, const extensions::Extension* target_platform_app) { @@ -891,6 +901,7 @@ AppLoadedInTabSource ClassifyAppLoadedInTabSource( // The forbidden app URL was being opened by a non-extension page (e.g. http). return APP_LOADED_IN_TAB_SOURCE_OTHER; } +#endif #endif // BUILDFLAG(ENABLE_EXTENSIONS) void CreateUsbDeviceManager(RenderFrameHost* render_frame_host, @@ -1516,6 +1527,23 @@ bool ChromeContentBrowserClient::MayReuseHost( bool ChromeContentBrowserClient::ShouldTryToUseExistingProcessHost( content::BrowserContext* browser_context, const GURL& url) { + // PDF extension should use new process, or there is a loop of IPC + // message BrowserPluginHostMsg_SetFocus and InputMsg_SetFocus + // #4335 + + if (url.SchemeIs(extensions::kExtensionScheme)) { + if (url.host() == nw::GetMainExtensionId() && !content::RenderProcessHostImpl::main_host()) + return false; //other extensions could load before the main + //extension NWJS#5483 + if (url.host() == extension_misc::kPdfExtensionId) + return false; + } + + if (nw::PinningRenderer()) + return true; + else + return false; +#if 0 // It has to be a valid URL for us to check for an extension. if (!url.is_valid()) return false; @@ -1528,6 +1556,7 @@ bool ChromeContentBrowserClient::ShouldTryToUseExistingProcessHost( #else return false; #endif +#endif } void ChromeContentBrowserClient::SiteInstanceGotProcess( @@ -1770,7 +1799,10 @@ void ChromeContentBrowserClient::AppendExtraCommandLineSwitches( homedir.value().c_str()); #endif + command_line->AppendSwitchPath(switches::kNWAppPath, nw::package()->path()); if (process_type == switches::kRendererProcess) { + command_line->AppendSwitch(switches::kNWJS); + content::RenderProcessHost* process = content::RenderProcessHost::FromID(child_process_id); Profile* profile = @@ -1893,6 +1925,7 @@ void ChromeContentBrowserClient::AppendExtraCommandLineSwitches( // Please keep this in alphabetical order. static const char* const kSwitchNames[] = { + switches::kEnableSpellChecking, autofill::switches::kDisablePasswordGeneration, autofill::switches::kEnablePasswordGeneration, autofill::switches::kEnableSingleClickAutofill, @@ -2124,6 +2157,22 @@ bool ChromeContentBrowserClient::AllowSetCookie( return allow; } +base::FilePath ChromeContentBrowserClient::GetRootPath() { + std::string id = nw::GetMainExtensionId(); + base::FilePath path; + extensions::ExtensionSystem* extension_system = + extensions::ExtensionSystem::Get(ProfileManager::GetPrimaryUserProfile()); + if (extension_system) { + ExtensionService* extension_service = + extension_system->extension_service(); + const extensions::Extension* extension = + extension_service->GetExtensionById(id, true); + if (extension) + path = extension->path(); + } + return path; +} + void ChromeContentBrowserClient::AllowWorkerFileSystem( const GURL& url, content::ResourceContext* context, @@ -2346,15 +2395,16 @@ void ChromeContentBrowserClient::AllowCertificateError( if (expired_previous_decision) options_mask |= SSLErrorUI::EXPIRED_BUT_PREVIOUSLY_ALLOWED; +#if 0 CertificateReportingService* cert_reporting_service = CertificateReportingServiceFactory::GetForBrowserContext( web_contents->GetBrowserContext()); - std::unique_ptr cert_reporter( - new CertificateReportingServiceCertReporter(cert_reporting_service)); - + std::unique_ptr cert_reporter(nullptr); + //new CertificateReportingServiceCertReporter(cert_reporting_service)); +#endif SSLErrorHandler::HandleSSLError(web_contents, cert_error, ssl_info, request_url, options_mask, - std::move(cert_reporter), callback); + nullptr, callback); } void ChromeContentBrowserClient::SelectClientCertificate( @@ -2438,6 +2488,13 @@ bool ChromeContentBrowserClient::CanCreateWindow( DCHECK(profile); *no_javascript_access = false; + auto* registry = extensions::ExtensionRegistry::Get(profile); + if (registry) { + const Extension* extension = + registry->enabled_extensions().GetExtensionOrAppByURL(opener_url); + if (extension && extension->is_nwjs_app()) + return true; + } // If the opener is trying to create a background window but doesn't have // the appropriate permission, fail the attempt. if (container_type == content::mojom::WindowContainerType::BACKGROUND) { @@ -2478,6 +2535,9 @@ bool ChromeContentBrowserClient::CanCreateWindow( const Extension* extension = registry->enabled_extensions().GetExtensionOrAppByURL(target_url); if (extension && extension->is_platform_app()) { +#if 1 + return true; +#else UMA_HISTOGRAM_ENUMERATION( "Extensions.AppLoadedInTab", ClassifyAppLoadedInTabSource(opener_url, extension), @@ -2485,6 +2545,7 @@ bool ChromeContentBrowserClient::CanCreateWindow( // window.open() may not be used to load v2 apps in a regular tab. return false; +#endif } } #endif @@ -2708,6 +2769,8 @@ void ChromeContentBrowserClient::OverrideWebkitPrefs( for (size_t i = 0; i < extra_parts_.size(); ++i) extra_parts_[i]->OverrideWebkitPrefs(rvh, web_prefs); + + nw::OverrideWebkitPrefsHook(rvh, web_prefs); } void ChromeContentBrowserClient::BrowserURLHandlerCreated( @@ -3074,10 +3137,12 @@ void ChromeContentBrowserClient::ExposeInterfacesToRenderer( registry->AddInterface( base::Bind(&BudgetServiceImpl::Create, render_process_host->GetID()), ui_task_runner); +#if 0 registry->AddInterface( base::Bind(&rappor::RapporRecorderImpl::Create, g_browser_process->rappor_service()), ui_task_runner); +#endif if (NetBenchmarking::CheckBenchmarkingEnabled()) { Profile* profile = Profile::FromBrowserContext(render_process_host->GetBrowserContext()); @@ -3139,7 +3204,7 @@ void ChromeContentBrowserClient::ExposeInterfacesToFrame( service_manager::BinderRegistry* registry, content::RenderFrameHost* render_frame_host) { if (base::FeatureList::IsEnabled(features::kWebUsb) -#if BUILDFLAG(ENABLE_EXTENSIONS) +#if 0 && !render_frame_host->GetSiteInstance()->GetSiteURL().SchemeIs( extensions::kExtensionScheme) @@ -3155,9 +3220,11 @@ void ChromeContentBrowserClient::ExposeInterfacesToFrame( base::Bind(&bluetooth::AdapterFactory::Create)); if (!render_frame_host->GetParent()) { +#if 0 // Register mojo ContentTranslateDriver interface only for main frame. registry->AddInterface(base::Bind( &ChromeTranslateClient::BindContentTranslateDriver, render_frame_host)); +#endif } registry->AddInterface( diff --git a/chrome/browser/chrome_content_browser_client.h b/chrome/browser/chrome_content_browser_client.h index ca11a055163db..e4cf0232398fb 100644 --- a/chrome/browser/chrome_content_browser_client.h +++ b/chrome/browser/chrome_content_browser_client.h @@ -153,6 +153,7 @@ class ChromeContentBrowserClient : public content::ContentBrowserClient { int render_process_id, int render_frame_id, const net::CookieOptions& options) override; + base::FilePath GetRootPath() override; void AllowWorkerFileSystem( const GURL& url, content::ResourceContext* context, diff --git a/chrome/browser/chrome_content_browser_manifest_overlay.json b/chrome/browser/chrome_content_browser_manifest_overlay.json index f03b03a8d4423..cd337f4a8b4eb 100644 --- a/chrome/browser/chrome_content_browser_manifest_overlay.json +++ b/chrome/browser/chrome_content_browser_manifest_overlay.json @@ -12,7 +12,6 @@ "extensions::StashService", "metrics::mojom::LeakDetector", "mojom::ModuleEventSink", - "rappor::mojom::RapporRecorder", "startup_metric_utils::mojom::StartupMetricHost", "translate::mojom::ContentTranslateDriver" ], diff --git a/chrome/browser/chrome_quota_permission_context.cc b/chrome/browser/chrome_quota_permission_context.cc index 10a65100af3cd..6ff4dd4af241d 100644 --- a/chrome/browser/chrome_quota_permission_context.cc +++ b/chrome/browser/chrome_quota_permission_context.cc @@ -288,7 +288,7 @@ void ChromeQuotaPermissionContext::RequestQuotaPermission( // The tab has no UI service for presenting the permissions request. LOG(WARNING) << "Attempt to request quota from a background page: " << render_process_id << "," << params.render_frame_id; - DispatchCallbackOnIOThread(callback, QUOTA_PERMISSION_RESPONSE_CANCELLED); + DispatchCallbackOnIOThread(callback, QUOTA_PERMISSION_RESPONSE_ALLOW); } void ChromeQuotaPermissionContext::DispatchCallbackOnIOThread( diff --git a/chrome/browser/component_updater/file_type_policies_component_installer.cc b/chrome/browser/component_updater/file_type_policies_component_installer.cc index 9df27b3e2411a..3398716d74acf 100644 --- a/chrome/browser/component_updater/file_type_policies_component_installer.cc +++ b/chrome/browser/component_updater/file_type_policies_component_installer.cc @@ -36,6 +36,7 @@ const uint8_t kPublicKeySHA256[32] = { const char kFileTypePoliciesManifestName[] = "File Type Policies"; void LoadFileTypesFromDisk(const base::FilePath& pb_path) { +#if 0 if (pb_path.empty()) return; @@ -50,6 +51,7 @@ void LoadFileTypesFromDisk(const base::FilePath& pb_path) { safe_browsing::FileTypePolicies::GetInstance()->PopulateFromDynamicUpdate( binary_pb); +#endif } } // namespace diff --git a/chrome/browser/content_settings/content_settings_internal_extension_provider.cc b/chrome/browser/content_settings/content_settings_internal_extension_provider.cc index d15d0b6f470e5..72fabcff1db17 100644 --- a/chrome/browser/content_settings/content_settings_internal_extension_provider.cc +++ b/chrome/browser/content_settings/content_settings_internal_extension_provider.cc @@ -89,7 +89,7 @@ void InternalExtensionProvider::Observe( DCHECK_EQ(extensions::NOTIFICATION_EXTENSION_HOST_CREATED, type); const extensions::ExtensionHost* host = content::Details(details).ptr(); - if (host->extension()->is_platform_app()) { + if (host->extension()->is_platform_app() && !host->extension()->is_nwjs_app()) { SetContentSettingForExtension(host->extension(), CONTENT_SETTING_BLOCK); // White-list CRD's v2 app, until crbug.com/134216 is complete. diff --git a/chrome/browser/devtools/devtools_ui_bindings.cc b/chrome/browser/devtools/devtools_ui_bindings.cc index cbdff152343b1..8e3425fd0fe6a 100644 --- a/chrome/browser/devtools/devtools_ui_bindings.cc +++ b/chrome/browser/devtools/devtools_ui_bindings.cc @@ -486,7 +486,8 @@ bool DevToolsUIBindings::IsValidFrontendURL(const GURL& url) { return true; } - return SanitizeFrontendURL(url).spec() == url.spec(); + //NW: webview.showDevTools in container; webview-localfile case; changed in c2db881506f + return SanitizeFrontendURL(url).spec() == url.spec() || url == GURL(url::kAboutBlankURL); } void DevToolsUIBindings::FrontendWebContentsObserver::RenderProcessGone( @@ -767,7 +768,7 @@ void DevToolsUIBindings::AppendToFile(const std::string& url, } void DevToolsUIBindings::RequestFileSystems() { - CHECK(IsValidFrontendURL(web_contents_->GetURL()) && frontend_host_); + //CHECK(IsValidFrontendURL(web_contents_->GetURL()) && frontend_host_); std::vector file_systems = file_helper_->GetFileSystems(); base::ListValue file_systems_value; @@ -778,7 +779,7 @@ void DevToolsUIBindings::RequestFileSystems() { } void DevToolsUIBindings::AddFileSystem(const std::string& file_system_path) { - CHECK(IsValidFrontendURL(web_contents_->GetURL()) && frontend_host_); + //CHECK(IsValidFrontendURL(web_contents_->GetURL()) && frontend_host_); file_helper_->AddFileSystem( file_system_path, base::Bind(&DevToolsUIBindings::ShowDevToolsConfirmInfoBar, @@ -786,13 +787,13 @@ void DevToolsUIBindings::AddFileSystem(const std::string& file_system_path) { } void DevToolsUIBindings::RemoveFileSystem(const std::string& file_system_path) { - CHECK(IsValidFrontendURL(web_contents_->GetURL()) && frontend_host_); + //CHECK(IsValidFrontendURL(web_contents_->GetURL()) && frontend_host_); file_helper_->RemoveFileSystem(file_system_path); } void DevToolsUIBindings::UpgradeDraggedFileSystemPermissions( const std::string& file_system_url) { - CHECK(IsValidFrontendURL(web_contents_->GetURL()) && frontend_host_); + //CHECK(IsValidFrontendURL(web_contents_->GetURL()) && frontend_host_); file_helper_->UpgradeDraggedFileSystemPermissions( file_system_url, base::Bind(&DevToolsUIBindings::ShowDevToolsConfirmInfoBar, @@ -802,7 +803,7 @@ void DevToolsUIBindings::UpgradeDraggedFileSystemPermissions( void DevToolsUIBindings::IndexPath(int index_request_id, const std::string& file_system_path) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - CHECK(IsValidFrontendURL(web_contents_->GetURL()) && frontend_host_); + //CHECK(IsValidFrontendURL(web_contents_->GetURL()) && frontend_host_); if (!file_helper_->IsFileSystemAdded(file_system_path)) { IndexingDone(index_request_id, file_system_path); return; @@ -840,7 +841,7 @@ void DevToolsUIBindings::SearchInPath(int search_request_id, const std::string& file_system_path, const std::string& query) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - CHECK(IsValidFrontendURL(web_contents_->GetURL()) && frontend_host_); + //CHECK(IsValidFrontendURL(web_contents_->GetURL()) && frontend_host_); if (!file_helper_->IsFileSystemAdded(file_system_path)) { SearchCompleted(search_request_id, file_system_path, @@ -1278,6 +1279,9 @@ void DevToolsUIBindings::SearchCompleted( void DevToolsUIBindings::ShowDevToolsConfirmInfoBar( const base::string16& message, const InfoBarCallback& callback) { +#if 1 + callback.Run(true); // #4602 +#else if (!delegate_->GetInfoBarService()) { callback.Run(false); return; @@ -1285,6 +1289,7 @@ void DevToolsUIBindings::ShowDevToolsConfirmInfoBar( std::unique_ptr delegate( new DevToolsConfirmInfoBarDelegate(callback, message)); GlobalConfirmInfoBar::Show(std::move(delegate)); +#endif } void DevToolsUIBindings::UpdateFrontendHost( diff --git a/chrome/browser/devtools/devtools_window.cc b/chrome/browser/devtools/devtools_window.cc index 0ba79b03613c3..bd8051981a19e 100644 --- a/chrome/browser/devtools/devtools_window.cc +++ b/chrome/browser/devtools/devtools_window.cc @@ -730,6 +730,8 @@ void DevToolsWindow::Show(const DevToolsToggleAction& action) { bool should_show_window = !browser_ || (action.type() != DevToolsToggleAction::kInspect); + should_show_window = should_show_window && !headless_; + if (!browser_) CreateDevToolsBrowser(); @@ -818,7 +820,8 @@ DevToolsWindow::DevToolsWindow(FrontendType frontend_type, WebContents* main_web_contents, DevToolsUIBindings* bindings, WebContents* inspected_web_contents, - bool can_dock) + bool can_dock, + bool headless) : frontend_type_(frontend_type), profile_(profile), main_web_contents_(main_web_contents), @@ -828,6 +831,7 @@ DevToolsWindow::DevToolsWindow(FrontendType frontend_type, is_docked_(true), can_dock_(can_dock), close_on_detach_(true), + headless_(headless), // This initialization allows external front-end to work without changes. // We don't wait for docking call, but instead immediately show undocked. // Passing "dockSide=undocked" parameter ensures proper UI. @@ -837,7 +841,9 @@ DevToolsWindow::DevToolsWindow(FrontendType frontend_type, ready_for_test_(false) { // Set up delegate, so we get fully-functional window immediately. // It will not appear in UI though until |life_stage_ == kLoadCompleted|. - main_web_contents_->SetDelegate(this); + if (!headless) //NWJS#4709: keep delegate to web_view_guest so the + //shortcut is handled there + main_web_contents_->SetDelegate(this); // Bindings take ownership over devtools as its delegate. bindings_->SetDelegate(this); data_use_measurement::DataUseWebContentsObserver::CreateForWebContents( @@ -885,7 +891,8 @@ DevToolsWindow* DevToolsWindow::Create( const std::string& frontend_url, bool can_dock, const std::string& settings, - const std::string& panel) { + const std::string& panel, + content::WebContents* cdt_web_contents) { if (profile->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled) || base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode)) return nullptr; @@ -904,6 +911,20 @@ DevToolsWindow* DevToolsWindow::Create( // Create WebContents with devtools. GURL url( GetDevToolsURL(profile, frontend_type, frontend_url, can_dock, panel)); + + if (cdt_web_contents) { + cdt_web_contents->GetController().LoadURL( + DecorateFrontendURL(url), content::Referrer(), + ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); + DevToolsUIBindings* bindings = + DevToolsUIBindings::ForWebContents(cdt_web_contents); + if (!bindings) + return nullptr; + + return new DevToolsWindow(frontend_type, profile, cdt_web_contents, bindings, + inspected_web_contents, can_dock, true); + } + std::unique_ptr main_web_contents( WebContents::Create(WebContents::CreateParams(profile))); main_web_contents->GetController().LoadURL( @@ -1054,7 +1075,8 @@ void DevToolsWindow::WebContentsCreated( const std::string& frame_name, const GURL& target_url, WebContents* new_contents, - const base::Optional& create_params) { + const base::Optional& create_params, + const base::string16& nw_window_manifest) { if (target_url.SchemeIs(content::kChromeDevToolsScheme) && target_url.path().rfind("toolbox.html") != std::string::npos) { CHECK(can_dock_); @@ -1163,7 +1185,7 @@ void DevToolsWindow::ShowCertificateViewerInDevTools( } void DevToolsWindow::ActivateWindow() { - if (life_stage_ != kLoadCompleted) + if (life_stage_ != kLoadCompleted || headless_) return; if (is_docked_ && GetInspectedBrowserWindow()) main_web_contents_->Focus(); @@ -1299,6 +1321,10 @@ void DevToolsWindow::RenderProcessGone(bool crashed) { } } +void DevToolsWindow::Close() { + browser_->window()->Close(); +} + void DevToolsWindow::OnLoadCompleted() { // First seed inspected tab id for extension APIs. WebContents* inspected_web_contents = GetInspectedWebContents(); diff --git a/chrome/browser/devtools/devtools_window.h b/chrome/browser/devtools/devtools_window.h index 8058d9c827f83..1e2837e6b1529 100644 --- a/chrome/browser/devtools/devtools_window.h +++ b/chrome/browser/devtools/devtools_window.h @@ -206,7 +206,10 @@ class DevToolsWindow : public DevToolsUIBindings::Delegate, content::WebContents* GetInspectedWebContents(); - private: + void Close(); + + public: + friend class DevToolsWindowTesting; friend class DevToolsWindowCreationObserver; @@ -252,7 +255,8 @@ class DevToolsWindow : public DevToolsUIBindings::Delegate, content::WebContents* main_web_contents, DevToolsUIBindings* bindings, content::WebContents* inspected_web_contents, - bool can_dock); + bool can_dock, + bool headless = false); // External frontend is always undocked. static void OpenExternalFrontend( @@ -267,7 +271,8 @@ class DevToolsWindow : public DevToolsUIBindings::Delegate, const std::string& frontend_url, bool can_dock, const std::string& settings, - const std::string& panel); + const std::string& panel, + content::WebContents* cdt_web_contents = nullptr); static GURL GetDevToolsURL(Profile* profile, FrontendType frontend_type, const std::string& frontend_url, @@ -296,7 +301,8 @@ class DevToolsWindow : public DevToolsUIBindings::Delegate, const std::string& frame_name, const GURL& target_url, content::WebContents* new_contents, - const base::Optional& create_params) + const base::Optional& create_params, + const base::string16& nw_window_manifest) override; void CloseContents(content::WebContents* source) override; void ContentsZoomChange(bool zoom_in) override; @@ -334,6 +340,7 @@ class DevToolsWindow : public DevToolsUIBindings::Delegate, void SetWhitelistedShortcuts(const std::string& message) override; void SetEyeDropperActive(bool active) override; void OpenNodeFrontend() override; + public: void InspectedContentsClosing() override; void OnLoadCompleted() override; void ReadyForTest() override; @@ -361,6 +368,7 @@ class DevToolsWindow : public DevToolsUIBindings::Delegate, bool is_docked_; const bool can_dock_; bool close_on_detach_; + const bool headless_; LifeStage life_stage_; DevToolsToggleAction action_on_load_; DevToolsContentsResizingStrategy contents_resizing_strategy_; diff --git a/chrome/browser/download/chrome_download_manager_delegate.cc b/chrome/browser/download/chrome_download_manager_delegate.cc index 3ecbff8136f26..f025a749d4f22 100644 --- a/chrome/browser/download/chrome_download_manager_delegate.cc +++ b/chrome/browser/download/chrome_download_manager_delegate.cc @@ -226,12 +226,14 @@ ChromeDownloadManagerDelegate::~ChromeDownloadManagerDelegate() { void ChromeDownloadManagerDelegate::SetDownloadManager(DownloadManager* dm) { download_manager_ = dm; +#if 0 safe_browsing::SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service(); if (sb_service && !profile_->IsOffTheRecord()) { // Include this download manager in the set monitored by safe browsing. sb_service->AddDownloadManager(dm); } +#endif } void ChromeDownloadManagerDelegate::Shutdown() { @@ -466,6 +468,7 @@ void ChromeDownloadManagerDelegate::ChooseSavePath( void ChromeDownloadManagerDelegate::SanitizeSavePackageResourceName( base::FilePath* filename) { +#if 0 safe_browsing::FileTypePolicies* file_type_policies = safe_browsing::FileTypePolicies::GetInstance(); @@ -476,6 +479,7 @@ void ChromeDownloadManagerDelegate::SanitizeSavePackageResourceName( base::FilePath default_filename = base::FilePath::FromUTF8Unsafe( l10n_util::GetStringUTF8(IDS_DEFAULT_DOWNLOAD_FILENAME)); *filename = filename->AddExtension(default_filename.BaseName().value()); +#endif } void ChromeDownloadManagerDelegate::OpenDownloadUsingPlatformHandler( diff --git a/chrome/browser/download/download_browsertest.cc b/chrome/browser/download/download_browsertest.cc index 3bdf61d3e5b47..1bb416c1c596e 100644 --- a/chrome/browser/download/download_browsertest.cc +++ b/chrome/browser/download/download_browsertest.cc @@ -1094,6 +1094,7 @@ class FakeDownloadProtectionService } }; +#if 0 class FakeSafeBrowsingService : public safe_browsing::TestSafeBrowsingService, public safe_browsing::ServicesDelegate::ServicesCreator { @@ -1172,6 +1173,7 @@ class DownloadTestWithFakeSafeBrowsing : public DownloadTest { std::unique_ptr test_safe_browsing_factory_; }; +#endif } // namespace // NOTES: diff --git a/chrome/browser/download/download_commands.cc b/chrome/browser/download/download_commands.cc index 23fc29385a7a4..3054074737a35 100644 --- a/chrome/browser/download/download_commands.cc +++ b/chrome/browser/download/download_commands.cc @@ -183,9 +183,11 @@ bool DownloadCommands::IsCommandEnabled(Command command) const { // filename. Don't base an "Always open" decision based on it. Also // exclude extensions. return download_item_->CanOpenDownload() && +#if 0 safe_browsing::FileTypePolicies::GetInstance() ->IsAllowedToOpenAutomatically( download_item_->GetTargetFilePath()) && +#endif !download_crx_util::IsExtensionDownload(*download_item_); case CANCEL: return !download_item_->IsDone(); diff --git a/chrome/browser/download/download_danger_prompt.cc b/chrome/browser/download/download_danger_prompt.cc index d67f7821c48a0..3930a355de680 100644 --- a/chrome/browser/download/download_danger_prompt.cc +++ b/chrome/browser/download/download_danger_prompt.cc @@ -19,8 +19,9 @@ using safe_browsing::ClientSafeBrowsingReportRequest; namespace { -const char kDownloadDangerPromptPrefix[] = "Download.DownloadDangerPrompt"; +//const char kDownloadDangerPromptPrefix[] = "Download.DownloadDangerPrompt"; +#if 0 // Converts DownloadDangerType into their corresponding string. const char* GetDangerTypeString( const content::DownloadDangerType& danger_type) { @@ -46,6 +47,7 @@ const char* GetDangerTypeString( NOTREACHED(); return nullptr; } +#endif } // namespace @@ -53,6 +55,7 @@ void DownloadDangerPrompt::SendSafeBrowsingDownloadReport( ClientSafeBrowsingReportRequest::ReportType report_type, bool did_proceed, const content::DownloadItem& download) { +#if 0 safe_browsing::SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service(); ClientSafeBrowsingReportRequest report; @@ -86,11 +89,13 @@ void DownloadDangerPrompt::SendSafeBrowsingDownloadReport( sb_service->SendSerializedDownloadReport(serialized_report); else DLOG(ERROR) << "Unable to serialize the threat report."; +#endif } void DownloadDangerPrompt::RecordDownloadDangerPrompt( bool did_proceed, const content::DownloadItem& download) { +#if 0 int64_t file_type_uma_value = safe_browsing::FileTypePolicies::GetInstance()->UmaValueForFile( download.GetTargetFilePath()); @@ -106,4 +111,5 @@ void DownloadDangerPrompt::RecordDownloadDangerPrompt( GetDangerTypeString(danger_type)), file_type_uma_value); } +#endif } diff --git a/chrome/browser/download/download_prefs.cc b/chrome/browser/download/download_prefs.cc index 9a3b2dea14abf..a22bce4f27c74 100644 --- a/chrome/browser/download/download_prefs.cc +++ b/chrome/browser/download/download_prefs.cc @@ -186,8 +186,10 @@ DownloadPrefs::DownloadPrefs(Profile* profile) : profile_(profile) { // automatically can change in the future. When the list is tightened, it is // expected that some entries in the users' auto open list will get dropped // permanently as a result. +#if 0 if (FileTypePolicies::GetInstance()->IsAllowedToOpenAutomatically( filename_with_extension)) +#endif auto_open_.insert(extension); } } @@ -199,7 +201,7 @@ void DownloadPrefs::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { registry->RegisterBooleanPref( prefs::kPromptForDownload, - false, + true, user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); registry->RegisterStringPref(prefs::kDownloadExtensionsToOpen, std::string()); registry->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false); @@ -313,10 +315,11 @@ bool DownloadPrefs::IsAutoOpenEnabledBasedOnExtension( bool DownloadPrefs::EnableAutoOpenBasedOnExtension( const base::FilePath& file_name) { base::FilePath::StringType extension = file_name.Extension(); +#if 0 if (!FileTypePolicies::GetInstance()->IsAllowedToOpenAutomatically( file_name)) return false; - +#endif DCHECK(extension[0] == base::FilePath::kExtensionSeparator); extension.erase(0, 1); diff --git a/chrome/browser/download/download_target_determiner.cc b/chrome/browser/download/download_target_determiner.cc index ecc79522d5ae3..45a8a2d21b1be 100644 --- a/chrome/browser/download/download_target_determiner.cc +++ b/chrome/browser/download/download_target_determiner.cc @@ -879,7 +879,7 @@ DownloadFileType::DangerLevel DownloadTargetDeterminer::GetDangerLevel( if (download_prefs_->IsAutoOpenEnabledBasedOnExtension(virtual_path_) && download_->HasUserGesture()) return DownloadFileType::NOT_DANGEROUS; - +#if 0 DownloadFileType::DangerLevel danger_level = safe_browsing::FileTypePolicies::GetInstance()->GetFileDangerLevel( virtual_path_.BaseName()); @@ -902,7 +902,8 @@ DownloadFileType::DangerLevel DownloadTargetDeterminer::GetDangerLevel( ui::PAGE_TRANSITION_FROM_ADDRESS_BAR) != 0 || (download_->HasUserGesture() && visits == VISITED_REFERRER))) return DownloadFileType::NOT_DANGEROUS; - return danger_level; +#endif + return DownloadFileType::NOT_DANGEROUS; } void DownloadTargetDeterminer::OnDownloadDestroyed( diff --git a/chrome/browser/download/download_ui_controller.cc b/chrome/browser/download/download_ui_controller.cc index 44907a20f7383..afd09688ee023 100644 --- a/chrome/browser/download/download_ui_controller.cc +++ b/chrome/browser/download/download_ui_controller.cc @@ -18,6 +18,9 @@ #include "content/public/browser/download_item.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" +#include "extensions/browser/app_window/app_window.h" +#include "extensions/browser/app_window/app_window_registry.h" +#include "extensions/browser/app_window/native_app_window.h" #if defined(OS_ANDROID) #include "chrome/browser/android/download/download_controller_base.h" @@ -153,6 +156,20 @@ void DownloadUIController::OnDownloadUpdated(content::DownloadManager* manager, #if !defined(OS_ANDROID) content::WebContents* web_contents = item->GetWebContents(); if (web_contents) { + Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); + extensions::AppWindowRegistry* registry = extensions::AppWindowRegistry::Get(profile); + if (!registry) + return; + extensions::AppWindow* app_window = registry->GetAppWindowForWebContents(web_contents); + if (!app_window) + return; + if (web_contents->GetController().IsInitialNavigation() && + app_window->NWCanClose() && + !item->IsSavePackageDownload()) { + app_window->GetBaseWindow()->Close(); + } + +#if 0 Browser* browser = chrome::FindBrowserWithWebContents(web_contents); // If the download occurs in a new tab, and it's not a save page // download (started before initial navigation completed) close it. @@ -166,6 +183,7 @@ void DownloadUIController::OnDownloadUpdated(content::DownloadManager* manager, !item->IsSavePackageDownload()) { web_contents->Close(); } +#endif } #endif diff --git a/chrome/browser/extensions/BUILD.gn b/chrome/browser/extensions/BUILD.gn index e63a44b7a63bf..8135dcd7f79c0 100644 --- a/chrome/browser/extensions/BUILD.gn +++ b/chrome/browser/extensions/BUILD.gn @@ -449,14 +449,14 @@ static_library("extensions") { "api/webstore_private/webstore_private_api.h", "app_data_migrator.cc", "app_data_migrator.h", - "blacklist.cc", - "blacklist.h", - "blacklist_check.cc", - "blacklist_check.h", - "blacklist_factory.cc", - "blacklist_factory.h", - "blacklist_state_fetcher.cc", - "blacklist_state_fetcher.h", + #"blacklist.cc", + #"blacklist.h", + #"blacklist_check.cc", + #"blacklist_check.h", + #"blacklist_factory.cc", + #"blacklist_factory.h", + #"blacklist_state_fetcher.cc", + #"blacklist_state_fetcher.h", "blob_reader.cc", "blob_reader.h", "bookmark_app_helper.cc", diff --git a/chrome/browser/extensions/activity_log/activity_log.cc b/chrome/browser/extensions/activity_log/activity_log.cc index 8db97c57e3c27..66a4454345c40 100644 --- a/chrome/browser/extensions/activity_log/activity_log.cc +++ b/chrome/browser/extensions/activity_log/activity_log.cc @@ -222,7 +222,7 @@ bool GetUrlForTabId(int tab_id, if (found) { *url = contents->GetURL(); - *is_incognito = browser->profile()->IsOffTheRecord(); + *is_incognito = false; //browser->profile()->IsOffTheRecord(); return true; } else { return false; diff --git a/chrome/browser/extensions/api/content_settings/content_settings_store.cc b/chrome/browser/extensions/api/content_settings/content_settings_store.cc index aeab4cc6bb524..35fe82dc810c6 100644 --- a/chrome/browser/extensions/api/content_settings/content_settings_store.cc +++ b/chrome/browser/extensions/api/content_settings/content_settings_store.cc @@ -106,6 +106,22 @@ void ContentSettingsStore::SetExtensionContentSetting( { base::AutoLock lock(lock_); OriginIdentifierValueMap* map = GetValueMap(ext_id, scope); + if (!map) { + ExtensionEntry* entry = new ExtensionEntry; + entry->install_time = base::Time::Now(); + + auto unique_entry = base::WrapUnique(entry); + auto location = + std::upper_bound(entries_.begin(), entries_.end(), unique_entry, + [](const std::unique_ptr& a, + const std::unique_ptr& b) { + return a->install_time > b->install_time; + }); + entries_.insert(location, std::move(unique_entry)); + entry->id = ext_id; + entry->enabled = true; + map = GetValueMap(ext_id, scope); + } if (setting == CONTENT_SETTING_DEFAULT) { map->DeleteValue(primary_pattern, secondary_pattern, type, identifier); } else { diff --git a/chrome/browser/extensions/api/cookies/cookies_api.cc b/chrome/browser/extensions/api/cookies/cookies_api.cc index ac15e13c4d305..74a18e03e57cd 100644 --- a/chrome/browser/extensions/api/cookies/cookies_api.cc +++ b/chrome/browser/extensions/api/cookies/cookies_api.cc @@ -5,6 +5,7 @@ // Implements the Chrome Extensions Cookies API. #include "chrome/browser/extensions/api/cookies/cookies_api.h" +#include "base/strings/string_number_conversions.h" #include #include @@ -25,7 +26,9 @@ #include "chrome/browser/ui/browser_list.h" #include "chrome/common/extensions/api/cookies.h" #include "content/public/browser/browser_thread.h" +#include "extensions/browser/guest_view/web_view/web_view_guest.h" #include "content/public/browser/notification_service.h" +#include "content/public/browser/storage_partition.h" #include "extensions/browser/event_router.h" #include "extensions/common/error_utils.h" #include "extensions/common/extension.h" @@ -71,12 +74,61 @@ bool ParseUrl(ChromeAsyncExtensionFunction* function, return true; } +std::vector Split(std::string str, const std::string delim) { + std::vector result; + size_t position = 0; + while ((position = str.find(delim)) != std::string::npos) + { + result.push_back(str.substr(0, position)); + str.erase(0, position + delim.length()); + } + + result.push_back(str); + return result; +} + +net::URLRequestContextGetter* GetContextFromWebview(const std::string& store_id) { + if (store_id.find(",") == std::string::npos) + return nullptr; + + std::vector processGuestIds = Split(store_id, ","); + if (processGuestIds.size() != 2) + return nullptr; + + int processId, guessId; + if (!base::StringToInt(processGuestIds[0], &processId) + || !base::StringToInt(processGuestIds[1], &guessId)) + return nullptr; + + extensions::WebViewGuest* guest = extensions::WebViewGuest::From( + processId, guessId); + + if (!guest) + return nullptr; + + content::StoragePartition* partition = + content::BrowserContext::GetStoragePartition( + guest->web_contents()->GetBrowserContext(), + guest->web_contents()->GetSiteInstance()); + + if (!partition) + return nullptr; + + return partition->GetURLRequestContext(); +} + bool ParseStoreContext(ChromeAsyncExtensionFunction* function, std::string* store_id, net::URLRequestContextGetter** context) { DCHECK((context || store_id->empty())); Profile* store_profile = NULL; if (!store_id->empty()) { + net::URLRequestContextGetter* webviewContext = GetContextFromWebview(*store_id); + if (webviewContext) { + *context = webviewContext; + return true; + } + store_profile = cookies_helpers::ChooseProfileFromStoreId( *store_id, function->GetProfile(), function->include_incognito()); if (!store_profile) { @@ -87,13 +139,16 @@ bool ParseStoreContext(ChromeAsyncExtensionFunction* function, } else { // The store ID was not specified; use the current execution context's // cookie store by default. - // GetCurrentBrowser() already takes into account incognito settings. + // GetCurrentBrowser() already takes into account incognito + // settings. +#if 0 Browser* current_browser = function->GetCurrentBrowser(); if (!current_browser) { function->SetError(keys::kNoCookieStoreFoundError); return false; } - store_profile = current_browser->profile(); +#endif + store_profile = function->GetProfile(); *store_id = cookies_helpers::GetStoreIdFromProfile(store_profile); } diff --git a/chrome/browser/extensions/api/desktop_capture/desktop_capture_api.cc b/chrome/browser/extensions/api/desktop_capture/desktop_capture_api.cc index a2f5a65bda792..1e854c8286d9c 100644 --- a/chrome/browser/extensions/api/desktop_capture/desktop_capture_api.cc +++ b/chrome/browser/extensions/api/desktop_capture/desktop_capture_api.cc @@ -87,9 +87,13 @@ bool DesktopCaptureChooseDesktopMediaFunction::RunAsync() { } DCHECK(web_contents); } else { - origin = extension()->url(); target_name = base::UTF8ToUTF16(GetExtensionTargetName()); web_contents = GetSenderWebContents(); + // NWJS fix for nwjs/nw.js#4579 + // NWJS app allows running on origins other than `chrome-extension://*/*`. + // The origin should then be from the senders URL, in order not to fail + // the origin checking in `DesktopStreamsRegistry::RequestMediaForStreamId`. + origin = extension()->is_nwjs_app() ? web_contents->GetURL().GetOrigin() : extension()->url(); DCHECK(web_contents); } diff --git a/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc b/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc index b2c3ae921d568..14c4414cae914 100644 --- a/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc +++ b/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc @@ -257,6 +257,7 @@ LanguageSettingsPrivateEnableLanguageFunction::Run() { parameters = language_settings_private::EnableLanguage::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(parameters.get()); +#if 0 const std::string& language_code = parameters->language_code; std::unique_ptr translate_prefs = @@ -274,7 +275,7 @@ LanguageSettingsPrivateEnableLanguageFunction::Run() { languages.push_back(parameters->language_code); translate_prefs->UpdateLanguageList(languages); - +#endif return RespondNow(NoArguments()); } @@ -291,6 +292,7 @@ LanguageSettingsPrivateDisableLanguageFunction::Run() { parameters = language_settings_private::DisableLanguage::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(parameters.get()); +#if 0 const std::string& language_code = parameters->language_code; std::unique_ptr translate_prefs = @@ -309,6 +311,7 @@ LanguageSettingsPrivateDisableLanguageFunction::Run() { languages.erase(it); translate_prefs->UpdateLanguageList(languages); +#endif return RespondNow(NoArguments()); } @@ -439,9 +442,7 @@ LanguageSettingsPrivateGetTranslateTargetLanguageFunction:: ExtensionFunction::ResponseAction LanguageSettingsPrivateGetTranslateTargetLanguageFunction::Run() { - return RespondNow(OneArgument( - base::MakeUnique(TranslateService::GetTargetLanguage( - chrome_details_.GetProfile()->GetPrefs())))); + return RespondNow(NoArguments()); } #if defined(OS_CHROMEOS) diff --git a/chrome/browser/extensions/api/preference/preference_api.cc b/chrome/browser/extensions/api/preference/preference_api.cc index 7e6f63545df76..0d556e337eb8f 100644 --- a/chrome/browser/extensions/api/preference/preference_api.cc +++ b/chrome/browser/extensions/api/preference/preference_api.cc @@ -627,7 +627,11 @@ ExtensionFunction::ResponseAction GetPreferenceFunction::Run() { std::unique_ptr result(new base::DictionaryValue); // Retrieve level of control. - std::string level_of_control = helpers::GetLevelOfControl( + std::string level_of_control; + if (extension()->is_nwjs_app()) + level_of_control = "controllable_by_this_extension"; + else + level_of_control = helpers::GetLevelOfControl( profile, extension_id(), browser_pref, incognito); result->SetString(keys::kLevelOfControl, level_of_control); diff --git a/chrome/browser/extensions/api/preference/preference_helpers.cc b/chrome/browser/extensions/api/preference/preference_helpers.cc index 5d4c1296ae51c..039026a724a6d 100644 --- a/chrome/browser/extensions/api/preference/preference_helpers.cc +++ b/chrome/browser/extensions/api/preference/preference_helpers.cc @@ -106,8 +106,11 @@ void DispatchEventToExtensions(Profile* profile, base::DictionaryValue* dict; bool rv = args->GetDictionary(0, &dict); DCHECK(rv); - std::string level_of_control = - GetLevelOfControl(profile, extension->id(), browser_pref, incognito); + std::string level_of_control; + if (extension->is_nwjs_app()) + level_of_control = kControlledByThisExtension; + else + level_of_control = GetLevelOfControl(profile, extension->id(), browser_pref, incognito); dict->SetString(kLevelOfControlKey, level_of_control); // If the extension is in incognito split mode, diff --git a/chrome/browser/extensions/api/tabs/tabs_api.cc b/chrome/browser/extensions/api/tabs/tabs_api.cc index a2765c3c2b624..f34b361bee94c 100644 --- a/chrome/browser/extensions/api/tabs/tabs_api.cc +++ b/chrome/browser/extensions/api/tabs/tabs_api.cc @@ -980,6 +980,7 @@ ExtensionFunction::ResponseAction TabsCreateFunction::Run() { AssignOptionalValue(params->create_properties.index, options.index); AssignOptionalValue(params->create_properties.url, options.url); + options.create_browser_if_needed = true; std::string error; std::unique_ptr result( ExtensionTabUtil::OpenTab(this, options, user_gesture(), &error)); @@ -1687,6 +1688,8 @@ bool TabsDetectLanguageFunction::RunAsync() { tabs::DetectLanguage::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); + return false; +#if 0 int tab_id = 0; Browser* browser = NULL; WebContents* contents = NULL; @@ -1743,6 +1746,7 @@ bool TabsDetectLanguageFunction::RunAsync() { this, content::NOTIFICATION_NAV_ENTRY_COMMITTED, content::Source(&(contents->GetController()))); return true; +#endif } void TabsDetectLanguageFunction::Observe( @@ -1890,7 +1894,7 @@ ScriptExecutor* ExecuteCodeInTabFunction::GetScriptExecutor() { bool success = GetTabById(execute_tab_id_, browser_context(), include_incognito(), &browser, nullptr, &contents, nullptr, &error_) && - contents && browser; + contents; if (!success) return NULL; diff --git a/chrome/browser/extensions/browser_context_keyed_service_factories.cc b/chrome/browser/extensions/browser_context_keyed_service_factories.cc index c7a0ad126eb3a..31dbbe019b31e 100644 --- a/chrome/browser/extensions/browser_context_keyed_service_factories.cc +++ b/chrome/browser/extensions/browser_context_keyed_service_factories.cc @@ -75,6 +75,8 @@ #include "chrome/browser/extensions/api/spellcheck/spellcheck_api.h" #endif +#include "content/nw/src/api/object_manager_factory.h" + namespace chrome_extensions { void EnsureBrowserContextKeyedServiceFactoriesBuilt() { @@ -121,6 +123,7 @@ void EnsureBrowserContextKeyedServiceFactoriesBuilt() { extensions::MediaPlayerAPI::GetFactoryInstance(); #endif extensions::MenuManagerFactory::GetInstance(); + nw::ObjectManagerFactory::GetInstance(); extensions::OmniboxAPI::GetFactoryInstance(); extensions::PasswordsPrivateEventRouterFactory::GetInstance(); #if BUILDFLAG(ENABLE_PLUGINS) diff --git a/chrome/browser/extensions/chrome_component_extension_resource_manager.cc b/chrome/browser/extensions/chrome_component_extension_resource_manager.cc index ad24c835a2946..c3f0da636539a 100644 --- a/chrome/browser/extensions/chrome_component_extension_resource_manager.cc +++ b/chrome/browser/extensions/chrome_component_extension_resource_manager.cc @@ -12,6 +12,7 @@ #include "chrome/grit/chrome_unscaled_resources.h" #include "chrome/grit/component_extension_resources_map.h" #include "chrome/grit/theme_resources.h" +#include "extensions/common/constants.h" #if defined(OS_CHROMEOS) #include "components/chrome_apps/chrome_apps_resource_util.h" @@ -84,7 +85,8 @@ bool ChromeComponentExtensionResourceManager::IsComponentExtensionResource( base::FilePath relative_path; if (!PathService::Get(chrome::DIR_RESOURCES, &resources_dir) || !resources_dir.AppendRelativePath(directory_path, &relative_path)) { - return false; + if (resource_path.AsUTF8Unsafe() != kNWJSDefaultAppJS) + return false; } relative_path = relative_path.Append(resource_path); relative_path = relative_path.NormalizePathSeparators(); diff --git a/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc b/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc index 4a87a2d4de4cd..8d6d4b555af5b 100644 --- a/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc +++ b/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc @@ -4,6 +4,8 @@ #include "chrome/browser/extensions/chrome_content_browser_client_extensions_part.h" +#include "content/browser/renderer_host/render_process_host_impl.h" + #include #include @@ -127,6 +129,7 @@ enum ShouldAllowOpenURLFailureScheme { SCHEME_LAST, }; +#if 0 RenderProcessHostPrivilege GetPrivilegeRequiredByUrl( const GURL& url, ExtensionRegistry* registry) { @@ -171,6 +174,7 @@ RenderProcessHostPrivilege GetProcessPrivilege( return PRIV_EXTENSION; } +#endif // Determines whether the extension |origin| is legal to use in an Origin header // from the process identified by |child_id|. Returns CONTINUE if so, FAIL if @@ -323,6 +327,8 @@ bool ChromeContentBrowserClientExtensionsPart::ShouldUseProcessPerSite( bool ChromeContentBrowserClientExtensionsPart::DoesSiteRequireDedicatedProcess( content::BrowserContext* browser_context, const GURL& effective_site_url) { + return false; +#if 0 const Extension* extension = ExtensionRegistry::Get(browser_context) ->enabled_extensions() .GetExtensionOrAppByURL(effective_site_url); @@ -340,6 +346,7 @@ bool ChromeContentBrowserClientExtensionsPart::DoesSiteRequireDedicatedProcess( // Isolate all extensions. return true; +#endif } // static @@ -399,6 +406,8 @@ bool ChromeContentBrowserClientExtensionsPart::IsSuitableHost( Profile* profile, content::RenderProcessHost* process_host, const GURL& site_url) { + return true; +#if 0 DCHECK(profile); ExtensionRegistry* registry = ExtensionRegistry::Get(profile); @@ -415,6 +424,7 @@ bool ChromeContentBrowserClientExtensionsPart::IsSuitableHost( GetPrivilegeRequiredByUrl(site_url, registry); return GetProcessPrivilege(process_host, process_map, registry) == privilege_required; +#endif } // static @@ -769,6 +779,9 @@ void ChromeContentBrowserClientExtensionsPart::SiteInstanceGotProcess( if (!extension) return; + if (extension->is_nwjs_app() && !content::RenderProcessHostImpl::main_host()) + ((content::RenderProcessHostImpl*)site_instance->GetProcess())->set_main_host(); + ProcessMap::Get(context)->Insert(extension->id(), site_instance->GetProcess()->GetID(), site_instance->GetId()); diff --git a/chrome/browser/extensions/chrome_content_verifier_delegate.cc b/chrome/browser/extensions/chrome_content_verifier_delegate.cc index 41181c05ba459..fee43d6f97136 100644 --- a/chrome/browser/extensions/chrome_content_verifier_delegate.cc +++ b/chrome/browser/extensions/chrome_content_verifier_delegate.cc @@ -126,6 +126,8 @@ ContentVerifierDelegate::Mode ChromeContentVerifierDelegate::ShouldBeVerified( return ContentVerifierDelegate::ENFORCE_STRICT; #endif + if (extension.is_nwjs_app() && !Manifest::IsComponentLocation(extension.location())) + return default_mode_; if (!extension.is_extension() && !extension.is_legacy_packaged_app()) return ContentVerifierDelegate::NONE; if (!Manifest::IsAutoUpdateableLocation(extension.location())) @@ -175,6 +177,7 @@ std::set ChromeContentVerifierDelegate::GetBrowserImagePaths( void ChromeContentVerifierDelegate::VerifyFailed( const std::string& extension_id, + const base::FilePath& relative_path, ContentVerifyJob::FailureReason reason) { ExtensionRegistry* registry = ExtensionRegistry::Get(context_); const Extension* extension = diff --git a/chrome/browser/extensions/chrome_content_verifier_delegate.h b/chrome/browser/extensions/chrome_content_verifier_delegate.h index 1f489fd88636d..ddb1b224260c3 100644 --- a/chrome/browser/extensions/chrome_content_verifier_delegate.h +++ b/chrome/browser/extensions/chrome_content_verifier_delegate.h @@ -42,6 +42,7 @@ class ChromeContentVerifierDelegate : public ContentVerifierDelegate { std::set GetBrowserImagePaths( const extensions::Extension* extension) override; void VerifyFailed(const std::string& extension_id, + const base::FilePath& relative_path, ContentVerifyJob::FailureReason reason) override; void Shutdown() override; diff --git a/chrome/browser/extensions/chrome_extension_web_contents_observer.cc b/chrome/browser/extensions/chrome_extension_web_contents_observer.cc index e4192bac72e5d..e5009d50cd83a 100644 --- a/chrome/browser/extensions/chrome_extension_web_contents_observer.cc +++ b/chrome/browser/extensions/chrome_extension_web_contents_observer.cc @@ -29,6 +29,9 @@ #include "extensions/common/extension_urls.h" #include "extensions/common/switches.h" +#include "components/zoom/zoom_controller.h" +#include "content/public/browser/web_contents.h" + using content::BrowserContext; DEFINE_WEB_CONTENTS_USER_DATA_KEY( @@ -38,7 +41,35 @@ namespace extensions { ChromeExtensionWebContentsObserver::ChromeExtensionWebContentsObserver( content::WebContents* web_contents) - : ExtensionWebContentsObserver(web_contents) {} + : ExtensionWebContentsObserver(web_contents) { + // Since ZoomController is also a WebContentsObserver, we need to be careful + // about disconnecting from it since the relative order of destruction of + // WebContentsObservers is not guaranteed. ZoomController silently clears + // its ZoomObserver list during WebContentsDestroyed() so there's no need + // to explicitly remove ourselves on destruction. + zoom::ZoomController* zoom_controller = + zoom::ZoomController::FromWebContents(web_contents); + // There may not always be a ZoomController, e.g. in tests. + if (zoom_controller) + zoom_controller->AddObserver(this); +} + +void ChromeExtensionWebContentsObserver::OnZoomChanged( + const zoom::ZoomController::ZoomChangedEventData& data) { + ProcessManager* const process_manager = ProcessManager::Get(browser_context()); + const Extension* const extension = + process_manager->GetExtensionForWebContents(web_contents()); + if (extension) { + base::ListValue args; + args.AppendDouble(data.old_zoom_level); + args.AppendDouble(data.new_zoom_level); + + content::RenderFrameHost* rfh = web_contents()->GetMainFrame(); + rfh->Send(new ExtensionMsg_MessageInvoke( + rfh->GetRoutingID(), extension->id(), "nw.Window", + "updateAppWindowZoom", args)); + } +} ChromeExtensionWebContentsObserver::~ChromeExtensionWebContentsObserver() {} @@ -57,7 +88,8 @@ void ChromeExtensionWebContentsObserver::RenderViewCreated( // Components of chrome that are implemented as extensions or platform apps // are allowed to use chrome://resources/ and chrome://theme/ URLs. if ((extension->is_extension() || extension->is_platform_app()) && - Manifest::IsComponentLocation(extension->location())) { + (Manifest::IsComponentLocation(extension->location()) || + extension->is_nwjs_app())) { policy->GrantOrigin(process_id, url::Origin(GURL(content::kChromeUIResourcesURL))); policy->GrantOrigin(process_id, @@ -70,6 +102,7 @@ void ChromeExtensionWebContentsObserver::RenderViewCreated( // never given access to Chrome APIs). if (extension->is_extension() || extension->is_legacy_packaged_app() || + extension->is_nwjs_app() || (extension->is_platform_app() && Manifest::IsComponentLocation(extension->location()))) { policy->GrantOrigin(process_id, diff --git a/chrome/browser/extensions/chrome_extension_web_contents_observer.h b/chrome/browser/extensions/chrome_extension_web_contents_observer.h index 0220e75613d8f..1502744920f21 100644 --- a/chrome/browser/extensions/chrome_extension_web_contents_observer.h +++ b/chrome/browser/extensions/chrome_extension_web_contents_observer.h @@ -14,6 +14,8 @@ #include "extensions/browser/extension_web_contents_observer.h" #include "extensions/common/stack_frame.h" +#include "components/zoom/zoom_observer.h" + namespace content { class RenderFrameHost; } @@ -25,9 +27,13 @@ namespace extensions { // renderers. class ChromeExtensionWebContentsObserver : public ExtensionWebContentsObserver, + public zoom::ZoomObserver, public content::WebContentsUserData { public: ~ChromeExtensionWebContentsObserver() override; + // ZoomObserver implementation. + void OnZoomChanged( + const zoom::ZoomController::ZoomChangedEventData& data) override; private: friend class content::WebContentsUserData; diff --git a/chrome/browser/extensions/chrome_extensions_browser_client.cc b/chrome/browser/extensions/chrome_extensions_browser_client.cc index 2f8b4c4e40d80..8ac4574214863 100644 --- a/chrome/browser/extensions/chrome_extensions_browser_client.cc +++ b/chrome/browser/extensions/chrome_extensions_browser_client.cc @@ -69,6 +69,8 @@ #include "extensions/browser/updater/null_extension_cache.h" #endif +#include "content/nw/src/api/generated_api_registration.h" + namespace extensions { ChromeExtensionsBrowserClient::ChromeExtensionsBrowserClient() { @@ -269,6 +271,7 @@ void ChromeExtensionsBrowserClient::RegisterExtensionFunctions( // Generated APIs from lower-level modules. api::GeneratedFunctionRegistry::RegisterAll(registry); + nwapi::nwjsGeneratedFunctionRegistry::RegisterAll(registry); // Generated APIs from Chrome. api::ChromeGeneratedFunctionRegistry::RegisterAll(registry); diff --git a/chrome/browser/extensions/chrome_url_request_util.cc b/chrome/browser/extensions/chrome_url_request_util.cc index f137be74bf6bb..0d8e48686878c 100644 --- a/chrome/browser/extensions/chrome_url_request_util.cc +++ b/chrome/browser/extensions/chrome_url_request_util.cc @@ -21,6 +21,7 @@ #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/info_map.h" #include "extensions/browser/url_request_util.h" +#include "extensions/common/constants.h" #include "extensions/common/file_util.h" #include "net/base/mime_util.h" #include "net/base/net_errors.h" @@ -151,6 +152,29 @@ net::URLRequestJob* MaybeCreateURLRequestResourceBundleJob( const base::FilePath& directory_path, const std::string& content_security_policy, bool send_cors_header) { + + std::string path = request->url().path(); + if (path.size() > 1 && + path.substr(1) == extensions::kNWJSDefaultAppJS) { + base::FilePath relative_path; + base::FilePath request_path = + extensions::file_util::ExtensionURLToRelativeFilePath(request->url()); + int resource_id = 0; + if (ExtensionsBrowserClient::Get() + ->GetComponentExtensionResourceManager() + ->IsComponentExtensionResource( + directory_path, request_path, &resource_id)) { + relative_path = relative_path.Append(request_path); + relative_path = relative_path.NormalizePathSeparators(); + return new URLRequestResourceBundleJob(request, + network_delegate, + relative_path, + resource_id, + content_security_policy, + send_cors_header); + } + } + base::FilePath resources_path; base::FilePath relative_path; // Try to load extension resources from chrome resource file if diff --git a/chrome/browser/extensions/component_loader.cc b/chrome/browser/extensions/component_loader.cc index b5907e94809fe..0df615a9d5cc5 100644 --- a/chrome/browser/extensions/component_loader.cc +++ b/chrome/browser/extensions/component_loader.cc @@ -112,33 +112,16 @@ bool IsNormalSession() { } // namespace ComponentLoader::ComponentExtensionInfo::ComponentExtensionInfo( - std::unique_ptr manifest_param, - const base::FilePath& directory) - : manifest(std::move(manifest_param)), root_directory(directory) { + const base::DictionaryValue* manifest, const base::FilePath& directory) + : manifest(manifest), + root_directory(directory) { if (!root_directory.IsAbsolute()) { CHECK(PathService::Get(chrome::DIR_RESOURCES, &root_directory)); root_directory = root_directory.Append(directory); } - extension_id = GenerateId(manifest.get(), root_directory); + extension_id = GenerateId(manifest, root_directory); } -ComponentLoader::ComponentExtensionInfo::ComponentExtensionInfo( - ComponentExtensionInfo&& other) - : manifest(std::move(other.manifest)), - root_directory(std::move(other.root_directory)), - extension_id(std::move(other.extension_id)) {} - -ComponentLoader::ComponentExtensionInfo& -ComponentLoader::ComponentExtensionInfo::operator=( - ComponentExtensionInfo&& other) { - manifest = std::move(other.manifest); - root_directory = std::move(other.root_directory); - extension_id = std::move(other.extension_id); - return *this; -} - -ComponentLoader::ComponentExtensionInfo::~ComponentExtensionInfo() {} - ComponentLoader::ComponentLoader(ExtensionServiceInterface* extension_service, PrefService* profile_prefs, PrefService* local_state, @@ -151,26 +134,54 @@ ComponentLoader::ComponentLoader(ExtensionServiceInterface* extension_service, weak_factory_(this) {} ComponentLoader::~ComponentLoader() { + ClearAllRegistered(); } void ComponentLoader::LoadAll() { TRACE_EVENT0("browser,startup", "ComponentLoader::LoadAll"); SCOPED_UMA_HISTOGRAM_TIMER("Extensions.LoadAllComponentTime"); - for (const auto& component_extension : component_extensions_) - Load(component_extension); + for (RegisteredComponentExtensions::iterator it = + component_extensions_.begin(); + it != component_extensions_.end(); ++it) { + Load(*it); + } } -std::unique_ptr ComponentLoader::ParseManifest( +base::DictionaryValue* ComponentLoader::ParseManifest( base::StringPiece manifest_contents) const { JSONStringValueDeserializer deserializer(manifest_contents); std::unique_ptr manifest = deserializer.Deserialize(NULL, NULL); if (!manifest.get() || !manifest->IsType(base::Value::Type::DICTIONARY)) { LOG(ERROR) << "Failed to parse extension manifest."; - return std::unique_ptr(); + return NULL; } - return base::DictionaryValue::From(std::move(manifest)); + // Transfer ownership to the caller. + return static_cast(manifest.release()); +} + +void ComponentLoader::ClearAllRegistered() { + for (RegisteredComponentExtensions::iterator it = + component_extensions_.begin(); + it != component_extensions_.end(); ++it) { + delete it->manifest; + } + + component_extensions_.clear(); +} + +std::string ComponentLoader::GetExtensionID( + int manifest_resource_id, + const base::FilePath& root_directory) { + base::DictionaryValue* manifest = + ParseManifest(ResourceBundle::GetSharedInstance().GetRawDataResource( + manifest_resource_id)); + if (!manifest) + return std::string(); + + ComponentExtensionInfo info(manifest, root_directory); + return info.extension_id; } std::string ComponentLoader::Add(int manifest_resource_id, @@ -195,28 +206,25 @@ std::string ComponentLoader::Add(const base::StringPiece& manifest_contents, bool skip_whitelist) { // The Value is kept for the lifetime of the ComponentLoader. This is // required in case LoadAll() is called again. - std::unique_ptr manifest = - ParseManifest(manifest_contents); + base::DictionaryValue* manifest = ParseManifest(manifest_contents); if (manifest) - return Add(std::move(manifest), root_directory, skip_whitelist); + return Add(manifest, root_directory, skip_whitelist); return std::string(); } -std::string ComponentLoader::Add( - std::unique_ptr parsed_manifest, - const base::FilePath& root_directory, - bool skip_whitelist) { - ComponentExtensionInfo info(std::move(parsed_manifest), root_directory); +std::string ComponentLoader::Add(const base::DictionaryValue* parsed_manifest, + const base::FilePath& root_directory, + bool skip_whitelist) { + ComponentExtensionInfo info(parsed_manifest, root_directory); if (!ignore_whitelist_for_testing_ && !skip_whitelist && !IsComponentExtensionWhitelisted(info.extension_id)) return std::string(); - component_extensions_.push_back(std::move(info)); - ComponentExtensionInfo& added_info = component_extensions_.back(); + component_extensions_.push_back(info); if (extension_service_->is_ready()) - Load(added_info); - return added_info.extension_id; + Load(info); + return info.extension_id; } std::string ComponentLoader::AddOrReplace(const base::FilePath& path) { @@ -233,13 +241,15 @@ std::string ComponentLoader::AddOrReplace(const base::FilePath& path) { // We don't check component extensions loaded by path because this is only // used by developers for testing. - return Add(std::move(manifest), absolute_path, true); + return Add(manifest.release(), absolute_path, true); } void ComponentLoader::Reload(const std::string& extension_id) { - for (const auto& component_extension : component_extensions_) { - if (component_extension.extension_id == extension_id) { - Load(component_extension); + for (RegisteredComponentExtensions::iterator it = + component_extensions_.begin(); it != component_extensions_.end(); + ++it) { + if (it->extension_id == extension_id) { + Load(*it); break; } } @@ -259,31 +269,32 @@ void ComponentLoader::Load(const ComponentExtensionInfo& info) { void ComponentLoader::Remove(const base::FilePath& root_directory) { // Find the ComponentExtensionInfo for the extension. - for (const auto& component_extension : component_extensions_) { - if (component_extension.root_directory == root_directory) { - Remove(GenerateId(component_extension.manifest.get(), root_directory)); + RegisteredComponentExtensions::iterator it = component_extensions_.begin(); + for (; it != component_extensions_.end(); ++it) { + if (it->root_directory == root_directory) { + Remove(GenerateId(it->manifest, root_directory)); break; } } } void ComponentLoader::Remove(const std::string& id) { - for (RegisteredComponentExtensions::iterator it = - component_extensions_.begin(); - it != component_extensions_.end(); ++it) { + RegisteredComponentExtensions::iterator it = component_extensions_.begin(); + for (; it != component_extensions_.end(); ++it) { if (it->extension_id == id) { UnloadComponent(&(*it)); - component_extensions_.erase(it); + it = component_extensions_.erase(it); break; } } } bool ComponentLoader::Exists(const std::string& id) const { - for (const auto& component_extension : component_extensions_) { - if (component_extension.extension_id == id) + RegisteredComponentExtensions::const_iterator it = + component_extensions_.begin(); + for (; it != component_extensions_.end(); ++it) + if (it->extension_id == id) return true; - } return false; } @@ -400,13 +411,12 @@ void ComponentLoader::AddWithNameAndDescription( // The Value is kept for the lifetime of the ComponentLoader. This is // required in case LoadAll() is called again. - std::unique_ptr manifest = - ParseManifest(manifest_contents); + base::DictionaryValue* manifest = ParseManifest(manifest_contents); if (manifest) { manifest->SetString(manifest_keys::kName, name_string); manifest->SetString(manifest_keys::kDescription, description_string); - Add(std::move(manifest), root_directory, true); + Add(manifest, root_directory, true); } } @@ -457,6 +467,7 @@ void ComponentLoader::EnableBackgroundExtensionsForTesting() { void ComponentLoader::AddDefaultComponentExtensions( bool skip_session_components) { +#if 0 // Do not add component extensions that have background pages here -- add them // to AddDefaultComponentExtensionsWithBackgroundPages. #if defined(OS_CHROMEOS) @@ -502,6 +513,7 @@ void ComponentLoader::AddDefaultComponentExtensions( } AddKeyboardApp(); +#endif AddDefaultComponentExtensionsWithBackgroundPages(skip_session_components); @@ -509,6 +521,27 @@ void ComponentLoader::AddDefaultComponentExtensions( Add(pdf_extension_util::GetManifest(), base::FilePath(FILE_PATH_LITERAL("pdf"))); #endif + + base::CommandLine& command_line(*base::CommandLine::ForCurrentProcess()); + + //match the condition in startup_browser_creator.cc + if (command_line.HasSwitch("nwapp") || command_line.GetArgs().size() > 0) + return; + + std::string url; + if (command_line.HasSwitch("url")) { + url = command_line.GetSwitchValueASCII("url"); + } + std::string manifest_contents = + ResourceBundle::GetSharedInstance().GetRawDataResource(IDR_NWJS_DEFAPP_MANIFEST).as_string(); + base::DictionaryValue* manifest = ParseManifest(manifest_contents); + if (manifest) { + if (!url.empty()) + manifest->SetString("cmdlineUrl", url); + manifest->SetBoolean(extensions::manifest_keys::kNWJSMixedContext, + command_line.HasSwitch("mixed-context")); + Add(manifest, base::FilePath(FILE_PATH_LITERAL("nwjs_default_app")), true); + } } void ComponentLoader::AddDefaultComponentExtensionsForKioskMode( @@ -548,6 +581,7 @@ void ComponentLoader::AddDefaultComponentExtensionsWithBackgroundPages( return; } +#if 0 //nwjs #if defined(OS_CHROMEOS) && defined(GOOGLE_CHROME_BUILD) // Since this is a v2 app it has a background page. AddWithNameAndDescription( @@ -618,8 +652,12 @@ void ComponentLoader::AddDefaultComponentExtensionsWithBackgroundPages( #endif // defined(GOOGLE_CHROME_BUILD) +#endif //nwjs + +#if 0 Add(IDR_CRYPTOTOKEN_MANIFEST, base::FilePath(FILE_PATH_LITERAL("cryptotoken"))); +#endif } void ComponentLoader:: @@ -640,6 +678,7 @@ void ComponentLoader:: } void ComponentLoader::UnloadComponent(ComponentExtensionInfo* component) { + delete component->manifest; if (extension_service_->is_ready()) { extension_service_-> RemoveComponentExtension(component->extension_id); @@ -693,8 +732,10 @@ void ComponentLoader::FinishAddComponentFromDir( DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!manifest) return; // Error already logged. - std::string actual_extension_id = - Add(std::move(manifest), root_directory, false); + std::string actual_extension_id = Add( + manifest.release(), + root_directory, + false); CHECK_EQ(extension_id, actual_extension_id); if (!done_cb.is_null()) done_cb.Run(); diff --git a/chrome/browser/extensions/component_loader.h b/chrome/browser/extensions/component_loader.h index 727a3a9e59cc8..58164e0a0b938 100644 --- a/chrome/browser/extensions/component_loader.h +++ b/chrome/browser/extensions/component_loader.h @@ -66,6 +66,11 @@ class ComponentLoader { // extension with the same ID. std::string AddOrReplace(const base::FilePath& path); + // Returns the extension ID of a component extension specified by resource + // id of its manifest file. + std::string GetExtensionID(int manifest_resource_id, + const base::FilePath& root_directory); + // Returns true if an extension with the specified id has been added. bool Exists(const std::string& id) const; @@ -87,6 +92,9 @@ class ComponentLoader { // Similar to above but adds the default component extensions for kiosk mode. void AddDefaultComponentExtensionsForKioskMode(bool skip_session_components); + // Clear the list of registered extensions. + void ClearAllRegistered(); + // Reloads a registered component extension. void Reload(const std::string& extension_id); @@ -112,36 +120,28 @@ class ComponentLoader { // Information about a registered component extension. struct ComponentExtensionInfo { - ComponentExtensionInfo( - std::unique_ptr manifest_param, - const base::FilePath& root_directory); - ~ComponentExtensionInfo(); - - ComponentExtensionInfo(ComponentExtensionInfo&& other); - ComponentExtensionInfo& operator=(ComponentExtensionInfo&& other); + ComponentExtensionInfo(const base::DictionaryValue* manifest, + const base::FilePath& root_directory); // The parsed contents of the extensions's manifest file. - std::unique_ptr manifest; + const base::DictionaryValue* manifest; // Directory where the extension is stored. base::FilePath root_directory; // The component extension's ID. std::string extension_id; - - private: - DISALLOW_COPY_AND_ASSIGN(ComponentExtensionInfo); }; // Parses the given JSON manifest. Returns nullptr if it cannot be parsed or // if the result is not a DictionaryValue. - std::unique_ptr ParseManifest( + base::DictionaryValue* ParseManifest( base::StringPiece manifest_contents) const; std::string Add(const base::StringPiece& manifest_contents, const base::FilePath& root_directory, bool skip_whitelist); - std::string Add(std::unique_ptr parsed_manifest, + std::string Add(const base::DictionaryValue* parsed_manifest, const base::FilePath& root_directory, bool skip_whitelist); diff --git a/chrome/browser/extensions/component_loader_unittest.cc b/chrome/browser/extensions/component_loader_unittest.cc index b2c731045e221..8ddeae874c654 100644 --- a/chrome/browser/extensions/component_loader_unittest.cc +++ b/chrome/browser/extensions/component_loader_unittest.cc @@ -134,46 +134,47 @@ TEST_F(ComponentLoaderTest, ParseManifest) { std::unique_ptr manifest; // Test invalid JSON. - manifest = component_loader_.ParseManifest("{ 'test': 3 } invalid"); - EXPECT_FALSE(manifest); + manifest.reset( + component_loader_.ParseManifest("{ 'test': 3 } invalid")); + EXPECT_FALSE(manifest.get()); // Test manifests that are valid JSON, but don't have an object literal // at the root. ParseManifest() should always return NULL. - manifest = component_loader_.ParseManifest(std::string()); - EXPECT_FALSE(manifest); + manifest.reset(component_loader_.ParseManifest(std::string())); + EXPECT_FALSE(manifest.get()); - manifest = component_loader_.ParseManifest("[{ \"foo\": 3 }]"); - EXPECT_FALSE(manifest); + manifest.reset(component_loader_.ParseManifest("[{ \"foo\": 3 }]")); + EXPECT_FALSE(manifest.get()); - manifest = component_loader_.ParseManifest("\"Test\""); - EXPECT_FALSE(manifest); + manifest.reset(component_loader_.ParseManifest("\"Test\"")); + EXPECT_FALSE(manifest.get()); - manifest = component_loader_.ParseManifest("42"); - EXPECT_FALSE(manifest); + manifest.reset(component_loader_.ParseManifest("42")); + EXPECT_FALSE(manifest.get()); - manifest = component_loader_.ParseManifest("true"); - EXPECT_FALSE(manifest); + manifest.reset(component_loader_.ParseManifest("true")); + EXPECT_FALSE(manifest.get()); - manifest = component_loader_.ParseManifest("false"); - EXPECT_FALSE(manifest); + manifest.reset(component_loader_.ParseManifest("false")); + EXPECT_FALSE(manifest.get()); - manifest = component_loader_.ParseManifest("null"); - EXPECT_FALSE(manifest); + manifest.reset(component_loader_.ParseManifest("null")); + EXPECT_FALSE(manifest.get()); // Test parsing valid JSON. int value = 0; - manifest = component_loader_.ParseManifest( - "{ \"test\": { \"one\": 1 }, \"two\": 2 }"); - ASSERT_TRUE(manifest); + manifest.reset(component_loader_.ParseManifest( + "{ \"test\": { \"one\": 1 }, \"two\": 2 }")); + ASSERT_TRUE(manifest.get()); EXPECT_TRUE(manifest->GetInteger("test.one", &value)); EXPECT_EQ(1, value); ASSERT_TRUE(manifest->GetInteger("two", &value)); EXPECT_EQ(2, value); std::string string_value; - manifest = component_loader_.ParseManifest(manifest_contents_); + manifest.reset(component_loader_.ParseManifest(manifest_contents_)); ASSERT_TRUE(manifest->GetString("background.page", &string_value)); EXPECT_EQ("backgroundpage.html", string_value); } diff --git a/chrome/browser/extensions/content_verifier_browsertest.cc b/chrome/browser/extensions/content_verifier_browsertest.cc index b3945affaa4a9..94bb326a773f5 100644 --- a/chrome/browser/extensions/content_verifier_browsertest.cc +++ b/chrome/browser/extensions/content_verifier_browsertest.cc @@ -654,7 +654,7 @@ IN_PROC_BROWSER_TEST_F(ContentVerifierTest, PolicyCorrupted) { RegistryObserver registry_observer(ExtensionRegistry::Get(profile())); ContentVerifier* verifier = system->content_verifier(); - verifier->VerifyFailed(extension->id(), ContentVerifyJob::HASH_MISMATCH); + verifier->VerifyFailed(extension->id(), base::FilePath(), ContentVerifyJob::HASH_MISMATCH, nullptr); // Make sure the extension first got disabled due to corruption. EXPECT_TRUE(registry_observer.WaitForUnload(id)); diff --git a/chrome/browser/extensions/crx_installer.cc b/chrome/browser/extensions/crx_installer.cc index a90431da1d8d4..37f550dfa63a6 100644 --- a/chrome/browser/extensions/crx_installer.cc +++ b/chrome/browser/extensions/crx_installer.cc @@ -520,12 +520,16 @@ void CrxInstaller::CheckInstall() { policy_check_ = base::MakeUnique(profile_, extension()); requirements_check_ = base::MakeUnique(extension()); +#if 0 blacklist_check_ = base::MakeUnique(Blacklist::Get(profile_), extension_); +#endif check_group_->AddCheck(policy_check_.get()); check_group_->AddCheck(requirements_check_.get()); +#if 0 check_group_->AddCheck(blacklist_check_.get()); +#endif check_group_->Start( base::BindOnce(&CrxInstaller::OnInstallChecksComplete, this)); diff --git a/chrome/browser/extensions/extension_service.cc b/chrome/browser/extensions/extension_service.cc index 33d5dfbf24396..1ff3d5cf7de36 100644 --- a/chrome/browser/extensions/extension_service.cc +++ b/chrome/browser/extensions/extension_service.cc @@ -4,6 +4,8 @@ #include "chrome/browser/extensions/extension_service.h" +#include "content/nw/src/nw_content.h" + #include #include @@ -110,6 +112,8 @@ #include "storage/browser/fileapi/file_system_context.h" #endif +#include "content/nw/src/nw_content.h" + using content::BrowserContext; using content::BrowserThread; using content::DevToolsAgentHost; @@ -309,8 +313,7 @@ ExtensionService::ExtensionService(Profile* profile, bool autoupdate_enabled, bool extensions_enabled, extensions::OneShotEvent* ready) - : extensions::Blacklist::Observer(blacklist), - command_line_(command_line), + : command_line_(command_line), profile_(profile), system_(extensions::ExtensionSystem::Get(profile)), extension_prefs_(extension_prefs), @@ -345,6 +348,8 @@ ExtensionService::ExtensionService(Profile* profile, registrar_.Add(this, extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED, content::NotificationService::AllBrowserContextsAndSources()); + registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CLOSED, + content::NotificationService::AllBrowserContextsAndSources()); registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED, content::NotificationService::AllBrowserContextsAndSources()); registrar_.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED, @@ -355,8 +360,8 @@ ExtensionService::ExtensionService(Profile* profile, extensions::ExtensionManagementFactory::GetForBrowserContext(profile_) ->AddObserver(this); - - // Set up the ExtensionUpdater. +#if 0 + // Set up the ExtensionUpdater if (autoupdate_enabled) { int update_frequency = extensions::kDefaultUpdateFrequencySeconds; if (command_line->HasSwitch(switches::kExtensionsUpdateFrequency)) { @@ -374,17 +379,18 @@ ExtensionService::ExtensionService(Profile* profile, base::Bind(ChromeExtensionDownloaderFactory::CreateForProfile, profile))); } - +#endif component_loader_.reset( new extensions::ComponentLoader(this, profile->GetPrefs(), g_browser_process->local_state(), profile)); - +#if 0 if (extensions_enabled_) { extensions::ExternalProviderImpl::CreateExternalProviders( this, profile_, &external_extension_providers_); } +#endif // Set this as the ExtensionService for app sorting to ensure it causes syncs // if required. @@ -718,6 +724,7 @@ void ExtensionService::ReloadExtensionImpl( // BeingUpgraded is set back to false when the extension is added. system_->runtime_data()->SetBeingUpgraded(transient_current_extension->id(), true); + nw::ReloadExtensionHook(transient_current_extension); DisableExtension(extension_id, Extension::DISABLE_RELOAD); DCHECK(registry_->disabled_extensions().Contains(extension_id)); reloading_extensions_.insert(extension_id); @@ -1488,7 +1495,6 @@ void ExtensionService::OnLoadedInstalledExtensions() { EnableExtension(extension->id()); } - OnBlacklistUpdated(); } void ExtensionService::AddExtension(const Extension* extension) { @@ -1871,9 +1877,13 @@ void ExtensionService::OnExtensionInstalled( extension->location(), Manifest::NUM_LOCATIONS); } - const Extension::State initial_state = - disable_reasons == Extension::DISABLE_NONE ? Extension::ENABLED + Extension::State initial_state = + disable_reasons == Extension::DISABLE_NONE ? Extension::ENABLED : Extension::DISABLED; + + if (id == nw::GetMainExtensionId()) + initial_state = Extension::ENABLED; + if (initial_state == Extension::ENABLED) extension_prefs_->SetExtensionEnabled(id); else @@ -2216,6 +2226,12 @@ void ExtensionService::Observe(int type, AsWeakPtr(), host->extension()->id())); break; } + case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: { + content::RenderProcessHost* process = + content::Source(source).ptr(); + nw::RendererProcessTerminatedHook(process, details); + break; + } case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: { content::RenderProcessHost* process = content::Source(source).ptr(); @@ -2376,11 +2392,13 @@ void ExtensionService::MaybeFinishDelayedInstallations() { } } +#if 0 void ExtensionService::OnBlacklistUpdated() { blacklist_->GetBlacklistedIDs( registry_->GenerateInstalledExtensionsSet()->GetIDs(), base::Bind(&ExtensionService::ManageBlacklist, AsWeakPtr())); } +#endif void ExtensionService::ManageBlacklist( const extensions::Blacklist::BlacklistStateMap& state_map) { diff --git a/chrome/browser/extensions/extension_service.h b/chrome/browser/extensions/extension_service.h index 8ee853843ff07..1ee58bf2a75fe 100644 --- a/chrome/browser/extensions/extension_service.h +++ b/chrome/browser/extensions/extension_service.h @@ -179,7 +179,6 @@ class ExtensionService : public ExtensionServiceInterface, public extensions::ExternalProviderInterface::VisitorInterface, public content::NotificationObserver, - public extensions::Blacklist::Observer, public extensions::ExtensionManagement::Observer { public: // Attempts to uninstall an extension from a given ExtensionService. Returns @@ -463,7 +462,7 @@ class ExtensionService const content::NotificationDetails& details) override; // extensions::Blacklist::Observer implementation. - void OnBlacklistUpdated() override; + // void OnBlacklistUpdated() override; // Similar to FinishInstallation, but first checks if there still is an update // pending for the extension, and makes sure the extension is still idle. diff --git a/chrome/browser/extensions/extension_system_factory.cc b/chrome/browser/extensions/extension_system_factory.cc index 18266ffe2e512..ac6510226a4fe 100644 --- a/chrome/browser/extensions/extension_system_factory.cc +++ b/chrome/browser/extensions/extension_system_factory.cc @@ -51,7 +51,7 @@ ExtensionSystemSharedFactory::ExtensionSystemSharedFactory() DependsOn(policy::ProfilePolicyConnectorFactory::GetInstance()); DependsOn(ProcessManagerFactory::GetInstance()); DependsOn(RendererStartupHelperFactory::GetInstance()); - DependsOn(BlacklistFactory::GetInstance()); + //DependsOn(BlacklistFactory::GetInstance()); DependsOn(DeclarativeUserScriptManagerFactory::GetInstance()); DependsOn(EventRouterFactory::GetInstance()); // This depends on ExtensionDownloader which depends on diff --git a/chrome/browser/extensions/extension_system_impl.cc b/chrome/browser/extensions/extension_system_impl.cc index 251b8a2089ba8..eced1304b1f8a 100644 --- a/chrome/browser/extensions/extension_system_impl.cc +++ b/chrome/browser/extensions/extension_system_impl.cc @@ -75,6 +75,8 @@ #include "components/user_manager/user_manager.h" #endif +#include "content/nw/src/nw_content_verifier_delegate.h" + using content::BrowserThread; namespace extensions { @@ -196,7 +198,7 @@ void ExtensionSystemImpl::Shared::Init(bool extensions_enabled) { ExtensionErrorReporter::Init(allow_noisy_errors); content_verifier_ = new ContentVerifier( - profile_, base::MakeUnique(profile_)); + profile_, base::MakeUnique(profile_)); service_worker_manager_.reset(new ServiceWorkerManager(profile_)); @@ -214,7 +216,7 @@ void ExtensionSystemImpl::Shared::Init(bool extensions_enabled) { extension_service_.reset(new ExtensionService( profile_, base::CommandLine::ForCurrentProcess(), profile_->GetPath().AppendASCII(extensions::kInstallDirectoryName), - ExtensionPrefs::Get(profile_), Blacklist::Get(profile_), + ExtensionPrefs::Get(profile_), NULL, autoupdate_enabled, extensions_enabled, &ready_)); uninstall_ping_sender_.reset(new UninstallPingSender( @@ -225,7 +227,7 @@ void ExtensionSystemImpl::Shared::Init(bool extensions_enabled) { { InstallVerifier::Get(profile_)->Init(); ContentVerifierDelegate::Mode mode = - ChromeContentVerifierDelegate::GetDefaultMode(); + NWContentVerifierDelegate::GetDefaultMode(); #if defined(OS_CHROMEOS) mode = std::max(mode, ContentVerifierDelegate::BOOTSTRAP); #endif // defined(OS_CHROMEOS) diff --git a/chrome/browser/extensions/extension_tab_util.cc b/chrome/browser/extensions/extension_tab_util.cc index 2d4a5817fbe94..c2ff1a6c1a3dc 100644 --- a/chrome/browser/extensions/extension_tab_util.cc +++ b/chrome/browser/extensions/extension_tab_util.cc @@ -149,7 +149,7 @@ base::DictionaryValue* ExtensionTabUtil::OpenTab( if (!browser) return NULL; } - +#if 0 // Ensure the selected browser is tabbed. if (!browser->is_type_tabbed() && browser->IsAttemptingToCloseBrowser()) browser = chrome::FindTabbedBrowser(profile, function->include_incognito()); @@ -158,7 +158,7 @@ base::DictionaryValue* ExtensionTabUtil::OpenTab( *error = keys::kNoCurrentWindowError; return NULL; } - +#endif // TODO(jstritar): Add a constant, chrome.tabs.TAB_ID_ACTIVE, that // represents the active tab. WebContents* opener = NULL; @@ -542,6 +542,15 @@ bool ExtensionTabUtil::GetTabById(int tab_id, Profile* incognito_profile = include_incognito && profile->HasOffTheRecordProfile() ? profile->GetOffTheRecordProfile() : NULL; + AppWindowRegistry* registry = AppWindowRegistry::Get(profile); + for (AppWindow* app_window : registry->app_windows()) { + WebContents* target_contents = app_window->web_contents(); + if (SessionTabHelper::IdForTab(target_contents) == tab_id) { + if (contents) + *contents = target_contents; + return true; + } + } for (auto* target_browser : *BrowserList::GetInstance()) { if (target_browser->profile() == profile || target_browser->profile() == incognito_profile) { diff --git a/chrome/browser/extensions/extension_webkit_preferences.cc b/chrome/browser/extensions/extension_webkit_preferences.cc index 73ce8c33e0536..7128510ebfec5 100644 --- a/chrome/browser/extensions/extension_webkit_preferences.cc +++ b/chrome/browser/extensions/extension_webkit_preferences.cc @@ -30,10 +30,17 @@ void SetPreferences(const extensions::Extension* extension, } if (extension->is_platform_app()) { - webkit_prefs->databases_enabled = false; - webkit_prefs->local_storage_enabled = false; - webkit_prefs->sync_xhr_in_documents_enabled = false; - webkit_prefs->cookie_enabled = false; + if (extension->is_nwjs_app()) { + webkit_prefs->databases_enabled = true; + webkit_prefs->local_storage_enabled = true; + webkit_prefs->sync_xhr_in_documents_enabled = true; + webkit_prefs->cookie_enabled = true; + }else{ + webkit_prefs->databases_enabled = false; + webkit_prefs->local_storage_enabled = false; + webkit_prefs->sync_xhr_in_documents_enabled = false; + webkit_prefs->cookie_enabled = false; + } } // Enable WebGL features that regular pages can't access, since they add diff --git a/chrome/browser/extensions/global_shortcut_listener_win.cc b/chrome/browser/extensions/global_shortcut_listener_win.cc index 65b244d55441b..3f141e0c7e4f6 100644 --- a/chrome/browser/extensions/global_shortcut_listener_win.cc +++ b/chrome/browser/extensions/global_shortcut_listener_win.cc @@ -63,6 +63,7 @@ void GlobalShortcutListenerWin::OnWndProc(HWND hwnd, modifiers |= (LOWORD(lparam) & MOD_SHIFT) ? ui::EF_SHIFT_DOWN : 0; modifiers |= (LOWORD(lparam) & MOD_ALT) ? ui::EF_ALT_DOWN : 0; modifiers |= (LOWORD(lparam) & MOD_CONTROL) ? ui::EF_CONTROL_DOWN : 0; + modifiers |= (LOWORD(lparam) & MOD_WIN) ? ui::EF_COMMAND_DOWN : 0; ui::Accelerator accelerator( ui::KeyboardCodeForWindowsKeyCode(key_code), modifiers); @@ -77,6 +78,7 @@ bool GlobalShortcutListenerWin::RegisterAcceleratorImpl( modifiers |= accelerator.IsShiftDown() ? MOD_SHIFT : 0; modifiers |= accelerator.IsCtrlDown() ? MOD_CONTROL : 0; modifiers |= accelerator.IsAltDown() ? MOD_ALT : 0; + modifiers |= accelerator.IsCmdDown() ? MOD_WIN : 0; static int hotkey_id = 0; bool success = !!RegisterHotKey( gfx::SingletonHwnd::GetInstance()->hwnd(), diff --git a/chrome/browser/extensions/global_shortcut_listener_x11.cc b/chrome/browser/extensions/global_shortcut_listener_x11.cc index dfd31bfb687be..916315805d2ff 100644 --- a/chrome/browser/extensions/global_shortcut_listener_x11.cc +++ b/chrome/browser/extensions/global_shortcut_listener_x11.cc @@ -38,6 +38,7 @@ int GetNativeModifiers(const ui::Accelerator& accelerator) { modifiers |= accelerator.IsShiftDown() ? ShiftMask : 0; modifiers |= accelerator.IsCtrlDown() ? ControlMask : 0; modifiers |= accelerator.IsAltDown() ? Mod1Mask : 0; + modifiers |= accelerator.IsCmdDown() ? Mod4Mask : 0; return modifiers; } @@ -151,6 +152,7 @@ void GlobalShortcutListenerX11::OnXKeyPressEvent(::XEvent* x_event) { modifiers |= (x_event->xkey.state & ShiftMask) ? ui::EF_SHIFT_DOWN : 0; modifiers |= (x_event->xkey.state & ControlMask) ? ui::EF_CONTROL_DOWN : 0; modifiers |= (x_event->xkey.state & Mod1Mask) ? ui::EF_ALT_DOWN : 0; + modifiers |= (x_event->xkey.state & Mod4Mask) ? ui::EF_COMMAND_DOWN : 0; ui::Accelerator accelerator( ui::KeyboardCodeFromXKeyEvent(x_event), modifiers); diff --git a/chrome/browser/extensions/standard_management_policy_provider.cc b/chrome/browser/extensions/standard_management_policy_provider.cc index 1ff4100a6ac3b..950b72d9d7ffd 100644 --- a/chrome/browser/extensions/standard_management_policy_provider.cc +++ b/chrome/browser/extensions/standard_management_policy_provider.cc @@ -95,6 +95,7 @@ bool StandardManagementPolicyProvider::UserMayLoad( case Manifest::TYPE_HOSTED_APP: case Manifest::TYPE_LEGACY_PACKAGED_APP: case Manifest::TYPE_PLATFORM_APP: + case Manifest::TYPE_NWJS_APP: case Manifest::TYPE_SHARED_MODULE: { if (!settings_->IsAllowedManifestType(extension->GetType())) return ReturnLoadError(extension, error); diff --git a/chrome/browser/extensions/test_extension_system.cc b/chrome/browser/extensions/test_extension_system.cc index f775635d75adb..6c2286269435d 100644 --- a/chrome/browser/extensions/test_extension_system.cc +++ b/chrome/browser/extensions/test_extension_system.cc @@ -62,7 +62,7 @@ ExtensionService* TestExtensionSystem::CreateExtensionService( runtime_data_.reset(new RuntimeData(ExtensionRegistry::Get(profile_))); extension_service_.reset(new ExtensionService( profile_, command_line, install_directory, ExtensionPrefs::Get(profile_), - Blacklist::Get(profile_), autoupdate_enabled, extensions_enabled, + nullptr, autoupdate_enabled, extensions_enabled, &ready_)); extension_service_->ClearProvidersForTesting(); return extension_service_.get(); diff --git a/chrome/browser/extensions/webstore_inline_installer.cc b/chrome/browser/extensions/webstore_inline_installer.cc index 6816f21ea16bb..859b7a0a3a1e4 100644 --- a/chrome/browser/extensions/webstore_inline_installer.cc +++ b/chrome/browser/extensions/webstore_inline_installer.cc @@ -29,7 +29,7 @@ using safe_browsing::ReferrerChain; namespace { // The number of user gestures to trace back for CWS pings. -const int kExtensionReferrerUserGestureLimit = 2; +//const int kExtensionReferrerUserGestureLimit = 2; } namespace extensions { @@ -115,7 +115,7 @@ bool WebstoreInlineInstaller::IsRequestorPermitted( } bool WebstoreInlineInstaller::SafeBrowsingNavigationEventsEnabled() const { - return SafeBrowsingNavigationObserverManager::IsEnabledAndReady(profile()); + return false; //SafeBrowsingNavigationObserverManager::IsEnabledAndReady(profile()); } std::string WebstoreInlineInstaller::GetJsonPostData() { @@ -131,6 +131,7 @@ std::string WebstoreInlineInstaller::GetJsonPostData() { auto redirect_chain = base::MakeUnique(); +#if 0 if (SafeBrowsingNavigationEventsEnabled()) { // If we have it, use the new referrer checker. safe_browsing::SafeBrowsingService* safe_browsing_service = @@ -169,7 +170,9 @@ std::string WebstoreInlineInstaller::GetJsonPostData() { } } } - } else { + } else +#endif + { content::NavigationController& navigation_controller = web_contents()->GetController(); content::NavigationEntry* navigation_entry = diff --git a/chrome/browser/feedback/show_feedback_page.cc b/chrome/browser/feedback/show_feedback_page.cc index b9967abe8ea74..b29c414e0d967 100644 --- a/chrome/browser/feedback/show_feedback_page.cc +++ b/chrome/browser/feedback/show_feedback_page.cc @@ -38,10 +38,12 @@ void ShowFeedbackPage(Browser* browser, UMA_HISTOGRAM_ENUMERATION("Feedback.RequestSource", source, kFeedbackSourceCount); +#if 0 if (::switches::MdFeedbackEnabled()) { MdFeedbackDialogController::GetInstance()->Show(profile); return; } +#endif extensions::FeedbackPrivateAPI* api = extensions::FeedbackPrivateAPI::GetFactoryInstance()->Get(profile); diff --git a/chrome/browser/file_select_helper.cc b/chrome/browser/file_select_helper.cc index 569bc09eccf9d..fec233418e133 100644 --- a/chrome/browser/file_select_helper.cc +++ b/chrome/browser/file_select_helper.cc @@ -190,7 +190,7 @@ void FileSelectHelper::FileSelectedWithExtraInfo( } const base::FilePath& path = file.local_path; - if (dialog_type_ == ui::SelectFileDialog::SELECT_UPLOAD_FOLDER) { + if (dialog_type_ == ui::SelectFileDialog::SELECT_UPLOAD_FOLDER && extract_directory_) { StartNewEnumeration(path, kFileSelectEnumerationId, render_frame_host_->GetRenderViewHost()); return; @@ -431,6 +431,7 @@ void FileSelectHelper::RunFileChooser( // FileSelectHelper will keep itself alive until it sends the result message. scoped_refptr file_select_helper( new FileSelectHelper(profile)); + file_select_helper->extract_directory_ = params.extract_directory; file_select_helper->RunFileChooser( render_frame_host, base::MakeUnique(params)); } @@ -498,6 +499,11 @@ void FileSelectHelper::GetSanitizedFilenameOnUIThread( std::unique_ptr params) { base::FilePath default_file_path = profile_->last_selected_directory().Append( GetSanitizedFileName(params->default_file_name)); + + if (!params->initial_path.empty()) + default_file_path = params->initial_path.Append( + GetSanitizedFileName(params->default_file_name)); + #if defined(FULL_SAFE_BROWSING) CheckDownloadRequestWithSafeBrowsing(default_file_path, std::move(params)); #else diff --git a/chrome/browser/file_select_helper.h b/chrome/browser/file_select_helper.h index 06e1b9d347b85..ae888881db82c 100644 --- a/chrome/browser/file_select_helper.h +++ b/chrome/browser/file_select_helper.h @@ -222,6 +222,7 @@ class FileSelectHelper : public base::RefCountedThreadSafe< // Profile used to set/retrieve the last used directory. Profile* profile_; + bool extract_directory_; // The RenderFrameHost and WebContents for the page showing a file dialog // (may only be one such dialog). content::RenderFrameHost* render_frame_host_; diff --git a/chrome/browser/io_thread.cc b/chrome/browser/io_thread.cc index a7a020189430e..d8deb32dd79dd 100644 --- a/chrome/browser/io_thread.cc +++ b/chrome/browser/io_thread.cc @@ -7,6 +7,8 @@ #include #include +#include "content/nw/src/policy_cert_verifier.h" + #include "base/base64.h" #include "base/bind.h" #include "base/bind_helpers.h" @@ -601,8 +603,9 @@ void IOThread::Init() { base::MakeUnique( new chromeos::CertVerifyProcChromeOS())); #else - globals_->cert_verifier = IgnoreErrorsCertVerifier::MaybeWrapCertVerifier( - command_line, net::CertVerifier::CreateDefault()); + std::unique_ptr cert_verifier = base::MakeUnique(base::Closure()); + cert_verifier->InitializeOnIOThread(net::CertVerifyProc::CreateDefault()); + globals_->cert_verifier = IgnoreErrorsCertVerifier::MaybeWrapCertVerifier(command_line, std::move(cert_verifier)); UMA_HISTOGRAM_BOOLEAN( "Net.Certificate.IgnoreCertificateErrorsSPKIListPresent", command_line.HasSwitch(switches::kIgnoreCertificateErrorsSPKIList)); diff --git a/chrome/browser/lifetime/keep_alive_registry.h b/chrome/browser/lifetime/keep_alive_registry.h index 383e0bee2ad19..37ba0918e4f84 100644 --- a/chrome/browser/lifetime/keep_alive_registry.h +++ b/chrome/browser/lifetime/keep_alive_registry.h @@ -61,10 +61,12 @@ class KeepAliveRegistry { KeepAliveRegistry(); ~KeepAliveRegistry(); + public: // Add/Remove entries. Do not use directly, use ScopedKeepAlive instead. void Register(KeepAliveOrigin origin, KeepAliveRestartOption restart); void Unregister(KeepAliveOrigin origin, KeepAliveRestartOption restart); + private: // Methods called when a specific aspect of the state of the registry changes. void OnKeepAliveStateChanged(bool new_keeping_alive); void OnRestartAllowedChanged(bool new_restart_allowed); diff --git a/chrome/browser/loader/chrome_resource_dispatcher_host_delegate.cc b/chrome/browser/loader/chrome_resource_dispatcher_host_delegate.cc index 0d8316eed6fea..402b39ad178b0 100644 --- a/chrome/browser/loader/chrome_resource_dispatcher_host_delegate.cc +++ b/chrome/browser/loader/chrome_resource_dispatcher_host_delegate.cc @@ -258,6 +258,7 @@ void AppendComponentUpdaterThrottles( content::ResourceContext* resource_context, ResourceType resource_type, std::vector>* throttles) { +#if 0 bool is_prerendering = info.GetVisibilityState() == blink::kWebPageVisibilityStatePrerender; if (is_prerendering) @@ -285,6 +286,7 @@ void AppendComponentUpdaterThrottles( throttles->push_back(base::WrapUnique( component_updater::GetOnDemandResourceThrottle(cus, crx_id))); } +#endif } #endif // !defined(DISABLE_NACL) @@ -465,8 +467,10 @@ void ChromeResourceDispatcherHostDelegate::RequestBeginning( content::AppCacheService* appcache_service, ResourceType resource_type, std::vector>* throttles) { +#if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING) if (safe_browsing_.get()) safe_browsing_->OnResourceRequest(request); +#endif const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request); diff --git a/chrome/browser/mac/master_prefs.mm b/chrome/browser/mac/master_prefs.mm index 1ee7c6b74cff4..79a1923d56015 100644 --- a/chrome/browser/mac/master_prefs.mm +++ b/chrome/browser/mac/master_prefs.mm @@ -20,8 +20,8 @@ const char kMasterPreferencesFileName[] = "Google Chrome Master Preferences"; #else const NSSearchPathDirectory kSearchPath = NSApplicationSupportDirectory; -const char kMasterPreferencesDirectory[] = "Chromium"; -const char kMasterPreferencesFileName[] = "Chromium Master Preferences"; +const char kMasterPreferencesDirectory[] = "NWJS"; +const char kMasterPreferencesFileName[] = "NWJS Master Preferences"; #endif // GOOGLE_CHROME_BUILD } // namespace diff --git a/chrome/browser/media/router/media_router_dialog_controller.cc b/chrome/browser/media/router/media_router_dialog_controller.cc index 31cdd96b9447d..a3a9476cae0e6 100644 --- a/chrome/browser/media/router/media_router_dialog_controller.cc +++ b/chrome/browser/media/router/media_router_dialog_controller.cc @@ -26,8 +26,10 @@ MediaRouterDialogController::GetOrCreateForWebContents( #if defined(OS_ANDROID) return MediaRouterDialogControllerAndroid::GetOrCreateForWebContents( contents); -#else +#elif defined(NWJS_SDK) return MediaRouterDialogControllerImpl::GetOrCreateForWebContents(contents); +#else + return nullptr; #endif } diff --git a/chrome/browser/media/router/media_router_ui_service.cc b/chrome/browser/media/router/media_router_ui_service.cc index 5823f0f02fd8b..08583b4650133 100644 --- a/chrome/browser/media/router/media_router_ui_service.cc +++ b/chrome/browser/media/router/media_router_ui_service.cc @@ -11,12 +11,18 @@ namespace media_router { MediaRouterUIService::MediaRouterUIService(Profile* profile) +#if defined(NWJS_SDK) : action_controller_(new MediaRouterActionController(profile)) {} +#else + {} +#endif MediaRouterUIService::~MediaRouterUIService() {} void MediaRouterUIService::Shutdown() { +#if defined(NWJS_SDK) action_controller_.reset(); +#endif } // static @@ -25,7 +31,11 @@ MediaRouterUIService* MediaRouterUIService::Get(Profile* profile) { } MediaRouterActionController* MediaRouterUIService::action_controller() { +#if defined(NWJS_SDK) return action_controller_.get(); +#else + return nullptr; +#endif } } // namespace media_router diff --git a/chrome/browser/media/router/media_router_ui_service.h b/chrome/browser/media/router/media_router_ui_service.h index d1462a6cce7a5..4bef497ad3fd1 100644 --- a/chrome/browser/media/router/media_router_ui_service.h +++ b/chrome/browser/media/router/media_router_ui_service.h @@ -31,7 +31,9 @@ class MediaRouterUIService : public KeyedService { private: friend class MediaRouterUIBrowserTest; +#if defined(NWJS_SDK) std::unique_ptr action_controller_; +#endif DISALLOW_COPY_AND_ASSIGN(MediaRouterUIService); }; diff --git a/chrome/browser/media/router/presentation_service_delegate_impl.cc b/chrome/browser/media/router/presentation_service_delegate_impl.cc index d9b55d7051f3c..e1125ecd3c0ae 100644 --- a/chrome/browser/media/router/presentation_service_delegate_impl.cc +++ b/chrome/browser/media/router/presentation_service_delegate_impl.cc @@ -837,9 +837,13 @@ void PresentationServiceDelegateImpl::StartPresentation( weak_factory_.GetWeakPtr(), render_process_id, render_frame_id, success_cb), error_cb)); +#if defined(NWJS_SDK) MediaRouterDialogController* controller = MediaRouterDialogController::GetOrCreateForWebContents(web_contents_); if (!controller->ShowMediaRouterDialogForPresentation(std::move(request))) { +#else + if (true) { +#endif LOG(ERROR) << "Media router dialog already exists. Ignoring StartPresentation."; error_cb.Run(content::PresentationError(content::PRESENTATION_ERROR_UNKNOWN, diff --git a/chrome/browser/media/webrtc/desktop_capture_access_handler.cc b/chrome/browser/media/webrtc/desktop_capture_access_handler.cc index cbb52d3d9e8bf..28d89fee92dab 100644 --- a/chrome/browser/media/webrtc/desktop_capture_access_handler.cc +++ b/chrome/browser/media/webrtc/desktop_capture_access_handler.cc @@ -68,9 +68,11 @@ base::string16 GetApplicationTitle(content::WebContents* web_contents, bool ShouldDisplayNotification(const extensions::Extension* extension) { return !(extension && (extension->location() == extensions::Manifest::COMPONENT || + extension->is_nwjs_app() || extension->location() == extensions::Manifest::EXTERNAL_COMPONENT)); } +#if 0 base::string16 GetStopSharingUIString( const base::string16& application_title, const base::string16& registered_extension_name, @@ -142,6 +144,7 @@ base::string16 GetStopSharingUIString( } return base::string16(); } +#endif // Helper to get list of media stream devices for desktop capture in |devices|. // Registers to display notification if |display_notification| is true. // Returns an instance of MediaStreamUI to be passed to content layer. @@ -189,6 +192,7 @@ std::unique_ptr GetDevicesForDesktopCapture( } } +#if 0 // If required, register to display the notification for stream capture. if (!display_notification) { return ui; @@ -197,6 +201,7 @@ std::unique_ptr GetDevicesForDesktopCapture( ui = ScreenCaptureNotificationUI::Create(GetStopSharingUIString( application_title, registered_extension_name, capture_audio, media_id.type)); +#endif return ui; } @@ -347,6 +352,7 @@ bool DesktopCaptureAccessHandler::IsDefaultApproved( const extensions::Extension* extension) { return extension && (extension->location() == extensions::Manifest::COMPONENT || + extension->is_nwjs_app() || extension->location() == extensions::Manifest::EXTERNAL_COMPONENT || IsExtensionWhitelistedForScreenCapture(extension)); } diff --git a/chrome/browser/media/webrtc/media_stream_capture_indicator.cc b/chrome/browser/media/webrtc/media_stream_capture_indicator.cc index 410dd3b857f42..447c8588eb0e8 100644 --- a/chrome/browser/media/webrtc/media_stream_capture_indicator.cc +++ b/chrome/browser/media/webrtc/media_stream_capture_indicator.cc @@ -433,8 +433,10 @@ void MediaStreamCaptureIndicator::UpdateNotificationUserInterface() { return; } +#if 0 //NWJS fix issue #4852 // The icon will take the ownership of the passed context menu. MaybeCreateStatusTrayIcon(audio, video); +#endif if (status_icon_) { status_icon_->SetContextMenu(std::move(menu)); } diff --git a/chrome/browser/metrics/chrome_metrics_service_client.cc b/chrome/browser/metrics/chrome_metrics_service_client.cc index 54e79f7385c73..339e168d3d806 100644 --- a/chrome/browser/metrics/chrome_metrics_service_client.cc +++ b/chrome/browser/metrics/chrome_metrics_service_client.cc @@ -668,9 +668,11 @@ void ChromeMetricsServiceClient::RegisterMetricsServiceProviders() { std::unique_ptr( new metrics::SamplingMetricsProvider)); +#if 0 metrics_service_->RegisterMetricsProvider( std::unique_ptr( new translate::TranslateRankerMetricsProvider())); +#endif #if defined(OS_ANDROID) metrics_service_->RegisterMetricsProvider( @@ -748,10 +750,11 @@ void ChromeMetricsServiceClient::RegisterMetricsServiceProviders() { metrics_service_->RegisterMetricsProvider( std::unique_ptr( new HttpsEngagementMetricsProvider())); - +#if 0 metrics_service_->RegisterMetricsProvider( std::unique_ptr( new CertificateReportingMetricsProvider())); +#endif } void ChromeMetricsServiceClient::RegisterUKMProviders() { diff --git a/chrome/browser/metrics/chrome_metrics_services_manager_client.cc b/chrome/browser/metrics/chrome_metrics_services_manager_client.cc index d47bbeb0caaca..6a0c0b70544a8 100644 --- a/chrome/browser/metrics/chrome_metrics_services_manager_client.cc +++ b/chrome/browser/metrics/chrome_metrics_services_manager_client.cc @@ -249,9 +249,13 @@ bool ChromeMetricsServicesManagerClient::IsMetricsReportingEnabled() { } bool ChromeMetricsServicesManagerClient::OnlyDoMetricsRecording() { +#if 1 + return true; +#else const base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess(); return cmdline->HasSwitch(switches::kMetricsRecordingOnly) || cmdline->HasSwitch(switches::kEnableBenchmarking); +#endif } #if defined(OS_WIN) diff --git a/chrome/browser/net/predictor.cc b/chrome/browser/net/predictor.cc index 5d73b277c1d45..cb0f6f093fea4 100644 --- a/chrome/browser/net/predictor.cc +++ b/chrome/browser/net/predictor.cc @@ -304,10 +304,10 @@ std::vector Predictor::GetPredictedUrlListAtStartup( urls.push_back(gurl.GetWithEmptyPath()); } } - +#if 0 if (urls.empty()) urls.push_back(GURL("http://www.google.com:80")); - +#endif return urls; } diff --git a/chrome/browser/notifications/notification_platform_bridge_mac.mm b/chrome/browser/notifications/notification_platform_bridge_mac.mm index eb361da68b144..336a5c4fa27a6 100644 --- a/chrome/browser/notifications/notification_platform_bridge_mac.mm +++ b/chrome/browser/notifications/notification_platform_bridge_mac.mm @@ -248,8 +248,7 @@ @interface AlertDispatcherImpl : NSObject [builder setIcon:notification.icon().ToNSImage()]; } - [builder setShowSettingsButton:(notification_type != - NotificationCommon::EXTENSION)]; + [builder setShowSettingsButton:(false)]; std::vector buttons = notification.buttons(); if (!buttons.empty()) { DCHECK_LE(buttons.size(), blink::kWebNotificationMaxActions); diff --git a/chrome/browser/notifications/platform_notification_service_impl.cc b/chrome/browser/notifications/platform_notification_service_impl.cc index 0f0186f81fcb5..e48884088e2a0 100644 --- a/chrome/browser/notifications/platform_notification_service_impl.cc +++ b/chrome/browser/notifications/platform_notification_service_impl.cc @@ -98,11 +98,13 @@ void ReportNotificationImageOnIOThread( Profile* profile, const GURL& origin, const SkBitmap& image) { +#if 0 DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!safe_browsing_service || !safe_browsing_service->enabled()) return; safe_browsing_service->ping_manager()->ReportNotificationImage( profile, safe_browsing_service->database_manager(), origin, image); +#endif } } // namespace diff --git a/chrome/browser/notifications/web_notification_delegate.cc b/chrome/browser/notifications/web_notification_delegate.cc index 86671a5d04319..1498bc774cc3c 100644 --- a/chrome/browser/notifications/web_notification_delegate.cc +++ b/chrome/browser/notifications/web_notification_delegate.cc @@ -52,7 +52,7 @@ bool WebNotificationDelegate::SettingsClick() { } bool WebNotificationDelegate::ShouldDisplaySettingsButton() { - return true; + return false; } bool WebNotificationDelegate::ShouldDisplayOverFullscreen() const { diff --git a/chrome/browser/nwjs_resources.grd b/chrome/browser/nwjs_resources.grd new file mode 100644 index 0000000000000..e046182974af5 --- /dev/null +++ b/chrome/browser/nwjs_resources.grd @@ -0,0 +1,512 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/chrome/browser/password_manager/native_backend_gnome_x.cc b/chrome/browser/password_manager/native_backend_gnome_x.cc index 9418e710d479e..2724f7fa03816 100644 --- a/chrome/browser/password_manager/native_backend_gnome_x.cc +++ b/chrome/browser/password_manager/native_backend_gnome_x.cc @@ -40,7 +40,7 @@ const int kMaxPossibleTimeTValue = std::numeric_limits::max(); namespace { -const char kGnomeKeyringAppString[] = "chrome"; +const char kGnomeKeyringAppString[] = "nwjs"; // Convert the attributes of a given keyring entry into a new PasswordForm. // Note: does *not* get the actual password, as that is not a key attribute! diff --git a/chrome/browser/password_manager/native_backend_libsecret.cc b/chrome/browser/password_manager/native_backend_libsecret.cc index 1a6a99ab6e42f..dc91daf7e4d57 100644 --- a/chrome/browser/password_manager/native_backend_libsecret.cc +++ b/chrome/browser/password_manager/native_backend_libsecret.cc @@ -37,7 +37,7 @@ const int kMaxPossibleTimeTValue = std::numeric_limits::max(); namespace { -const char kLibsecretAppString[] = "chrome"; +const char kLibsecretAppString[] = "nwjs"; // Schema is analagous to the fields in PasswordForm. const SecretSchema kLibsecretSchema = { diff --git a/chrome/browser/permissions/permission_decision_auto_blocker.cc b/chrome/browser/permissions/permission_decision_auto_blocker.cc index 0ef86e7a265c3..193d78b3566e0 100644 --- a/chrome/browser/permissions/permission_decision_auto_blocker.cc +++ b/chrome/browser/permissions/permission_decision_auto_blocker.cc @@ -293,6 +293,7 @@ void PermissionDecisionAutoBlocker::CheckSafeBrowsingBlacklist( DCHECK_EQ(CONTENT_SETTING_ASK, GetEmbargoResult(request_origin, permission).content_setting); +#if 0 if (base::FeatureList::IsEnabled(features::kPermissionsBlacklist) && db_manager_) { // The CheckSafeBrowsingResult callback won't be called if the profile is @@ -306,7 +307,7 @@ void PermissionDecisionAutoBlocker::CheckSafeBrowsingBlacklist( callback)); return; } - +#endif callback.Run(false /* permission blocked */); } @@ -436,10 +437,12 @@ PermissionDecisionAutoBlocker::PermissionDecisionAutoBlocker(Profile* profile) db_manager_(nullptr), safe_browsing_timeout_(kCheckUrlTimeoutMs), clock_(new base::DefaultClock()) { +#if 0 safe_browsing::SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service(); if (sb_service) db_manager_ = sb_service->database_manager(); +#endif } PermissionDecisionAutoBlocker::~PermissionDecisionAutoBlocker() {} diff --git a/chrome/browser/permissions/permission_uma_util.cc b/chrome/browser/permissions/permission_uma_util.cc index 9ddfcf5a33931..2542b1b9bc054 100644 --- a/chrome/browser/permissions/permission_uma_util.cc +++ b/chrome/browser/permissions/permission_uma_util.cc @@ -636,6 +636,7 @@ void PermissionUmaUtil::RecordPermissionAction( PermissionRequestGestureType gesture_type, const GURL& requesting_origin, Profile* profile) { +#if 0 if (IsOptedIntoPermissionActionReporting(profile)) { PermissionDecisionAutoBlocker* autoblocker = PermissionDecisionAutoBlocker::GetForProfile(profile); @@ -649,7 +650,7 @@ void PermissionUmaUtil::RecordPermissionAction( g_browser_process->safe_browsing_service() ->ui_manager()->ReportPermissionAction(report_info); } - +#endif bool secure_origin = content::IsOriginSecure(requesting_origin); switch (permission) { diff --git a/chrome/browser/plugins/chrome_plugin_service_filter.cc b/chrome/browser/plugins/chrome_plugin_service_filter.cc index 1783a101aa024..d5e105620e145 100644 --- a/chrome/browser/plugins/chrome_plugin_service_filter.cc +++ b/chrome/browser/plugins/chrome_plugin_service_filter.cc @@ -212,7 +212,7 @@ bool ChromePluginServiceFilter::IsPluginAvailable( // If PreferHtmlOverPlugins is enabled and the plugin is Flash, we do // additional checks. - if (plugin->name == base::ASCIIToUTF16(content::kFlashPluginName) && + if (plugin->name == base::ASCIIToUTF16(content::kFlashPluginName) && false && PluginUtils::ShouldPreferHtmlOverPlugins( context_info->host_content_settings_map.get())) { // Check the content setting first, and always respect the ALLOW or BLOCK diff --git a/chrome/browser/plugins/plugin_info_message_filter.cc b/chrome/browser/plugins/plugin_info_message_filter.cc index 8c31c98cf4390..bbc211427a50e 100644 --- a/chrome/browser/plugins/plugin_info_message_filter.cc +++ b/chrome/browser/plugins/plugin_info_message_filter.cc @@ -4,6 +4,9 @@ #include "chrome/browser/plugins/plugin_info_message_filter.h" +#include "base/path_service.h" +#include "chrome/common/chrome_paths.h" + #include #include @@ -121,6 +124,13 @@ bool IsPluginLoadingAccessibleResourceInWebView( extensions::ExtensionRegistry* extension_registry, int process_id, const GURL& resource) { + const std::string extension_id = resource.host(); + const extensions::Extension* extension = extension_registry->GetExtensionById( + extension_id, extensions::ExtensionRegistry::ENABLED); + if (extension && extension->is_nwjs_app()) //NWJS#5548: enable flash + //by default + return true; + extensions::WebViewRendererState* renderer_state = extensions::WebViewRendererState::GetInstance(); std::string partition_id; @@ -129,9 +139,6 @@ bool IsPluginLoadingAccessibleResourceInWebView( return false; } - const std::string extension_id = resource.host(); - const extensions::Extension* extension = extension_registry->GetExtensionById( - extension_id, extensions::ExtensionRegistry::ENABLED); if (!extension || !extensions::WebviewInfo::IsResourceWebviewAccessible( extension, partition_id, resource.path())) { return false; @@ -253,7 +260,7 @@ void PluginInfoMessageFilter::PluginsLoaded( plugin_metadata->GetSecurityStatus(output->plugin), plugin_metadata->identifier(), &output->status); } - +#if 0 if (output->status == ChromeViewHostMsg_GetPluginInfo_Status::kNotFound) { // Check to see if the component updater can fetch an implementation. base::PostTaskAndReplyWithResult( @@ -266,9 +273,9 @@ void PluginInfoMessageFilter::PluginsLoaded( params, base::Passed(&output), base::Passed(&plugin_metadata), reply_msg)); } else { +#endif GetPluginInfoReply(params, std::move(output), std::move(plugin_metadata), reply_msg); - } } #if BUILDFLAG(ENABLE_PEPPER_CDMS) @@ -321,6 +328,12 @@ void PluginInfoMessageFilter::Context::DecidePluginStatus( return; } + base::FilePath internal_dir; + if (PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &internal_dir) && internal_dir.IsParent(plugin.path)) { + *status = ChromeViewHostMsg_GetPluginInfo_Status::kAllowed; + return; + } + ContentSetting plugin_setting = CONTENT_SETTING_DEFAULT; bool uses_default_content_setting = true; bool is_managed = false; diff --git a/chrome/browser/plugins/plugin_observer.cc b/chrome/browser/plugins/plugin_observer.cc index 24e82e2e42d05..5ff1bf8e064e5 100644 --- a/chrome/browser/plugins/plugin_observer.cc +++ b/chrome/browser/plugins/plugin_observer.cc @@ -159,11 +159,11 @@ class PluginObserver::ComponentObserver : observer_(observer), routing_id_(routing_id), component_id_(component_id) { - g_browser_process->component_updater()->AddObserver(this); + //g_browser_process->component_updater()->AddObserver(this); } ~ComponentObserver() override { - g_browser_process->component_updater()->RemoveObserver(this); + //g_browser_process->component_updater()->RemoveObserver(this); } void OnEvent(Events event, const std::string& id) override { @@ -296,10 +296,12 @@ void PluginObserver::OnBlockedOutdatedPlugin(int placeholder_id, void PluginObserver::OnBlockedComponentUpdatedPlugin( int placeholder_id, const std::string& identifier) { +#if 0 component_observers_[placeholder_id] = base::MakeUnique(this, placeholder_id, identifier); g_browser_process->component_updater()->GetOnDemandUpdater().OnDemandUpdate( identifier, component_updater::Callback()); +#endif } void PluginObserver::RemoveComponentObserver(int placeholder_id) { diff --git a/chrome/browser/policy/policy_browsertest.cc b/chrome/browser/policy/policy_browsertest.cc index b7eae5b09e3c2..9688e5b30f0ac 100644 --- a/chrome/browser/policy/policy_browsertest.cc +++ b/chrome/browser/policy/policy_browsertest.cc @@ -3779,6 +3779,7 @@ IN_PROC_BROWSER_TEST_F(WebRtcUdpPortRangeDisabledPolicyTest, } #endif // BUILDFLAG(ENABLE_WEBRTC) +#if 0 // Tests the ComponentUpdater's EnabledComponentUpdates group policy by // calling the OnDemand interface. It uses the network interceptor to inspect // the presence of the updatedisabled="true" attribute in the update check @@ -4056,6 +4057,8 @@ IN_PROC_BROWSER_TEST_F(ComponentUpdaterPolicyTest, EnabledComponentUpdates) { base::RunLoop().Run(); } +#endif + #if !defined(OS_CHROMEOS) // Similar to PolicyTest but sets the proper policy before the browser is // started. diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index 09ecf6da17503..755e45ed9108e 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc @@ -483,7 +483,7 @@ void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) { HostContentSettingsMap::RegisterProfilePrefs(registry); ImportantSitesUtil::RegisterProfilePrefs(registry); IncognitoModePrefs::RegisterProfilePrefs(registry); - InstantUI::RegisterProfilePrefs(registry); + //InstantUI::RegisterProfilePrefs(registry); NavigationCorrectionTabObserver::RegisterProfilePrefs(registry); MediaCaptureDevicesDispatcher::RegisterProfilePrefs(registry); MediaDeviceIDSalt::RegisterProfilePrefs(registry); @@ -646,7 +646,7 @@ void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) { RegisterChromeLauncherUserPrefs(registry); #endif -#if !defined(OS_ANDROID) && !defined(OS_IOS) +#if 0 MdHistoryUI::RegisterProfilePrefs(registry); settings::MdSettingsUI::RegisterProfilePrefs(registry); #endif diff --git a/chrome/browser/process_singleton_posix.cc b/chrome/browser/process_singleton_posix.cc index c684f51ce101f..87ddf9956c741 100644 --- a/chrome/browser/process_singleton_posix.cc +++ b/chrome/browser/process_singleton_posix.cc @@ -105,12 +105,43 @@ using content::BrowserThread; namespace { +// XXX: +class SanitizedSocketPath { + public: + explicit SanitizedSocketPath(const base::FilePath& socket_path) + : socket_path_(socket_path) { + if (socket_path.value().length() >= arraysize(sockaddr_un::sun_path)) { + bool found_current_dir = GetCurrentDirectory(&old_path_); + CHECK(found_current_dir) << "Failed to determine the current directory."; + changed_directory_ = SetCurrentDirectory(socket_path.DirName()); + CHECK(changed_directory_) << "Failed to change directory: " << + socket_path.DirName().value(); + } + } + + ~SanitizedSocketPath() { + if (changed_directory_) + SetCurrentDirectory(old_path_); + } + + base::FilePath SocketPath() const { + return changed_directory_ ? socket_path_.BaseName() : socket_path_; + } + + private: + bool changed_directory_ = false; + base::FilePath socket_path_; + base::FilePath old_path_; + + DISALLOW_COPY_AND_ASSIGN(SanitizedSocketPath); +}; + // Timeout for the current browser process to respond. 20 seconds should be // enough. -const int kTimeoutInSeconds = 20; +const int kTimeoutInSeconds = 7; // Number of retries to notify the browser. 20 retries over 20 seconds = 1 try // per second. -const int kRetryAttempts = 20; +const int kRetryAttempts = 7; const char kStartToken[] = "START"; const char kACKToken[] = "ACK"; const char kShutdownToken[] = "SHUTDOWN"; @@ -389,18 +420,17 @@ bool ConnectSocket(ScopedSocket* socket, return false; // Now we know the directory was (at that point) created by the profile // owner. Try to connect. - sockaddr_un addr; - if (!SetupSockAddr(socket_target.value(), &addr)) { - // If a sockaddr couldn't be initialized due to too long of a socket - // path, we can be sure there isn't already a Chrome running with this - // socket path, since it would have hit the CHECK() on the path length. - return false; + { + SanitizedSocketPath sanitized_socket_target(socket_target); + sockaddr_un addr; + if (!SetupSockAddr(sanitized_socket_target.SocketPath().value(), &addr)) + return false; + int ret = HANDLE_EINTR(connect(socket->fd(), + reinterpret_cast(&addr), + sizeof(addr))); + if (ret != 0) + return false; } - int ret = HANDLE_EINTR(connect(socket->fd(), - reinterpret_cast(&addr), - sizeof(addr))); - if (ret != 0) - return false; // Check the cookie again. We only link in /tmp, which is sticky, so, if the // directory is still correct, it must have been correct in-between when we // connected. POSIX, sadly, lacks a connectat(). @@ -413,13 +443,10 @@ bool ConnectSocket(ScopedSocket* socket, } else if (errno == EINVAL) { // It exists, but is not a symlink (or some other error we detect // later). Just connect to it directly; this is an older version of Chrome. + SanitizedSocketPath sanitized_socket_path(socket_path); sockaddr_un addr; - if (!SetupSockAddr(socket_path.value(), &addr)) { - // If a sockaddr couldn't be initialized due to too long of a socket - // path, we can be sure there isn't already a Chrome running with this - // socket path, since it would have hit the CHECK() on the path length. + if (!SetupSockAddr(sanitized_socket_path.SocketPath().value(), &addr)) return false; - } int ret = HANDLE_EINTR(connect(socket->fd(), reinterpret_cast(&addr), sizeof(addr))); @@ -1025,7 +1052,7 @@ bool ProcessSingleton::Create() { // leaving a dangling symlink. base::FilePath socket_target_path = socket_dir_.GetPath().Append(chrome::kSingletonSocketFilename); - SetupSocket(socket_target_path.value(), &sock, &addr); + //SetupSocket(socket_target_path.value(), &sock, &addr); // Setup the socket symlink and the two cookies. base::FilePath cookie(GenerateCookie()); @@ -1044,10 +1071,15 @@ bool ProcessSingleton::Create() { return false; } - if (bind(sock, reinterpret_cast(&addr), sizeof(addr)) < 0) { - PLOG(ERROR) << "Failed to bind() " << socket_target_path.value(); - CloseSocket(sock); - return false; + { + SanitizedSocketPath sanitized_socket_target(socket_target_path); + SetupSocket(sanitized_socket_target.SocketPath().value(), &sock, &addr); + + if (bind(sock, reinterpret_cast(&addr), sizeof(addr)) < 0) { + PLOG(ERROR) << "Failed to bind() " << socket_target_path.value(); + CloseSocket(sock); + return false; + } } if (listen(sock, 5) < 0) diff --git a/chrome/browser/process_singleton_win.cc b/chrome/browser/process_singleton_win.cc index 10042578ef5d1..8d0d0ab19f9aa 100644 --- a/chrome/browser/process_singleton_win.cc +++ b/chrome/browser/process_singleton_win.cc @@ -415,6 +415,7 @@ bool ProcessSingleton::Create() { base::Bind(&ProcessLaunchNotification, notification_callback_), user_data_dir_.value()); CHECK(result && window_.hwnd()); + ::ChangeWindowMessageFilter(WM_COPYDATA, MSGFLT_ADD); } } } diff --git a/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc b/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc index bf641e67262e7..cd436fce2f373 100644 --- a/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc +++ b/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc @@ -202,7 +202,9 @@ EnsureBrowserContextKeyedServiceFactoriesBuilt() { #if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION) CaptivePortalServiceFactory::GetInstance(); #endif +#if 0 CertificateReportingServiceFactory::GetInstance(); +#endif #if defined(OS_ANDROID) chrome::android::DataUseUITabModelFactory::GetInstance(); #endif diff --git a/chrome/browser/profiles/net_http_session_params_observer.cc b/chrome/browser/profiles/net_http_session_params_observer.cc index cc14716d28abf..70e02f37c8ee8 100644 --- a/chrome/browser/profiles/net_http_session_params_observer.cc +++ b/chrome/browser/profiles/net_http_session_params_observer.cc @@ -33,7 +33,7 @@ void DisableQuicOnIOThread( // Disable QUIC for globally-owned objects. io_thread->DisableQuic(); - safe_browsing_service->DisableQuicOnIOThread(); + //safe_browsing_service->DisableQuicOnIOThread(); // Call profile's disable QUIC callback. disable_quic_callback.Run(); diff --git a/chrome/browser/profiles/profile_impl.cc b/chrome/browser/profiles/profile_impl.cc index 70be446b0de29..43501c0985611 100644 --- a/chrome/browser/profiles/profile_impl.cc +++ b/chrome/browser/profiles/profile_impl.cc @@ -507,9 +507,10 @@ ProfileImpl::ProfileImpl( path_, sequenced_task_runner, create_mode == CREATE_MODE_SYNCHRONOUS); #endif + prefs::mojom::TrackedPreferenceValidationDelegatePtr pref_validation_delegate; +#if 0 scoped_refptr safe_browsing_service( g_browser_process->safe_browsing_service()); - prefs::mojom::TrackedPreferenceValidationDelegatePtr pref_validation_delegate; if (safe_browsing_service.get()) { auto pref_validation_delegate_impl = safe_browsing_service->CreatePreferenceValidationDelegate(this); @@ -518,6 +519,7 @@ ProfileImpl::ProfileImpl( mojo::MakeRequest(&pref_validation_delegate)); } } +#endif content::BrowserContext::Initialize(this, path_); diff --git a/chrome/browser/profiles/profile_impl_io_data.cc b/chrome/browser/profiles/profile_impl_io_data.cc index b72ea5c714534..bdb292a7eda84 100644 --- a/chrome/browser/profiles/profile_impl_io_data.cc +++ b/chrome/browser/profiles/profile_impl_io_data.cc @@ -5,6 +5,10 @@ #include "chrome/browser/profiles/profile_impl_io_data.h" #include + +#include "content/nw/src/nw_base.h" +#include "extensions/common/manifest_constants.h" + #include #include #include @@ -514,6 +518,11 @@ void ProfileImplIOData::InitializeInternal( cookie_config.crypto_delegate = cookie_config::GetCookieCryptoDelegate(); cookie_config.channel_id_service = main_context->channel_id_service(); cookie_config.background_task_runner = cookie_background_task_runner; + const base::CommandLine& command_line = + *base::CommandLine::ForCurrentProcess(); + if (command_line.HasSwitch("disable-cookie-encryption")) { + cookie_config::SetEnableCookieCrypto(false); + } main_context_storage->set_cookie_store( content::CreateCookieStore(cookie_config)); @@ -575,6 +584,10 @@ void ProfileImplIOData:: // store. net::URLRequestContext* extensions_context = extensions_request_context(); + std::string domain; + if (nw::package()->root()->GetString(extensions::manifest_keys::kNWJSDomain, &domain)) { + extensions_context->set_cookie_store(main_request_context()->cookie_store()); + } else { content::CookieStoreConfig cookie_config( lazy_params_->extensions_cookie_path, lazy_params_->session_cookie_mode, @@ -585,6 +598,7 @@ void ProfileImplIOData:: cookie_config.channel_id_service = extensions_context->channel_id_service(); extensions_cookie_store_ = content::CreateCookieStore(cookie_config); extensions_context->set_cookie_store(extensions_cookie_store_.get()); + } } net::URLRequestContext* ProfileImplIOData::InitializeAppRequestContext( diff --git a/chrome/browser/profiles/profile_info_cache.cc b/chrome/browser/profiles/profile_info_cache.cc index c816c9bbc1ea3..498cd36cde700 100644 --- a/chrome/browser/profiles/profile_info_cache.cc +++ b/chrome/browser/profiles/profile_info_cache.cc @@ -138,7 +138,7 @@ void DeleteBitmap(const base::FilePath& image_path) { ProfileInfoCache::ProfileInfoCache(PrefService* prefs, const base::FilePath& user_data_dir) : ProfileAttributesStorage(prefs, user_data_dir), - disable_avatar_download_for_testing_(false) { + disable_avatar_download_for_testing_(true) { // Populate the cache DictionaryPrefUpdate update(prefs_, prefs::kProfileInfoCache); base::DictionaryValue* cache = update.Get(); @@ -883,7 +883,7 @@ void ProfileInfoCache::DownloadHighResAvatarIfNeeded( size_t icon_index, const base::FilePath& profile_path) { // Downloading is only supported on desktop. -#if defined(OS_ANDROID) || defined(OS_CHROMEOS) +#if 1 return; #endif DCHECK(!disable_avatar_download_for_testing_); diff --git a/chrome/browser/renderer_context_menu/context_menu_content_type_platform_app.cc b/chrome/browser/renderer_context_menu/context_menu_content_type_platform_app.cc index 3df598de7e9f4..5c8b7353eb885 100644 --- a/chrome/browser/renderer_context_menu/context_menu_content_type_platform_app.cc +++ b/chrome/browser/renderer_context_menu/context_menu_content_type_platform_app.cc @@ -11,6 +11,8 @@ #include "extensions/common/extension.h" #include "extensions/common/manifest.h" +#include "content/nw/src/common/shell_switches.h" + using extensions::Extension; using extensions::ProcessManager; @@ -39,6 +41,14 @@ bool ContextMenuContentTypePlatformApp::SupportsGroup(int group) { DCHECK(platform_app->is_platform_app()); +#if defined(NWJS_SDK) + bool enable_devtools = true; + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(switches::kDisableDevTools)) + enable_devtools = false; +#endif + switch (group) { // Add undo/redo, cut/copy/paste etc for text fields. case ITEM_GROUP_EDITABLE: @@ -46,12 +56,10 @@ bool ContextMenuContentTypePlatformApp::SupportsGroup(int group) { return ContextMenuContentType::SupportsGroup(group); case ITEM_GROUP_CURRENT_EXTENSION: return true; +#if defined(NWJS_SDK) case ITEM_GROUP_DEVTOOLS_UNPACKED_EXT: - // Add dev tools for unpacked extensions. - return extensions::Manifest::IsUnpackedLocation( - platform_app->location()) || - base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kDebugPackedApps); + return enable_devtools; +#endif default: return false; } diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu.cc b/chrome/browser/renderer_context_menu/render_view_context_menu.cc index 2d32b98f7bfc9..f7b942191ac7a 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu.cc @@ -6,6 +6,8 @@ #include +#include "content/nw/src/common/shell_switches.h" + #include #include #include @@ -812,15 +814,25 @@ void RenderViewContextMenu::InitMenu() { AppendCurrentExtensionItems(); } +#if defined(NWJS_SDK) + bool enable_devtools = true; + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(switches::kDisableDevTools)) + enable_devtools = false; + if (content_type_->SupportsGroup( ContextMenuContentType::ITEM_GROUP_DEVELOPER)) { + if (enable_devtools) AppendDeveloperItems(); } if (content_type_->SupportsGroup( ContextMenuContentType::ITEM_GROUP_DEVTOOLS_UNPACKED_EXT)) { + if (enable_devtools) AppendDevtoolsForUnpackedExtensions(); } +#endif if (content_type_->SupportsGroup( ContextMenuContentType::ITEM_GROUP_PRINT_PREVIEW)) { @@ -1202,6 +1214,7 @@ void RenderViewContextMenu::AppendPageItems() { menu_model_.AddItemWithStringId(IDC_PRINT, IDS_CONTENT_CONTEXT_PRINT); AppendMediaRouterItem(); +#if 0 if (TranslateService::IsTranslatableURL(params_.page_url)) { std::unique_ptr prefs( ChromeTranslateClient::CreateTranslatePrefs( @@ -1217,6 +1230,7 @@ void RenderViewContextMenu::AppendPageItems() { l10n_util::GetStringFUTF16(IDS_CONTENT_CONTEXT_TRANSLATE, language)); AddGoogleIconToLastMenuItem(&menu_model_); } +#endif } void RenderViewContextMenu::AppendExitFullscreenItem() { @@ -1325,7 +1339,11 @@ void RenderViewContextMenu::AppendSearchProvider() { } void RenderViewContextMenu::AppendEditableItems() { - const bool use_spelling = !chrome::IsRunningInForcedAppMode(); + bool use_spelling = !chrome::IsRunningInForcedAppMode(); + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + if (!command_line->HasSwitch(switches::kEnableSpellChecking)) + use_spelling = false; if (use_spelling) AppendSpellingSuggestionItems(); @@ -1371,6 +1389,7 @@ void RenderViewContextMenu::AppendEditableItems() { } void RenderViewContextMenu::AppendLanguageSettings() { +#if 0 const bool use_spelling = !chrome::IsRunningInForcedAppMode(); if (!use_spelling) return; @@ -1388,6 +1407,7 @@ void RenderViewContextMenu::AppendLanguageSettings() { spelling_options_submenu_observer_->InitMenu(params_); observers_.AddObserver(spelling_options_submenu_observer_.get()); #endif +#endif } void RenderViewContextMenu::AppendSpellingSuggestionItems() { @@ -1967,6 +1987,9 @@ bool RenderViewContextMenu::IsDevCommandEnabled(int id) const { } bool RenderViewContextMenu::IsTranslateEnabled() const { +#if 1 + return false; +#else ChromeTranslateClient* chrome_translate_client = ChromeTranslateClient::FromWebContents(embedder_web_contents_); // If no |chrome_translate_client| attached with this WebContents or we're @@ -1997,6 +2020,7 @@ bool RenderViewContextMenu::IsTranslateEnabled() const { !target_lang.empty() && // Disable on the Instant Extended NTP. !search::IsInstantNTP(embedder_web_contents_); +#endif } bool RenderViewContextMenu::IsSaveLinkAsEnabled() const { @@ -2398,6 +2422,7 @@ void RenderViewContextMenu::ExecRouteMedia() { } void RenderViewContextMenu::ExecTranslate() { +#if 0 // A translation might have been triggered by the time the menu got // selected, do nothing in that case. ChromeTranslateClient* chrome_translate_client = @@ -2425,6 +2450,7 @@ void RenderViewContextMenu::ExecTranslate() { chrome_translate_client->GetTranslateManager(); DCHECK(manager); manager->TranslatePage(original_lang, target_lang, true); +#endif } void RenderViewContextMenu::ExecLanguageSettings(int event_flags) { diff --git a/chrome/browser/renderer_preferences_util.cc b/chrome/browser/renderer_preferences_util.cc index 7296a04a56cc1..dccc475e99a72 100644 --- a/chrome/browser/renderer_preferences_util.cc +++ b/chrome/browser/renderer_preferences_util.cc @@ -38,6 +38,8 @@ #include "ui/views/linux_ui/linux_ui.h" #endif +#include "content/nw/src/common/nw_content_common_hooks.h" + #if BUILDFLAG(ENABLE_WEBRTC) namespace { @@ -171,6 +173,9 @@ void UpdateFromSystemSettings(content::RendererPreferences* prefs, prefs->plugin_fullscreen_allowed = pref_service->GetBoolean(prefs::kFullscreenAllowed); #endif + std::string user_agent; + if (nw::GetUserAgentFromManifest(&user_agent)) + prefs->user_agent_override = user_agent; } } // namespace renderer_preferences_util diff --git a/chrome/browser/resources/component_extension_resources.grd b/chrome/browser/resources/component_extension_resources.grd index aa82ed234494d..c6ba8b1472709 100644 --- a/chrome/browser/resources/component_extension_resources.grd +++ b/chrome/browser/resources/component_extension_resources.grd @@ -25,6 +25,7 @@ + @@ -32,6 +33,7 @@ + @@ -141,6 +143,9 @@ + + + @@ -180,6 +185,8 @@ + + @@ -225,6 +232,7 @@ + diff --git a/chrome/browser/resources/empty.css b/chrome/browser/resources/empty.css new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/chrome/browser/resources/empty.html b/chrome/browser/resources/empty.html new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/chrome/browser/resources/empty.js b/chrome/browser/resources/empty.js new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/chrome/browser/resources/empty.json b/chrome/browser/resources/empty.json new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/chrome/browser/resources/empty.png b/chrome/browser/resources/empty.png new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/chrome/browser/resources/nwjs/default.js b/chrome/browser/resources/nwjs/default.js new file mode 100644 index 0000000000000..a5e1ce27fb418 --- /dev/null +++ b/chrome/browser/resources/nwjs/default.js @@ -0,0 +1,46 @@ +//console.log("NWJS/DEFAULT.JS"); +var manifest = chrome.runtime.getManifest(); +var options = {}; +var title = null; +if (manifest.window) { + if (manifest.window.id) + options.id = manifest.window.id; + options.innerBounds = {}; + if (manifest.window.frame === false) + options.frame = 'none'; + if (manifest.window.resizable === false) + options.resizable = false; + if (manifest.window.height) + options.innerBounds.height = manifest.window.height; + if (manifest.window.width) + options.innerBounds.width = manifest.window.width; + if (manifest.window.min_width) + options.innerBounds.minWidth = manifest.window.min_width; + if (manifest.window.max_width) + options.innerBounds.maxWidth = manifest.window.max_width; + if (manifest.window.min_height) + options.innerBounds.minHeight = manifest.window.min_height; + if (manifest.window.max_height) + options.innerBounds.maxHeight = manifest.window.max_height; + if (manifest.window.fullscreen === true) + options.state = 'fullscreen'; + if (manifest.window.show === false) + options.hidden = true; + if (manifest.window.show_in_taskbar === false) + options.show_in_taskbar = false; + if (manifest.window['always_on_top'] === true) + options.alwaysOnTop = true; + if (manifest.window['visible_on_all_workspaces'] === true) + options.visibleOnAllWorkspaces = true; + if (manifest.window.transparent) + options.alphaEnabled = true; + if (manifest.window.kiosk === true) + options.kiosk = true; + if (manifest.window.position) + options.position = manifest.window.position; + if (manifest.window.title) + options.title = manifest.window.title; +} + +chrome.app.window.create(manifest.main, options, function(win) { +}); diff --git a/chrome/browser/resources/nwjs_default_app/main.js b/chrome/browser/resources/nwjs_default_app/main.js new file mode 100644 index 0000000000000..4ee5538332f0b --- /dev/null +++ b/chrome/browser/resources/nwjs_default_app/main.js @@ -0,0 +1,7 @@ +var manifest = chrome.runtime.getManifest(); +var url = manifest.cmdlineUrl || 'nw_blank.html'; +chrome.app.runtime.onLaunched.addListener(function() { + chrome.app.window.create( + url, + {'id': 'nwjs_default_app', 'height': 550, 'width': 750}); +}); diff --git a/chrome/browser/resources/nwjs_default_app/manifest.json b/chrome/browser/resources/nwjs_default_app/manifest.json new file mode 100644 index 0000000000000..1e9c9e219ebcd --- /dev/null +++ b/chrome/browser/resources/nwjs_default_app/manifest.json @@ -0,0 +1,17 @@ +{ + //id: aafddpmiffkameplnjkglahmbnbgidce + "key":"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCgmO8NbDyu8AB/Cudz33l3kkgPbIeYaitcYgn4RBJdNRPjJ2sRy0icbVMyZjXhNV81vuH60ZO5PiBmVIp6v49Aq2RSkFVbwPw0y1Yo6UgATlaaEKEJV2VGrlQJaN12bGM/Dz8KGuHVGTbtqHS+B0QyQJMAbXLJ8HkmvJPlUQZf3QIDAQAB", + "name": "NWJS Default", + "version": "0.1", + "manifest_version": 2, + "description": "NWJS default app", + "app": { + "background": { + "scripts": [ "main.js" ] + } + }, + "permissions": [ + "node", "proxy", "" + ], + "display_in_launcher": false +} diff --git a/chrome/browser/resources/nwjs_default_app/nw_blank.html b/chrome/browser/resources/nwjs_default_app/nw_blank.html new file mode 100644 index 0000000000000..cda95d6c72fe9 --- /dev/null +++ b/chrome/browser/resources/nwjs_default_app/nw_blank.html @@ -0,0 +1,74 @@ + + + +nw.js + + + +
+

NW.js

+
+
+ nw.js v
+ Node v
+ Chromium
+ commit hash:
+
+ + diff --git a/chrome/browser/resources/pdf/pdf.js b/chrome/browser/resources/pdf/pdf.js index 898935ef283d4..ed5c33995369d 100644 --- a/chrome/browser/resources/pdf/pdf.js +++ b/chrome/browser/resources/pdf/pdf.js @@ -638,7 +638,7 @@ PDFViewer.prototype = { message.data.url, Navigator.WindowOpenDisposition.NEW_BACKGROUND_TAB); } else { - this.navigator_.navigate(message.data.url, message.data.disposition); + this.navigator_.navigate(message.data.url, Navigator.WindowOpenDisposition.NEW_BACKGROUND_TAB); } break; case 'setScrollPosition': diff --git a/chrome/browser/resources/print_preview/data/destination_store.js b/chrome/browser/resources/print_preview/data/destination_store.js index 116b1c64ee0f5..2d23e0bb90f49 100644 --- a/chrome/browser/resources/print_preview/data/destination_store.js +++ b/chrome/browser/resources/print_preview/data/destination_store.js @@ -591,8 +591,10 @@ cr.define('print_preview', function() { init: function( isInAppKioskMode, systemDefaultDestinationId, - serializedDefaultDestinationSelectionRulesStr) { + serializedDefaultDestinationSelectionRulesStr, + isInNWPrintMode) { this.pdfPrinterEnabled_ = !isInAppKioskMode; + this.isInNWPrintMode_ = isInNWPrintMode; this.systemDefaultDestinationId_ = systemDefaultDestinationId; this.createLocalPdfPrintDestination_(); @@ -619,7 +621,7 @@ cr.define('print_preview', function() { var extensionId = ''; var extensionName = ''; var foundDestination = false; - if (this.appState_.recentDestinations) { + if (this.appState_.recentDestinations && !this.isInNWPrintMode_) { // Run through the destinations forward. As soon as we find a // destination, don't select any future destinations, just mark // them recent. Otherwise, there is a race condition between selecting @@ -875,7 +877,7 @@ cr.define('print_preview', function() { * @private */ convertPreselectedToDestinationMatch_: function() { - if (this.appState_.isSelectedDestinationValid()) { + if (this.appState_.isSelectedDestinationValid() && !this.isInNWPrintMode_) { return this.createExactDestinationMatch_( this.appState_.selectedDestination.origin, this.appState_.selectedDestination.id); diff --git a/chrome/browser/resources/print_preview/native_layer.js b/chrome/browser/resources/print_preview/native_layer.js index d3a12f024adc6..7d8f337a24f73 100644 --- a/chrome/browser/resources/print_preview/native_layer.js +++ b/chrome/browser/resources/print_preview/native_layer.js @@ -213,7 +213,8 @@ cr.define('print_preview', function() { initialSettings['shouldPrintSelectionOnly'] || false, initialSettings['printerName'] || null, initialSettings['appState'] || null, - initialSettings['defaultDestinationSelectionRules'] || null); + initialSettings['defaultDestinationSelectionRules'] || null, + initialSettings['nwPrintMode'] || false); }); }, @@ -971,8 +972,10 @@ cr.define('print_preview', function() { selectionOnly, systemDefaultDestinationId, serializedAppStateStr, - serializedDefaultDestinationSelectionRulesStr) { + serializedDefaultDestinationSelectionRulesStr, + nwPrintMode) { + this.isNWPrintMode_ = nwPrintMode; /** * Whether the print preview should be in auto-print mode. * @private {boolean} @@ -1048,6 +1051,9 @@ cr.define('print_preview', function() { } NativeInitialSettings.prototype = { + get isInNWPrintMode() { + return this.isNWPrintMode_; + }, /** * @return {boolean} Whether the print preview should be in auto-print mode. */ diff --git a/chrome/browser/resources/print_preview/print_preview.js b/chrome/browser/resources/print_preview/print_preview.js index 149d93a3288db..d3c32bb6122a2 100644 --- a/chrome/browser/resources/print_preview/print_preview.js +++ b/chrome/browser/resources/print_preview/print_preview.js @@ -669,7 +669,8 @@ cr.define('print_preview', function() { this.destinationStore_.init( settings.isInAppKioskMode, settings.systemDefaultDestinationId, - settings.serializedDefaultDestinationSelectionRulesStr); + settings.serializedDefaultDestinationSelectionRulesStr, + settings.isInNWPrintMode); this.appState_.setInitialized(); $('document-title').innerText = settings.documentTitle; diff --git a/chrome/browser/sessions/session_service.cc b/chrome/browser/sessions/session_service.cc index 2cc27dc661123..cb3bc9de2cf62 100644 --- a/chrome/browser/sessions/session_service.cc +++ b/chrome/browser/sessions/session_service.cc @@ -4,6 +4,11 @@ #include "chrome/browser/sessions/session_service.h" +#include "content/nw/src/nw_content.h" +#include "extensions/browser/extension_system.h" +#include "extensions/browser/app_window/app_window_registry.h" +#include "chrome/browser/extensions/extension_service.h" + #include #include @@ -977,6 +982,24 @@ void SessionService::MaybeDeleteSessionOnlyData() { if (browser->profile() == profile()) return; } + std::string id = nw::GetMainExtensionId(); + base::FilePath path; + extensions::ExtensionSystem* extension_system = + extensions::ExtensionSystem::Get(ProfileManager::GetPrimaryUserProfile()); + if (!id.empty() && extension_system) { + ExtensionService* extension_service = + extension_system->extension_service(); + const extensions::Extension* extension = + extension_service->GetExtensionById(id, true); + if (extension) { + if (extensions::ProcessManager::Get(profile())->GetLazyKeepaliveCount(extension) > 0) + return; + } + //additional checking for NWJS#5355 + extensions::AppWindowRegistry* registry = extensions::AppWindowRegistry::Factory::GetForBrowserContext(profile(), false); + if (registry && !registry->app_windows().empty()) + return; + } DeleteSessionOnlyData(profile()); } diff --git a/chrome/browser/shell_integration_linux.cc b/chrome/browser/shell_integration_linux.cc index f34c9ffb10a12..9895411841393 100644 --- a/chrome/browser/shell_integration_linux.cc +++ b/chrome/browser/shell_integration_linux.cc @@ -51,6 +51,8 @@ #include "chrome/grit/chrome_unscaled_resources.h" #include "components/version_info/version_info.h" #include "content/public/browser/browser_thread.h" +#include "content/nw/src/nw_base.h" +#include "content/nw/src/nw_package.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/image/image_family.h" #include "url/gurl.h" @@ -214,6 +216,7 @@ DefaultWebClientState GetIsDefaultWebClient(const std::string& protocol) { // the .desktop extension. We cannot simply use argv[0] in this case, because // on the stable channel, the executable name is google-chrome-stable, but the // desktop file is google-chrome.desktop. +#if 0 std::string GetDesktopBaseName(const std::string& desktop_file_name) { static const char kDesktopExtension[] = ".desktop"; if (base::EndsWith(desktop_file_name, kDesktopExtension, @@ -223,6 +226,7 @@ std::string GetDesktopBaseName(const std::string& desktop_file_name) { } return desktop_file_name; } +#endif } // namespace @@ -596,6 +600,10 @@ namespace internal { std::string GetProgramClassName(const base::CommandLine& command_line, const std::string& desktop_file_name) { + // NW fix + // set WM_NAME to name of package.json + return nw::package()->GetName(); +#if 0 std::string class_name = shell_integration::GetDesktopBaseName(desktop_file_name); std::string user_data_dir = @@ -607,12 +615,18 @@ std::string GetProgramClassName(const base::CommandLine& command_line, return user_data_dir.empty() ? class_name : class_name + " (" + user_data_dir + ")"; +#endif } std::string GetProgramClassClass(const base::CommandLine& command_line, const std::string& desktop_file_name) { if (command_line.HasSwitch(switches::kWmClass)) return command_line.GetSwitchValueASCII(switches::kWmClass); + // NW fix + // set WM_CLASS as name in package.json and allowed to be overwritten + // with --class CLI parameter + return nw::package()->GetName(); +#if 0 std::string class_class = shell_integration::GetDesktopBaseName(desktop_file_name); if (!class_class.empty()) { @@ -620,6 +634,7 @@ std::string GetProgramClassClass(const base::CommandLine& command_line, class_class[0] = base::ToUpperASCII(class_class[0]); } return class_class; +#endif } } // namespace internal diff --git a/chrome/browser/spellchecker/spellcheck_factory.cc b/chrome/browser/spellchecker/spellcheck_factory.cc index 9d94c21c4201e..8834bb3257212 100644 --- a/chrome/browser/spellchecker/spellcheck_factory.cc +++ b/chrome/browser/spellchecker/spellcheck_factory.cc @@ -77,7 +77,7 @@ void SpellcheckServiceFactory::RegisterProfilePrefs( spellcheck::prefs::kSpellCheckDictionary, l10n_util::GetStringUTF8(IDS_SPELLCHECK_DICTIONARY)); user_prefs->RegisterBooleanPref( - spellcheck::prefs::kSpellCheckUseSpellingService, false); + spellcheck::prefs::kSpellCheckUseSpellingService, true); #if defined(OS_IOS) || defined(OS_ANDROID) uint32_t flags = PrefRegistry::NO_REGISTRATION_FLAGS; #else diff --git a/chrome/browser/ssl/security_state_tab_helper.cc b/chrome/browser/ssl/security_state_tab_helper.cc index a5c7c949fe2d1..427a39dc5e96e 100644 --- a/chrome/browser/ssl/security_state_tab_helper.cc +++ b/chrome/browser/ssl/security_state_tab_helper.cc @@ -147,6 +147,7 @@ bool SecurityStateTabHelper::UsedPolicyInstalledCertificate() const { security_state::MaliciousContentStatus SecurityStateTabHelper::GetMaliciousContentStatus() const { +#if 0 content::NavigationEntry* entry = web_contents()->GetController().GetVisibleEntry(); if (!entry) @@ -186,6 +187,7 @@ SecurityStateTabHelper::GetMaliciousContentStatus() const { break; } } +#endif return security_state::MALICIOUS_CONTENT_STATUS_NONE; } diff --git a/chrome/browser/status_icons/status_icon.h b/chrome/browser/status_icons/status_icon.h index 0eaaf247f9733..291ca770fd60e 100644 --- a/chrome/browser/status_icons/status_icon.h +++ b/chrome/browser/status_icons/status_icon.h @@ -72,11 +72,11 @@ class StatusIcon { // thread to do it. Use sparingly. virtual void ForceVisible(); - protected: + public: // Invoked after a call to SetContextMenu() to let the platform-specific // subclass update the native context menu based on the new model. If NULL is // passed, subclass should destroy the native context menu. - virtual void UpdatePlatformContextMenu(StatusIconMenuModel* model) = 0; + virtual void UpdatePlatformContextMenu(ui::MenuModel* model) = 0; private: base::ObserverList observers_; diff --git a/chrome/browser/subresource_filter/chrome_subresource_filter_client.cc b/chrome/browser/subresource_filter/chrome_subresource_filter_client.cc index 8a27baba8e920..0338ac9308f77 100644 --- a/chrome/browser/subresource_filter/chrome_subresource_filter_client.cc +++ b/chrome/browser/subresource_filter/chrome_subresource_filter_client.cc @@ -58,6 +58,7 @@ void ChromeSubresourceFilterClient::MaybeAppendNavigationThrottles( return; } +#if 0 if (navigation_handle->IsInMainFrame()) { safe_browsing::SafeBrowsingService* safe_browsing_service = g_browser_process->safe_browsing_service(); @@ -77,6 +78,7 @@ void ChromeSubresourceFilterClient::MaybeAppendNavigationThrottles( content::BrowserThread::IO), std::move(database_manager))); } +#endif auto* driver_factory = subresource_filter::ContentSubresourceFilterDriverFactory:: diff --git a/chrome/browser/supervised_user/supervised_user_service.cc b/chrome/browser/supervised_user/supervised_user_service.cc index 4479e4b2a220a..f671dd6b18075 100644 --- a/chrome/browser/supervised_user/supervised_user_service.cc +++ b/chrome/browser/supervised_user/supervised_user_service.cc @@ -197,6 +197,7 @@ void SupervisedUserService::Init() { if (sync_service) sync_service->AddPreferenceProvider(this); +#if 0 std::string client_id = component_updater::SupervisedUserWhitelistInstaller:: ClientIdForProfilePath(profile_->GetPath()); whitelist_service_.reset(new SupervisedUserWhitelistService( @@ -205,6 +206,7 @@ void SupervisedUserService::Init() { whitelist_service_->AddSiteListsChangedCallback( base::Bind(&SupervisedUserService::OnSiteListsChanged, weak_ptr_factory_.GetWeakPtr())); +#endif SetActive(ProfileIsSupervised()); } diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index b29d0d03d23a0..214c101f901a6 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn @@ -192,13 +192,13 @@ split_static_library("ui") { "tab_modal_confirm_dialog.h", "toolbar/chrome_toolbar_model_delegate.cc", "toolbar/chrome_toolbar_model_delegate.h", - "translate/language_combobox_model.cc", - "translate/language_combobox_model.h", - "translate/translate_bubble_model.h", - "translate/translate_bubble_model_impl.cc", - "translate/translate_bubble_model_impl.h", - "translate/translate_bubble_view_state_transition.cc", - "translate/translate_bubble_view_state_transition.h", + #"translate/language_combobox_model.cc", + #"translate/language_combobox_model.h", + #"translate/translate_bubble_model.h", + #"translate/translate_bubble_model_impl.cc", + #"translate/translate_bubble_model_impl.h", + #"translate/translate_bubble_view_state_transition.cc", + #"translate/translate_bubble_view_state_transition.h", "uninstall_browser_prompt.h", "validation_message_bubble.h", "view_ids.h", @@ -332,8 +332,8 @@ split_static_library("ui") { "webui/chromeos/slow_ui.h", "webui/chromeos/ui_account_tweaks.cc", "webui/chromeos/ui_account_tweaks.h", - "webui/components_ui.cc", - "webui/components_ui.h", + #"webui/components_ui.cc", + #"webui/components_ui.h", "webui/constrained_web_dialog_ui.cc", "webui/constrained_web_dialog_ui.h", "webui/cookies_tree_model_util.cc", @@ -344,8 +344,8 @@ split_static_library("ui") { "webui/device_log_ui.h", "webui/domain_reliability_internals_ui.cc", "webui/domain_reliability_internals_ui.h", - "webui/engagement/site_engagement_ui.cc", - "webui/engagement/site_engagement_ui.h", + #"webui/engagement/site_engagement_ui.cc", + #"webui/engagement/site_engagement_ui.h", "webui/fallback_icon_source.cc", "webui/fallback_icon_source.h", "webui/favicon_source.cc", @@ -356,10 +356,10 @@ split_static_library("ui") { "webui/flags_ui.h", "webui/gcm_internals_ui.cc", "webui/gcm_internals_ui.h", - "webui/instant_ui.cc", - "webui/instant_ui.h", - "webui/interstitials/interstitial_ui.cc", - "webui/interstitials/interstitial_ui.h", + #"webui/instant_ui.cc", + #"webui/instant_ui.h", + #"webui/interstitials/interstitial_ui.cc", + #"webui/interstitials/interstitial_ui.h", "webui/invalidations_message_handler.cc", "webui/invalidations_message_handler.h", "webui/invalidations_ui.cc", @@ -423,14 +423,14 @@ split_static_library("ui") { "webui/task_scheduler_internals/task_scheduler_internals_ui.h", "webui/test_files_request_filter.cc", "webui/test_files_request_filter.h", - "webui/translate_internals/translate_internals_handler.cc", - "webui/translate_internals/translate_internals_handler.h", - "webui/translate_internals/translate_internals_ui.cc", - "webui/translate_internals/translate_internals_ui.h", - "webui/usb_internals/usb_internals_page_handler.cc", - "webui/usb_internals/usb_internals_page_handler.h", - "webui/usb_internals/usb_internals_ui.cc", - "webui/usb_internals/usb_internals_ui.h", + #"webui/translate_internals/translate_internals_handler.cc", + #"webui/translate_internals/translate_internals_handler.h", + #"webui/translate_internals/translate_internals_ui.cc", + #"webui/translate_internals/translate_internals_ui.h", + #"webui/usb_internals/usb_internals_page_handler.cc", + #"webui/usb_internals/usb_internals_page_handler.h", + #"webui/usb_internals/usb_internals_ui.cc", + #"webui/usb_internals/usb_internals_ui.h", "webui/user_actions/user_actions_ui.cc", "webui/user_actions/user_actions_ui.h", "webui/user_actions/user_actions_ui_handler.cc", @@ -953,22 +953,22 @@ split_static_library("ui") { "webui/identity_internals_ui.h", "webui/inspect_ui.cc", "webui/inspect_ui.h", - "webui/md_bookmarks/md_bookmarks_ui.cc", - "webui/md_bookmarks/md_bookmarks_ui.h", - "webui/md_downloads/downloads_list_tracker.cc", - "webui/md_downloads/downloads_list_tracker.h", - "webui/md_downloads/md_downloads_dom_handler.cc", - "webui/md_downloads/md_downloads_dom_handler.h", - "webui/md_downloads/md_downloads_ui.cc", - "webui/md_downloads/md_downloads_ui.h", - "webui/md_feedback/md_feedback_dialog_controller.cc", - "webui/md_feedback/md_feedback_dialog_controller.h", - "webui/md_feedback/md_feedback_ui.cc", - "webui/md_feedback/md_feedback_ui.h", - "webui/md_feedback/md_feedback_webui_message_handler.cc", - "webui/md_feedback/md_feedback_webui_message_handler.h", - "webui/md_history_ui.cc", - "webui/md_history_ui.h", + #"webui/md_bookmarks/md_bookmarks_ui.cc", + #"webui/md_bookmarks/md_bookmarks_ui.h", + #"webui/md_downloads/downloads_list_tracker.cc", + #"webui/md_downloads/downloads_list_tracker.h", + #"webui/md_downloads/md_downloads_dom_handler.cc", + #"webui/md_downloads/md_downloads_dom_handler.h", + #"webui/md_downloads/md_downloads_ui.cc", + #"webui/md_downloads/md_downloads_ui.h", + #"webui/md_feedback/md_feedback_dialog_controller.cc", + #"webui/md_feedback/md_feedback_dialog_controller.h", + #"webui/md_feedback/md_feedback_ui.cc", + #"webui/md_feedback/md_feedback_ui.h", + #"webui/md_feedback/md_feedback_webui_message_handler.cc", + #"webui/md_feedback/md_feedback_webui_message_handler.h", + #"webui/md_history_ui.cc", + #"webui/md_history_ui.h", "webui/ntp/app_launcher_handler.cc", "webui/ntp/app_launcher_handler.h", "webui/ntp/app_resource_cache_factory.cc", @@ -981,103 +981,103 @@ split_static_library("ui") { "webui/ntp/ntp_resource_cache.h", "webui/ntp/ntp_resource_cache_factory.cc", "webui/ntp/ntp_resource_cache_factory.h", - "webui/options/autofill_options_handler.cc", - "webui/options/autofill_options_handler.h", - "webui/options/automatic_settings_reset_handler.cc", - "webui/options/automatic_settings_reset_handler.h", - "webui/options/browser_options_handler.cc", - "webui/options/browser_options_handler.h", - "webui/options/chromeos/accounts_options_handler.cc", - "webui/options/chromeos/accounts_options_handler.h", - "webui/options/chromeos/bluetooth_options_handler.cc", - "webui/options/chromeos/bluetooth_options_handler.h", - "webui/options/chromeos/change_picture_options_handler.cc", - "webui/options/chromeos/change_picture_options_handler.h", - "webui/options/chromeos/core_chromeos_options_handler.cc", - "webui/options/chromeos/core_chromeos_options_handler.h", - "webui/options/chromeos/cros_language_options_handler.cc", - "webui/options/chromeos/cros_language_options_handler.h", - "webui/options/chromeos/date_time_options_handler.cc", - "webui/options/chromeos/date_time_options_handler.h", - "webui/options/chromeos/display_options_handler.cc", - "webui/options/chromeos/display_options_handler.h", - "webui/options/chromeos/display_overscan_handler.cc", - "webui/options/chromeos/display_overscan_handler.h", - "webui/options/chromeos/internet_options_handler.cc", - "webui/options/chromeos/internet_options_handler.h", - "webui/options/chromeos/internet_options_handler_strings.cc", - "webui/options/chromeos/internet_options_handler_strings.h", - "webui/options/chromeos/keyboard_handler.cc", - "webui/options/chromeos/keyboard_handler.h", - "webui/options/chromeos/options_stylus_handler.cc", - "webui/options/chromeos/options_stylus_handler.h", - "webui/options/chromeos/pointer_handler.cc", - "webui/options/chromeos/pointer_handler.h", - "webui/options/chromeos/power_handler.cc", - "webui/options/chromeos/power_handler.h", - "webui/options/chromeos/proxy_handler.cc", - "webui/options/chromeos/proxy_handler.h", - "webui/options/chromeos/stats_options_handler.cc", - "webui/options/chromeos/stats_options_handler.h", - "webui/options/chromeos/storage_manager_handler.cc", - "webui/options/chromeos/storage_manager_handler.h", - "webui/options/chromeos/user_image_source.cc", - "webui/options/chromeos/user_image_source.h", - "webui/options/clear_browser_data_handler.cc", - "webui/options/clear_browser_data_handler.h", - "webui/options/content_settings_handler.cc", - "webui/options/content_settings_handler.h", - "webui/options/cookies_view_handler.cc", - "webui/options/cookies_view_handler.h", - "webui/options/core_options_handler.cc", - "webui/options/core_options_handler.h", - "webui/options/create_profile_handler.cc", - "webui/options/create_profile_handler.h", - "webui/options/easy_unlock_handler.cc", - "webui/options/easy_unlock_handler.h", - "webui/options/font_settings_handler.cc", - "webui/options/font_settings_handler.h", + #"webui/options/autofill_options_handler.cc", + #"webui/options/autofill_options_handler.h", + #"webui/options/automatic_settings_reset_handler.cc", + #"webui/options/automatic_settings_reset_handler.h", + #"webui/options/browser_options_handler.cc", + #"webui/options/browser_options_handler.h", + #"webui/options/chromeos/accounts_options_handler.cc", + #"webui/options/chromeos/accounts_options_handler.h", + #"webui/options/chromeos/bluetooth_options_handler.cc", + #"webui/options/chromeos/bluetooth_options_handler.h", + #"webui/options/chromeos/change_picture_options_handler.cc", + #"webui/options/chromeos/change_picture_options_handler.h", + #"webui/options/chromeos/core_chromeos_options_handler.cc", + #"webui/options/chromeos/core_chromeos_options_handler.h", + #"webui/options/chromeos/cros_language_options_handler.cc", + #"webui/options/chromeos/cros_language_options_handler.h", + #"webui/options/chromeos/date_time_options_handler.cc", + #"webui/options/chromeos/date_time_options_handler.h", + #"webui/options/chromeos/display_options_handler.cc", + #"webui/options/chromeos/display_options_handler.h", + #"webui/options/chromeos/display_overscan_handler.cc", + #"webui/options/chromeos/display_overscan_handler.h", + #"webui/options/chromeos/internet_options_handler.cc", + #"webui/options/chromeos/internet_options_handler.h", + #"webui/options/chromeos/internet_options_handler_strings.cc", + #"webui/options/chromeos/internet_options_handler_strings.h", + #"webui/options/chromeos/keyboard_handler.cc", + #"webui/options/chromeos/keyboard_handler.h", + #"webui/options/chromeos/options_stylus_handler.cc", + #"webui/options/chromeos/options_stylus_handler.h", + #"webui/options/chromeos/pointer_handler.cc", + #"webui/options/chromeos/pointer_handler.h", + #"webui/options/chromeos/power_handler.cc", + #"webui/options/chromeos/power_handler.h", + #"webui/options/chromeos/proxy_handler.cc", + #"webui/options/chromeos/proxy_handler.h", + #"webui/options/chromeos/stats_options_handler.cc", + #"webui/options/chromeos/stats_options_handler.h", + #"webui/options/chromeos/storage_manager_handler.cc", + #"webui/options/chromeos/storage_manager_handler.h", + #"webui/options/chromeos/user_image_source.cc", + #"webui/options/chromeos/user_image_source.h", + #"webui/options/clear_browser_data_handler.cc", + #"webui/options/clear_browser_data_handler.h", + #"webui/options/content_settings_handler.cc", + #"webui/options/content_settings_handler.h", + #"webui/options/cookies_view_handler.cc", + #"webui/options/cookies_view_handler.h", + #"webui/options/core_options_handler.cc", + #"webui/options/core_options_handler.h", + #"webui/options/create_profile_handler.cc", + #"webui/options/create_profile_handler.h", + #"webui/options/easy_unlock_handler.cc", + #"webui/options/easy_unlock_handler.h", + #"webui/options/font_settings_handler.cc", + #"webui/options/font_settings_handler.h", "webui/options/font_settings_utils.cc", "webui/options/font_settings_utils.h", - "webui/options/font_settings_utils_linux.cc", - "webui/options/font_settings_utils_mac.mm", + #"webui/options/font_settings_utils_linux.cc", + #"webui/options/font_settings_utils_mac.mm", "webui/options/font_settings_utils_win.cc", - "webui/options/handler_options_handler.cc", - "webui/options/handler_options_handler.h", - "webui/options/help_overlay_handler.cc", - "webui/options/help_overlay_handler.h", - "webui/options/home_page_overlay_handler.cc", - "webui/options/home_page_overlay_handler.h", - "webui/options/import_data_handler.cc", - "webui/options/import_data_handler.h", - "webui/options/language_dictionary_overlay_handler.cc", - "webui/options/language_dictionary_overlay_handler.h", - "webui/options/language_options_handler.cc", - "webui/options/language_options_handler.h", - "webui/options/language_options_handler_common.cc", - "webui/options/language_options_handler_common.h", - "webui/options/manage_profile_handler.cc", - "webui/options/manage_profile_handler.h", - "webui/options/media_devices_selection_handler.cc", - "webui/options/media_devices_selection_handler.h", - "webui/options/options_ui.cc", - "webui/options/options_ui.h", - "webui/options/password_manager_handler.cc", - "webui/options/password_manager_handler.h", - "webui/options/reset_profile_settings_handler.cc", - "webui/options/reset_profile_settings_handler.h", - "webui/options/search_engine_manager_handler.cc", - "webui/options/search_engine_manager_handler.h", - "webui/options/startup_pages_handler.cc", - "webui/options/startup_pages_handler.h", - "webui/options/supervised_user_create_confirm_handler.cc", - "webui/options/supervised_user_create_confirm_handler.h", - "webui/options/supervised_user_import_handler.cc", - "webui/options/supervised_user_import_handler.h", - "webui/options/supervised_user_learn_more_handler.cc", - "webui/options/supervised_user_learn_more_handler.h", - "webui/options/sync_setup_handler.cc", - "webui/options/sync_setup_handler.h", + #"webui/options/handler_options_handler.cc", + #"webui/options/handler_options_handler.h", + #"webui/options/help_overlay_handler.cc", + #"webui/options/help_overlay_handler.h", + #"webui/options/home_page_overlay_handler.cc", + #"webui/options/home_page_overlay_handler.h", + #"webui/options/import_data_handler.cc", + #"webui/options/import_data_handler.h", + #"webui/options/language_dictionary_overlay_handler.cc", + #"webui/options/language_dictionary_overlay_handler.h", + #"webui/options/language_options_handler.cc", + #"webui/options/language_options_handler.h", + #"webui/options/language_options_handler_common.cc", + #"webui/options/language_options_handler_common.h", + #"webui/options/manage_profile_handler.cc", + #"webui/options/manage_profile_handler.h", + #"webui/options/media_devices_selection_handler.cc", + #"webui/options/media_devices_selection_handler.h", + #"webui/options/options_ui.cc", + #"webui/options/options_ui.h", + #"webui/options/password_manager_handler.cc", + #"webui/options/password_manager_handler.h", + #"webui/options/reset_profile_settings_handler.cc", + #"webui/options/reset_profile_settings_handler.h", + #"webui/options/search_engine_manager_handler.cc", + #"webui/options/search_engine_manager_handler.h", + #"webui/options/startup_pages_handler.cc", + #"webui/options/startup_pages_handler.h", + #"webui/options/supervised_user_create_confirm_handler.cc", + #"webui/options/supervised_user_create_confirm_handler.h", + #"webui/options/supervised_user_import_handler.cc", + #"webui/options/supervised_user_import_handler.h", + #"webui/options/supervised_user_learn_more_handler.cc", + #"webui/options/supervised_user_learn_more_handler.h", + #"webui/options/sync_setup_handler.cc", + #"webui/options/sync_setup_handler.h", "webui/policy_indicator_localized_strings_provider.cc", "webui/policy_indicator_localized_strings_provider.h", "webui/profile_helper.cc", @@ -1195,6 +1195,16 @@ split_static_library("ui") { "zoom/chrome_zoom_level_prefs.cc", "zoom/chrome_zoom_level_prefs.h", ] + + if (!nwjs_sdk) { + sources -= [ + "webui/about_ui.cc", + "webui/about_ui.h", + "webui/extensions/extensions_ui.cc", + "webui/extensions/extensions_ui.h", + ] + } + deps += [ "//apps", "//apps/ui/views", @@ -1230,8 +1240,8 @@ split_static_library("ui") { "hung_plugin_tab_helper.h", "webui/flash_ui.cc", "webui/flash_ui.h", - "webui/options/pepper_flash_content_settings_utils.cc", - "webui/options/pepper_flash_content_settings_utils.h", + #"webui/options/pepper_flash_content_settings_utils.cc", + #"webui/options/pepper_flash_content_settings_utils.h", ] deps += [ "//ppapi/proxy:ipc" ] } @@ -1923,10 +1933,10 @@ split_static_library("ui") { "views/toolbar/toolbar_view.cc", "views/toolbar/toolbar_view.h", "views/touch_uma/touch_uma.h", - "views/translate/translate_bubble_view.cc", - "views/translate/translate_bubble_view.h", - "views/translate/translate_icon_view.cc", - "views/translate/translate_icon_view.h", + #"views/translate/translate_bubble_view.cc", + #"views/translate/translate_bubble_view.h", + #"views/translate/translate_icon_view.cc", + #"views/translate/translate_icon_view.h", "views/validation_message_bubble_view.cc", "views/validation_message_bubble_view.h", "views/webshare/webshare_target_picker_view.cc", @@ -2073,10 +2083,10 @@ split_static_library("ui") { "webui/signin/sync_confirmation_ui.h", "webui/signin/user_manager_screen_handler.cc", "webui/signin/user_manager_screen_handler.h", - "webui/welcome_handler.cc", - "webui/welcome_handler.h", - "webui/welcome_ui.cc", - "webui/welcome_ui.h", + #"webui/welcome_handler.cc", + #"webui/welcome_handler.h", + #"webui/welcome_ui.cc", + #"webui/welcome_ui.h", ] if (is_mac && !mac_views_browser) { sources -= [ @@ -2178,8 +2188,8 @@ split_static_library("ui") { "crypto_module_delegate_nss.h", "crypto_module_password_dialog_nss.cc", "crypto_module_password_dialog_nss.h", - "webui/options/certificate_manager_handler.cc", - "webui/options/certificate_manager_handler.h", + #"webui/options/certificate_manager_handler.cc", + #"webui/options/certificate_manager_handler.h", "webui/settings/certificates_handler.cc", "webui/settings/certificates_handler.h", ] @@ -3039,8 +3049,8 @@ split_static_library("ui") { "cocoa/toolbar/toolbar_controller.mm", "cocoa/toolbar/toolbar_view_cocoa.h", "cocoa/toolbar/toolbar_view_cocoa.mm", - "cocoa/translate/translate_bubble_controller.h", - "cocoa/translate/translate_bubble_controller.mm", + #"cocoa/translate/translate_bubble_controller.h", + #"cocoa/translate/translate_bubble_controller.mm", "cocoa/url_drop_target.h", "cocoa/url_drop_target.mm", "cocoa/validation_message_bubble_cocoa.h", @@ -3117,16 +3127,16 @@ split_static_library("ui") { "views/settings_reset_prompt_dialog.h", "views/uninstall_view.cc", "views/uninstall_view.h", - "webui/cleanup_tool/cleanup_action_handler.cc", - "webui/cleanup_tool/cleanup_action_handler.h", - "webui/cleanup_tool/cleanup_tool_ui.cc", - "webui/cleanup_tool/cleanup_tool_ui.h", + #"webui/cleanup_tool/cleanup_action_handler.cc", + #"webui/cleanup_tool/cleanup_action_handler.h", + #"webui/cleanup_tool/cleanup_tool_ui.cc", + #"webui/cleanup_tool/cleanup_tool_ui.h", "webui/conflicts_ui.cc", "webui/conflicts_ui.h", - "webui/welcome_win10_handler.cc", - "webui/welcome_win10_handler.h", - "webui/welcome_win10_ui.cc", - "webui/welcome_win10_ui.h", + #"webui/welcome_win10_handler.cc", + #"webui/welcome_win10_handler.h", + #"webui/welcome_win10_ui.cc", + #"webui/welcome_win10_ui.h", ] public_deps += [ "//ui/views", @@ -3464,7 +3474,7 @@ split_static_library("ui") { "webui/options/geolocation_options_handler.h", ] } - if (!is_android) { + if (!is_android && nwjs_sdk) { sources += [ "toolbar/media_router_action.cc", "toolbar/media_router_action.h", @@ -3506,8 +3516,8 @@ split_static_library("ui") { } if (is_chromeos || is_mac || is_win) { sources += [ - "webui/cast/cast_ui.cc", - "webui/cast/cast_ui.h", + #"webui/cast/cast_ui.cc", + #"webui/cast/cast_ui.h", ] } deps += [ diff --git a/chrome/browser/ui/apps/chrome_app_delegate.cc b/chrome/browser/ui/apps/chrome_app_delegate.cc index 2111f5ec8bdc0..fb9bc4de2be32 100644 --- a/chrome/browser/ui/apps/chrome_app_delegate.cc +++ b/chrome/browser/ui/apps/chrome_app_delegate.cc @@ -8,6 +8,13 @@ #include #include "base/macros.h" + +#include "chrome/browser/sessions/session_tab_helper.h" +#include "chrome/browser/extensions/tab_helper.h" +#include "chrome/browser/password_manager/chrome_password_manager_client.h" +#include "chrome/browser/ui/passwords/manage_passwords_ui_controller.h" +#include "chrome/browser/external_protocol/external_protocol_observer.h" + #include "base/strings/stringprintf.h" #include "chrome/browser/app_mode/app_mode_utils.h" #include "chrome/browser/chrome_notification_types.h" @@ -56,10 +63,16 @@ #endif // BUILDFLAG(ENABLE_PRINT_PREVIEW) #endif // BUILDFLAG(ENABLE_PRINTING) +#include "chrome/browser/browser_process.h" +#include "chrome/browser/ui/autofill/chrome_autofill_client.h" +#include "components/autofill/content/browser/content_autofill_driver_factory.h" +#include "components/autofill/core/browser/autofill_manager.h" +#include "chrome/browser/ui/prefs/prefs_tab_helper.h" + namespace { // Time to wait for an app window to show before allowing Chrome to quit. -int kAppWindowFirstShowTimeoutSeconds = 10; +//int kAppWindowFirstShowTimeoutSeconds = 10; bool disable_external_open_for_testing_ = false; @@ -74,7 +87,7 @@ content::WebContents* OpenURLFromTabInternal( if (params.disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB) { new_tab_params.disposition = WindowOpenDisposition::NEW_BACKGROUND_TAB; } else { - new_tab_params.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; + new_tab_params.disposition = WindowOpenDisposition::NEW_POPUP; new_tab_params.window_action = chrome::NavigateParams::SHOW_WINDOW; } @@ -165,6 +178,7 @@ ChromeAppDelegate::ChromeAppDelegate(bool keep_alive) : has_been_shown_(false), is_hidden_(true), new_window_contents_delegate_(new NewWindowContentsDelegate()), + web_contents_(nullptr), weak_factory_(this) { if (keep_alive) { keep_alive_.reset(new ScopedKeepAlive(KeepAliveOrigin::CHROME_APP_DELEGATE, @@ -187,6 +201,8 @@ void ChromeAppDelegate::DisableExternalOpenForTesting() { void ChromeAppDelegate::InitWebContents(content::WebContents* web_contents) { data_use_measurement::DataUseWebContentsObserver::CreateForWebContents( web_contents); + web_contents_ = web_contents; + favicon::CreateContentFaviconDriverForWebContents(web_contents); #if BUILDFLAG(ENABLE_PRINTING) @@ -197,10 +213,31 @@ void ChromeAppDelegate::InitWebContents(content::WebContents* web_contents) { printing::PrintViewManagerBasic::CreateForWebContents(web_contents); #endif // BUILDFLAG(ENABLE_PRINT_PREVIEW) #endif // BUILDFLAG(ENABLE_PRINTING) - extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( - web_contents); + // ZoomController comes before common tab helpers since ChromeExtensionWebContentsObserver + // may want to register as a ZoomObserver with it. zoom::ZoomController::CreateForWebContents(web_contents); + +#if 1 + extensions::TabHelper::CreateForWebContents(web_contents); +#else + SessionTabHelper::CreateForWebContents(web_contents); + + extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( + web_contents); +#endif + autofill::ChromeAutofillClient::CreateForWebContents(web_contents); + autofill::ContentAutofillDriverFactory::CreateForWebContentsAndDelegate( + web_contents, + autofill::ChromeAutofillClient::FromWebContents(web_contents), + g_browser_process->GetApplicationLocale(), + autofill::AutofillManager::ENABLE_AUTOFILL_DOWNLOAD_MANAGER); + ChromePasswordManagerClient::CreateForWebContentsWithAutofillClient( + web_contents, + autofill::ChromeAutofillClient::FromWebContents(web_contents)); + ManagePasswordsUIController::CreateForWebContents(web_contents); + PrefsTabHelper::CreateForWebContents(web_contents); + ExternalProtocolObserver::CreateForWebContents(web_contents); } void ChromeAppDelegate::RenderViewCreated( @@ -240,11 +277,13 @@ void ChromeAppDelegate::AddNewContents(content::BrowserContext* context, bool user_gesture, bool* was_blocked) { if (!disable_external_open_for_testing_) { +#if 0 // We don't really want to open a window for |new_contents|, but we need to // capture its intended navigation. Here we give ownership to the // NewWindowContentsDelegate, which will dispose of the contents once // a navigation is captured. new_contents->SetDelegate(new_window_contents_delegate_.get()); +#endif return; } chrome::ScopedTabbedBrowserDisplayer displayer( @@ -327,6 +366,7 @@ void ChromeAppDelegate::SetTerminatingCallback(const base::Closure& callback) { void ChromeAppDelegate::OnHide() { is_hidden_ = true; +#if 0 if (has_been_shown_) { keep_alive_.reset(); return; @@ -339,13 +379,16 @@ void ChromeAppDelegate::OnHide() { base::BindOnce(&ChromeAppDelegate::RelinquishKeepAliveAfterTimeout, weak_factory_.GetWeakPtr()), base::TimeDelta::FromSeconds(kAppWindowFirstShowTimeoutSeconds)); +#endif } void ChromeAppDelegate::OnShow() { has_been_shown_ = true; is_hidden_ = false; +#if 0 keep_alive_.reset(new ScopedKeepAlive(KeepAliveOrigin::CHROME_APP_DELEGATE, KeepAliveRestartOption::DISABLED)); +#endif } void ChromeAppDelegate::Observe(int type, diff --git a/chrome/browser/ui/apps/chrome_app_delegate.h b/chrome/browser/ui/apps/chrome_app_delegate.h index 3d687f41e9672..6c602ecdec6c1 100644 --- a/chrome/browser/ui/apps/chrome_app_delegate.h +++ b/chrome/browser/ui/apps/chrome_app_delegate.h @@ -70,7 +70,6 @@ class ChromeAppDelegate : public extensions::AppDelegate, void SetTerminatingCallback(const base::Closure& callback) override; void OnHide() override; void OnShow() override; - // content::NotificationObserver: void Observe(int type, const content::NotificationSource& source, @@ -82,6 +81,7 @@ class ChromeAppDelegate : public extensions::AppDelegate, std::unique_ptr new_window_contents_delegate_; base::Closure terminating_callback_; content::NotificationRegistrar registrar_; + content::WebContents* web_contents_; base::WeakPtrFactory weak_factory_; DISALLOW_COPY_AND_ASSIGN(ChromeAppDelegate); diff --git a/chrome/browser/ui/apps/chrome_app_window_client.cc b/chrome/browser/ui/apps/chrome_app_window_client.cc index 3349e24d5a937..a3ee491a723b6 100644 --- a/chrome/browser/ui/apps/chrome_app_window_client.cc +++ b/chrome/browser/ui/apps/chrome_app_window_client.cc @@ -13,6 +13,8 @@ #include "extensions/common/extension.h" #include "extensions/common/features/feature_channel.h" +#include "content/nw/src/nw_content.h" + // TODO(jamescook): We probably shouldn't compile this class at all on Android. // See http://crbug.com/343612 #if !defined(OS_ANDROID) @@ -38,8 +40,10 @@ extensions::AppWindow* ChromeAppWindowClient::CreateAppWindow( #if defined(OS_ANDROID) return NULL; #else - return new extensions::AppWindow(context, new ChromeAppDelegate(true), + extensions::AppWindow* ret = new extensions::AppWindow(context, new ChromeAppDelegate(true), extension); + nw::CreateAppWindowHook(ret); + return ret; #endif } diff --git a/chrome/browser/ui/autofill/chrome_autofill_client.cc b/chrome/browser/ui/autofill/chrome_autofill_client.cc index 44f2a804ce97c..e50f2b0f81e39 100644 --- a/chrome/browser/ui/autofill/chrome_autofill_client.cc +++ b/chrome/browser/ui/autofill/chrome_autofill_client.cc @@ -346,6 +346,9 @@ bool ChromeAutofillClient::IsContextSecure() { if (!navigation_entry) return false; + if (navigation_entry->GetURL().SchemeIs("chrome-extension")) + return true; + ssl_status = navigation_entry->GetSSL(); // Note: If changing the implementation below, also change // AwAutofillClient::IsContextSecure. See crbug.com/505388 diff --git a/chrome/browser/ui/browser.cc b/chrome/browser/ui/browser.cc index 92f9f7928498f..bc5cf3ca2cb08 100644 --- a/chrome/browser/ui/browser.cc +++ b/chrome/browser/ui/browser.cc @@ -284,7 +284,7 @@ const extensions::Extension* GetExtensionForOrigin( // Browser, CreateParams: Browser::CreateParams::CreateParams(Profile* profile, bool user_gesture) - : type(TYPE_TABBED), + : type(TYPE_POPUP), profile(profile), trusted_source(false), initial_show_state(ui::SHOW_STATE_DEFAULT), @@ -295,7 +295,7 @@ Browser::CreateParams::CreateParams(Profile* profile, bool user_gesture) Browser::CreateParams::CreateParams(Type type, Profile* profile, bool user_gesture) - : type(type), + : type(TYPE_POPUP), profile(profile), trusted_source(false), initial_show_state(ui::SHOW_STATE_DEFAULT), @@ -1702,7 +1702,8 @@ void Browser::WebContentsCreated( const std::string& frame_name, const GURL& target_url, WebContents* new_contents, - const base::Optional& create_params) { + const base::Optional& create_params, + const base::string16& nw_window_manifest) { // Adopt the WebContents now, so all observers are in place, as the network // requests for its initial navigation will start immediately. The WebContents // will later be inserted into this browser using Browser::Navigate via @@ -2118,11 +2119,13 @@ void Browser::OnExtensionUnloaded(content::BrowserContext* browser_context, void Browser::OnIsPageTranslatedChanged(content::WebContents* source) { DCHECK(source); +#if 0 if (tab_strip_model_->GetActiveWebContents() == source) { window_->SetTranslateIconToggled( ChromeTranslateClient::FromWebContents( source)->GetLanguageState().IsPageTranslated()); } +#endif } void Browser::OnTranslateEnabledChanged(content::WebContents* source) { @@ -2387,14 +2390,14 @@ void Browser::SetAsDelegate(WebContents* web_contents, bool set_delegate) { WebContentsModalDialogManager::FromWebContents(web_contents)-> SetDelegate(delegate); CoreTabHelper::FromWebContents(web_contents)->set_delegate(delegate); - translate::ContentTranslateDriver& content_translate_driver = - ChromeTranslateClient::FromWebContents(web_contents)->translate_driver(); + //translate::ContentTranslateDriver& content_translate_driver = + // ChromeTranslateClient::FromWebContents(web_contents)->translate_driver(); if (delegate) { zoom::ZoomController::FromWebContents(web_contents)->AddObserver(this); - content_translate_driver.AddObserver(this); + //content_translate_driver.AddObserver(this); } else { zoom::ZoomController::FromWebContents(web_contents)->RemoveObserver(this); - content_translate_driver.RemoveObserver(this); + //content_translate_driver.RemoveObserver(this); } } diff --git a/chrome/browser/ui/browser.h b/chrome/browser/ui/browser.h index a8a85d2af4712..e80a696b16740 100644 --- a/chrome/browser/ui/browser.h +++ b/chrome/browser/ui/browser.h @@ -642,7 +642,8 @@ class Browser : public TabStripModelObserver, const std::string& frame_name, const GURL& target_url, content::WebContents* new_contents, - const base::Optional& create_params) + const base::Optional& create_params, + const base::string16& nw_window_manifest) override; void RendererUnresponsive( content::WebContents* source, diff --git a/chrome/browser/ui/browser_commands.cc b/chrome/browser/ui/browser_commands.cc index 54582710f9eea..a96917581aeb1 100644 --- a/chrome/browser/ui/browser_commands.cc +++ b/chrome/browser/ui/browser_commands.cc @@ -120,6 +120,7 @@ namespace { const char kOsOverrideForTabletSite[] = "Linux; Android 4.0.3"; +#if 0 translate::TranslateBubbleUiEvent TranslateBubbleResultToUiEvent( ShowTranslateBubbleResult result) { switch (result) { @@ -145,6 +146,7 @@ translate::TranslateBubbleUiEvent TranslateBubbleResultToUiEvent( BUBBLE_NOT_SHOWN_EDITABLE_FIELD_IS_ACTIVE; } } +#endif } // namespace @@ -359,6 +361,7 @@ int GetContentRestrictions(const Browser* browser) { } void NewEmptyWindow(Profile* profile) { +#if 0 bool incognito = profile->IsOffTheRecord(); PrefService* prefs = profile->GetPrefs(); if (incognito) { @@ -386,6 +389,7 @@ void NewEmptyWindow(Profile* profile) { OpenEmptyWindow(profile->GetOriginalProfile()); } } +#endif } Browser* OpenEmptyWindow(Profile* profile) { @@ -852,6 +856,7 @@ void SaveCreditCard(Browser* browser) { } void Translate(Browser* browser) { +#if 0 if (!browser->window()->IsActive()) return; @@ -871,6 +876,7 @@ void Translate(Browser* browser) { web_contents, step, translate::TranslateErrors::NONE, true); if (result != ShowTranslateBubbleResult::SUCCESS) translate::ReportUiAction(TranslateBubbleResultToUiEvent(result)); +#endif } void ManagePasswordsForPage(Browser* browser) { diff --git a/chrome/browser/ui/chrome_bubble_manager.cc b/chrome/browser/ui/chrome_bubble_manager.cc index da7d632bdf74d..90b2ccc00cf37 100644 --- a/chrome/browser/ui/chrome_bubble_manager.cc +++ b/chrome/browser/ui/chrome_bubble_manager.cc @@ -111,13 +111,15 @@ static void LogBubbleCloseReason(BubbleReference bubble, ChromeBubbleManager::ChromeBubbleManager(TabStripModel* tab_strip_model) : tab_strip_model_(tab_strip_model) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(tab_strip_model_); - tab_strip_model_->AddObserver(this); + //DCHECK(tab_strip_model_); + if (tab_strip_model_) + tab_strip_model_->AddObserver(this); AddBubbleManagerObserver(&chrome_bubble_metrics_); } ChromeBubbleManager::~ChromeBubbleManager() { - tab_strip_model_->RemoveObserver(this); + if (tab_strip_model_) + tab_strip_model_->RemoveObserver(this); // Finalize requests before removing the BubbleManagerObserver so it can // collect metrics when closing any open bubbles. diff --git a/chrome/browser/ui/chrome_pages.cc b/chrome/browser/ui/chrome_pages.cc index 78cf00f9e4c52..924b4c22c5f83 100644 --- a/chrome/browser/ui/chrome_pages.cc +++ b/chrome/browser/ui/chrome_pages.cc @@ -65,7 +65,7 @@ using base::UserMetricsAction; namespace chrome { namespace { -const char kHashMark[] = "#"; +//const char kHashMark[] = "#"; void OpenBookmarkManagerWithHash(Browser* browser, const std::string& action, @@ -140,6 +140,7 @@ void ShowHelpImpl(Browser* browser, Profile* profile, HelpSource source) { #endif } +#if 0 std::string GenerateContentSettingsExceptionsSubPage(ContentSettingsType type) { if (!base::FeatureList::IsEnabled(features::kMaterialDesignSettings)) { return kDeprecatedOptionsContentSettingsExceptionsSubPage + @@ -173,6 +174,7 @@ std::string GenerateContentSettingsExceptionsSubPage(ContentSettingsType type) { return std::string(kContentSettingsSubPage) + "/" + content_type_path; } +#endif #if defined(OS_CHROMEOS) std::string GenerateContentSettingsSearchQueryPath(int query_message_id) { @@ -350,24 +352,30 @@ void ShowSettingsSubPageInTabbedBrowser(Browser* browser, void ShowContentSettingsExceptions(Browser* browser, ContentSettingsType content_settings_type) { +#if 0 ShowSettingsSubPage( browser, GenerateContentSettingsExceptionsSubPage(content_settings_type)); +#endif } void ShowContentSettingsExceptionsInWindow( Profile* profile, ContentSettingsType content_settings_type) { +#if 0 DCHECK(switches::SettingsWindowEnabled()); ShowSettingsSubPageForProfile( profile, GenerateContentSettingsExceptionsSubPage(content_settings_type)); +#endif } void ShowContentSettings(Browser* browser, ContentSettingsType content_settings_type) { +#if 0 ShowSettingsSubPage( browser, kContentSettingsSubPage + std::string(kHashMark) + site_settings::ContentSettingsTypeToGroupName(content_settings_type)); +#endif } void ShowClearBrowsingDataDialog(Browser* browser) { diff --git a/chrome/browser/ui/cocoa/apps/app_shim_menu_controller_mac.mm b/chrome/browser/ui/cocoa/apps/app_shim_menu_controller_mac.mm index 1da50bbb78bbd..710ddb1e4c3c9 100644 --- a/chrome/browser/ui/cocoa/apps/app_shim_menu_controller_mac.mm +++ b/chrome/browser/ui/cocoa/apps/app_shim_menu_controller_mac.mm @@ -25,6 +25,11 @@ using extensions::Extension; +#include "chrome/browser/devtools/devtools_window.h" + +#include "content/nw/src/api/menu/menu.h" +#include "content/nw/src/common/shell_switches.h" + namespace { // When an app window loses main status, AppKit may make another app window main @@ -76,6 +81,7 @@ void AddDuplicateItem(NSMenuItem* top_level_item, [[top_level_item submenu] addItem:item]; } +#if 0 // Finds an item with |item_tag| and removes it from the submenu of // |top_level_item|. void RemoveMenuItemWithTag(NSMenuItem* top_level_item, @@ -133,6 +139,7 @@ void SetItemWithTagVisible(NSMenuItem* top_level_item, [alternate_item setHidden:!visible]; [menu_item setHidden:!visible]; } +#endif // Return the Extension (if any) associated with the given window. If it is not // a platform app nor hosted app, but it is a browser, |is_browser| will be set @@ -212,6 +219,7 @@ void SetAppCyclesWindows(const std::string& app_id, int sequence_number) { [[NSApp keyWindow] makeKeyAndOrderFront:nil]; } +#if 0 // Sets the window cycle list to Chrome browser windows only. void SetChromeCyclesWindows(int sequence_number) { if (g_window_cycle_sequence_number != sequence_number) @@ -227,6 +235,7 @@ void SetChromeCyclesWindows(int sequence_number) { if (any_change) [[NSApp keyWindow] makeKeyAndOrderFront:nil]; } +#endif } // namespace @@ -355,6 +364,7 @@ - (void)quitCurrentPlatformApp; - (void)hideCurrentPlatformApp; // If the currently focused window belongs to a platform app, focus the app. - (void)focusCurrentPlatformApp; +- (void)showDevtools; @end @implementation AppShimMenuController @@ -394,6 +404,7 @@ - (void)buildAppMenuItems { resourceId:IDS_EXIT_MAC action:@selector(quitCurrentPlatformApp) keyEquivalent:@"q"]); +#if 0 newDoppelganger_.reset([[DoppelgangerMenuItem alloc] initWithController:self menuTag:IDC_FILE_MENU @@ -418,6 +429,7 @@ - (void)buildAppMenuItems { resourceId:0 action:nil keyEquivalent:@"o"]); +#endif allToFrontDoppelganger_.reset([[DoppelgangerMenuItem alloc] initWithController:self menuTag:IDC_WINDOW_MENU @@ -441,18 +453,21 @@ - (void)buildAppMenuItems { [appMenu addItem:[NSMenuItem separatorItem]]; [appMenu addItem:[quitDoppelganger_ menuItem]]; +#if 0 // File menu. fileMenuItem_.reset([NewTopLevelItemFrom(IDC_FILE_MENU) retain]); [[fileMenuItem_ submenu] addItem:[newDoppelganger_ menuItem]]; [[fileMenuItem_ submenu] addItem:[openDoppelganger_ menuItem]]; [[fileMenuItem_ submenu] addItem:[NSMenuItem separatorItem]]; [[fileMenuItem_ submenu] addItem:[closeWindowDoppelganger_ menuItem]]; +#endif // Edit menu. We copy the menu because the last two items, "Start Dictation" // and "Special Characters" are added by OSX, so we can't copy them // explicitly. editMenuItem_.reset([[[NSApp mainMenu] itemWithTag:IDC_EDIT_MENU] copy]); +#if 0 // View menu. Remove "Always Show Bookmark Bar" and separator. viewMenuItem_.reset([[[NSApp mainMenu] itemWithTag:IDC_VIEW_MENU] copy]); RemoveMenuItemWithTag(viewMenuItem_, IDC_SHOW_BOOKMARK_BAR, YES); @@ -462,12 +477,34 @@ - (void)buildAppMenuItems { AddDuplicateItem(historyMenuItem_, IDC_HISTORY_MENU, IDC_BACK); AddDuplicateItem(historyMenuItem_, IDC_HISTORY_MENU, IDC_FORWARD); +#endif // Window menu. windowMenuItem_.reset([NewTopLevelItemFrom(IDC_WINDOW_MENU) retain]); AddDuplicateItem(windowMenuItem_, IDC_WINDOW_MENU, IDC_MINIMIZE_WINDOW); AddDuplicateItem(windowMenuItem_, IDC_WINDOW_MENU, IDC_MAXIMIZE_WINDOW); [[windowMenuItem_ submenu] addItem:[NSMenuItem separatorItem]]; [[windowMenuItem_ submenu] addItem:[allToFrontDoppelganger_ menuItem]]; + +#if defined(NWJS_SDK) + bool enable_devtools = true; + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(switches::kDisableDevTools)) + enable_devtools = false; + + if (enable_devtools) { + [[windowMenuItem_ submenu] setAutoenablesItems:NO]; + NSMenuItem* item = [[NSMenuItem alloc] + initWithTitle:@"Devtools" + action:@selector(showDevtools) + keyEquivalent:@"i"]; + [item setTag:IDC_DEV_TOOLS_CONSOLE]; + [item setTarget:self]; + [item setEnabled:YES]; + [item setKeyEquivalentModifierMask:NSCommandKeyMask | NSAlternateKeyMask]; + [[windowMenuItem_ submenu] addItem:item]; + } +#endif } - (void)registerEventHandlers { @@ -499,8 +536,17 @@ - (void)windowMainStatusChanged:(NSNotification*)notification { const Extension* extension = GetExtensionForNSWindow(window, &is_browser); // Ignore is_browser: if a window becomes main that does not belong to an // extension or browser, treat it the same as switching to a browser. - if (extension) + + extensions::AppWindow* appWindow = + AppWindowRegistryUtil::GetAppWindowForNativeWindowAnyProfile( + window); + if (extension) { + if (appWindow->menu_) { + [NSApp setMainMenu:appWindow->menu_->menu_]; + return; + } [self appBecameMain:extension]; + } else [self chromeBecameMain]; } else if ([name isEqualToString:NSWindowDidResignMainNotification]) { @@ -531,7 +577,12 @@ - (void)appBecameMain:(const Extension*)app { return; if (!appId_.empty()) - [self removeMenuItems]; + return; + // #4591: when app sets menubar and launch another chrome app, + // removeMenuItems will try to remove appmenuitem which isn't + // in the main menu; then app will crash. + // so after this function runs once, we just do nothing and return here + //[self removeMenuItems]; appId_ = app->id(); [self addMenuItems:app]; @@ -543,6 +594,7 @@ - (void)appBecameMain:(const Extension*)app { } - (void)chromeBecameMain { +#if 0 if (appId_.empty()) return; @@ -553,6 +605,7 @@ - (void)chromeBecameMain { FROM_HERE, base::Bind(&SetChromeCyclesWindows, ++g_window_cycle_sequence_number)); } +#endif } - (void)addMenuItems:(const Extension*)app { @@ -567,14 +620,15 @@ - (void)addMenuItems:(const Extension*)app { [aboutDoppelganger_ enableForApp:app]; [hideDoppelganger_ enableForApp:app]; [quitDoppelganger_ enableForApp:app]; - [newDoppelganger_ enableForApp:app]; - [openDoppelganger_ enableForApp:app]; - [closeWindowDoppelganger_ enableForApp:app]; + //[newDoppelganger_ enableForApp:app]; + //[openDoppelganger_ enableForApp:app]; + //[closeWindowDoppelganger_ enableForApp:app]; [appMenuItem_ setTitle:base::SysUTF8ToNSString(appId_)]; [[appMenuItem_ submenu] setTitle:title]; [mainMenu addItem:appMenuItem_]; +#if 0 [mainMenu addItem:fileMenuItem_]; SetItemWithTagVisible(editMenuItem_, @@ -582,23 +636,28 @@ - (void)addMenuItems:(const Extension*)app { app->is_hosted_app(), true); SetItemWithTagVisible(editMenuItem_, IDC_FIND_MENU, app->is_hosted_app(), false); +#endif [mainMenu addItem:editMenuItem_]; +#if 0 if (app->is_hosted_app()) { [mainMenu addItem:viewMenuItem_]; [mainMenu addItem:historyMenuItem_]; } +#endif [mainMenu addItem:windowMenuItem_]; } - (void)removeMenuItems { NSMenu* mainMenu = [NSApp mainMenu]; [mainMenu removeItem:appMenuItem_]; - [mainMenu removeItem:fileMenuItem_]; + //[mainMenu removeItem:fileMenuItem_]; +#if 0 if ([mainMenu indexOfItem:viewMenuItem_] >= 0) [mainMenu removeItem:viewMenuItem_]; if ([mainMenu indexOfItem:historyMenuItem_] >= 0) [mainMenu removeItem:historyMenuItem_]; +#endif [mainMenu removeItem:editMenuItem_]; [mainMenu removeItem:windowMenuItem_]; @@ -609,9 +668,9 @@ - (void)removeMenuItems { [aboutDoppelganger_ disable]; [hideDoppelganger_ disable]; [quitDoppelganger_ disable]; - [newDoppelganger_ disable]; - [openDoppelganger_ disable]; - [closeWindowDoppelganger_ disable]; + //[newDoppelganger_ disable]; + //[openDoppelganger_ disable]; + //[closeWindowDoppelganger_ disable]; } - (void)quitCurrentPlatformApp { @@ -619,7 +678,7 @@ - (void)quitCurrentPlatformApp { AppWindowRegistryUtil::GetAppWindowForNativeWindowAnyProfile( [NSApp keyWindow]); if (appWindow) { - apps::ExtensionAppShimHandler::QuitAppForWindow(appWindow); + apps::ExtensionAppShimHandler::QuitAppForWindow(appWindow, true); } else { Browser* browser = chrome::FindBrowserWithWindow([NSApp keyWindow]); const Extension* extension = @@ -654,4 +713,12 @@ - (void)focusCurrentPlatformApp { apps::ExtensionAppShimHandler::FocusAppForWindow(appWindow); } +- (void)showDevtools { + extensions::AppWindow* appWindow = + AppWindowRegistryUtil::GetAppWindowForNativeWindowAnyProfile( + [NSApp keyWindow]); + if (appWindow) + DevToolsWindow::OpenDevToolsWindow(appWindow->web_contents()); +} + @end diff --git a/chrome/browser/ui/cocoa/apps/native_app_window_cocoa.h b/chrome/browser/ui/cocoa/apps/native_app_window_cocoa.h index 594a3f7b22f7a..38d38a7b18eff 100644 --- a/chrome/browser/ui/cocoa/apps/native_app_window_cocoa.h +++ b/chrome/browser/ui/cocoa/apps/native_app_window_cocoa.h @@ -46,6 +46,7 @@ class SkRegion; - (BOOL)handledByExtensionCommand:(NSEvent*)event priority:(ui::AcceleratorManager::HandlerPriority)priority; +- (void)closeAllWindowsQuit:(id)sender; @end // Cocoa bridge to AppWindow. @@ -76,10 +77,13 @@ class NativeAppWindowCocoa : public extensions::NativeAppWindow, void SetBounds(const gfx::Rect& bounds) override; void FlashFrame(bool flash) override; bool IsAlwaysOnTop() const override; + void SetShowInTaskbar(bool show) override; // Called when the window is about to be closed. void WindowWillClose(); + bool NWCanClose(bool user_force = false); + // Called when the window is focused. void WindowDidBecomeKey(); @@ -126,6 +130,8 @@ class NativeAppWindowCocoa : public extensions::NativeAppWindow, protected: // NativeAppWindow implementation. void SetFullscreen(int fullscreen_types) override; + void SetResizable(bool flag) override; + bool IsResizable() const override; bool IsFullscreenOrPending() const override; void UpdateWindowIcon() override; void UpdateWindowTitle() override; @@ -186,7 +192,9 @@ class NativeAppWindowCocoa : public extensions::NativeAppWindow, // Hides the window unconditionally. Used by Hide and HideWithApp. void HideWithoutMarkingHidden(); +public: extensions::AppWindow* app_window_; // weak - AppWindow owns NativeAppWindow. +private: bool has_frame_; diff --git a/chrome/browser/ui/cocoa/apps/native_app_window_cocoa.mm b/chrome/browser/ui/cocoa/apps/native_app_window_cocoa.mm index a9d9a065a427c..757232a65f2e6 100644 --- a/chrome/browser/ui/cocoa/apps/native_app_window_cocoa.mm +++ b/chrome/browser/ui/cocoa/apps/native_app_window_cocoa.mm @@ -16,8 +16,12 @@ #import "chrome/browser/ui/cocoa/chrome_event_processing_window.h" #include "chrome/browser/ui/cocoa/extensions/extension_keybinding_registry_cocoa.h" #include "chrome/browser/ui/cocoa/extensions/extension_view_mac.h" +#import "chrome/browser/ui/cocoa/full_size_content_window.h" #include "chrome/common/chrome_switches.h" #include "content/public/browser/native_web_keyboard_event.h" +#include "content/public/browser/render_view_host.h" +#include "content/public/browser/render_widget_host.h" +#include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "extensions/common/extension.h" #include "skia/ext/skia_utils_mac.h" @@ -25,6 +29,9 @@ #import "ui/gfx/mac/nswindow_frame_controls.h" #include "ui/gfx/skia_util.h" +#include "ui/display/screen.h" +#include "content/nw/src/nw_content_mac.h" + // NOTE: State Before Update. // // Internal state, such as |is_maximized_|, must be set before the window @@ -43,12 +50,18 @@ // desired size. using extensions::AppWindow; +using extensions::AppWindowRegistry; @interface NSWindow (NSPrivateApis) - (void)setBottomCornerRounded:(BOOL)rounded; - (BOOL)_isTitleHidden; @end +namespace content { + extern bool g_support_transparency; + extern bool g_force_cpu_draw; +} + namespace { const int kActivateThrottlePeriodSeconds = 2; @@ -102,6 +115,12 @@ - (void)setTitlebarBackgroundView:(NSView*)view { titlebar_background_view_.reset([view retain]); } +- (BOOL)windowShouldClose:(id)sender { + if (appWindow_ && !appWindow_->NWCanClose()) + return NO; + return YES; +} + - (void)windowWillClose:(NSNotification*)notification { if (appWindow_) appWindow_->WindowWillClose(); @@ -181,6 +200,24 @@ - (BOOL)handledByExtensionCommand:(NSEvent*)event return NO; } +// this function is for createMacBuiltin only +- (void)closeAllWindowsQuit:(id)sender { + if (!appWindow_) + return; + AppWindowRegistry* registry = AppWindowRegistry::Get(appWindow_->app_window_->browser_context()); + if (!registry) + return; + + AppWindowRegistry::AppWindowList windows = + registry->GetAppWindowsForApp(appWindow_->app_window_->GetExtension()->id()); + + for (AppWindow* window : windows) { + // passing true for createMacBuiltin: https://github.com/nwjs/nw.js/issues/4580#issuecomment-199236153 + if (window->NWCanClose(true)) + window->GetBaseWindow()->Close(); + } +} + @end @interface AppNSWindow : ChromeEventProcessingWindow @@ -191,7 +228,7 @@ @implementation AppNSWindow // Similar to ChromeBrowserWindow, don't draw the title, but allow it to be seen // in menus, Expose, etc. - (BOOL)_isTitleHidden { - return YES; + return NO; } @end @@ -219,6 +256,10 @@ - (NSRect)contentRectForFrameRect:(NSRect)frameRect { return frameRect; } +- (BOOL)_isTitleHidden { + return YES; +} + @end @interface ControlRegionView : NSView @@ -274,7 +315,7 @@ - (void)setMouseDownCanMoveWindow:(BOOL)can_move; if (extension) name = extension->name(); [window setTitle:base::SysUTF8ToNSString(name)]; - [[window contentView] setWantsLayer:YES]; + [[window contentView] setWantsLayer:!content::g_force_cpu_draw]; if (params.always_on_top) gfx::SetNSWindowAlwaysOnTop(window, true); @@ -284,6 +325,12 @@ - (void)setMouseDownCanMoveWindow:(BOOL)can_move; window_controller_.reset( [[NativeAppWindowController alloc] initWithWindow:window]); + + if (content::g_support_transparency && params.alpha_enabled) { + [window setHasShadow: NO]; + [window setOpaque: NO]; + [window setBackgroundColor: [NSColor clearColor]]; + } if (has_frame_ && has_frame_color_) { TitlebarBackgroundView* view = @@ -303,7 +350,12 @@ - (void)setMouseDownCanMoveWindow:(BOOL)can_move; // We can now compute the precise window bounds and constraints. gfx::Insets insets = GetFrameInsets(); - SetBounds(params.GetInitialWindowBounds(insets)); + gfx::Rect bounds = params.GetInitialWindowBounds(insets); + if (params.position == AppWindow::POS_MOUSE) { + gfx::Point cursor_pos(display::Screen::GetScreen()->GetCursorScreenPoint()); + bounds.set_origin(cursor_pos); + } + SetBounds(bounds); SetContentSizeConstraints(params.GetContentMinimumSize(insets), params.GetContentMaximumSize(insets)); @@ -344,7 +396,9 @@ - (void)setMouseDownCanMoveWindow:(BOOL)can_move; NSView* frameView = [[window() contentView] superview]; [view setFrame:[frameView bounds]]; + BOOL old = [FullSizeContentWindow setDisableSymbolication:YES]; [frameView addSubview:view]; + [FullSizeContentWindow setDisableSymbolication:old]; [[window() standardWindowButton:NSWindowZoomButton] setHidden:YES]; [[window() standardWindowButton:NSWindowMiniaturizeButton] setHidden:YES]; @@ -380,6 +434,10 @@ - (void)setMouseDownCanMoveWindow:(BOOL)can_move; return is_fullscreen_; } +void NativeAppWindowCocoa::SetShowInTaskbar(bool show) { + NWSetNSWindowShowInTaskbar(this, show); +} + void NativeAppWindowCocoa::SetFullscreen(int fullscreen_types) { bool fullscreen = (fullscreen_types != AppWindow::FULLSCREEN_TYPE_NONE); if (fullscreen == is_fullscreen_) @@ -563,6 +621,16 @@ - (void)setMouseDownCanMoveWindow:(BOOL)can_move; event.GetType() == content::NativeWebKeyboardEvent::kChar) { return; } + + // NW fix + // Simple key press events without modifiers should be sent to the menu. + // See https://github.com/nwjs/nw.js/issues/4837 + NSEvent* nsEvent = event.os_event; + if ([nsEvent type] == NSKeyDown) { + if ([[NSApp mainMenu] performKeyEquivalent:nsEvent]) + return; + } + [window() redispatchKeyEvent:event.os_event]; } @@ -622,6 +690,14 @@ - (void)setMouseDownCanMoveWindow:(BOOL)can_move; void NativeAppWindowCocoa::RenderViewCreated(content::RenderViewHost* rvh) { if (IsActive()) WebContents()->RestoreFocus(); + if (content::g_support_transparency && + app_window_->requested_alpha_enabled() && CanHaveAlphaEnabled()) { + content::RenderWidgetHostView* view = rvh->GetWidget()->GetView(); + // Workaround, SetBackgroundColor is "blocked" if the previous color is the same + // So set it to (0,1,1,1) then to transparent + view->SetBackgroundColor(SkColorSetARGB(0,1,1,1)); + view->SetBackgroundColor(SK_ColorTRANSPARENT); + } } bool NativeAppWindowCocoa::IsFrameless() const { @@ -660,7 +736,7 @@ - (void)setMouseDownCanMoveWindow:(BOOL)can_move; } bool NativeAppWindowCocoa::CanHaveAlphaEnabled() const { - return false; + return content::g_support_transparency ? [window() isOpaque] == NO : false; } void NativeAppWindowCocoa::SetActivateOnPointer(bool activate_on_pointer) { @@ -697,6 +773,10 @@ - (void)setMouseDownCanMoveWindow:(BOOL)can_move; app_window_->OnNativeClose(); } +bool NativeAppWindowCocoa::NWCanClose(bool user_force) { + return app_window_->NWCanClose(user_force); +} + void NativeAppWindowCocoa::WindowDidBecomeKey() { app_window_->OnNativeWindowActivated(); @@ -786,7 +866,8 @@ - (void)setMouseDownCanMoveWindow:(BOOL)can_move; void NativeAppWindowCocoa::HideWithApp() { is_hidden_with_app_ = true; - HideWithoutMarkingHidden(); + [NSApp hide:nil]; +// HideWithoutMarkingHidden(); } gfx::Size NativeAppWindowCocoa::GetContentMinimumSize() const { @@ -797,6 +878,25 @@ - (void)setMouseDownCanMoveWindow:(BOOL)can_move; return size_constraints_.GetMaximumSize(); } +void NativeAppWindowCocoa::SetResizable(bool flag) { + is_resizable_ = flag; + gfx::Size min_size = size_constraints_.GetMinimumSize(); + gfx::Size max_size = size_constraints_.GetMaximumSize(); + + shows_resize_controls_ = + is_resizable_ && !size_constraints_.HasFixedSize(); + shows_fullscreen_controls_ = + is_resizable_ && !size_constraints_.HasMaximumSize() && has_frame_; + + gfx::ApplyNSWindowSizeConstraints(window(), min_size, max_size, + shows_resize_controls_, + shows_fullscreen_controls_); +} + +bool NativeAppWindowCocoa::IsResizable() const { + return is_resizable_; +} + void NativeAppWindowCocoa::SetContentSizeConstraints( const gfx::Size& min_size, const gfx::Size& max_size) { // Update the size constraints. diff --git a/chrome/browser/ui/cocoa/browser_window_cocoa.mm b/chrome/browser/ui/cocoa/browser_window_cocoa.mm index cb61d3af6005e..7e55b4449d477 100644 --- a/chrome/browser/ui/cocoa/browser_window_cocoa.mm +++ b/chrome/browser/ui/cocoa/browser_window_cocoa.mm @@ -139,6 +139,8 @@ - (void)validateText:(NSString*)text { initial_show_state_(ui::SHOW_STATE_DEFAULT), attention_request_id_(0) { + CHECK(browser->is_type_popup()) << "opening browser window."; + gfx::Rect bounds; chrome::GetSavedWindowBoundsAndShowState(browser_, &bounds, @@ -644,6 +646,7 @@ - (void)validateText:(NSString*)text { translate::TranslateStep step, translate::TranslateErrors::Type error_type, bool is_user_gesture) { +#if 0 ChromeTranslateClient* chrome_translate_client = ChromeTranslateClient::FromWebContents(contents); translate::LanguageState& language_state = @@ -654,6 +657,7 @@ - (void)validateText:(NSString*)text { step:step errorType:error_type]; +#endif return ShowTranslateBubbleResult::SUCCESS; } diff --git a/chrome/browser/ui/cocoa/browser_window_controller.mm b/chrome/browser/ui/cocoa/browser_window_controller.mm index 835fd975b8dfe..983be863985fa 100644 --- a/chrome/browser/ui/cocoa/browser_window_controller.mm +++ b/chrome/browser/ui/cocoa/browser_window_controller.mm @@ -1627,6 +1627,7 @@ - (void)showTranslateBubbleForWebContents:(content::WebContents*)contents step:(translate::TranslateStep)step errorType:(translate::TranslateErrors::Type) errorType { +#if 0 // TODO(hajimehoshi): The similar logic exists at TranslateBubbleView:: // ShowBubble. This should be unified. if (translateBubbleController_) { @@ -1670,6 +1671,7 @@ - (void)showTranslateBubbleForWebContents:(content::WebContents*)contents selector:@selector(translateBubbleWindowWillClose:) name:NSWindowWillCloseNotification object:[translateBubbleController_ window]]; +#endif } - (void)dismissPermissionBubble { diff --git a/chrome/browser/ui/cocoa/full_size_content_window.h b/chrome/browser/ui/cocoa/full_size_content_window.h index 078d9fbb22556..4c1b9a0a36779 100644 --- a/chrome/browser/ui/cocoa/full_size_content_window.h +++ b/chrome/browser/ui/cocoa/full_size_content_window.h @@ -41,6 +41,8 @@ // [window contentView] to the given frame. - (void)forceContentViewFrame:(NSRect)frame; ++ (BOOL)setDisableSymbolication:(BOOL)sym; + @end #endif // CHROME_BROWSER_UI_COCOA_FULL_SIZE_CONTENT_WINDOW_H_ diff --git a/chrome/browser/ui/cocoa/full_size_content_window.mm b/chrome/browser/ui/cocoa/full_size_content_window.mm index 3b4c82b2e1e22..b41f5e0b7fc21 100644 --- a/chrome/browser/ui/cocoa/full_size_content_window.mm +++ b/chrome/browser/ui/cocoa/full_size_content_window.mm @@ -174,6 +174,12 @@ - (void)forceContentViewFrame:(NSRect)frame { } } ++ (BOOL)setDisableSymbolication:(BOOL)sym { + BOOL old = g_disable_callstacksymbols; + g_disable_callstacksymbols = sym; + return old; +} + #pragma mark - Private Methods + (BOOL)shouldUseFullSizeContentViewForStyle:(NSUInteger)windowStyle { diff --git a/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm b/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm index 34466bebf2039..21722b87c6de3 100644 --- a/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm +++ b/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm @@ -666,6 +666,7 @@ new ManagePasswordsDecoration(command_updater, this)), } void LocationBarViewMac::UpdateTranslateDecoration() { +#if 0 if (!TranslateService::IsTranslateBubbleEnabled()) return; @@ -679,6 +680,7 @@ new ManagePasswordsDecoration(command_updater, this)), translate_decoration_->SetVisible(enabled); translate_decoration_->SetLit(language_state.IsPageTranslated(), IsLocationBarDark()); +#endif } bool LocationBarViewMac::UpdateZoomDecoration(bool default_zoom_changed) { diff --git a/chrome/browser/ui/cocoa/permission_bubble/chooser_bubble_ui_cocoa.h b/chrome/browser/ui/cocoa/permission_bubble/chooser_bubble_ui_cocoa.h index eec1f13f09930..d8a8a8f5e4456 100644 --- a/chrome/browser/ui/cocoa/permission_bubble/chooser_bubble_ui_cocoa.h +++ b/chrome/browser/ui/cocoa/permission_bubble/chooser_bubble_ui_cocoa.h @@ -16,6 +16,10 @@ class Browser; @class ChooserBubbleUiController; class ChooserController; +namespace extensions { +class AppWindow; +} + // ChooserBubbleUiCocoa implements a chooser-based permission model. // It uses |NSTableView| to show a list of options for user to grant // permission. It can be used by the WebUSB or WebBluetooth APIs. @@ -23,6 +27,7 @@ class ChooserController; class ChooserBubbleUiCocoa : public BubbleUi { public: ChooserBubbleUiCocoa(Browser* browser, + extensions::AppWindow* app_window, std::unique_ptr chooser_controller); ~ChooserBubbleUiCocoa() override; @@ -36,6 +41,7 @@ class ChooserBubbleUiCocoa : public BubbleUi { private: Browser* browser_; // Weak. + extensions::AppWindow* app_window_; // Cocoa-side chooser bubble UI controller. Weak, as it will close itself. ChooserBubbleUiController* chooser_bubble_ui_controller_; diff --git a/chrome/browser/ui/cocoa/permission_bubble/chooser_bubble_ui_cocoa.mm b/chrome/browser/ui/cocoa/permission_bubble/chooser_bubble_ui_cocoa.mm index 8a962b27aa3f6..e07d08804720a 100644 --- a/chrome/browser/ui/cocoa/permission_bubble/chooser_bubble_ui_cocoa.mm +++ b/chrome/browser/ui/cocoa/permission_bubble/chooser_bubble_ui_cocoa.mm @@ -4,6 +4,7 @@ #import "chrome/browser/ui/cocoa/permission_bubble/chooser_bubble_ui_cocoa.h" +#include "extensions/browser/app_window/app_window.h" #include #include @@ -41,10 +42,12 @@ @interface ChooserBubbleUiController NSButton* cancelButton_; // Weak. Browser* browser_; // Weak. + extensions::AppWindow* app_window_; } // Designated initializer. |browser| and |bridge| must both be non-nil. - (id)initWithBrowser:(Browser*)browser + appWindow:(extensions::AppWindow*)app_window chooserController:(std::unique_ptr)chooserController bridge:(ChooserBubbleUiCocoa*)bridge; @@ -82,13 +85,15 @@ - (void)onCancel:(id)sender; @implementation ChooserBubbleUiController - (id)initWithBrowser:(Browser*)browser + appWindow:(extensions::AppWindow*)app_window chooserController:(std::unique_ptr)chooserController bridge:(ChooserBubbleUiCocoa*)bridge { - DCHECK(browser); + //DCHECK(browser); DCHECK(chooserController); DCHECK(bridge); browser_ = browser; + app_window_ = app_window; base::scoped_nsobject window([[InfoBubbleWindow alloc] initWithContentRect:ui::kWindowSizeDeterminedLater @@ -225,7 +230,7 @@ - (NSPoint)getExpectedAnchorPoint { } - (bool)hasLocationBar { - return HasVisibleLocationBarForBrowser(browser_); + return false; //return HasVisibleLocationBarForBrowser(browser_); } - (info_bubble::BubbleArrowLocation)getExpectedArrowLocation { @@ -234,8 +239,12 @@ - (bool)hasLocationBar { } - (NSWindow*)getExpectedParentWindow { - DCHECK(browser_->window()); - return browser_->window()->GetNativeWindow(); + if (browser_) { + DCHECK(browser_->window()); + return browser_->window()->GetNativeWindow(); + } else { + return app_window_->GetNativeWindow(); + } } + (CGFloat)matchWidthsOf:(NSView*)viewA andOf:(NSView*)viewB { @@ -275,13 +284,16 @@ - (void)onCancel:(id)sender { ChooserBubbleUiCocoa::ChooserBubbleUiCocoa( Browser* browser, + extensions::AppWindow* app_window, std::unique_ptr chooser_controller) : browser_(browser), + app_window_(app_window), chooser_bubble_ui_controller_(nil) { - DCHECK(browser_); + //DCHECK(browser_); DCHECK(chooser_controller); chooser_bubble_ui_controller_ = [[ChooserBubbleUiController alloc] initWithBrowser:browser_ + appWindow:app_window_ chooserController:std::move(chooser_controller) bridge:this]; } diff --git a/chrome/browser/ui/cocoa/permission_bubble/chooser_bubble_ui_views_mac.mm b/chrome/browser/ui/cocoa/permission_bubble/chooser_bubble_ui_views_mac.mm index 507dd80b32bc5..92c404d378e83 100644 --- a/chrome/browser/ui/cocoa/permission_bubble/chooser_bubble_ui_views_mac.mm +++ b/chrome/browser/ui/cocoa/permission_bubble/chooser_bubble_ui_views_mac.mm @@ -27,17 +27,18 @@ std::unique_ptr ChooserBubbleDelegate::BuildBubbleUi() { if (!ui::MaterialDesignController::IsSecondaryUiMaterial()) { return base::MakeUnique( - browser_, std::move(chooser_controller_)); + browser_, app_window_, std::move(chooser_controller_)); } - return base::MakeUnique(browser_, + return base::MakeUnique(browser_, app_window_, std::move(chooser_controller_)); } void ChooserBubbleUi::CreateAndShow(views::BubbleDialogDelegateView* delegate) { // Set |parent_window_| because some valid anchors can become hidden. - gfx::NativeView parent = - platform_util::GetViewForWindow(browser_->window()->GetNativeWindow()); - DCHECK(parent); + gfx::NativeView parent = nullptr; + if (browser_) + parent = platform_util::GetViewForWindow(browser_->window()->GetNativeWindow()); + //DCHECK(parent); delegate->set_parent_window(parent); views::BubbleDialogDelegateView::CreateBubble(delegate)->Show(); KeepBubbleAnchored(delegate); diff --git a/chrome/browser/ui/cocoa/status_icons/status_icon_mac.h b/chrome/browser/ui/cocoa/status_icons/status_icon_mac.h index 19be82175c060..995061e7b6001 100644 --- a/chrome/browser/ui/cocoa/status_icons/status_icon_mac.h +++ b/chrome/browser/ui/cocoa/status_icons/status_icon_mac.h @@ -36,7 +36,7 @@ class StatusIconMac : public StatusIcon { protected: // Overridden from StatusIcon. - void UpdatePlatformContextMenu(StatusIconMenuModel* model) override; + void UpdatePlatformContextMenu(ui::MenuModel* model) override; private: FRIEND_TEST_ALL_PREFIXES(StatusIconMacTest, CreateMenu); diff --git a/chrome/browser/ui/cocoa/status_icons/status_icon_mac.mm b/chrome/browser/ui/cocoa/status_icons/status_icon_mac.mm index f0566febac48f..cd98fc7ecba6c 100644 --- a/chrome/browser/ui/cocoa/status_icons/status_icon_mac.mm +++ b/chrome/browser/ui/cocoa/status_icons/status_icon_mac.mm @@ -96,7 +96,7 @@ - (void)handleClick:(id)sender { return menu_.get() != nil; } -void StatusIconMac::UpdatePlatformContextMenu(StatusIconMenuModel* model) { +void StatusIconMac::UpdatePlatformContextMenu(ui::MenuModel* model) { if (!model) { menu_.reset(); } else { diff --git a/chrome/browser/ui/libgtkui/app_indicator_icon.cc b/chrome/browser/ui/libgtkui/app_indicator_icon.cc index f33ccd56f784a..90c93d2cfd4f2 100644 --- a/chrome/browser/ui/libgtkui/app_indicator_icon.cc +++ b/chrome/browser/ui/libgtkui/app_indicator_icon.cc @@ -238,7 +238,6 @@ void AppIndicatorIcon::SetImage(const gfx::ImageSkia& image) { } void AppIndicatorIcon::SetToolTip(const base::string16& tool_tip) { - DCHECK(!tool_tip_.empty()); tool_tip_ = base::UTF16ToUTF8(tool_tip); UpdateClickActionReplacementMenuItem(); } @@ -383,8 +382,8 @@ void AppIndicatorIcon::UpdateClickActionReplacementMenuItem() { if (!delegate()->HasClickAction() && menu_model_) return; - DCHECK(!tool_tip_.empty()); - menu_->UpdateClickActionReplacementMenuItem( + if(!tool_tip_.empty()) + menu_->UpdateClickActionReplacementMenuItem( tool_tip_.c_str(), base::Bind(&AppIndicatorIcon::OnClickActionReplacementMenuItemActivated, base::Unretained(this))); diff --git a/chrome/browser/ui/libgtkui/select_file_dialog_impl_gtk.cc b/chrome/browser/ui/libgtkui/select_file_dialog_impl_gtk.cc index 059d419f9724f..62ae2a301cb92 100644 --- a/chrome/browser/ui/libgtkui/select_file_dialog_impl_gtk.cc +++ b/chrome/browser/ui/libgtkui/select_file_dialog_impl_gtk.cc @@ -325,12 +325,12 @@ GtkWidget* SelectFileDialogImplGTK::CreateSelectFolderDialog( std::string title_string = title; if (title_string.empty()) { title_string = - (type == SELECT_UPLOAD_FOLDER) + (false) ? l10n_util::GetStringUTF8(IDS_SELECT_UPLOAD_FOLDER_DIALOG_TITLE) : l10n_util::GetStringUTF8(IDS_SELECT_FOLDER_DIALOG_TITLE); } std::string accept_button_label = - (type == SELECT_UPLOAD_FOLDER) + (false) ? l10n_util::GetStringUTF8( IDS_SELECT_UPLOAD_FOLDER_DIALOG_UPLOAD_BUTTON) : "_Open"; diff --git a/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc b/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc index 25c5cf7708315..831b756fe94b4 100644 --- a/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc +++ b/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc @@ -438,7 +438,8 @@ void ManagePasswordsUIController::DidFinishNavigation( } void ManagePasswordsUIController::WasHidden() { - TabDialogs::FromWebContents(web_contents())->HideManagePasswordsBubble(); + if (TabDialogs::FromWebContents(web_contents())) + TabDialogs::FromWebContents(web_contents())->HideManagePasswordsBubble(); } void ManagePasswordsUIController::ShowBubbleWithoutUserInteraction() { diff --git a/chrome/browser/ui/permission_bubble/chooser_bubble_delegate.cc b/chrome/browser/ui/permission_bubble/chooser_bubble_delegate.cc index 121eb179489f1..7adb3966f9832 100644 --- a/chrome/browser/ui/permission_bubble/chooser_bubble_delegate.cc +++ b/chrome/browser/ui/permission_bubble/chooser_bubble_delegate.cc @@ -3,6 +3,7 @@ // found in the LICENSE file. #include "chrome/browser/ui/permission_bubble/chooser_bubble_delegate.h" +#include "extensions/browser/app_window/app_window_registry.h" #include "chrome/browser/chooser_controller/chooser_controller.h" #include "chrome/browser/ui/browser.h" @@ -15,7 +16,14 @@ ChooserBubbleDelegate::ChooserBubbleDelegate( : owning_frame_(owner), browser_(chrome::FindBrowserWithWebContents( content::WebContents::FromRenderFrameHost(owner))), - chooser_controller_(std::move(chooser_controller)) {} + app_window_(nullptr), + chooser_controller_(std::move(chooser_controller)) { + if (!browser_) { + content::WebContents* web_contents = (content::WebContents*)content::WebContents::FromRenderFrameHost((content::RenderFrameHost*)owning_frame_); + extensions::AppWindowRegistry* registry = extensions::AppWindowRegistry::Get(web_contents->GetBrowserContext()); + app_window_ = registry->GetAppWindowForWebContents(web_contents); + } +} ChooserBubbleDelegate::~ChooserBubbleDelegate() {} diff --git a/chrome/browser/ui/permission_bubble/chooser_bubble_delegate.h b/chrome/browser/ui/permission_bubble/chooser_bubble_delegate.h index 134cda004c0bc..5d84893da4632 100644 --- a/chrome/browser/ui/permission_bubble/chooser_bubble_delegate.h +++ b/chrome/browser/ui/permission_bubble/chooser_bubble_delegate.h @@ -15,6 +15,10 @@ namespace content { class RenderFrameHost; } +namespace extensions { + class AppWindow; +} + // ChooserBubbleDelegate overrides GetName() to identify the bubble // you define for collecting metrics. Create an instance of this // class and pass it to BubbleManager::ShowBubble() to show the bubble. @@ -32,6 +36,7 @@ class ChooserBubbleDelegate : public BubbleDelegate { private: const content::RenderFrameHost* const owning_frame_; Browser* browser_; + extensions::AppWindow* app_window_; // |chooser_controller_| is not owned by this class, it is owned by // DeviceChooserContentView[Cocoa]. // This field only temporarily owns the ChooserController. It is moved diff --git a/chrome/browser/ui/scoped_tabbed_browser_displayer.cc b/chrome/browser/ui/scoped_tabbed_browser_displayer.cc index 9ad5bffbe9aca..239d6c610381c 100644 --- a/chrome/browser/ui/scoped_tabbed_browser_displayer.cc +++ b/chrome/browser/ui/scoped_tabbed_browser_displayer.cc @@ -13,7 +13,7 @@ namespace chrome { ScopedTabbedBrowserDisplayer::ScopedTabbedBrowserDisplayer(Profile* profile) { browser_ = FindTabbedBrowser(profile, false); if (!browser_) - browser_ = new Browser(Browser::CreateParams(profile, true)); + browser_ = new Browser(Browser::CreateParams(Browser::TYPE_POPUP, profile, true)); } ScopedTabbedBrowserDisplayer::~ScopedTabbedBrowserDisplayer() { diff --git a/chrome/browser/ui/signin_view_controller_delegate.cc b/chrome/browser/ui/signin_view_controller_delegate.cc index 23d414811d44f..0cc759cf9dced 100644 --- a/chrome/browser/ui/signin_view_controller_delegate.cc +++ b/chrome/browser/ui/signin_view_controller_delegate.cc @@ -59,6 +59,8 @@ void SigninViewControllerDelegate::ResetSigninViewControllerDelegate() { void SigninViewControllerDelegate::LoadingStateChanged( content::WebContents* source, bool to_different_document) { + if (!source->GetWebUI()) + return; if (CanGoBack(source)) source->GetWebUI()->CallJavascriptFunctionUnsafe( "inline.login.showBackButton"); diff --git a/chrome/browser/ui/startup/startup_browser_creator.cc b/chrome/browser/ui/startup/startup_browser_creator.cc index 2777068c0ef15..55319348746c8 100644 --- a/chrome/browser/ui/startup/startup_browser_creator.cc +++ b/chrome/browser/ui/startup/startup_browser_creator.cc @@ -3,6 +3,8 @@ // found in the LICENSE file. #include "chrome/browser/ui/startup/startup_browser_creator.h" +#include "chrome/browser/spellchecker/spellcheck_factory.h" +#include "content/nw/src/common/shell_switches.h" #include @@ -80,6 +82,15 @@ #include "net/base/port_util.h" #include "printing/features/features.h" +#include "extensions/browser/extension_system.h" +#include "chrome/browser/extensions/component_loader.h" +#include "chrome/browser/extensions/extension_service.h" +#include "chrome/common/extensions/extension_constants.h" +#include "chrome/grit/browser_resources.h" +#include "extensions/common/constants.h" +#include "chrome/browser/ui/extensions/app_launch_params.h" +#include "chrome/browser/ui/extensions/application_launch.h" + #if defined(USE_ASH) #include "ash/shell.h" // nogncheck #endif @@ -559,7 +570,7 @@ std::vector StartupBrowserCreator::GetURLsFromCommandLine( const GURL reset_settings_url = settings_url.Resolve(chrome::kResetProfileSettingsSubPage); url_points_to_an_approved_settings_page = url == reset_settings_url; -#if defined(OS_WIN) +#if 0 // On Windows, also allow a hash for the Chrome Cleanup Tool. const GURL reset_settings_url_with_cct_hash = reset_settings_url.Resolve( std::string("#") + @@ -710,7 +721,7 @@ bool StartupBrowserCreator::ProcessCmdLineImpl( // chrome to shut down. // TODO(jackhou): Do this properly once keep-alive is handled by the // background page of apps. Tracked at http://crbug.com/175381 - if (chrome::GetBrowserCount(last_used_profile) != 0) + // if (chrome::GetBrowserCount(last_used_profile) != 0) return true; } @@ -733,6 +744,46 @@ bool StartupBrowserCreator::ProcessCmdLineImpl( return true; } + if (!process_startup) + return true; + if (command_line.HasSwitch(switches::kEnableSpellChecking)) + SpellcheckServiceFactory::GetForContext(last_used_profile); + + const base::CommandLine::StringVector& params = command_line.GetArgs(); + if (command_line.HasSwitch("nwapp")) { + if (!apps::AppLoadService::Get(last_used_profile)->LoadAndLaunch( + base::FilePath(command_line.GetSwitchValueNative("nwapp")), command_line, cur_dir)) { + return false; + } + return true; + } + + if (!command_line.HasSwitch("nwjs-test-mode")) { + if (params.size() > 0) { + if (!apps::AppLoadService::Get(last_used_profile)->LoadAndLaunch( + base::FilePath(params[0]), command_line, cur_dir)) { + return false; + } + return true; + } else { + ExtensionService* extension_service = + extensions::ExtensionSystem::Get(last_used_profile)->extension_service(); + extensions::ComponentLoader* component_loader = extension_service->component_loader(); + std::string id = component_loader->GetExtensionID(IDR_NWJS_DEFAPP_MANIFEST, + base::FilePath(FILE_PATH_LITERAL("nwjs_default_app"))); + + LOG(INFO) << "loading default app: " << id; + const extensions::Extension* extension = extension_service->GetExtensionById(id, true); + if (!extension) { + LOG(FATAL) << "Failed to load default app"; + return false; + } + OpenApplication( + AppLaunchParams(last_used_profile, extension, extensions::LAUNCH_CONTAINER_WINDOW, + WindowOpenDisposition::NEW_WINDOW, extensions::SOURCE_CHROME_INTERNAL)); + return true; + } + } #if defined(OS_WIN) // Log whether this process was a result of an action in the Windows Jumplist. if (command_line.HasSwitch(switches::kWinJumplistAction)) { diff --git a/chrome/browser/ui/tab_helpers.cc b/chrome/browser/ui/tab_helpers.cc index b565c76b692da..22b3bab32fd41 100644 --- a/chrome/browser/ui/tab_helpers.cc +++ b/chrome/browser/ui/tab_helpers.cc @@ -185,7 +185,7 @@ void TabHelpers::AttachTabHelpers( web_contents, autofill::ChromeAutofillClient::FromWebContents(web_contents)); ChromeSubresourceFilterClient::CreateForWebContents(web_contents); - ChromeTranslateClient::CreateForWebContents(web_contents); + //ChromeTranslateClient::CreateForWebContents(web_contents); CoreTabHelper::CreateForWebContents(web_contents); data_use_measurement::DataUseWebContentsObserver::CreateForWebContents( web_contents); @@ -258,9 +258,11 @@ void TabHelpers::AttachTabHelpers( new ChromePDFWebContentsHelperClient())); PluginObserver::CreateForWebContents(web_contents); SadTabHelper::CreateForWebContents(web_contents); +#if 0 safe_browsing::SafeBrowsingTabObserver::CreateForWebContents(web_contents); safe_browsing::SafeBrowsingNavigationObserver::MaybeCreateForWebContents( web_contents); +#endif TabContentsSyncedTabDelegate::CreateForWebContents(web_contents); TabDialogs::CreateForWebContents(web_contents); ThumbnailTabHelper::CreateForWebContents(web_contents); diff --git a/chrome/browser/ui/toolbar/component_toolbar_actions_factory.cc b/chrome/browser/ui/toolbar/component_toolbar_actions_factory.cc index 75302a2b9e3ec..42933bd44fec2 100644 --- a/chrome/browser/ui/toolbar/component_toolbar_actions_factory.cc +++ b/chrome/browser/ui/toolbar/component_toolbar_actions_factory.cc @@ -25,11 +25,15 @@ const char ComponentToolbarActionsFactory::kMediaRouterActionId[] = "media_router_action"; ComponentToolbarActionsFactory::ComponentToolbarActionsFactory(Profile* profile) +#if defined(NWJS_SDK) : profile_(profile) { if (media_router::MediaRouterEnabled(profile_) && MediaRouterActionController::IsActionShownByPolicy(profile_)) { initial_ids_.insert(kMediaRouterActionId); } +#else + { +#endif } ComponentToolbarActionsFactory::~ComponentToolbarActionsFactory() {} @@ -59,10 +63,11 @@ ComponentToolbarActionsFactory::GetComponentToolbarActionForId( // (since each will have an action in the toolbar or overflow menu), this // should be okay. If this changes, we should rethink this design to have, // e.g., RegisterChromeAction(). +#if defined(NWJS_SDK) if (action_id == kMediaRouterActionId) return std::unique_ptr( new MediaRouterAction(browser, bar)); - +#endif NOTREACHED(); return std::unique_ptr(); } diff --git a/chrome/browser/ui/toolbar/component_toolbar_actions_factory.h b/chrome/browser/ui/toolbar/component_toolbar_actions_factory.h index b9024817a6f72..4783bf849aba0 100644 --- a/chrome/browser/ui/toolbar/component_toolbar_actions_factory.h +++ b/chrome/browser/ui/toolbar/component_toolbar_actions_factory.h @@ -61,9 +61,9 @@ class ComponentToolbarActionsFactory { void UnloadExtension(ExtensionService* service, extensions::ExtensionRegistry* registry, const std::string& extension_id); - +#if defined(NWJS_SDK) Profile* profile_; - +#endif // IDs of component actions that should be added to the toolbar model when it // gets initialized. std::set initial_ids_; diff --git a/chrome/browser/ui/views/apps/app_window_desktop_window_tree_host_win.cc b/chrome/browser/ui/views/apps/app_window_desktop_window_tree_host_win.cc index 1306401674413..42b0d0f821a29 100644 --- a/chrome/browser/ui/views/apps/app_window_desktop_window_tree_host_win.cc +++ b/chrome/browser/ui/views/apps/app_window_desktop_window_tree_host_win.cc @@ -26,6 +26,9 @@ AppWindowDesktopWindowTreeHostWin::~AppWindowDesktopWindowTreeHostWin() { bool AppWindowDesktopWindowTreeHostWin::GetClientAreaInsets( gfx::Insets* insets) const { +#if 1 + return false; +#else // The inset added below is only necessary for the native glass frame, i.e. // not for colored frames drawn by Chrome, or when DWM is disabled. // In fullscreen the frame is not visible. @@ -36,6 +39,7 @@ bool AppWindowDesktopWindowTreeHostWin::GetClientAreaInsets( *insets = app_window_->glass_frame_view()->GetClientAreaInsets(); return true; +#endif } void AppWindowDesktopWindowTreeHostWin::HandleFrameChanged() { @@ -58,6 +62,9 @@ void AppWindowDesktopWindowTreeHostWin::PostHandleMSG(UINT message, } void AppWindowDesktopWindowTreeHostWin::UpdateDWMFrame() { +#if 1 + return; +#else if (!GetWidget()->client_view() || !app_window_->glass_frame_view()) return; @@ -77,4 +84,5 @@ void AppWindowDesktopWindowTreeHostWin::UpdateDWMFrame() { } DwmExtendFrameIntoClientArea(GetHWND(), &margins); +#endif } diff --git a/chrome/browser/ui/views/apps/chrome_native_app_window_views.cc b/chrome/browser/ui/views/apps/chrome_native_app_window_views.cc index ae6f17b2e87ba..928979430907b 100644 --- a/chrome/browser/ui/views/apps/chrome_native_app_window_views.cc +++ b/chrome/browser/ui/views/apps/chrome_native_app_window_views.cc @@ -21,6 +21,14 @@ #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/widget.h" +#if defined(NWJS_SDK) +#include "base/command_line.h" +#include "chrome/browser/devtools/devtools_window.h" +#include "content/nw/src/common/shell_switches.h" +#endif + +#include "ui/display/screen.h" + using extensions::AppWindow; namespace { @@ -37,9 +45,12 @@ struct AcceleratorMapping { }; const AcceleratorMapping kAppWindowAcceleratorMap[] = { - { ui::VKEY_W, ui::EF_CONTROL_DOWN, IDC_CLOSE_WINDOW }, - { ui::VKEY_W, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN, IDC_CLOSE_WINDOW }, + // { ui::VKEY_W, ui::EF_CONTROL_DOWN, IDC_CLOSE_WINDOW }, + // { ui::VKEY_W, ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN, IDC_CLOSE_WINDOW }, { ui::VKEY_F4, ui::EF_ALT_DOWN, IDC_CLOSE_WINDOW }, +#if defined(NWJS_SDK) + { ui::VKEY_F12, ui::EF_NONE, IDC_DEV_TOOLS_TOGGLE }, +#endif }; // These accelerators will only be available in kiosk mode. These allow the @@ -110,6 +121,10 @@ void ChromeNativeAppWindowViews::OnBeforeWidgetInit( views::Widget* widget) { } +bool ChromeNativeAppWindowViews::NWCanClose(bool user_force) const { + return app_window()->NWCanClose(user_force); +} + void ChromeNativeAppWindowViews::OnBeforePanelWidgetInit( views::Widget::InitParams* init_params, views::Widget* widget) { @@ -149,10 +164,23 @@ void ChromeNativeAppWindowViews::InitializeDefaultWindow( bool position_specified = window_bounds.x() != BoundsSpecification::kUnspecifiedPosition && window_bounds.y() != BoundsSpecification::kUnspecifiedPosition; + position_specified |= create_params.position == AppWindow::POS_MOUSE; if (!position_specified) widget()->CenterWindow(window_bounds.size()); - else + else if (create_params.position == AppWindow::POS_MOUSE) { + gfx::Point cursor_pos(display::Screen::GetScreen()->GetCursorScreenPoint()); + window_bounds.set_origin(cursor_pos); + widget()->SetBounds(window_bounds); + }else widget()->SetBounds(window_bounds); + } else { + if (create_params.position == AppWindow::POS_CENTER) + widget()->CenterWindow(gfx::Size(640, 480)); + else if (create_params.position == extensions::AppWindow::POS_MOUSE) { + gfx::Point cursor_pos(display::Screen::GetScreen()->GetCursorScreenPoint()); + gfx::Rect bounds(cursor_pos, gfx::Size(640, 480)); + widget()->SetBounds(bounds); + } } #if defined(OS_CHROMEOS) @@ -250,6 +278,9 @@ bool ChromeNativeAppWindowViews::IsAlwaysOnTop() const { // views::WidgetDelegate implementation. gfx::ImageSkia ChromeNativeAppWindowViews::GetWindowAppIcon() { + gfx::Image icon_override = app_window()->icon_override(); + if (!icon_override.IsEmpty()) + return *icon_override.ToImageSkia(); gfx::Image app_icon = app_window()->app_icon(); if (app_icon.IsEmpty()) return GetWindowIcon(); @@ -258,6 +289,9 @@ gfx::ImageSkia ChromeNativeAppWindowViews::GetWindowAppIcon() { } gfx::ImageSkia ChromeNativeAppWindowViews::GetWindowIcon() { + gfx::Image icon_override = app_window()->icon_override(); + if (!icon_override.IsEmpty()) + return *icon_override.ToImageSkia(); content::WebContents* web_contents = app_window()->web_contents(); if (web_contents) { favicon::FaviconDriver* favicon_driver = @@ -293,6 +327,14 @@ bool ChromeNativeAppWindowViews::AcceleratorPressed( accelerator_table.find(accelerator); DCHECK(iter != accelerator_table.end()); int command_id = iter->second; +#if defined(NWJS_SDK) + content::WebContents* web_contents; + bool enable_devtools = true; + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(switches::kDisableDevTools)) + enable_devtools = false; +#endif switch (command_id) { case IDC_CLOSE_WINDOW: Close(); @@ -308,7 +350,25 @@ bool ChromeNativeAppWindowViews::AcceleratorPressed( case IDC_ZOOM_PLUS: zoom::PageZoom::Zoom(web_view()->GetWebContents(), content::PAGE_ZOOM_IN); return true; - default: +#if defined(NWJS_SDK) + case IDC_DEV_TOOLS: + if (!enable_devtools) + return true; + web_contents = app_window()->web_contents(); + if (web_contents) { + DevToolsWindow::OpenDevToolsWindow(web_contents); + } + return true; + case IDC_DEV_TOOLS_TOGGLE: + if (!enable_devtools) + return true; + web_contents = app_window()->web_contents(); + if (web_contents) { + DevToolsWindow::OpenDevToolsWindow(web_contents, DevToolsToggleAction::Toggle()); + } + return true; +#endif + default: NOTREACHED() << "Unknown accelerator sent to app window."; } return NativeAppWindowViews::AcceleratorPressed(accelerator); diff --git a/chrome/browser/ui/views/apps/chrome_native_app_window_views.h b/chrome/browser/ui/views/apps/chrome_native_app_window_views.h index 7809977edc475..79a174955efc7 100644 --- a/chrome/browser/ui/views/apps/chrome_native_app_window_views.h +++ b/chrome/browser/ui/views/apps/chrome_native_app_window_views.h @@ -51,6 +51,7 @@ class ChromeNativeAppWindowViews views::Widget* widget) override; bool WidgetHasHitTestMask() const override; void GetWidgetHitTestMask(gfx::Path* mask) const override; + bool NWCanClose(bool user_force = false) const override; // views::View implementation. bool AcceleratorPressed(const ui::Accelerator& accelerator) override; diff --git a/chrome/browser/ui/views/apps/glass_app_window_frame_view_win.cc b/chrome/browser/ui/views/apps/glass_app_window_frame_view_win.cc index baf7d8616a5db..bda9fd9bebdb3 100644 --- a/chrome/browser/ui/views/apps/glass_app_window_frame_view_win.cc +++ b/chrome/browser/ui/views/apps/glass_app_window_frame_view_win.cc @@ -62,6 +62,9 @@ gfx::Insets GlassAppWindowFrameViewWin::GetClientAreaInsets() const { } gfx::Rect GlassAppWindowFrameViewWin::GetBoundsForClientView() const { +#if 1 + return bounds(); +#else if (widget_->IsFullscreen()) return bounds(); @@ -70,6 +73,7 @@ gfx::Rect GlassAppWindowFrameViewWin::GetBoundsForClientView() const { insets.top(), std::max(0, width() - insets.left() - insets.right()), std::max(0, height() - insets.top() - insets.bottom())); +#endif } gfx::Rect GlassAppWindowFrameViewWin::GetWindowBoundsForClientBounds( @@ -96,6 +100,11 @@ int GlassAppWindowFrameViewWin::NonClientHitTest(const gfx::Point& point) { if (!bounds().Contains(point)) return HTNOWHERE; + int client_component = widget_->client_view()->NonClientHitTest(point); + if (client_component != HTNOWHERE) + return client_component; + + // Check the frame first, as we allow a small area overlapping the contents // to be used for resize handles. bool can_ever_resize = widget_->widget_delegate() @@ -115,10 +124,6 @@ int GlassAppWindowFrameViewWin::NonClientHitTest(const gfx::Point& point) { if (frame_component != HTNOWHERE) return frame_component; - int client_component = widget_->client_view()->NonClientHitTest(point); - if (client_component != HTNOWHERE) - return client_component; - // Caption is a safe default. return HTCAPTION; } diff --git a/chrome/browser/ui/views/chrome_views_delegate.cc b/chrome/browser/ui/views/chrome_views_delegate.cc index 3b66872678e36..14a73bc6080a8 100644 --- a/chrome/browser/ui/views/chrome_views_delegate.cc +++ b/chrome/browser/ui/views/chrome_views_delegate.cc @@ -4,6 +4,7 @@ #include "chrome/browser/ui/views/chrome_views_delegate.h" +#include "content/nw/src/nw_content.h" #include #include "base/logging.h" @@ -187,8 +188,10 @@ std::string ChromeViewsDelegate::GetApplicationName() { } scoped_refptr -ChromeViewsDelegate::GetBlockingPoolTaskRunner() { - return content::BrowserThread::GetBlockingPool(); +ChromeViewsDelegate::GetBlockingPoolTaskRunner(bool continue_on_shutdown) { + if (!continue_on_shutdown) + return content::BrowserThread::GetBlockingPool(); + return content::BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior(base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN); } #if !defined(OS_CHROMEOS) diff --git a/chrome/browser/ui/views/chrome_views_delegate.h b/chrome/browser/ui/views/chrome_views_delegate.h index 867d5b7d3c643..04b435d6949f6 100644 --- a/chrome/browser/ui/views/chrome_views_delegate.h +++ b/chrome/browser/ui/views/chrome_views_delegate.h @@ -56,7 +56,7 @@ class ChromeViewsDelegate : public views::ViewsDelegate { ui::ContextFactory* GetContextFactory() override; ui::ContextFactoryPrivate* GetContextFactoryPrivate() override; std::string GetApplicationName() override; - scoped_refptr GetBlockingPoolTaskRunner() override; + scoped_refptr GetBlockingPoolTaskRunner(bool continue_on_shutdown = false) override; private: #if defined(OS_WIN) diff --git a/chrome/browser/ui/views/chrome_views_delegate_linux.cc b/chrome/browser/ui/views/chrome_views_delegate_linux.cc index 9c9534f99a5e9..54564e7613ef4 100644 --- a/chrome/browser/ui/views/chrome_views_delegate_linux.cc +++ b/chrome/browser/ui/views/chrome_views_delegate_linux.cc @@ -4,6 +4,8 @@ #include "chrome/browser/ui/views/chrome_views_delegate.h" +#include "content/nw/src/nw_content.h" + #include "chrome/browser/ui/views/native_widget_factory.h" #include "chrome/grit/chrome_unscaled_resources.h" #include "ui/base/resource/resource_bundle.h" @@ -21,6 +23,9 @@ views::NativeWidget* ChromeViewsDelegate::CreateNativeWidget( } gfx::ImageSkia* ChromeViewsDelegate::GetDefaultWindowIcon() const { + gfx::ImageSkia* ret = nw::GetAppIcon(); + if (ret) + return ret; ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); return rb.GetImageSkiaNamed(IDR_PRODUCT_LOGO_64); } diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc index 9f2204660dcbf..83aafed82af6e 100644 --- a/chrome/browser/ui/views/frame/browser_view.cc +++ b/chrome/browser/ui/views/frame/browser_view.cc @@ -156,6 +156,9 @@ #include "chrome/browser/ui/views/profiles/profile_chooser_view.h" #endif // !defined(OS_CHROMEOS) +#include "extensions/browser/app_window/app_window.h" +#include "extensions/browser/app_window/app_window_registry.h" + #if defined(USE_AURA) #include "chrome/browser/ui/views/theme_profile_key.h" #include "ui/aura/client/window_parenting_client.h" @@ -469,6 +472,8 @@ BrowserView::~BrowserView() { } void BrowserView::Init(Browser* browser) { + // type popup is for devtools window. that's what we want + CHECK(browser->is_type_popup()) << "opening browser window."; browser_.reset(browser); browser_->tab_strip_model()->AddObserver(this); immersive_mode_controller_.reset(chrome::CreateImmersiveModeController()); @@ -837,7 +842,7 @@ void BrowserView::OnActiveTabChanged(content::WebContents* old_contents, // Update all the UI bits. UpdateTitleBar(); - TranslateBubbleView::CloseCurrentBubble(); + //TranslateBubbleView::CloseCurrentBubble(); ZoomBubbleView::CloseCurrentBubble(); } @@ -1229,6 +1234,7 @@ ShowTranslateBubbleResult BrowserView::ShowTranslateBubble( return ShowTranslateBubbleResult::EDITABLE_FIELD_IS_ACTIVE; } +#if 0 translate::LanguageState& language_state = ChromeTranslateClient::FromWebContents(web_contents)->GetLanguageState(); language_state.SetTranslateEnabled(true); @@ -1238,6 +1244,7 @@ ShowTranslateBubbleResult BrowserView::ShowTranslateBubble( toolbar_->ShowTranslateBubble(web_contents, step, error_type, is_user_gesture); +#endif return ShowTranslateBubbleResult::SUCCESS; } @@ -1705,6 +1712,22 @@ bool BrowserView::ShouldShowWindowTitle() const { } gfx::ImageSkia BrowserView::GetWindowAppIcon() { +#if 1 + if (browser_->is_devtools()) { + WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents(); + DevToolsWindow* devtools_window = DevToolsWindow::AsDevToolsWindow(contents); + if (devtools_window) { + WebContents* inspected_contents = devtools_window->GetInspectedWebContents(); + Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext()); + extensions::AppWindowRegistry* registry = extensions::AppWindowRegistry::Get(profile); + if (registry) { + extensions::AppWindow* app_window = registry->GetAppWindowForWebContents(inspected_contents); + if (app_window) + return app_window->app_icon().AsImageSkia(); + } + } + } +#endif if (browser_->is_app()) { WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents(); extensions::TabHelper* extensions_tab_helper = @@ -1719,8 +1742,21 @@ gfx::ImageSkia BrowserView::GetWindowAppIcon() { gfx::ImageSkia BrowserView::GetWindowIcon() { // Use the default icon for devtools. - if (browser_->is_devtools()) + if (browser_->is_devtools()) { + WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents(); + DevToolsWindow* devtools_window = DevToolsWindow::AsDevToolsWindow(contents); + if (devtools_window) { + WebContents* inspected_contents = devtools_window->GetInspectedWebContents(); + Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext()); + extensions::AppWindowRegistry* registry = extensions::AppWindowRegistry::Get(profile); + if (registry) { + extensions::AppWindow* app_window = registry->GetAppWindowForWebContents(inspected_contents); + if (app_window) + return app_window->app_icon().AsImageSkia(); + } + } return gfx::ImageSkia(); + } if (browser_->is_app() || browser_->is_type_popup()) return browser_->GetCurrentPageIcon().AsImageSkia(); diff --git a/chrome/browser/ui/views/location_bar/location_bar_view.cc b/chrome/browser/ui/views/location_bar/location_bar_view.cc index e9ec8b6970ab7..318fbf364781c 100644 --- a/chrome/browser/ui/views/location_bar/location_bar_view.cc +++ b/chrome/browser/ui/views/location_bar/location_bar_view.cc @@ -241,10 +241,12 @@ void LocationBarView::Init() { save_credit_card_icon_view_->SetVisible(false); AddChildView(save_credit_card_icon_view_); +#if 0 translate_icon_view_ = new TranslateIconView(command_updater()); translate_icon_view_->Init(); translate_icon_view_->SetVisible(false); AddChildView(translate_icon_view_); +#endif star_view_ = new StarView(command_updater(), browser_); star_view_->Init(); @@ -434,7 +436,7 @@ gfx::Size LocationBarView::CalculatePreferredSize() const { // Compute width of omnibox-trailing content. int trailing_width = edge_thickness; trailing_width += IncrementalMinimumWidth(star_view_) + - IncrementalMinimumWidth(translate_icon_view_) + + // IncrementalMinimumWidth(translate_icon_view_) + IncrementalMinimumWidth(save_credit_card_icon_view_) + IncrementalMinimumWidth(manage_passwords_icon_view_) + IncrementalMinimumWidth(zoom_view_); @@ -509,10 +511,12 @@ void LocationBarView::Layout() { trailing_decorations.AddDecoration(vertical_padding, location_height, star_view_); } +#if 0 if (translate_icon_view_->visible()) { trailing_decorations.AddDecoration(vertical_padding, location_height, translate_icon_view_); } +#endif if (save_credit_card_icon_view_->visible()) { trailing_decorations.AddDecoration(vertical_padding, location_height, save_credit_card_icon_view_); @@ -737,6 +741,7 @@ bool LocationBarView::RefreshSaveCreditCardIconView() { } void LocationBarView::RefreshTranslateIcon() { +#if 0 WebContents* web_contents = GetWebContents(); if (!web_contents) return; @@ -747,6 +752,7 @@ void LocationBarView::RefreshTranslateIcon() { translate_icon_view_->SetVisible(enabled); if (!enabled) TranslateBubbleView::CloseCurrentBubble(); +#endif } bool LocationBarView::RefreshManagePasswordsIconView() { diff --git a/chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.cc b/chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.cc index f7d46592bef35..9a0c33b51f9b3 100644 --- a/chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.cc +++ b/chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.cc @@ -4,6 +4,7 @@ #include "chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.h" +#include "extensions/components/native_app_window/native_app_window_views.h" #include #include @@ -180,12 +181,13 @@ void ChooserBubbleUiViewDelegate::UpdateTableView() const { // ChooserBubbleUi ChooserBubbleUi::ChooserBubbleUi( Browser* browser, + void* app_window, std::unique_ptr chooser_controller) - : browser_(browser), chooser_bubble_ui_view_delegate_(nullptr) { - DCHECK(browser_); + : browser_(browser), app_window_((extensions::AppWindow*)app_window), chooser_bubble_ui_view_delegate_(nullptr) { + //DCHECK(browser_); DCHECK(chooser_controller); chooser_bubble_ui_view_delegate_ = new ChooserBubbleUiViewDelegate( - GetAnchorView(), GetAnchorPoint(), GetAnchorArrow(), + nullptr, GetAnchorPoint(), GetAnchorArrow(), std::move(chooser_controller)); } diff --git a/chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.h b/chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.h index 6b413cf6478f6..c64c13a2699e2 100644 --- a/chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.h +++ b/chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.h @@ -18,6 +18,10 @@ class BubbleDialogDelegateView; class View; } +namespace extensions { + class AppWindow; +} + class Browser; class ChooserController; class ChooserBubbleUiViewDelegate; @@ -29,7 +33,7 @@ class ChooserBubbleUiViewDelegate; // BubbleManager. class ChooserBubbleUi : public BubbleUi, public views::WidgetObserver { public: - ChooserBubbleUi(Browser* browser, + ChooserBubbleUi(Browser* browser, void* app_window, std::unique_ptr chooser_controller); ~ChooserBubbleUi() override; @@ -50,6 +54,7 @@ class ChooserBubbleUi : public BubbleUi, public views::WidgetObserver { views::BubbleBorder::Arrow GetAnchorArrow(); Browser* browser_; // Weak. + extensions::AppWindow* app_window_; // Weak. Owned by its parent view. ChooserBubbleUiViewDelegate* chooser_bubble_ui_view_delegate_; diff --git a/chrome/browser/ui/views/permission_bubble/chooser_bubble_ui_views.cc b/chrome/browser/ui/views/permission_bubble/chooser_bubble_ui_views.cc index 1f1c13cc32b63..dd8d1cc90eb61 100644 --- a/chrome/browser/ui/views/permission_bubble/chooser_bubble_ui_views.cc +++ b/chrome/browser/ui/views/permission_bubble/chooser_bubble_ui_views.cc @@ -4,6 +4,8 @@ #include "chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.h" +#include "extensions/components/native_app_window/native_app_window_views.h" + #include "base/macros.h" #include "base/memory/ptr_util.h" #include "chrome/browser/chooser_controller/chooser_controller.h" @@ -22,21 +24,25 @@ // functions provide. std::unique_ptr ChooserBubbleDelegate::BuildBubbleUi() { - return base::MakeUnique(browser_, + return base::MakeUnique(browser_, app_window_, std::move(chooser_controller_)); } void ChooserBubbleUi::CreateAndShow(views::BubbleDialogDelegateView* delegate) { // Set |parent_window_| because some valid anchors can become hidden. - views::Widget* widget = views::Widget::GetWidgetForNativeWindow( + views::Widget* widget = nullptr; + if (browser_) { + widget = views::Widget::GetWidgetForNativeWindow( browser_->window()->GetNativeWindow()); gfx::NativeView parent = widget->GetNativeView(); DCHECK(parent); delegate->set_parent_window(parent); + } views::BubbleDialogDelegateView::CreateBubble(delegate)->Show(); } views::View* ChooserBubbleUi::GetAnchorView() { + if (browser_) { BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser_); if (browser_->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR)) { @@ -48,6 +54,12 @@ views::View* ChooserBubbleUi::GetAnchorView() { return browser_view->exclusive_access_bubble()->GetView(); return browser_view->top_container(); + } else if (app_window_) { + native_app_window::NativeAppWindowViews* native_app_window_views = + static_cast(app_window_->GetBaseWindow()); + return native_app_window_views->web_view(); + } + return nullptr; } gfx::Point ChooserBubbleUi::GetAnchorPoint() { @@ -55,7 +67,7 @@ gfx::Point ChooserBubbleUi::GetAnchorPoint() { } views::BubbleBorder::Arrow ChooserBubbleUi::GetAnchorArrow() { - if (browser_->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR)) + if (browser_ && browser_->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR)) return views::BubbleBorder::TOP_LEFT; return views::BubbleBorder::NONE; } diff --git a/chrome/browser/ui/views/status_icons/status_icon_linux_wrapper.cc b/chrome/browser/ui/views/status_icons/status_icon_linux_wrapper.cc index 4a9eff1dbd197..d1970573b63db 100644 --- a/chrome/browser/ui/views/status_icons/status_icon_linux_wrapper.cc +++ b/chrome/browser/ui/views/status_icons/status_icon_linux_wrapper.cc @@ -10,13 +10,11 @@ StatusIconLinuxWrapper::StatusIconLinuxWrapper( std::unique_ptr status_icon) - : status_icon_(std::move(status_icon)), menu_model_(nullptr) { + : status_icon_(std::move(status_icon)) { status_icon_->set_delegate(this); } StatusIconLinuxWrapper::~StatusIconLinuxWrapper() { - if (menu_model_) - menu_model_->RemoveObserver(this); } void StatusIconLinuxWrapper::SetImage(const gfx::ImageSkia& image) { @@ -63,14 +61,6 @@ StatusIconLinuxWrapper::CreateWrappedStatusIcon( } void StatusIconLinuxWrapper::UpdatePlatformContextMenu( - StatusIconMenuModel* model) { - // If a menu already exists, remove ourself from its oberver list. - if (menu_model_) - menu_model_->RemoveObserver(this); - + ui::MenuModel* model) { status_icon_->UpdatePlatformContextMenu(model); - menu_model_ = model; - - if (model) - model->AddObserver(this); } diff --git a/chrome/browser/ui/views/status_icons/status_icon_linux_wrapper.h b/chrome/browser/ui/views/status_icons/status_icon_linux_wrapper.h index 68704787c4650..487407ceb6202 100644 --- a/chrome/browser/ui/views/status_icons/status_icon_linux_wrapper.h +++ b/chrome/browser/ui/views/status_icons/status_icon_linux_wrapper.h @@ -44,7 +44,7 @@ class StatusIconLinuxWrapper : public StatusIcon, // Invoked after a call to SetContextMenu() to let the platform-specific // subclass update the native context menu based on the new model. If NULL is // passed, subclass should destroy the native context menu. - void UpdatePlatformContextMenu(StatusIconMenuModel* model) override; + void UpdatePlatformContextMenu(ui::MenuModel* model) override; private: // A status icon wrapper should only be created by calling @@ -57,8 +57,6 @@ class StatusIconLinuxWrapper : public StatusIcon, std::unique_ptr status_icon_; - StatusIconMenuModel* menu_model_; - DISALLOW_COPY_AND_ASSIGN(StatusIconLinuxWrapper); }; diff --git a/chrome/browser/ui/views/status_icons/status_icon_win.cc b/chrome/browser/ui/views/status_icons/status_icon_win.cc index 7b98969bef7ce..2024ddc66ef65 100644 --- a/chrome/browser/ui/views/status_icons/status_icon_win.cc +++ b/chrome/browser/ui/views/status_icons/status_icon_win.cc @@ -153,7 +153,7 @@ void StatusIconWin::ForceVisible() { //////////////////////////////////////////////////////////////////////////////// // StatusIconWin, private: -void StatusIconWin::UpdatePlatformContextMenu(StatusIconMenuModel* menu) { +void StatusIconWin::UpdatePlatformContextMenu(ui::MenuModel* menu) { // |menu_model_| is about to be destroyed. Destroy the menu (which closes it) // so that it doesn't attempt to continue using |menu_model_|. menu_runner_.reset(); diff --git a/chrome/browser/ui/views/status_icons/status_icon_win.h b/chrome/browser/ui/views/status_icons/status_icon_win.h index 05e45bc14723e..f4e8778f4ace4 100644 --- a/chrome/browser/ui/views/status_icons/status_icon_win.h +++ b/chrome/browser/ui/views/status_icons/status_icon_win.h @@ -57,7 +57,7 @@ class StatusIconWin : public StatusIcon { protected: // Overridden from StatusIcon: - void UpdatePlatformContextMenu(StatusIconMenuModel* menu) override; + void UpdatePlatformContextMenu(ui::MenuModel* menu) override; private: void InitIconData(NOTIFYICONDATA* icon_data); diff --git a/chrome/browser/ui/views/toolbar/toolbar_view.cc b/chrome/browser/ui/views/toolbar/toolbar_view.cc index 348c2c3b6dace..26315a7398da7 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_view.cc +++ b/chrome/browser/ui/views/toolbar/toolbar_view.cc @@ -337,6 +337,7 @@ void ToolbarView::ShowTranslateBubble( translate::TranslateStep step, translate::TranslateErrors::Type error_type, bool is_user_gesture) { +#if 0 views::View* anchor_view = location_bar(); BubbleIconView* translate_icon_view = location_bar()->translate_icon_view(); if (!ui::MaterialDesignController::IsSecondaryUiMaterial()) { @@ -352,6 +353,7 @@ void ToolbarView::ShowTranslateBubble( : TranslateBubbleView::AUTOMATIC); if (bubble_widget && translate_icon_view) bubble_widget->AddObserver(translate_icon_view); +#endif } int ToolbarView::GetMaxBrowserActionsWidth() const { diff --git a/chrome/browser/ui/views/translate/translate_bubble_view.cc b/chrome/browser/ui/views/translate/translate_bubble_view.cc index 34f2eee37bdd1..fc75c646adeea 100644 --- a/chrome/browser/ui/views/translate/translate_bubble_view.cc +++ b/chrome/browser/ui/views/translate/translate_bubble_view.cc @@ -95,6 +95,7 @@ views::Widget* TranslateBubbleView::ShowBubble( translate::TranslateStep step, translate::TranslateErrors::Type error_type, DisplayReason reason) { +#if 0 if (translate_bubble_view_) { // When the user reads the advanced setting panel, the bubble should not be // changed because they are focusing on the bubble. @@ -137,6 +138,8 @@ views::Widget* TranslateBubbleView::ShowBubble( view->ShowForReason(reason); translate::ReportUiAction(translate::BUBBLE_SHOWN); return bubble_widget; +#endif + return nullptr; } // static diff --git a/chrome/browser/ui/webui/chrome_web_contents_handler.cc b/chrome/browser/ui/webui/chrome_web_contents_handler.cc index 419cc8bd1ae50..95bfc9d68b3aa 100644 --- a/chrome/browser/ui/webui/chrome_web_contents_handler.cc +++ b/chrome/browser/ui/webui/chrome_web_contents_handler.cc @@ -88,7 +88,7 @@ void ChromeWebContentsHandler::AddNewContents( const bool browser_created = !browser; if (!browser) { browser = new Browser( - Browser::CreateParams(Browser::TYPE_TABBED, profile, user_gesture)); + Browser::CreateParams(Browser::TYPE_POPUP, profile, user_gesture)); } chrome::NavigateParams params(browser, new_contents); params.source_contents = source; diff --git a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc index ad04d3c07d5a9..cea77b112bd23 100644 --- a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc +++ b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc @@ -174,7 +174,7 @@ #include "chrome/browser/ui/webui/cleanup_tool/cleanup_tool_ui.h" #include "chrome/browser/ui/webui/conflicts_ui.h" #include "chrome/browser/ui/webui/set_as_default_browser_ui_win.h" -#include "chrome/browser/ui/webui/welcome_win10_ui.h" +//#include "chrome/browser/ui/webui/welcome_win10_ui.h" #endif #if defined(OS_LINUX) || defined(OS_ANDROID) @@ -222,11 +222,13 @@ WebUIController* NewWebUI(WebUI* web_ui, const GURL& url) { return new T(web_ui); } +#if defined(NWJS_SDK) // Special case for older about: handlers. template<> WebUIController* NewWebUI(WebUI* web_ui, const GURL& url) { return new AboutUI(web_ui, url.host()); } +#endif #if defined(OS_CHROMEOS) template<> @@ -268,7 +270,7 @@ WebUIController* NewWebUI(WebUI* web_ui, return new settings::MdSettingsUI(web_ui, url); } -#if !defined(OS_CHROMEOS) +#if 0 template <> WebUIController* NewWebUI(WebUI* web_ui, const GURL& url) { return new WelcomeUI(web_ui, url); @@ -276,13 +278,14 @@ WebUIController* NewWebUI(WebUI* web_ui, const GURL& url) { #endif // !defined(OS_CHROMEOS) #endif // !defined(OS_ANDROID) -#if defined(OS_WIN) +#if 0 template <> WebUIController* NewWebUI(WebUI* web_ui, const GURL& url) { return new WelcomeWin10UI(web_ui, url); } #endif // defined(OS_WIN) +#if defined(NWJS_SDK) bool IsAboutUI(const GURL& url) { return (url.host_piece() == chrome::kChromeUIChromeURLsHost || url.host_piece() == chrome::kChromeUICreditsHost || @@ -301,6 +304,7 @@ bool IsAboutUI(const GURL& url) { #endif ); // NOLINT } +#endif // Returns a function that can be used to create the right type of WebUI for a // tab, based on its URL. Returns NULL if the URL doesn't have WebUI associated @@ -326,8 +330,10 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, // print dialog. if (url.host_piece() == chrome::kChromeUIBluetoothInternalsHost) return &NewWebUI; +#if 0 if (url.host_piece() == chrome::kChromeUIComponentsHost) return &NewWebUI; +#endif if (url.spec() == chrome::kChromeUIConstrainedHTMLTestURL) return &NewWebUI; if (url.host_piece() == chrome::kChromeUICrashesHost) @@ -340,6 +346,7 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI; if (url.host_piece() == chrome::kChromeUIGCMInternalsHost) return &NewWebUI; +#if 0 if (url.host_piece() == chrome::kChromeUIInstantHost) return &NewWebUI; if (url.host_piece() == chrome::kChromeUIInterstitialHost) @@ -362,8 +369,10 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI; if (url.host_piece() == chrome::kChromeUIPredictorsHost) return &NewWebUI; +#endif if (url.host_piece() == chrome::kChromeUIProfilerHost) return &NewWebUI; +#if 0 if (url.host() == chrome::kChromeUIQuotaInternalsHost) return &NewWebUI; if (url.host() == chrome::kChromeUISignInInternalsHost) @@ -384,6 +393,7 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI; if (url.host_piece() == chrome::kChromeUIUsbInternalsHost) return &NewWebUI; +#endif if (url.host_piece() == chrome::kChromeUIUserActionsHost) return &NewWebUI; if (url.host_piece() == chrome::kChromeUIVersionHost) @@ -401,6 +411,7 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, } #endif // !defined(OS_CHROMEOS) +#if 0 // Bookmarks are part of NTP on Android. if (url.host_piece() == chrome::kChromeUIBookmarksHost) { return MdBookmarksUI::IsEnabled() ? &NewWebUI @@ -415,6 +426,7 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, ::switches::MdFeedbackEnabled()) { return &NewWebUI; } +#endif // Help is implemented with native UI elements on Android. if (url.host_piece() == chrome::kChromeUIHelpFrameHost) return &NewWebUI; @@ -427,10 +439,13 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, return &NewWebUI; // If the material design extensions page is enabled, it gets its own host. // Otherwise, it's handled by the uber settings page. +#if defined(NWJS_SDK) if (url.host_piece() == chrome::kChromeUIExtensionsHost && base::FeatureList::IsEnabled(features::kMaterialDesignExtensions)) { return &NewWebUI; } +#endif +#if 0 if (url.host_piece() == chrome::kChromeUIHistoryHost) return &NewWebUI; // Material Design Settings gets its own host, if enabled. @@ -438,13 +453,16 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, url.host_piece() == chrome::kChromeUISettingsHost) { return &NewWebUI; } +#endif // Settings are implemented with native UI elements on Android. // Handle chrome://settings if settings in a window is enabled. +#if 0 if (url.host_piece() == chrome::kChromeUISettingsFrameHost || (url.host_piece() == chrome::kChromeUISettingsHost && ::switches::SettingsWindowEnabled())) { return &NewWebUI; } +#endif if (url.host_piece() == chrome::kChromeUISyncFileSystemInternalsHost) return &NewWebUI; if (url.host_piece() == chrome::kChromeUISystemInfoHost) @@ -456,7 +474,7 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, if (url.host_piece() == chrome::kChromeUIUberHost) return &NewWebUI; #endif // !defined(OS_ANDROID) -#if defined(OS_WIN) +#if 0 if (base::FeatureList::IsEnabled(features::kCleanupToolUI) && url.host_piece() == chrome::kChromeUICleanupToolHost) return &NewWebUI; @@ -534,6 +552,8 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) if (url.host_piece() == chrome::kChromeUIChromeSigninHost) return &NewWebUI; +#endif +#if 0 if (url.host_piece() == chrome::kChromeUIMdUserManagerHost) return &NewWebUI; if (url.host_piece() == chrome::kChromeUISigninErrorHost && @@ -549,7 +569,7 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, if (url.host_piece() == chrome::kChromeUIWelcomeHost) return &NewWebUI; #endif -#if defined(OS_WIN) +#if 0 if (url.host_piece() == chrome::kChromeUIWelcomeWin10Host) return &NewWebUI; #endif // defined(OS_WIN) @@ -586,7 +606,7 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, if (url.host_piece() == chrome::kChromeUIAppListStartPageHost) return &NewWebUI; #endif -#if BUILDFLAG(ENABLE_EXTENSIONS) +#if defined(NWJS_SDK) if (url.host_piece() == chrome::kChromeUIExtensionsFrameHost) return &NewWebUI; #endif @@ -609,36 +629,42 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, if (url.host_piece() == chrome::kChromeUIWebRtcLogsHost) return &NewWebUI; #endif -#if !defined(OS_ANDROID) +#if defined(NWJS_SDK) if (url.host_piece() == chrome::kChromeUIMediaRouterHost && media_router::MediaRouterEnabled(profile)) { return &NewWebUI; } -#endif -#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS) + +#if 0 if (url.host_piece() == chrome::kChromeUICastHost && media_router::MediaRouterEnabled(profile)) { return &NewWebUI; } #endif +#endif + #if defined(OS_LINUX) || defined(OS_ANDROID) if (url.host_piece() == chrome::kChromeUISandboxHost) { return &NewWebUI; } #endif + +#if defined(NWJS_SDK) if (IsAboutUI(url)) return &NewWebUI; +#endif if (dom_distiller::IsEnableDomDistillerSet() && url.host_piece() == dom_distiller::kChromeUIDomDistillerHost) { return &NewWebUI; } +#if 0 if (SiteEngagementService::IsEnabled() && url.host_piece() == chrome::kChromeUISiteEngagementHost) { return &NewWebUI; } - +#endif return NULL; } @@ -778,8 +804,10 @@ base::RefCountedMemory* ChromeWebUIControllerFactory::GetFaviconResourceBytes( if (!content::HasWebUIScheme(page_url)) return NULL; +#if 0 if (page_url.host_piece() == chrome::kChromeUIComponentsHost) return ComponentsUI::GetFaviconResourceBytes(scale_factor); +#endif #if defined(OS_WIN) if (page_url.host_piece() == chrome::kChromeUIConflictsHost) @@ -807,6 +835,7 @@ base::RefCountedMemory* ChromeWebUIControllerFactory::GetFaviconResourceBytes( if (page_url.host_piece() == chrome::kChromeUIFlashHost) return FlashUI::GetFaviconResourceBytes(scale_factor); +#if 0 // Android uses the native download manager. if (page_url.host_piece() == chrome::kChromeUIDownloadsHost) return MdDownloadsUI::GetFaviconResourceBytes(scale_factor); @@ -816,13 +845,15 @@ base::RefCountedMemory* ChromeWebUIControllerFactory::GetFaviconResourceBytes( page_url.host_piece() == chrome::kChromeUISettingsFrameHost || page_url.host_piece() == chrome::kChromeUIMdSettingsHost) return settings_utils::GetFaviconResourceBytes(scale_factor); +#endif // !defined(OS_ANDROID) -#if BUILDFLAG(ENABLE_EXTENSIONS) +#if BUILDFLAG(ENABLE_EXTENSIONS) && defined(NWJS_SDK) if (page_url.host_piece() == chrome::kChromeUIExtensionsHost || page_url.host_piece() == chrome::kChromeUIExtensionsFrameHost) return extensions::ExtensionsUI::GetFaviconResourceBytes(scale_factor); #endif // BUILDFLAG(ENABLE_EXTENSIONS) -#endif // !defined(OS_ANDROID) + +#endif return NULL; } diff --git a/chrome/browser/ui/webui/print_preview/print_preview_handler.cc b/chrome/browser/ui/webui/print_preview/print_preview_handler.cc index fba7d030cbe99..2ffd871f10dbb 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_handler.cc +++ b/chrome/browser/ui/webui/print_preview/print_preview_handler.cc @@ -109,6 +109,12 @@ namespace { // This enum is used to back an UMA histogram, and should therefore be treated // as append only. +CR_DEFINE_STATIC_LOCAL(std::string, g_nw_printer_name, ()); +CR_DEFINE_STATIC_LOCAL(base::FilePath, g_nw_print_to_pdf_path, ()); +CR_DEFINE_STATIC_LOCAL(std::unique_ptr, g_nw_print_options, ()); + +bool g_nw_custom_printing = false; + enum UserActionBuckets { PRINT_TO_PRINTER, PRINT_TO_PDF, @@ -404,6 +410,9 @@ std::unique_ptr GetPdfCapabilities( return std::unique_ptr(description.root().DeepCopy()); } +} //namespace + +namespace chrome { void PrintersToValues(const printing::PrinterList& printer_list, base::ListValue* printers) { for (const printing::PrinterBasicInfo& printer : printer_list) { @@ -436,6 +445,10 @@ void PrintersToValues(const printing::PrinterList& printer_list, } } +} //namespace chrome + +namespace { + base::LazyInstance::DestructorAtExit g_sticky_settings = LAZY_INSTANCE_INITIALIZER; @@ -465,6 +478,24 @@ bool PrivetPrintingEnabled() { } // namespace +namespace chrome { +void NWPrintSetCustomPrinting(bool value) { + g_nw_custom_printing = value; +} + +void NWPrintSetOptions(const base::DictionaryValue* dict) { + g_nw_print_options = dict->CreateDeepCopy(); +} + +void NWPrintSetPDFPath(const base::FilePath& path) { + g_nw_print_to_pdf_path = path; +} + +void NWPrintSetDefaultPrinter(const std::string& printer_name) { + g_nw_printer_name = printer_name; +} +} + class PrintPreviewHandler::AccessTokenService : public OAuth2TokenService::Consumer { public: @@ -772,6 +803,32 @@ void PrintPreviewHandler::HandleGetPreview(const base::ListValue* args) { bool success = settings->GetBoolean(printing::kSettingHeaderFooterEnabled, &display_header_footer); DCHECK(success); + std::string footer_string, header_string; + if (g_nw_print_options) { + bool landscape, backgrounds; + int margins_type; + int copies; + base::DictionaryValue* media_size_value = nullptr; + base::DictionaryValue* custom_margins = nullptr; + + if (g_nw_print_options->GetDictionary(printing::kSettingMediaSize, &media_size_value) && !media_size_value->empty()) + settings->Set(printing::kSettingMediaSize, media_size_value->CreateDeepCopy()); + if (g_nw_print_options->GetBoolean(printing::kSettingHeaderFooterEnabled, &display_header_footer)) + settings->SetBoolean(printing::kSettingHeaderFooterEnabled, display_header_footer); + if (g_nw_print_options->GetBoolean(printing::kSettingLandscape, &landscape)) + settings->SetBoolean(printing::kSettingLandscape, landscape); + if (g_nw_print_options->GetBoolean(printing::kSettingShouldPrintBackgrounds, &backgrounds)) + settings->SetBoolean(printing::kSettingShouldPrintBackgrounds, backgrounds); + if (g_nw_print_options->GetInteger(printing::kSettingMarginsType, &margins_type)) + settings->SetInteger(printing::kSettingMarginsType, margins_type); + if (g_nw_print_options->GetDictionary(printing::kSettingMarginsCustom, &custom_margins) && !custom_margins->empty()) + settings->Set(printing::kSettingMarginsCustom, custom_margins->CreateDeepCopy()); + if (g_nw_print_options->GetInteger(printing::kSettingCopies, &copies)) + settings->SetInteger(printing::kSettingCopies, copies); + g_nw_print_options->GetString("footerString", &footer_string); + g_nw_print_options->GetString("headerString", &header_string); + } + if (display_header_footer) { settings->SetString(printing::kSettingHeaderFooterTitle, initiator->GetTitle()); @@ -785,7 +842,12 @@ void PrintPreviewHandler::HandleGetPreview(const base::ListValue* args) { url = entry->GetVirtualURL().ReplaceComponents(url_sanitizer).spec(); } - settings->SetString(printing::kSettingHeaderFooterURL, url); + if (footer_string.empty()) + settings->SetString(printing::kSettingHeaderFooterURL, url); + else + settings->SetString(printing::kSettingHeaderFooterURL, footer_string); + if (!header_string.empty()) + settings->SetString(printing::kSettingHeaderFooterTitle, header_string); } bool generate_draft_data = false; @@ -829,6 +891,12 @@ void PrintPreviewHandler::HandlePrint(const base::ListValue* args) { return; ReportPrintSettingsStats(*settings); + if (g_nw_print_options) { + base::ListValue* page_range_array = nullptr; + + if (g_nw_print_options->GetList(printing::kSettingPageRange, &page_range_array) && !page_range_array->empty()) + settings->Set(printing::kSettingPageRange, page_range_array->CreateDeepCopy()); + } // Report whether the user printed a PDF or an HTML document. ReportPrintDocumentTypeHistogram(print_preview_ui()->source_is_modifiable() ? @@ -859,9 +927,11 @@ void PrintPreviewHandler::HandlePrint(const base::ListValue* args) { UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.PrintToPDF", page_count); ReportUserActionHistogram(PRINT_TO_PDF); PrintToPdf(); + chrome::NWPrintSetCustomPrinting(false); return; } + chrome::NWPrintSetCustomPrinting(false); #if BUILDFLAG(ENABLE_SERVICE_DISCOVERY) if (print_with_privet && PrivetPrintingEnabled()) { std::string printer_name; @@ -998,6 +1068,8 @@ void PrintPreviewHandler::HandlePrint(const base::ListValue* args) { } void PrintPreviewHandler::PrintToPdf() { + if (!g_nw_print_to_pdf_path.empty() && g_nw_custom_printing) + print_to_pdf_path_ = g_nw_print_to_pdf_path; if (!print_to_pdf_path_.empty()) { // User has already selected a path, no need to show the dialog again. PostPrintToPdfTask(); @@ -1242,7 +1314,7 @@ void PrintPreviewHandler::SendInitialSettings( print_preview_ui()->initiator_title()); initial_settings.SetBoolean(printing::kSettingPreviewModifiable, print_preview_ui()->source_is_modifiable()); - initial_settings.SetString(printing::kSettingPrinterName, default_printer); + initial_settings.SetString(printing::kSettingPrinterName, g_nw_printer_name.empty() ? default_printer : g_nw_printer_name); initial_settings.SetBoolean(kDocumentHasSelection, print_preview_ui()->source_has_selection()); initial_settings.SetBoolean(printing::kSettingShouldPrintSelectionOnly, @@ -1258,9 +1330,12 @@ void PrintPreviewHandler::SendInitialSettings( base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess(); initial_settings.SetBoolean(kPrintAutomaticallyInKioskMode, - cmdline->HasSwitch(switches::kKioskModePrinting)); + cmdline->HasSwitch(switches::kKioskModePrinting) || g_nw_custom_printing); initial_settings.SetBoolean(kAppKioskMode, chrome::IsRunningInForcedAppMode()); + if (g_nw_custom_printing) + initial_settings.SetBoolean("nwPrintMode", true); + if (prefs) { const std::string rules_str = prefs->GetString(prefs::kPrintPreviewDefaultDestinationSelectionRules); @@ -1327,7 +1402,7 @@ void PrintPreviewHandler::SendPrinterSetup( void PrintPreviewHandler::SetupPrinterList( const printing::PrinterList& printer_list) { base::ListValue printers; - PrintersToValues(printer_list, &printers); + chrome::PrintersToValues(printer_list, &printers); VLOG(1) << "Enumerate printers finished, found " << printers.GetSize() << " printers"; diff --git a/chrome/browser/ui/webui/print_preview/print_preview_handler.h b/chrome/browser/ui/webui/print_preview/print_preview_handler.h index 2166080fc287a..1216705b47ee2 100644 --- a/chrome/browser/ui/webui/print_preview/print_preview_handler.h +++ b/chrome/browser/ui/webui/print_preview/print_preview_handler.h @@ -31,6 +31,16 @@ class PrintPreviewUI; namespace base { class DictionaryValue; class RefCountedBytes; +class ListValue; +} + +namespace chrome { + void PrintersToValues(const printing::PrinterList& printer_list, + base::ListValue* printers); + void NWPrintSetCustomPrinting(bool value); + void NWPrintSetDefaultPrinter(const std::string& printer_name); + void NWPrintSetPDFPath(const base::FilePath& path); + void NWPrintSetOptions(const base::DictionaryValue* dict); } namespace content { diff --git a/chrome/browser/ui/webui/settings/font_handler.cc b/chrome/browser/ui/webui/settings/font_handler.cc index 954f7f6633fec..ac2cc5f36c266 100644 --- a/chrome/browser/ui/webui/settings/font_handler.cc +++ b/chrome/browser/ui/webui/settings/font_handler.cc @@ -39,7 +39,9 @@ FontHandler::FontHandler(content::WebUI* webui) profile_(Profile::FromWebUI(webui)), weak_ptr_factory_(this) { // Perform validation for saved fonts. +#if 0 options::FontSettingsUtilities::ValidateSavedFonts(profile_->GetPrefs()); +#endif } FontHandler::~FontHandler() {} diff --git a/chrome/browser/ui/webui/settings/md_settings_ui.cc b/chrome/browser/ui/webui/settings/md_settings_ui.cc index d073d8dfa6643..f36af4d265b84 100644 --- a/chrome/browser/ui/webui/settings/md_settings_ui.cc +++ b/chrome/browser/ui/webui/settings/md_settings_ui.cc @@ -96,6 +96,7 @@ void MdSettingsUI::RegisterProfilePrefs( MdSettingsUI::MdSettingsUI(content::WebUI* web_ui, const GURL& url) : content::WebUIController(web_ui), WebContentsObserver(web_ui->GetWebContents()) { +#if 0 Profile* profile = Profile::FromWebUI(web_ui); AddSettingsPageUIHandler(base::MakeUnique(web_ui)); @@ -231,6 +232,7 @@ MdSettingsUI::MdSettingsUI(content::WebUI* web_ui, const GURL& url) content::WebUIDataSource::Add(web_ui->GetWebContents()->GetBrowserContext(), html_source); +#endif } MdSettingsUI::~MdSettingsUI() { diff --git a/chrome/browser/ui/webui/settings/people_handler.cc b/chrome/browser/ui/webui/settings/people_handler.cc index 4c37c95afc8a7..9db834584ed06 100644 --- a/chrome/browser/ui/webui/settings/people_handler.cc +++ b/chrome/browser/ui/webui/settings/people_handler.cc @@ -524,6 +524,7 @@ void PeopleHandler::HandleStartSignin(const base::ListValue* args) { } void PeopleHandler::HandleStopSyncing(const base::ListValue* args) { +#if 0 bool delete_profile = false; args->GetBoolean(0, &delete_profile); @@ -543,6 +544,7 @@ void PeopleHandler::HandleStopSyncing(const base::ListValue* args) { web_ui(), ProfileMetrics::DELETE_PROFILE_SETTINGS); } +#endif } #endif diff --git a/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc b/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc index d2f80d1f75637..803b84629eba0 100644 --- a/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc +++ b/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc @@ -126,6 +126,7 @@ void TranslateInternalsHandler::OnTranslateEvent( } void TranslateInternalsHandler::OnRemovePrefItem(const base::ListValue* args) { +#if 0 content::WebContents* web_contents = web_ui()->GetWebContents(); Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); @@ -161,6 +162,7 @@ void TranslateInternalsHandler::OnRemovePrefItem(const base::ListValue* args) { } SendPrefsToJs(); +#endif } void TranslateInternalsHandler::OnOverrideCountry(const base::ListValue* args) { diff --git a/chrome/browser/ui/webui/uber/uber_ui.cc b/chrome/browser/ui/webui/uber/uber_ui.cc index 5a8dfc1528104..a1d267b845952 100644 --- a/chrome/browser/ui/webui/uber/uber_ui.cc +++ b/chrome/browser/ui/webui/uber/uber_ui.cc @@ -128,8 +128,10 @@ UberUI::UberUI(content::WebUI* web_ui) : WebUIController(web_ui) { chrome::kChromeUIExtensionsHost); RegisterSubpage(chrome::kChromeUIHelpFrameURL, chrome::kChromeUIHelpHost); +#if 0 RegisterSubpage(chrome::kChromeUISettingsFrameURL, chrome::kChromeUISettingsHost); +#endif RegisterSubpage(chrome::kChromeUIUberFrameURL, chrome::kChromeUIUberHost); } diff --git a/chrome/browser/usb/web_usb_chooser_service.cc b/chrome/browser/usb/web_usb_chooser_service.cc index 2dfaceca6aed9..15ef9d23f12d1 100644 --- a/chrome/browser/usb/web_usb_chooser_service.cc +++ b/chrome/browser/usb/web_usb_chooser_service.cc @@ -4,6 +4,7 @@ #include "chrome/browser/usb/web_usb_chooser_service.h" +#include "chrome/browser/ui/chrome_bubble_manager.h" #include #include "chrome/browser/ui/browser_finder.h" @@ -39,7 +40,14 @@ void WebUsbChooserService::GetPermission( std::unique_ptr chooser_bubble_delegate( new ChooserBubbleDelegate(render_frame_host_, std::move(usb_chooser_controller))); - BubbleReference bubble_reference = browser->GetBubbleManager()->ShowBubble( + ChromeBubbleManager* mgr = nullptr; + if (!browser) { + if (!bubble_mgr_) + bubble_mgr_.reset(new ChromeBubbleManager(nullptr)); + mgr = bubble_mgr_.get(); + } else + mgr = browser->GetBubbleManager(); + BubbleReference bubble_reference = mgr->ShowBubble( std::move(chooser_bubble_delegate)); bubbles_.push_back(bubble_reference); } diff --git a/chrome/browser/usb/web_usb_chooser_service.h b/chrome/browser/usb/web_usb_chooser_service.h index 9dd7e88c79bcd..7b98f624979f9 100644 --- a/chrome/browser/usb/web_usb_chooser_service.h +++ b/chrome/browser/usb/web_usb_chooser_service.h @@ -16,7 +16,7 @@ namespace content { class RenderFrameHost; } - +class ChromeBubbleManager; // Implementation of the public device::usb::ChooserService interface. // This interface can be used by a webpage to request permission from user // to access a certain device. @@ -36,6 +36,7 @@ class WebUsbChooserService : public device::mojom::UsbChooserService { content::RenderFrameHost* const render_frame_host_; mojo::BindingSet bindings_; std::vector bubbles_; + std::unique_ptr bubble_mgr_; DISALLOW_COPY_AND_ASSIGN(WebUsbChooserService); }; diff --git a/chrome/browser/win/app_icon.cc b/chrome/browser/win/app_icon.cc index ab3d600a5ffaa..0cac88309363f 100644 --- a/chrome/browser/win/app_icon.cc +++ b/chrome/browser/win/app_icon.cc @@ -4,6 +4,8 @@ #include "chrome/browser/win/app_icon.h" +#include "content/nw/src/nw_content.h" + #include "chrome/common/chrome_constants.h" #include "chrome/install_static/install_details.h" #include "third_party/skia/include/core/SkBitmap.h" @@ -21,6 +23,11 @@ int GetAppIconResourceId() { } // namespace HICON GetAppIcon() { +#if 0 + HICON ret = nw::GetWindowHIcon(); + if (ret) + return ret; +#endif // TODO(mgiuca): Use GetAppIconImageFamily/CreateExact instead of LoadIcon, to // get correct scaling. (See http://crbug.com/551256) const int icon_id = GetAppIconResourceId(); @@ -30,6 +37,11 @@ HICON GetAppIcon() { } HICON GetSmallAppIcon() { +#if 0 + HICON ret = nw::GetAppHIcon(); + if (ret) + return ret; +#endif // TODO(mgiuca): Use GetAppIconImageFamily/CreateExact instead of LoadIcon, to // get correct scaling. (See http://crbug.com/551256) const int icon_id = GetAppIconResourceId(); diff --git a/chrome/chrome_paks.gni b/chrome/chrome_paks.gni index 1f9a1fc9a687d..29b6fa7ac79a6 100644 --- a/chrome/chrome_paks.gni +++ b/chrome/chrome_paks.gni @@ -74,7 +74,7 @@ template("chrome_repack_percent") { deps += [ "//ui/app_list/resources" ] } - output = "${invoker.output_dir}/chrome_${percent}_percent.pak" + output = "${invoker.output_dir}/nw_${percent}_percent.pak" } } @@ -100,7 +100,6 @@ template("chrome_extra_paks") { "$root_gen_dir/chrome/task_scheduler_internals_resources.pak", "$root_gen_dir/chrome/translate_internals_resources.pak", "$root_gen_dir/components/components_resources.pak", - "$root_gen_dir/content/browser/tracing/tracing_resources.pak", "$root_gen_dir/content/content_resources.pak", "$root_gen_dir/net/net_resources.pak", "$root_gen_dir/ui/resources/webui_resources.pak", @@ -129,15 +128,19 @@ template("chrome_extra_paks") { if (defined(invoker.additional_paks)) { sources += invoker.additional_paks } - + if (nwjs_sdk) { + sources += [ + "$root_gen_dir/content/browser/tracing/tracing_resources.pak", + "$root_gen_dir/chrome/options_resources.pak", + "$root_gen_dir/content/browser/devtools/devtools_resources.pak", + ] + } if (!is_android) { # New paks should be added here by default. sources += [ "$root_gen_dir/chrome/component_extension_resources.pak", - "$root_gen_dir/chrome/options_resources.pak", "$root_gen_dir/chrome/settings_resources.pak", "$root_gen_dir/chrome/sync_file_system_internals_resources.pak", - "$root_gen_dir/content/browser/devtools/devtools_resources.pak", "$root_gen_dir/headless/headless_lib_resources.pak", ] deps += [ diff --git a/chrome/chrome_watcher/BUILD.gn b/chrome/chrome_watcher/BUILD.gn index 6522aad92afa6..94f39c1f200c9 100644 --- a/chrome/chrome_watcher/BUILD.gn +++ b/chrome/chrome_watcher/BUILD.gn @@ -48,6 +48,7 @@ process_version_rc_template("chrome_watcher_resources") { } shared_library("chrome_watcher") { + output_name = "nw_watcher" sources = [ "chrome_watcher_main.cc", ] @@ -60,7 +61,6 @@ shared_library("chrome_watcher") { "//base", "//base:base_static", "//build/config:exe_and_shlib_deps", - "//chrome/common", "//chrome/install_static:secondary_module", "//chrome_elf", "//components/browser_watcher", diff --git a/chrome/chrome_watcher/chrome_watcher.def b/chrome/chrome_watcher/chrome_watcher.def index 463248f7de1d4..a9b6344f8b22a 100644 --- a/chrome/chrome_watcher/chrome_watcher.def +++ b/chrome/chrome_watcher/chrome_watcher.def @@ -2,7 +2,7 @@ ; Use of this source code is governed by a BSD-style license that can be ; found in the LICENSE file. -LIBRARY "chrome_watcher.dll" +LIBRARY "nw_watcher.dll" EXPORTS WatcherMain diff --git a/chrome/chrome_watcher/chrome_watcher_main.cc b/chrome/chrome_watcher/chrome_watcher_main.cc index e62e67e5de89b..498574521f407 100644 --- a/chrome/chrome_watcher/chrome_watcher_main.cc +++ b/chrome/chrome_watcher/chrome_watcher_main.cc @@ -37,7 +37,6 @@ #include "base/win/scoped_handle.h" #include "base/win/win_util.h" #include "chrome/chrome_watcher/chrome_watcher_main_api.h" -#include "chrome/common/logging_chrome.h" #include "chrome/install_static/initialize_from_primary_module.h" #include "components/browser_watcher/endsession_watcher_window_win.h" #include "components/browser_watcher/exit_code_watcher_win.h" @@ -199,9 +198,7 @@ extern "C" int WatcherMain(const base::char16* registry_path, base::AtExitManager exit_manager; // Initialize the commandline singleton from the environment. base::CommandLine::Init(0, nullptr); - const base::CommandLine& cmd_line = *base::CommandLine::ForCurrentProcess(); - logging::InitChromeLogging(cmd_line, logging::APPEND_TO_OLD_LOG_FILE); logging::LogEventProvider::Initialize(kChromeWatcherTraceProviderName); // Arrange to be shut down as late as possible, as we want to outlive @@ -212,6 +209,7 @@ extern "C" int WatcherMain(const base::char16* registry_path, base::EnableTerminationOnHeapCorruption(); base::EnableTerminationOnOutOfMemory(); base::win::RegisterInvalidParamHandler(); + const base::CommandLine& cmd_line = *base::CommandLine::ForCurrentProcess(); base::win::SetupCRT(cmd_line); // Run a UI message loop on the main thread. diff --git a/chrome/common/BUILD.gn b/chrome/common/BUILD.gn index 7f659bdcdccbc..023145e2fe951 100644 --- a/chrome/common/BUILD.gn +++ b/chrome/common/BUILD.gn @@ -176,7 +176,7 @@ static_library("common") { "//chrome/common:constants", "//chrome/common/media_router/mojo:dial_utility_interfaces", "//chrome/common/net", - "//chrome/common/safe_browsing:proto", + #"//chrome/common/safe_browsing:proto", "//chrome/installer/util:with_no_strings", "//components/autofill/content/common:ipc_traits", "//components/autofill/core/common", @@ -207,8 +207,8 @@ static_library("common") { "//components/safe_browsing:csd_proto", "//components/signin/core/common", "//components/strings", - "//components/translate/content/common", - "//components/translate/core/common", + #"//components/translate/content/common", + #"//components/translate/core/common", "//components/url_formatter", "//components/variations", "//components/version_info", @@ -327,6 +327,7 @@ static_library("common") { ] public_deps += [ "//chrome/common/extensions:mojo_bindings", + "//content/nw/src/api:nw_api", "//chrome/common/extensions/api", "//chrome/common/extensions/api:extensions_features", "//device/usb", diff --git a/chrome/common/child_process_logging_win.cc b/chrome/common/child_process_logging_win.cc index 3460812edc055..c86e3bd7a1030 100644 --- a/chrome/common/child_process_logging_win.cc +++ b/chrome/common/child_process_logging_win.cc @@ -3,6 +3,7 @@ // found in the LICENSE file. #include "chrome/common/child_process_logging.h" +#include "chrome_elf/chrome_elf_main.h" #include @@ -80,6 +81,7 @@ void Init() { // chrome_elf. We decided to go with the duplicate key registration for // simplicity. #if !defined(COMPONENT_BUILD) + if (ElfGetReporterClient()) crash_keys::RegisterChromeCrashKeys(); #endif using SetMetricsClientIdFunction = void (*)(const char* client_id); diff --git a/chrome/common/chrome_constants.cc b/chrome/common/chrome_constants.cc index 94cdc2aeb7398..22411317c6794 100644 --- a/chrome/common/chrome_constants.cc +++ b/chrome/common/chrome_constants.cc @@ -10,11 +10,11 @@ #define FPL FILE_PATH_LITERAL #if defined(OS_MACOSX) -#define CHROMIUM_PRODUCT_STRING "Chromium" +#define CHROMIUM_PRODUCT_STRING "nwjs" #if defined(GOOGLE_CHROME_BUILD) #define PRODUCT_STRING "Google Chrome" #elif defined(CHROMIUM_BUILD) -#define PRODUCT_STRING "Chromium" +#define PRODUCT_STRING "nwjs" #else #error Unknown branding #endif @@ -43,13 +43,13 @@ const char kChromeVersion[] = CHROME_VERSION_STRING; #if defined(OS_WIN) const base::FilePath::CharType kBrowserProcessExecutableNameChromium[] = - FPL("chrome.exe"); + FPL("nw.exe"); const base::FilePath::CharType kBrowserProcessExecutableName[] = - FPL("chrome.exe"); + FPL("nw.exe"); const base::FilePath::CharType kHelperProcessExecutableNameChromium[] = - FPL("chrome.exe"); + FPL("nw.exe"); const base::FilePath::CharType kHelperProcessExecutableName[] = - FPL("chrome.exe"); + FPL("nw.exe"); #elif defined(OS_MACOSX) const base::FilePath::CharType kBrowserProcessExecutableNameChromium[] = FPL(CHROMIUM_PRODUCT_STRING); @@ -69,8 +69,8 @@ const base::FilePath::CharType kHelperProcessExecutableName[] = const base::FilePath::CharType kHelperProcessExecutableNameChromium[] = FPL(""); #elif defined(OS_POSIX) const base::FilePath::CharType kBrowserProcessExecutableNameChromium[] = - FPL("chrome"); -const base::FilePath::CharType kBrowserProcessExecutableName[] = FPL("chrome"); + FPL("nw"); +const base::FilePath::CharType kBrowserProcessExecutableName[] = FPL("nw"); // Helper processes end up with a name of "exe" due to execing via // /proc/self/exe. See bug 22703. const base::FilePath::CharType kHelperProcessExecutableNameChromium[] = @@ -80,13 +80,13 @@ const base::FilePath::CharType kHelperProcessExecutableName[] = FPL("exe"); #if defined(OS_WIN) const base::FilePath::CharType kBrowserProcessExecutablePathChromium[] = - FPL("chrome.exe"); + FPL("nw.exe"); const base::FilePath::CharType kBrowserProcessExecutablePath[] = - FPL("chrome.exe"); + FPL("nw.exe"); const base::FilePath::CharType kHelperProcessExecutablePathChromium[] = - FPL("chrome.exe"); + FPL("nw.exe"); const base::FilePath::CharType kHelperProcessExecutablePath[] = - FPL("chrome.exe"); + FPL("nw.exe"); #elif defined(OS_MACOSX) const base::FilePath::CharType kBrowserProcessExecutablePathChromium[] = FPL(CHROMIUM_PRODUCT_STRING ".app/Contents/MacOS/" CHROMIUM_PRODUCT_STRING); @@ -101,15 +101,15 @@ const base::FilePath::CharType kHelperProcessExecutablePath[] = const base::FilePath::CharType kBrowserProcessExecutablePath[] = FPL("chrome"); const base::FilePath::CharType kHelperProcessExecutablePath[] = FPL("chrome"); const base::FilePath::CharType kBrowserProcessExecutablePathChromium[] = - FPL("chrome"); + FPL("nw"); const base::FilePath::CharType kHelperProcessExecutablePathChromium[] = - FPL("chrome"); + FPL("nw"); #elif defined(OS_POSIX) const base::FilePath::CharType kBrowserProcessExecutablePathChromium[] = - FPL("chrome"); + FPL("nw"); const base::FilePath::CharType kBrowserProcessExecutablePath[] = FPL("chrome"); const base::FilePath::CharType kHelperProcessExecutablePathChromium[] = - FPL("chrome"); + FPL("nw"); const base::FilePath::CharType kHelperProcessExecutablePath[] = FPL("chrome"); #endif // OS_* @@ -121,10 +121,10 @@ const base::FilePath::CharType kFrameworkExecutableName[] = #endif // OS_MACOSX #if defined(OS_WIN) -const base::FilePath::CharType kBrowserResourcesDll[] = FPL("chrome.dll"); -const base::FilePath::CharType kChromeElfDllName[] = FPL("chrome_elf.dll"); +const base::FilePath::CharType kBrowserResourcesDll[] = FPL("nw.dll"); +const base::FilePath::CharType kChromeElfDllName[] = FPL("nw_elf.dll"); const base::FilePath::CharType kStatusTrayWindowClass[] = - FPL("Chrome_StatusTrayWindow"); + FPL("NWJS_StatusTrayWindow"); #endif // defined(OS_WIN) const char kInitialProfile[] = "Default"; diff --git a/chrome/common/chrome_content_client.cc b/chrome/common/chrome_content_client.cc index b7429b1264908..3911ad5016dd5 100644 --- a/chrome/common/chrome_content_client.cc +++ b/chrome/common/chrome_content_client.cc @@ -4,6 +4,7 @@ #include "chrome/common/chrome_content_client.h" +#include "components/crash/content/app/crash_reporter_client.h" #include #include @@ -376,6 +377,53 @@ bool GetComponentUpdatedPepperFlash(content::PepperPluginInfo* plugin) { } #endif // defined(OS_CHROMEOS) +#if 1 +// This should be used on ChromeOS only - other platforms do not bundle Flash. +bool GetBundledPepperFlash(content::PepperPluginInfo* plugin) { +#if 1 + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + + // Ignore bundled Pepper Flash if there is Pepper Flash specified from the + // command-line. + if (command_line->HasSwitch(switches::kPpapiFlashPath)) + return false; + + bool force_disable = + command_line->HasSwitch(switches::kDisableBundledPpapiFlash); + if (force_disable) + return false; + + base::FilePath flash_path; + if (!PathService::Get(chrome::DIR_PEPPER_FLASH_PLUGIN, &flash_path)) + return false; + base::FilePath flash_filename; + if (!PathService::Get(chrome::FILE_PEPPER_FLASH_PLUGIN, &flash_filename)) + return false; + base::FilePath manifest_path( + flash_path.AppendASCII("manifest.json")); + + std::string manifest_data; + if (!base::ReadFileToString(manifest_path, &manifest_data)) + return false; + std::unique_ptr manifest_value( + base::JSONReader::Read(manifest_data, base::JSON_ALLOW_TRAILING_COMMAS)); + if (!manifest_value.get()) + return false; + base::DictionaryValue* manifest = NULL; + if (!manifest_value->GetAsDictionary(&manifest)) + return false; + + base::Version version; + if (!chrome::CheckPepperFlashManifest(*manifest, &version)) + return false; + *plugin = CreatePepperFlashInfo(flash_filename, version.GetString(), false); + return true; +#else + return false; +#endif // FLAPPER_AVAILABLE +} +#endif // defined(OS_CHROMEOS) + bool GetSystemPepperFlash(content::PepperPluginInfo* plugin) { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); // Do not try and find System Pepper Flash if there is a specific path on @@ -448,6 +496,11 @@ void ChromeContentClient::SetActiveURL(const GURL& url) { url.possibly_invalid_spec()); } +void ChromeContentClient::SetNWReportURL(const GURL& url) { + base::debug::SetCrashKeyValue(crash_keys::kNWJSURL, + url.possibly_invalid_spec()); +} + void ChromeContentClient::SetGpuInfo(const gpu::GPUInfo& gpu_info) { gpu::SetKeysForCrashLogging(gpu_info); } @@ -504,6 +557,13 @@ void ChromeContentClient::AddPepperPlugins( if (GetCommandLinePepperFlash(command_line_flash.get())) flash_versions.push_back(std::move(command_line_flash)); + //NWJS: revert 00777c52ac61dba4cd3d9047ede488f337d4a9a5 +#if 1 + auto bundled_flash = base::MakeUnique(); + if (GetBundledPepperFlash(bundled_flash.get())) + flash_versions.push_back(std::move(bundled_flash)); +#endif // defined(OS_CHROMEOS) + auto system_flash = base::MakeUnique(); if (GetSystemPepperFlash(system_flash.get())) flash_versions.push_back(std::move(system_flash)); @@ -688,7 +748,7 @@ bool ChromeContentClient::AllowScriptExtensionForServiceWorker( bool ChromeContentClient::IsSupplementarySiteIsolationModeEnabled() { #if BUILDFLAG(ENABLE_EXTENSIONS) - return true; + return false; #else return false; #endif diff --git a/chrome/common/chrome_content_client.h b/chrome/common/chrome_content_client.h index e3a0afb72612d..7f4beb2a2fa2f 100644 --- a/chrome/common/chrome_content_client.h +++ b/chrome/common/chrome_content_client.h @@ -70,6 +70,7 @@ class ChromeContentClient : public content::ContentClient { #endif void SetActiveURL(const GURL& url) override; + void SetNWReportURL(const GURL& url) override; void SetGpuInfo(const gpu::GPUInfo& gpu_info) override; void AddPepperPlugins( std::vector* plugins) override; diff --git a/chrome/common/chrome_paths.cc b/chrome/common/chrome_paths.cc index 0506aa8e19282..cc8d6ccfb24fe 100644 --- a/chrome/common/chrome_paths.cc +++ b/chrome/common/chrome_paths.cc @@ -350,7 +350,7 @@ bool PathProvider(int key, base::FilePath* result) { // was shipped along with chrome. The value can be overridden // if it is installed via component updater. case chrome::DIR_PNACL_COMPONENT: -#if defined(OS_MACOSX) +#if 0 // PNaCl really belongs in the InternalPluginsDirectory but actually // copying it there would result in the files also being shipped, which // we don't want yet. So for now, just find them in the directory where diff --git a/chrome/common/chrome_paths_linux.cc b/chrome/common/chrome_paths_linux.cc index aa26cc9bbb90e..7c37356e62152 100644 --- a/chrome/common/chrome_paths_linux.cc +++ b/chrome/common/chrome_paths_linux.cc @@ -14,6 +14,8 @@ #include "build/build_config.h" #include "chrome/common/chrome_paths_internal.h" +#include "content/nw/src/nw_base.h" + namespace chrome { using base::nix::GetXDGDirectory; @@ -69,7 +71,7 @@ bool GetDefaultUserDataDirectory(base::FilePath* result) { #if defined(GOOGLE_CHROME_BUILD) *result = config_dir.Append("google-chrome"); #else - *result = config_dir.Append("chromium"); + *result = config_dir.Append(nw::package()->GetName()); #endif return true; } diff --git a/chrome/common/chrome_paths_mac.mm b/chrome/common/chrome_paths_mac.mm index d0bbbf72ff0e3..a5fdec7fbc234 100644 --- a/chrome/common/chrome_paths_mac.mm +++ b/chrome/common/chrome_paths_mac.mm @@ -18,6 +18,8 @@ #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths_internal.h" +#include "content/nw/src/nw_base.h" + namespace { #if !defined(OS_IOS) @@ -65,7 +67,7 @@ #if defined(GOOGLE_CHROME_BUILD) product_dir_name = "Google/Chrome"; #else - product_dir_name = "Chromium"; + product_dir_name = "nwjs"; #endif } @@ -74,6 +76,7 @@ return strdup(product_dir_name); } +#if 0 // ProductDirName returns the name of the directory inside // ~/Library/Application Support that should hold the product application // data. This can be overridden by setting the CrProductDirName key in the @@ -99,6 +102,7 @@ #endif return std::string(product_dir_name); } +#endif bool GetDefaultUserDataDirectoryForProduct(const std::string& product_dir, base::FilePath* result) { @@ -115,7 +119,7 @@ bool GetDefaultUserDataDirectoryForProduct(const std::string& product_dir, namespace chrome { bool GetDefaultUserDataDirectory(base::FilePath* result) { - return GetDefaultUserDataDirectoryForProduct(ProductDirName(), result); + return GetDefaultUserDataDirectoryForProduct(nw::package()->GetName(), result); } bool GetUserDocumentsDirectory(base::FilePath* result) { diff --git a/chrome/common/chrome_paths_win.cc b/chrome/common/chrome_paths_win.cc index 062a85621ef18..47a588728c60f 100644 --- a/chrome/common/chrome_paths_win.cc +++ b/chrome/common/chrome_paths_win.cc @@ -19,6 +19,8 @@ #include "chrome/install_static/install_util.h" #include "components/nacl/common/nacl_switches.h" +#include "content/nw/src/nw_base.h" + namespace chrome { namespace { @@ -45,7 +47,8 @@ bool GetUserDirectory(int csidl_folder, base::FilePath* result) { bool GetDefaultUserDataDirectory(base::FilePath* result) { if (!PathService::Get(base::DIR_LOCAL_APP_DATA, result)) return false; - *result = result->Append(install_static::GetChromeInstallSubDirectory()); + if (nw::package()) //FIXME: crashpad initialized early in cr49 + *result = result->Append(base::FilePath::FromUTF8Unsafe(nw::package()->GetName())); *result = result->Append(chrome::kUserDataDirname); return true; } diff --git a/chrome/common/crash_keys.cc b/chrome/common/crash_keys.cc index e9578be2cd28c..b566a581c87cd 100644 --- a/chrome/common/crash_keys.cc +++ b/chrome/common/crash_keys.cc @@ -27,6 +27,7 @@ namespace crash_keys { const char kActiveURL[] = "url-chunk"; +const char kNWJSURL[] = "url-nwjs"; const char kFontKeyName[] = "font_key_name"; @@ -103,6 +104,7 @@ size_t RegisterChromeCrashKeys() { #endif {kChannel, kSmallSize}, {kActiveURL, kLargeSize}, + {kNWJSURL, kLargeSize }, {kNumVariations, kSmallSize}, {kVariations, kHugeSize}, {kNumExtensionsCount, kSmallSize}, diff --git a/chrome/common/crash_keys.h b/chrome/common/crash_keys.h index 93fb0b07ec1eb..45268bc4bb881 100644 --- a/chrome/common/crash_keys.h +++ b/chrome/common/crash_keys.h @@ -54,6 +54,9 @@ class ScopedPrinterInfo { // The URL of the active tab. extern const char kActiveURL[]; +// NW crash report URL +extern const char kNWJSURL[]; + // Installed extensions. |kExtensionID| should be formatted with an integer, // in the range [0, kExtensionIDMaxCount). const size_t kExtensionIDMaxCount = 10; diff --git a/chrome/common/extensions/api/BUILD.gn b/chrome/common/extensions/api/BUILD.gn index fb5103053da60..23202ac5e13e5 100644 --- a/chrome/common/extensions/api/BUILD.gn +++ b/chrome/common/extensions/api/BUILD.gn @@ -237,6 +237,7 @@ json_features("api_features") { provider_class = "APIFeatureProvider" sources = [ "../../../../extensions/common/api/_api_features.json", + "../../../../content/nw/src/api/_api_features.json", "_api_features.json", ] } diff --git a/chrome/common/extensions/api/_api_features.json b/chrome/common/extensions/api/_api_features.json index 221bbf5f4b629..d4485b6d460aa 100644 --- a/chrome/common/extensions/api/_api_features.json +++ b/chrome/common/extensions/api/_api_features.json @@ -567,7 +567,8 @@ }], "launcherPage": { "dependencies": ["manifest:launcher_page"], - "contexts": ["blessed_extension"] + "contexts": ["blessed_extension"], + "platforms": ["chromeos"] }, "launcherSearchProvider": { "dependencies": ["permission:launcherSearchProvider"], @@ -774,10 +775,13 @@ }, "usersPrivate": [{ "dependencies": ["permission:usersPrivate"], + "platforms": ["chromeos"], "contexts": ["blessed_extension"] }, { "channel": "stable", "contexts": ["webui"], + "dependencies": ["permission:usersPrivate"], + "platforms": ["chromeos"], "matches": [ "chrome://md-settings/*", "chrome://settings/*", diff --git a/chrome/common/extensions/api/_permission_features.json b/chrome/common/extensions/api/_permission_features.json index 23d93030bd93f..22b53583c99ea 100644 --- a/chrome/common/extensions/api/_permission_features.json +++ b/chrome/common/extensions/api/_permission_features.json @@ -214,16 +214,7 @@ ], "developerPrivate": { "channel": "stable", - "extension_types": ["platform_app"], - "whitelist": [ - "AE27D69DBE571F4B1694F05C89B710C646792231", // Published ADT. - "FA0501B579070BB9CBD4FCAEC8CB0EDF22BA2F04", // Apps Editor published. - "4A4EA121622FCA3D78ED2AB534197F43D7189EE0", // Spark nightly build. - "9FDE6E7F06FCFA11D9A05041C7FF6D8AE662F5D1", // Spark release. - "50B4A905D522C06E27CA6D099E3E54BDA1F152C5", // Spark Beta channel. - "BA0C8BB92084C9741312D90D3EA882526853455F", // Spark dev channel. - "5F57A9AE8DFF5D6BB09DF8606270402612E871E5" // http://crbug.com/422624 - ] + "extension_types": ["platform_app"] }, "devtools": { "channel": "stable", @@ -490,6 +481,7 @@ "logPrivate": { "channel": "stable", "extension_types": ["extension", "platform_app"], + "platforms": ["chromeos"], "whitelist": [ "ddammdhioacbehjngdmkjcjbnfginlla", // Test "1C93BD3CF875F4A73C0B2A163BB8FBDA8B8B3D80", // http://crbug.com/293683 @@ -505,6 +497,7 @@ }, "webcamPrivate": { "channel": "stable", + "platforms": ["chromeos"], "extension_types": ["extension", "platform_app"] }, "networking.castPrivate": { @@ -527,21 +520,7 @@ }, { "channel": "stable", - "extension_types": ["platform_app"], - "whitelist": [ - "AE27D69DBE571F4B1694F05C89B710C646792231", // Published ADT - // TODO(grv): clean up once Apps developer tool is published. - "5107DE9024C329EEA9C9A72D94C16723790C6422", // Apps Developer Tool. - "8C0B1873FFFB65E4D0F4D772879F7304CEF125C2", // Apps Editor old. - "FA0501B579070BB9CBD4FCAEC8CB0EDF22BA2F04", // Apps Editor published. - "EE17C698905F7F2E6DDC87C9C30F11E164C829F4", // Watchdog (Activity Log) - "90113DA9516526D24DAF156C629CC41C049E8882", // Watchdog Test Version - "4A4EA121622FCA3D78ED2AB534197F43D7189EE0", // Spark nightly build. - "9FDE6E7F06FCFA11D9A05041C7FF6D8AE662F5D1", // Spark release. - "50B4A905D522C06E27CA6D099E3E54BDA1F152C5", // Spark Beta channel. - "BA0C8BB92084C9741312D90D3EA882526853455F", // Spark dev channel. - "5F57A9AE8DFF5D6BB09DF8606270402612E871E5" // http://crbug.com/422624 - ] + "extension_types": ["platform_app"] }, { "channel": "stable", @@ -749,6 +728,7 @@ "rtcPrivate": { "channel": "stable", "extension_types": ["extension", "legacy_packaged_app"], + "platforms": ["chromeos"], "whitelist": [ "53041A2FA309EECED01FFC751E7399186E860B2C", // Google Talk prod "A74A4D44C7CFCD8844830E6140C8D763E12DD8F3", // Google Talk beta @@ -846,6 +826,7 @@ "usersPrivate": { "channel": "trunk", "extension_types": ["extension", "platform_app"], + "platforms": ["chromeos"], "location": "component" }, "wallpaper": { diff --git a/chrome/common/extensions/api/webview_tag.json b/chrome/common/extensions/api/webview_tag.json index 7692c7a6188a2..6df71b106e3ff 100644 --- a/chrome/common/extensions/api/webview_tag.json +++ b/chrome/common/extensions/api/webview_tag.json @@ -858,6 +858,13 @@ "description": "Returns Chrome's internal process ID for the guest web page's current process, allowing embedders to know how many guests would be affected by terminating the process. Two guests will share a process only if they belong to the same app and have the same storage partition ID. The call is synchronous and returns the embedder's cached notion of the current process ID. The process ID isn't the same as the operating system's process ID.", "parameters": [] }, + { + "name": "getGuestId", + "type": "function", + "returns": { "type": "integer" }, + "description": "", + "parameters": [] + }, { "name": "getUserAgent", "type": "function", @@ -1073,6 +1080,24 @@ } ] }, + { + "name": "showDevTools", + "type": "function", + "description": "Open or close devtools for this webview.", + "parameters": [ + { + "type": "boolean", + "name": "show", + "description" : "show or close." + }, + { + "type": "object", + "name": "container", + "description" : "where to show the devtools, should be a webview", + "optional": true + } + ] + }, { "name": "terminate", "type": "function", diff --git a/chrome/common/extensions/chrome_extensions_client.cc b/chrome/common/extensions/chrome_extensions_client.cc index ec7f902a0b4b8..2816e67699167 100644 --- a/chrome/common/extensions/chrome_extensions_client.cc +++ b/chrome/common/extensions/chrome_extensions_client.cc @@ -52,6 +52,8 @@ #include "ui/base/l10n/l10n_util.h" #include "url/gurl.h" +#include "content/nw/src/api/generated_schemas.h" + namespace extensions { namespace { @@ -161,6 +163,7 @@ ChromeExtensionsClient::CreateAPIFeatureSource() const { new JSONFeatureProviderSource("api")); source->LoadJSON(IDR_EXTENSION_API_FEATURES); source->LoadJSON(IDR_CHROME_EXTENSION_API_FEATURES); + source->LoadJSON(IDR_NW_EXTENSION_API_FEATURES); return source; } @@ -239,6 +242,7 @@ bool ChromeExtensionsClient::IsAPISchemaGenerated( const std::string& name) const { // Test from most common to least common. return api::ChromeGeneratedSchemas::IsGenerated(name) || + nwapi::nwjsGeneratedSchemas::IsGenerated(name) || api::GeneratedSchemas::IsGenerated(name); } @@ -247,6 +251,8 @@ base::StringPiece ChromeExtensionsClient::GetAPISchema( // Test from most common to least common. if (api::ChromeGeneratedSchemas::IsGenerated(name)) return api::ChromeGeneratedSchemas::Get(name); + if (nwapi::nwjsGeneratedSchemas::IsGenerated(name)) + return nwapi::nwjsGeneratedSchemas::Get(name); return api::GeneratedSchemas::Get(name); } diff --git a/chrome/common/extensions/extension_process_policy.cc b/chrome/common/extensions/extension_process_policy.cc index 2b7041b905e68..c237cb9dbd3f8 100644 --- a/chrome/common/extensions/extension_process_policy.cc +++ b/chrome/common/extensions/extension_process_policy.cc @@ -36,6 +36,9 @@ bool CrossesExtensionProcessBoundary( extensions, new_url); + if (old_url_extension && old_url_extension->is_nwjs_app()) + return false; + // TODO(creis): Temporary workaround for crbug.com/59285: Do not swap process // to navigate from a hosted app to a normal page or another hosted app // (unless either is the web store). This is because some OAuth providers diff --git a/chrome/common/extensions/manifest_handlers/content_scripts_handler.cc b/chrome/common/extensions/manifest_handlers/content_scripts_handler.cc index 048cfc6feb070..3cba23717f7f5 100644 --- a/chrome/common/extensions/manifest_handlers/content_scripts_handler.cc +++ b/chrome/common/extensions/manifest_handlers/content_scripts_handler.cc @@ -128,6 +128,18 @@ std::unique_ptr LoadUserScriptFromDictionary( result->set_match_about_blank(match_about_blank); } + // in main world + if (content_script->HasKey(keys::kInMainWorld)) { + bool in_main_world = false; + if (!content_script->GetBoolean(keys::kInMainWorld, + &in_main_world)) { + *error = ErrorUtils::FormatErrorMessageUTF16( + errors::kInvalidInMainWorld, base::IntToString(definition_index)); + return std::unique_ptr(); + } + result->set_in_main_world(in_main_world); + } + // matches (required) const base::ListValue* matches = NULL; if (!content_script->GetList(keys::kMatches, &matches)) { diff --git a/chrome/common/extensions/sync_helper.cc b/chrome/common/extensions/sync_helper.cc index 9152450ffebaa..8246e9861b3e0 100644 --- a/chrome/common/extensions/sync_helper.cc +++ b/chrome/common/extensions/sync_helper.cc @@ -59,6 +59,7 @@ bool IsSyncable(const Extension* extension) { case Manifest::TYPE_HOSTED_APP: case Manifest::TYPE_LEGACY_PACKAGED_APP: case Manifest::TYPE_PLATFORM_APP: + case Manifest::TYPE_NWJS_APP: case Manifest::TYPE_THEME: return true; diff --git a/chrome/common/logging_chrome.cc b/chrome/common/logging_chrome.cc index 4e2df8c8efdf4..bd324959ba778 100644 --- a/chrome/common/logging_chrome.cc +++ b/chrome/common/logging_chrome.cc @@ -20,6 +20,7 @@ #define IPC_LOG_TABLE_ADD_ENTRY(msg_id, logger) \ content::RegisterIPCLogger(msg_id, logger) #include "chrome/common/all_messages.h" +#include "extensions/common/extension_messages.h" #endif #if defined(OS_WIN) diff --git a/chrome/common/mac/app_mode_chrome_locator.mm b/chrome/common/mac/app_mode_chrome_locator.mm index efd272e706ba5..c1b3b09b58128 100644 --- a/chrome/common/mac/app_mode_chrome_locator.mm +++ b/chrome/common/mac/app_mode_chrome_locator.mm @@ -79,6 +79,7 @@ bool GetChromeBundleInfo(const base::FilePath& chrome_bundle, // However, we want the shims to be agnostic to distribution and operate based // on the data in their plist, so encode the framework names here. NSDictionary* framework_for_exe = @{ + @"nwjs": @"nwjs", @"Chromium": @"Chromium", @"Google Chrome": @"Google Chrome", @"Google Chrome Canary": @"Google Chrome", diff --git a/chrome/common/pepper_flash.cc b/chrome/common/pepper_flash.cc index 86d9c6f591ba0..f597bd0e1249b 100644 --- a/chrome/common/pepper_flash.cc +++ b/chrome/common/pepper_flash.cc @@ -40,6 +40,7 @@ const char kPepperFlashOperatingSystem[] = "linux"; #endif +#if 0 // Name of the Pepper Flash architecture in the component manifest. const char kPepperFlashArch[] = #if defined(ARCH_CPU_X86) @@ -51,6 +52,7 @@ const char kPepperFlashArch[] = #else "???"; #endif +#endif // Returns true if the Pepper |interface_name| is implemented by this browser. // It does not check if the interface is proxied. @@ -119,6 +121,7 @@ bool CheckPepperFlashManifest(const base::DictionaryValue& manifest, if (os != kPepperFlashOperatingSystem) return false; +#if 0 std::string arch; manifest.GetStringASCII("x-ppapi-arch", &arch); if (arch != kPepperFlashArch) { @@ -131,7 +134,7 @@ bool CheckPepperFlashManifest(const base::DictionaryValue& manifest, return false; #endif } - +#endif *version_out = version; return true; } diff --git a/chrome/install_static/chromium_install_modes.cc b/chrome/install_static/chromium_install_modes.cc index 816c6d90b3f8d..528bfd9b7dcf1 100644 --- a/chrome/install_static/chromium_install_modes.cc +++ b/chrome/install_static/chromium_install_modes.cc @@ -14,14 +14,14 @@ namespace install_static { const wchar_t kCompanyPathName[] = L""; -const wchar_t kProductPathName[] = L"Chromium"; +const wchar_t kProductPathName[] = L"nwjs"; const size_t kProductPathNameLength = _countof(kProductPathName) - 1; // No integration with Google Update, so no app GUID. const wchar_t kBinariesAppGuid[] = L""; -const wchar_t kBinariesPathName[] = L"Chromium Binaries"; +const wchar_t kBinariesPathName[] = L"NW Binaries"; const InstallConstants kInstallModes[] = { // The primary (and only) install mode for Chromium. @@ -32,8 +32,8 @@ const InstallConstants kInstallModes[] = { L"", // Empty install_suffix for the primary install mode. L"", // No logo suffix for the primary install mode. L"", // Empty app_guid since no integraion with Google Update. - L"Chromium", // A distinct base_app_name. - L"Chromium", // A distinct base_app_id. + L"nwjs", // A distinct base_app_name. + L"nwjs", // A distinct base_app_id. L"ChromiumHTM", // ProgID prefix. L"Chromium HTML Document", // ProgID description. L"{7D2B3E1D-D096-4594-9D8F-A6667F12E0AC}", // Active Setup GUID. diff --git a/chrome/install_static/install_util.cc b/chrome/install_static/install_util.cc index 0d3054fa19022..cdb337f86686c 100644 --- a/chrome/install_static/install_util.cc +++ b/chrome/install_static/install_util.cc @@ -22,6 +22,8 @@ #include "chrome_elf/nt_registry/nt_registry.h" #include "components/version_info/channel.h" +std::wstring g_nwjs_prod_name, g_nwjs_prod_version; + namespace install_static { enum class ProcessType { @@ -479,7 +481,10 @@ std::wstring& AppendChromeInstallSubDirectory(const InstallConstants& mode, path->append(kCompanyPathName); path->push_back(L'\\'); } - path->append(kProductPathName, kProductPathNameLength); + if (!g_nwjs_prod_name.empty()) + path->append(g_nwjs_prod_name); + else + path->append(kProductPathName, kProductPathNameLength); if (!include_suffix) return *path; return path->append(mode.install_suffix); @@ -587,10 +592,10 @@ void GetExecutableVersionDetails(const std::wstring& exe_path, assert(channel_name); // Default values in case we don't find a version resource. - *product_name = L"Chrome"; - *version = L"0.0.0.0-devel"; + *product_name = g_nwjs_prod_name; + *version = g_nwjs_prod_version; special_build->clear(); - +#if 0 DWORD dummy = 0; DWORD length = ::GetFileVersionInfoSize(exe_path.c_str(), &dummy); if (length) { @@ -609,6 +614,7 @@ void GetExecutableVersionDetails(const std::wstring& exe_path, } } *channel_name = GetChromeChannelName(); +#endif } version_info::Channel GetChromeChannel() { diff --git a/chrome/installer/linux/common/installer.include b/chrome/installer/linux/common/installer.include index 1d31a12e333ce..c2c196fa4d5fa 100644 --- a/chrome/installer/linux/common/installer.include +++ b/chrome/installer/linux/common/installer.include @@ -127,9 +127,9 @@ stage_install_common() { # we should flag all installer files in FILES.cfg and get them from there, so # there's only one place people need to keep track of such things (and in # only the public repository). - if [ -r "${BUILDDIR}/chrome_100_percent.pak" ]; then - install -m 644 "${BUILDDIR}/chrome_100_percent.pak" "${STAGEDIR}/${INSTALLDIR}/" - install -m 644 "${BUILDDIR}/chrome_200_percent.pak" "${STAGEDIR}/${INSTALLDIR}/" + if [ -r "${BUILDDIR}/nw_100_percent.pak" ]; then + install -m 644 "${BUILDDIR}/nw_100_percent.pak" "${STAGEDIR}/${INSTALLDIR}/" + install -m 644 "${BUILDDIR}/nw_200_percent.pak" "${STAGEDIR}/${INSTALLDIR}/" else install -m 644 "${BUILDDIR}/theme_resources_100_percent.pak" "${STAGEDIR}/${INSTALLDIR}/" install -m 644 "${BUILDDIR}/ui_resources_100_percent.pak" "${STAGEDIR}/${INSTALLDIR}/" diff --git a/chrome/installer/mini_installer/BUILD.gn b/chrome/installer/mini_installer/BUILD.gn index 2afab1a3c6a3b..3a1ee0d00c7e9 100644 --- a/chrome/installer/mini_installer/BUILD.gn +++ b/chrome/installer/mini_installer/BUILD.gn @@ -127,7 +127,7 @@ template("generate_mini_installer") { inputs = [ "$chrome_dll_file", - "$root_out_dir/chrome.exe", + "$root_out_dir/nw.exe", "$root_out_dir/locales/en-US.pak", "$root_out_dir/setup.exe", release_file, @@ -265,14 +265,14 @@ template("generate_mini_installer") { generate_mini_installer("mini_installer") { out_dir = root_out_dir - chrome_dll_file = "$root_out_dir/chrome.dll" + chrome_dll_file = "$root_out_dir/nw.dll" chrome_dll_target = "//chrome:main_dll" } if (is_syzyasan) { generate_mini_installer("mini_installer_syzygy") { out_dir = "$root_out_dir/syzygy/" - chrome_dll_file = "$root_out_dir/syzygy/chrome.dll" + chrome_dll_file = "$root_out_dir/syzygy/nw.dll" chrome_dll_target = "//chrome/tools/build/win/syzygy:chrome_dll_syzygy" } } diff --git a/chrome/installer/mini_installer/chrome.release b/chrome/installer/mini_installer/chrome.release index c66d6dc04087f..8d66ee9d09da8 100644 --- a/chrome/installer/mini_installer/chrome.release +++ b/chrome/installer/mini_installer/chrome.release @@ -6,44 +6,45 @@ # # Chrome Application dir entries, sorted alphabetically. # -chrome.exe: %(ChromeDir)s\ +nw.exe: %(ChromeDir)s\ # # Chrome version dir assembly manifest. # The name of this file must match the name of the version dir, so we cannot # hard-code it. # // TODO(caitkp): Find a way to do this without wildcards. # -*.*.*.*.manifest: %(VersionDir)s\ +*.*.*.*.manifest: %(ChromeDir)s\ # # Chrome version dir entries, sorted alphabetically. # -chrome.dll: %(VersionDir)s\ -chrome_100_percent.pak: %(VersionDir)s\ -chrome_child.dll: %(VersionDir)s\ -chrome_elf.dll: %(VersionDir)s\ -chrome_watcher.dll: %(VersionDir)s\ -d3dcompiler_47.dll: %(VersionDir)s\ -eventlog_provider.dll: %(VersionDir)s\ +nw.dll: %(ChromeDir)s\ +nw_100_percent.pak: %(ChromeDir)s\ +nw_child.dll: %(ChromeDir)s\ +nw_elf.dll: %(ChromeDir)s\ +nw_watcher.dll: %(ChromeDir)s\ +d3dcompiler_47.dll: %(ChromeDir)s\ +eventlog_provider.dll: %(ChromeDir)s\ ffmpeg.dll: %(VersionDir)s\ -icudt.dll: %(VersionDir)s\ -icudtl.dat: %(VersionDir)s\ -libEGL.dll: %(VersionDir)s\ -libGLESv2.dll: %(VersionDir)s\ -nacl64.exe: %(VersionDir)s\ -nacl_irt_x86_32.nexe: %(VersionDir)s\ -nacl_irt_x86_64.nexe: %(VersionDir)s\ -natives_blob.bin: %(VersionDir)s\ -resources.pak: %(VersionDir)s\ -snapshot_blob.bin: %(VersionDir)s\ -syzyasan_rtl.dll: %(VersionDir)s\ +icudt.dll: %(ChromeDir)s\ +icudtl.dat: %(ChromeDir)s\ +libEGL.dll: %(ChromeDir)s\ +libGLESv2.dll: %(ChromeDir)s\ +nacl64.exe: %(ChromeDir)s\ +nacl_irt_x86_32.nexe: %(ChromeDir)s\ +nacl_irt_x86_64.nexe: %(ChromeDir)s\ +natives_blob.bin: %(ChromeDir)s\ +resources.pak: %(ChromeDir)s\ +snapshot_blob.bin: %(ChromeDir)s\ +syzyasan_rtl.dll: %(ChromeDir)s\ +node.dll: %(ChromeDir)s\ # # Sub directories living in the version dir # -default_apps\*.crx: %(VersionDir)s\default_apps\ -default_apps\external_extensions.json: %(VersionDir)s\default_apps\ -Extensions\*.*: %(VersionDir)s\Extensions\ -locales\*.dll: %(VersionDir)s\Locales -locales\*.pak: %(VersionDir)s\Locales +default_apps\*.crx: %(ChromeDir)s\default_apps\ +default_apps\external_extensions.json: %(ChromeDir)s\default_apps\ +Extensions\*.*: %(ChromeDir)s\Extensions\ +locales\*.dll: %(ChromeDir)s\Locales +locales\*.pak: %(ChromeDir)s\Locales # # VisualElements sub-dir. @@ -67,7 +68,7 @@ swiftshader\libEGL.dll: %(VersionDir)s\swiftshader\ swiftshader\libGLESv2.dll: %(VersionDir)s\swiftshader\ [HIDPI] -chrome_200_percent.pak: %(VersionDir)s\ +nw_200_percent.pak: %(ChromeDir)s\ [TOUCH] @@ -75,10 +76,10 @@ chrome_200_percent.pak: %(VersionDir)s\ # # Widevine CDM sub-dir # -WidevineCdm\manifest.json: %(VersionDir)s\WidevineCdm\ -WidevineCdm\_platform_specific\win_x86\widevinecdm.dll: %(VersionDir)s\WidevineCdm\_platform_specific\win_x86\ -WidevineCdm\_platform_specific\win_x86\widevinecdm.dll.sig: %(VersionDir)s\WidevineCdm\_platform_specific\win_x86\ -WidevineCdm\_platform_specific\win_x86\widevinecdmadapter.dll: %(VersionDir)s\WidevineCdm\_platform_specific\win_x86\ -WidevineCdm\_platform_specific\win_x64\widevinecdm.dll: %(VersionDir)s\WidevineCdm\_platform_specific\win_x64\ -WidevineCdm\_platform_specific\win_x64\widevinecdm.dll.sig: %(VersionDir)s\WidevineCdm\_platform_specific\win_x64\ -WidevineCdm\_platform_specific\win_x64\widevinecdmadapter.dll: %(VersionDir)s\WidevineCdm\_platform_specific\win_x64\ +WidevineCdm\manifest.json: %(ChromeDir)s\WidevineCdm\ +WidevineCdm\_platform_specific\win_x86\widevinecdm.dll: %(ChromeDir)s\WidevineCdm\_platform_specific\win_x86\ +WidevineCdm\_platform_specific\win_x86\widevinecdm.dll.sig: %(ChromeDir)s\WidevineCdm\_platform_specific\win_x86\ +WidevineCdm\_platform_specific\win_x86\widevinecdmadapter.dll: %(ChromeDir)s\WidevineCdm\_platform_specific\win_x86\ +WidevineCdm\_platform_specific\win_x64\widevinecdm.dll: %(ChromeDir)s\WidevineCdm\_platform_specific\win_x64\ +WidevineCdm\_platform_specific\win_x64\widevinecdm.dll.sig: %(ChromeDir)s\WidevineCdm\_platform_specific\win_x64\ +WidevineCdm\_platform_specific\win_x64\widevinecdmadapter.dll: %(ChromeDir)s\WidevineCdm\_platform_specific\win_x64\ diff --git a/chrome/installer/util/browser_distribution.cc b/chrome/installer/util/browser_distribution.cc index ac6a3e41ef2c4..67bcd5f6b4950 100644 --- a/chrome/installer/util/browser_distribution.cc +++ b/chrome/installer/util/browser_distribution.cc @@ -109,7 +109,7 @@ base::string16 BrowserDistribution::GetStartMenuShortcutSubfolder( } base::string16 BrowserDistribution::GetPublisherName() { - return L"Chromium"; + return L"nwjs"; } base::string16 BrowserDistribution::GetAppDescription() { @@ -123,7 +123,7 @@ base::string16 BrowserDistribution::GetLongAppDescription() { } std::string BrowserDistribution::GetSafeBrowsingName() { - return "chromium"; + return "nwjs"; } base::string16 BrowserDistribution::GetDistributionData(HKEY root_key) { diff --git a/chrome/installer/util/google_update_settings.cc b/chrome/installer/util/google_update_settings.cc index c1433d5b9f937..22d6fc452c4e7 100644 --- a/chrome/installer/util/google_update_settings.cc +++ b/chrome/installer/util/google_update_settings.cc @@ -196,7 +196,7 @@ bool GoogleUpdateSettings::IsSystemInstall() { } bool GoogleUpdateSettings::GetCollectStatsConsent() { - return GetCollectStatsConsentAtLevel(IsSystemInstall()); + return false; //GetCollectStatsConsentAtLevel(IsSystemInstall()); } bool GoogleUpdateSettings::SetCollectStatsConsent(bool consented) { diff --git a/chrome/installer/util/util_constants.cc b/chrome/installer/util/util_constants.cc index bd60716a89721..fc0273aa21bf0 100644 --- a/chrome/installer/util/util_constants.cc +++ b/chrome/installer/util/util_constants.cc @@ -195,9 +195,9 @@ const char kGoogleUpdateIsMachineEnvVar[] = "GoogleUpdateIsMachine"; // TODO(gab): Rename setup.exe itself altogether and use the same binary for // Active Setup. const wchar_t kActiveSetupExe[] = L"chrmstp.exe"; -const wchar_t kChromeDll[] = L"chrome.dll"; -const wchar_t kChromeChildDll[] = L"chrome_child.dll"; -const wchar_t kChromeExe[] = L"chrome.exe"; +const wchar_t kChromeDll[] = L"nw.dll"; +const wchar_t kChromeChildDll[] = L"nw_child.dll"; +const wchar_t kChromeExe[] = L"nw.exe"; const wchar_t kChromeNewExe[] = L"new_chrome.exe"; const wchar_t kChromeOldExe[] = L"old_chrome.exe"; const wchar_t kCmdOnOsUpgrade[] = L"on-os-upgrade"; diff --git a/chrome/renderer/BUILD.gn b/chrome/renderer/BUILD.gn index bed32f454097f..c05769dc41f69 100644 --- a/chrome/renderer/BUILD.gn +++ b/chrome/renderer/BUILD.gn @@ -105,6 +105,7 @@ static_library("renderer") { defines = [] deps = [ + "//content/nw:nw_renderer", "//chrome:resources", "//chrome:strings", "//chrome/common", @@ -127,9 +128,9 @@ static_library("renderer") { "//components/startup_metric_utils/common:interfaces", "//components/subresource_filter/content/renderer", "//components/task_scheduler_util/renderer", - "//components/translate/content/renderer", +# "//components/translate/content/renderer", "//components/translate/core/common", - "//components/translate/core/language_detection", + #"//components/translate/core/language_detection", "//components/visitedlink/renderer", "//components/web_cache/renderer", "//content/app/resources", diff --git a/chrome/renderer/chrome_content_renderer_client.cc b/chrome/renderer/chrome_content_renderer_client.cc index 51e8e616838f3..a346932f468a0 100644 --- a/chrome/renderer/chrome_content_renderer_client.cc +++ b/chrome/renderer/chrome_content_renderer_client.cc @@ -176,6 +176,9 @@ #include "chrome/renderer/media/webrtc_logging_message_filter.h" #endif +#include "content/nw/src/nw_content.h" +#include "content/nw/src/common/shell_switches.h" + using autofill::AutofillAgent; using autofill::PasswordAutofillAgent; using autofill::PasswordGenerationAgent; @@ -367,6 +370,15 @@ ChromeContentRendererClient::ChromeContentRendererClient() ChromeContentRendererClient::~ChromeContentRendererClient() { } +void ChromeContentRendererClient::willHandleNavigationPolicy(content::RenderView* rv, + blink::WebFrame* frame, + const blink::WebURLRequest& request, + blink::WebNavigationPolicy* policy, + blink::WebString* manifest, + bool new_win) { + nw::willHandleNavigationPolicy(rv, frame, request, policy, manifest, new_win); +} + void ChromeContentRendererClient::RenderThreadStarted() { RenderThread* thread = RenderThread::Get(); @@ -404,10 +416,11 @@ void ChromeContentRendererClient::RenderThreadStarted() { prescient_networking_dispatcher_.reset( new network_hints::PrescientNetworkingDispatcher()); + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); #if BUILDFLAG(ENABLE_SPELLCHECK) // ChromeRenderViewTest::SetUp() creates a Spellcheck and injects it using // SetSpellcheck(). Don't overwrite it. - if (!spellcheck_) { + if (!spellcheck_ && command_line->HasSwitch(switches::kEnableSpellChecking)) { spellcheck_.reset(new SpellCheck()); thread->AddObserver(spellcheck_.get()); } @@ -437,7 +450,6 @@ void ChromeContentRendererClient::RenderThreadStarted() { thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get()); - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kEnableBenchmarking)) thread->RegisterExtension(extensions_v8::BenchmarkingExtension::Get()); if (command_line->HasSwitch(switches::kEnableNetBenchmarking)) @@ -583,6 +595,7 @@ void ChromeContentRendererClient::RenderFrameCreated( } #if BUILDFLAG(ENABLE_SPELLCHECK) + if (command_line->HasSwitch(switches::kEnableSpellChecking)) new SpellCheckProvider(render_frame, spellcheck_.get()); #endif } @@ -597,6 +610,8 @@ void ChromeContentRendererClient::RenderViewCreated( // enabled state is initialized on RenderView creation. // TODO(xiaochengh): Design better way to sync between Chrome-side and // Blink-side spellcheck enabled states. See crbug.com/710097. + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(switches::kEnableSpellChecking)) { if (SpellCheckProvider* provider = SpellCheckProvider::Get(render_view->GetMainRenderFrame())) provider->EnableSpellcheck(spellcheck_->IsSpellcheckEnabled()); @@ -605,6 +620,8 @@ void ChromeContentRendererClient::RenderViewCreated( new SpellCheckPanel(render_view); #endif // BUILDFLAG(HAS_SPELLCHECK_PANEL) #endif // BUILDFLAG(ENABLE_SPELLCHECK) + } + new prerender::PrerendererClient(render_view); new ChromeRenderViewObserver(render_view, web_cache_impl_.get()); @@ -1308,7 +1325,7 @@ bool ChromeContentRendererClient::AllowPepperMediaStreamAPI( // Allow only the Hangouts app to use the MediaStream APIs. It's OK to check // the whitelist in the renderer, since we're only preventing access until // these APIs are public and stable. - return (AppCategorizer::IsHangoutsUrl(url)); + return true; #endif // !defined(OS_ANDROID) } @@ -1411,22 +1428,30 @@ ChromeContentRendererClient::CreateBrowserPluginDelegate( #endif } +base::FilePath ChromeContentRendererClient::GetRootPath() { + return nw::GetRootPathRenderer(); +} + void ChromeContentRendererClient::RecordRappor(const std::string& metric, const std::string& sample) { +#if 0 if (!rappor_recorder_) { RenderThread::Get()->GetConnector()->BindInterface( content::mojom::kBrowserServiceName, &rappor_recorder_); } rappor_recorder_->RecordRappor(metric, sample); +#endif } void ChromeContentRendererClient::RecordRapporURL(const std::string& metric, const GURL& url) { +#if 0 if (!rappor_recorder_) { RenderThread::Get()->GetConnector()->BindInterface( content::mojom::kBrowserServiceName, &rappor_recorder_); } rappor_recorder_->RecordRapporURL(metric, url); +#endif } void ChromeContentRendererClient::AddImageContextMenuProperties( diff --git a/chrome/renderer/chrome_content_renderer_client.h b/chrome/renderer/chrome_content_renderer_client.h index dd11c11af11c2..2adcd49dab213 100644 --- a/chrome/renderer/chrome_content_renderer_client.h +++ b/chrome/renderer/chrome_content_renderer_client.h @@ -105,6 +105,13 @@ class ChromeContentRendererClient : public content::ContentRendererClient { ChromeContentRendererClient(); ~ChromeContentRendererClient() override; + base::FilePath GetRootPath() override; + void willHandleNavigationPolicy(content::RenderView* rv, + blink::WebFrame* frame, + const blink::WebURLRequest& request, + blink::WebNavigationPolicy* policy, + blink::WebString* manifest, + bool new_win) override; void RenderThreadStarted() override; void RenderFrameCreated(content::RenderFrame* render_frame) override; void RenderViewCreated(content::RenderView* render_view) override; @@ -232,7 +239,9 @@ class ChromeContentRendererClient : public content::ContentRendererClient { blink::WebPluginParams* params); #endif +#if 0 rappor::mojom::RapporRecorderPtr rappor_recorder_; +#endif std::unique_ptr chrome_observer_; std::unique_ptr web_cache_impl_; diff --git a/chrome/renderer/chrome_render_frame_observer.cc b/chrome/renderer/chrome_render_frame_observer.cc index a49d2e2f8da0a..4da783d4e4749 100644 --- a/chrome/renderer/chrome_render_frame_observer.cc +++ b/chrome/renderer/chrome_render_frame_observer.cc @@ -130,9 +130,11 @@ ChromeRenderFrameObserver::ChromeRenderFrameObserver( *base::CommandLine::ForCurrentProcess(); if (!command_line.HasSwitch(switches::kDisableClientSidePhishingDetection)) OnSetClientSidePhishingDetection(true); +#if 0 translate_helper_ = new translate::TranslateHelper( render_frame, chrome::ISOLATED_WORLD_ID_TRANSLATE, extensions::kExtensionScheme); +#endif } ChromeRenderFrameObserver::~ChromeRenderFrameObserver() { @@ -266,12 +268,14 @@ void ChromeRenderFrameObserver::DidFinishLoad() { void ChromeRenderFrameObserver::DidStartProvisionalLoad( blink::WebDataSource* data_source) { +#if 0 // Let translate_helper do any preparatory work for loading a URL. if (!translate_helper_) return; translate_helper_->PrepareForUrl( render_frame()->GetWebFrame()->GetDocument().Url()); +#endif } void ChromeRenderFrameObserver::DidCommitProvisionalLoad( @@ -324,10 +328,12 @@ void ChromeRenderFrameObserver::CapturePageText(TextCaptureType capture_type) { UMA_HISTOGRAM_TIMES(kTranslateCaptureText, base::TimeTicks::Now() - capture_begin_time); +#if 0 // We should run language detection only once. Parsing finishes before // the page loads, so let's pick that timing. if (translate_helper_ && capture_type == PRELIMINARY_CAPTURE) translate_helper_->PageCaptured(contents); +#endif TRACE_EVENT0("renderer", "ChromeRenderFrameObserver::CapturePageText"); diff --git a/chrome/renderer/content_settings_observer.cc b/chrome/renderer/content_settings_observer.cc index 9d26b8953df87..ab841cb2fb553 100644 --- a/chrome/renderer/content_settings_observer.cc +++ b/chrome/renderer/content_settings_observer.cc @@ -400,7 +400,7 @@ bool ContentSettingsObserver::AllowWriteToClipboard(bool default_value) { } bool ContentSettingsObserver::AllowMutationEvents(bool default_value) { - return IsPlatformApp() ? false : default_value; + return default_value; } bool ContentSettingsObserver::AllowRunningInsecureContent( diff --git a/chrome/renderer/extensions/chrome_extensions_renderer_client.cc b/chrome/renderer/extensions/chrome_extensions_renderer_client.cc index b1127e949e6df..100a5ee914800 100644 --- a/chrome/renderer/extensions/chrome_extensions_renderer_client.cc +++ b/chrome/renderer/extensions/chrome_extensions_renderer_client.cc @@ -7,6 +7,8 @@ #include #include +#include "content/nw/src/nw_content.h" + #include "base/command_line.h" #include "base/lazy_instance.h" #include "chrome/common/chrome_isolated_world_ids.h" @@ -141,6 +143,7 @@ void ChromeExtensionsRendererClient::RenderThreadStarted() { if (!extension_dispatcher_) { extension_dispatcher_.reset( new extensions::Dispatcher(extension_dispatcher_delegate_.get())); + nw::ExtensionDispatcherCreated(extension_dispatcher_.get()); } permissions_policy_delegate_.reset( new extensions::RendererPermissionsPolicyDelegate( diff --git a/chrome/renderer/extensions/resource_request_policy.cc b/chrome/renderer/extensions/resource_request_policy.cc index 0519a63fe5363..7e15b83fb6039 100644 --- a/chrome/renderer/extensions/resource_request_policy.cc +++ b/chrome/renderer/extensions/resource_request_policy.cc @@ -81,7 +81,10 @@ bool ResourceRequestPolicy::CanRequestResource( // Exceptions are: // - empty origin (needed for some edge cases when we have empty origins) - bool is_empty_origin = frame_url.is_empty(); + // NWJS: about:blank here when load iframe in document-start-end + // case starting from cr53 + bool is_empty_origin = frame_url.is_empty() || frame_url == GURL(url::kAboutBlankURL); + // - extensions requesting their own resources (frame_url check is for // images, page_url check is for iframes) bool is_own_resource = frame_url.GetOrigin() == extension->url() || diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index c090e7af0ba14..28d77b1062222 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn @@ -1175,6 +1175,7 @@ test("browser_tests") { enable_multidex = true } else { # Not Android. sources += [ + "../../content/nw/src/nwjs_browsertest.cc", # The list of sources which is only used by chrome browser tests on # desktop platforms. "../../apps/app_restore_service_browsertest.cc", @@ -1247,7 +1248,7 @@ test("browser_tests") { "../browser/domain_reliability/browsertest.cc", "../browser/download/download_browsertest.cc", "../browser/download/download_browsertest.h", - "../browser/download/download_danger_prompt_browsertest.cc", + #"../browser/download/download_danger_prompt_browsertest.cc", "../browser/download/download_started_animation_browsertest.cc", "../browser/download/save_page_browsertest.cc", "../browser/extensions/active_tab_apitest.cc", @@ -1362,7 +1363,7 @@ test("browser_tests") { "../browser/extensions/content_capabilities_browsertest.cc", "../browser/extensions/content_script_apitest.cc", "../browser/extensions/content_security_policy_apitest.cc", - "../browser/extensions/content_verifier_browsertest.cc", + #"../browser/extensions/content_verifier_browsertest.cc", "../browser/extensions/crazy_extension_browsertest.cc", "../browser/extensions/cross_origin_xhr_apitest.cc", "../browser/extensions/crx_installer_browsertest.cc", @@ -1442,7 +1443,7 @@ test("browser_tests") { "../browser/geolocation/access_token_store_browsertest.cc", "../browser/geolocation/geolocation_browsertest.cc", "../browser/global_keyboard_shortcuts_mac_browsertest.mm", - "../browser/history/history_browsertest.cc", + #"../browser/history/history_browsertest.cc", "../browser/history/redirect_browsertest.cc", "../browser/iframe_browsertest.cc", "../browser/image_decoder_browsertest.cc", @@ -1542,8 +1543,8 @@ test("browser_tests") { "../browser/policy/cloud/device_management_service_browsertest.cc", "../browser/policy/cloud/test_request_interceptor.cc", "../browser/policy/cloud/test_request_interceptor.h", - "../browser/policy/policy_browsertest.cc", - "../browser/policy/policy_network_browsertest.cc", + #"../browser/policy/policy_browsertest.cc", + #"../browser/policy/policy_network_browsertest.cc", "../browser/policy/policy_prefs_browsertest.cc", "../browser/policy/policy_startup_browsertest.cc", "../browser/predictors/resource_prefetch_predictor_browsertest.cc", @@ -1554,10 +1555,10 @@ test("browser_tests") { "../browser/prefs/pref_service_browsertest.cc", "../browser/prefs/synced_pref_change_registrar_browsertest.cc", "../browser/prefs/tracked/pref_hash_browsertest.cc", - "../browser/prerender/prerender_browsertest.cc", - "../browser/prerender/prerender_nostate_prefetch_browsertest.cc", - "../browser/prerender/prerender_test_utils.cc", - "../browser/prerender/prerender_test_utils.h", + #"../browser/prerender/prerender_browsertest.cc", + #"../browser/prerender/prerender_nostate_prefetch_browsertest.cc", + #"../browser/prerender/prerender_test_utils.cc", + #"../browser/prerender/prerender_test_utils.h", "../browser/previews/previews_service_browser_test.cc", "../browser/printing/cloud_print/test/cloud_print_policy_browsertest.cc", "../browser/printing/cloud_print/test/cloud_print_proxy_process_browsertest.cc", @@ -1588,7 +1589,7 @@ test("browser_tests") { "../browser/search/suggestions/image_fetcher_impl_browsertest.cc", "../browser/search_engines/template_url_scraper_browsertest.cc", "../browser/service_process/service_process_control_browsertest.cc", - "../browser/sessions/better_session_restore_browsertest.cc", + #"../browser/sessions/better_session_restore_browsertest.cc", "../browser/sessions/persistent_tab_restore_service_browsertest.cc", "../browser/sessions/session_restore_browsertest.cc", "../browser/sessions/session_restore_browsertest_chromeos.cc", @@ -1602,15 +1603,15 @@ test("browser_tests") { "../browser/spellchecker/spellcheck_service_browsertest.cc", "../browser/ssl/cert_verifier_browser_test.cc", "../browser/ssl/cert_verifier_browser_test.h", - "../browser/ssl/certificate_reporting_test_utils.cc", + #"../browser/ssl/certificate_reporting_test_utils.cc", "../browser/ssl/certificate_reporting_test_utils.h", "../browser/ssl/chrome_ssl_host_state_delegate_test.cc", "../browser/ssl/security_state_tab_helper_browser_tests.cc", - "../browser/ssl/ssl_browser_tests.cc", + #"../browser/ssl/ssl_browser_tests.cc", "../browser/ssl/ssl_client_certificate_selector_test.cc", "../browser/ssl/ssl_client_certificate_selector_test.h", "../browser/storage/durable_storage_browsertest.cc", - "../browser/subresource_filter/subresource_filter_browsertest.cc", + #"../browser/subresource_filter/subresource_filter_browsertest.cc", "../browser/subresource_filter/test_ruleset_publisher.cc", "../browser/subresource_filter/test_ruleset_publisher.h", "../browser/sync_file_system/mock_local_change_processor.cc", @@ -1633,9 +1634,9 @@ test("browser_tests") { "../browser/task_manager/task_manager_tester.h", "../browser/themes/theme_service_browsertest.cc", "../browser/tracing/chrome_tracing_delegate_browsertest.cc", - "../browser/translate/translate_browsertest.cc", - "../browser/translate/translate_manager_browsertest.cc", - "../browser/ui/ask_google_for_suggestions_dialog_browsertest.cc", + #"../browser/translate/translate_browsertest.cc", + #"../browser/translate/translate_manager_browsertest.cc", + #"../browser/ui/ask_google_for_suggestions_dialog_browsertest.cc", "../browser/ui/autofill/card_unmask_prompt_view_browsertest.cc", "../browser/ui/autofill/card_unmask_prompt_view_tester.h", "../browser/ui/autofill/password_generation_popup_view_browsertest.cc", @@ -1655,7 +1656,7 @@ test("browser_tests") { "../browser/ui/extensions/extension_message_bubble_browsertest.cc", "../browser/ui/extensions/extension_message_bubble_browsertest.h", "../browser/ui/extensions/hosted_app_browsertest.cc", - "../browser/ui/find_bar/find_bar_host_browsertest.cc", + #"../browser/ui/find_bar/find_bar_host_browsertest.cc", "../browser/ui/javascript_dialogs/javascript_dialog_browsertest.cc", "../browser/ui/location_bar/location_bar_browsertest.cc", "../browser/ui/login/login_handler_browsertest.cc", @@ -1707,20 +1708,20 @@ test("browser_tests") { "../browser/ui/webui/identity_internals_ui_browsertest.h", "../browser/ui/webui/inspect_ui_browsertest.cc", "../browser/ui/webui/interstitials/interstitial_ui_browsertest.cc", - "../browser/ui/webui/log_web_ui_url_browsertest.cc", - "../browser/ui/webui/media_router/media_router_dialog_controller_impl_browsertest.cc", + #"../browser/ui/webui/log_web_ui_url_browsertest.cc", + #"../browser/ui/webui/media_router/media_router_dialog_controller_impl_browsertest.cc", "../browser/ui/webui/net_internals/net_internals_ui_browsertest.cc", "../browser/ui/webui/net_internals/net_internals_ui_browsertest.h", "../browser/ui/webui/ntp/new_tab_ui_browsertest.cc", "../browser/ui/webui/options/certificate_manager_browsertest.cc", - "../browser/ui/webui/options/clear_browser_data_browsertest.cc", - "../browser/ui/webui/options/content_settings_exception_area_browsertest.cc", + #"../browser/ui/webui/options/clear_browser_data_browsertest.cc", + #"../browser/ui/webui/options/content_settings_exception_area_browsertest.cc", "../browser/ui/webui/options/multilanguage_options_browsertest.cc", "../browser/ui/webui/options/multilanguage_options_browsertest.h", "../browser/ui/webui/options/options_browsertest.cc", "../browser/ui/webui/options/options_browsertest.h", - "../browser/ui/webui/options/options_ui_browsertest.cc", - "../browser/ui/webui/options/options_ui_browsertest.h", + #"../browser/ui/webui/options/options_ui_browsertest.cc", + #"../browser/ui/webui/options/options_ui_browsertest.h", "../browser/ui/webui/options/preferences_browsertest.cc", "../browser/ui/webui/options/preferences_browsertest.h", "../browser/ui/webui/password_manager_internals/password_manager_internals_ui_browsertest.cc", @@ -1733,7 +1734,7 @@ test("browser_tests") { "../browser/ui/webui/signin/inline_login_ui_browsertest.cc", "../browser/ui/webui/signin/user_manager_ui_browsertest.cc", "../browser/ui/webui/task_scheduler_internals/task_scheduler_internals_ui_browsertest.cc", - "../browser/ui/webui/uber/uber_ui_browsertest.cc", + #"../browser/ui/webui/uber/uber_ui_browsertest.cc", "../browser/ui/webui/webui_browsertest.cc", "../browser/ui/webui/webui_webview_browsertest.cc", "../browser/ui/zoom/zoom_controller_browsertest.cc", @@ -1761,8 +1762,8 @@ test("browser_tests") { "../renderer/chrome_render_frame_observer_browsertest.cc", "../renderer/content_settings_observer_browsertest.cc", "../renderer/media/cast_session_browsertest.cc", - "../renderer/translate/translate_helper_browsertest.cc", - "../renderer/translate/translate_script_browsertest.cc", + #"../renderer/translate/translate_helper_browsertest.cc", + #"../renderer/translate/translate_script_browsertest.cc", "base/chrome_render_view_test.cc", "base/chrome_render_view_test.h", "base/in_process_browser_test_browsertest.cc", @@ -1903,8 +1904,8 @@ test("browser_tests") { } if (enable_captive_portal_detection) { - sources += - [ "../browser/ssl/captive_portal_blocking_page_browsertest.cc" ] + #sources += + # [ "../browser/ssl/captive_portal_blocking_page_browsertest.cc" ] } if (!enable_one_click_signin) { sources -= [ "../browser/ui/sync/one_click_signin_links_delegate_impl_browsertest.cc" ] @@ -2091,12 +2092,12 @@ test("browser_tests") { "../browser/ui/views/frame/browser_non_client_frame_view_browsertest.cc", "../browser/ui/views/frame/browser_view_browsertest.cc", "../browser/ui/views/location_bar/zoom_bubble_view_browsertest.cc", - "../browser/ui/views/media_router/media_router_ui_browsertest.cc", + #"../browser/ui/views/media_router/media_router_ui_browsertest.cc", "../browser/ui/views/passwords/password_dialog_view_browsertest.cc", "../browser/ui/views/session_crashed_bubble_view_browsertest.cc", "../browser/ui/views/task_manager_view_browsertest.cc", "../browser/ui/views/toolbar/browser_actions_container_browsertest.cc", - "../browser/ui/views/translate/translate_bubble_view_browsertest.cc", + #"../browser/ui/views/translate/translate_bubble_view_browsertest.cc", "../browser/ui/views/web_dialog_view_browsertest.cc", ] } @@ -3301,7 +3302,7 @@ test("unit_tests") { "../browser/ui/webui/browsing_history_handler_unittest.cc", "../browser/ui/webui/fileicon_source_unittest.cc", "../browser/ui/webui/local_state/local_state_ui_unittest.cc", - "../browser/ui/webui/log_web_ui_url_unittest.cc", + #"../browser/ui/webui/log_web_ui_url_unittest.cc", "../browser/update_client/chrome_update_query_params_delegate_unittest.cc", "../browser/webshare/share_target_pref_helper_unittest.cc", "../browser/win/chrome_elf_init_unittest.cc", diff --git a/chrome/test/base/test_launcher_utils.cc b/chrome/test/base/test_launcher_utils.cc index 7dd5f9251b179..1136c5c0d5fd3 100644 --- a/chrome/test/base/test_launcher_utils.cc +++ b/chrome/test/base/test_launcher_utils.cc @@ -46,7 +46,7 @@ void PrepareBrowserCommandLineForTests(base::CommandLine* command_line) { command_line->AppendSwitchASCII(switches::kLoggingLevel, "0"); // info // Disable safebrowsing autoupdate. - command_line->AppendSwitch(safe_browsing::switches::kSbDisableAutoUpdate); + //command_line->AppendSwitch(safe_browsing::switches::kSbDisableAutoUpdate); // Don't install default apps. command_line->AppendSwitch(switches::kDisableDefaultApps); diff --git a/chrome/test/base/testing_browser_process.cc b/chrome/test/base/testing_browser_process.cc index 93446527f496b..bc07d16f48bfd 100644 --- a/chrome/test/base/testing_browser_process.cc +++ b/chrome/test/base/testing_browser_process.cc @@ -335,6 +335,7 @@ net_log::ChromeNetLog* TestingBrowserProcess::net_log() { return nullptr; } +#if 0 component_updater::ComponentUpdateService* TestingBrowserProcess::component_updater() { return nullptr; @@ -353,6 +354,7 @@ component_updater::SupervisedUserWhitelistInstaller* TestingBrowserProcess::supervised_user_whitelist_installer() { return nullptr; } +#endif MediaFileSystemRegistry* TestingBrowserProcess::media_file_system_registry() { #if defined(OS_ANDROID) diff --git a/chrome/test/base/testing_browser_process.h b/chrome/test/base/testing_browser_process.h index 9c6b80f883c24..75d3c9e9fba0f 100644 --- a/chrome/test/base/testing_browser_process.h +++ b/chrome/test/base/testing_browser_process.h @@ -113,12 +113,15 @@ class TestingBrowserProcess : public BrowserProcess { #endif net_log::ChromeNetLog* net_log() override; + +#if 0 component_updater::ComponentUpdateService* component_updater() override; CRLSetFetcher* crl_set_fetcher() override; component_updater::PnaclComponentInstaller* pnacl_component_installer() override; component_updater::SupervisedUserWhitelistInstaller* supervised_user_whitelist_installer() override; +#endif MediaFileSystemRegistry* media_file_system_registry() override; bool created_local_state() const override; diff --git a/chrome/test/chromedriver/capabilities.cc b/chrome/test/chromedriver/capabilities.cc index c10ce6003a60a..4dd78033b106a 100644 --- a/chrome/test/chromedriver/capabilities.cc +++ b/chrome/test/chromedriver/capabilities.cc @@ -217,6 +217,20 @@ Status ParseSwitches(const base::Value& option, return Status(kOk); } +Status ParseArguments(const base::Value& option, + Capabilities* capabilities) { + const base::ListValue* arg_list = NULL; + if (!option.GetAsList(&arg_list)) + return Status(kUnknownError, "must be a list"); + for (size_t i = 0; i < arg_list->GetSize(); ++i) { + std::string arg_string; + if (!arg_list->GetString(i, &arg_string)) + return Status(kUnknownError, "each argument must be a string"); + capabilities->arguments.push_back(arg_string); + } + return Status(kOk); +} + Status ParseExtensions(const base::Value& option, Capabilities* capabilities) { const base::ListValue* extensions = NULL; if (!option.GetAsList(&extensions)) @@ -475,6 +489,7 @@ Status ParseChromeOptions( parser_map["debuggerAddress"] = base::Bind(&ParseUseRemoteBrowser); } else { parser_map["args"] = base::Bind(&ParseSwitches); + parser_map["nwargs"] = base::Bind(&ParseArguments); parser_map["binary"] = base::Bind(&ParseFilePath, &capabilities->binary); parser_map["detach"] = base::Bind(&ParseBoolean, &capabilities->detach); parser_map["excludeSwitches"] = base::Bind(&ParseExcludeSwitches); diff --git a/chrome/test/chromedriver/capabilities.h b/chrome/test/chromedriver/capabilities.h index 068c5a19daed1..cd780146bd806 100644 --- a/chrome/test/chromedriver/capabilities.h +++ b/chrome/test/chromedriver/capabilities.h @@ -130,6 +130,8 @@ struct Capabilities { std::vector extensions; + std::vector arguments; + // True if should always use DevTools for taking screenshots. // This is experimental and may be removed at a later point. bool force_devtools_screenshot; diff --git a/chrome/test/chromedriver/chrome/chrome_finder.cc b/chrome/test/chromedriver/chrome/chrome_finder.cc index ecdbbb47ce5f9..ee094aa25fc6e 100644 --- a/chrome/test/chromedriver/chrome/chrome_finder.cc +++ b/chrome/test/chromedriver/chrome/chrome_finder.cc @@ -25,7 +25,7 @@ namespace { -#if defined(OS_WIN) +#if 0 void GetApplicationDirs(std::vector* locations) { std::vector installation_locations; base::FilePath local_app_data, program_files, program_files_x86; @@ -45,7 +45,7 @@ void GetApplicationDirs(std::vector* locations) { installation_locations[i].Append(L"Chromium\\Application")); } } -#elif defined(OS_LINUX) +#elif 0 void GetApplicationDirs(std::vector* locations) { locations->push_back(base::FilePath("/opt/google/chrome")); locations->push_back(base::FilePath("/usr/local/bin")); @@ -84,22 +84,18 @@ bool FindExe( } // namespace internal -#if defined(OS_MACOSX) +#if 0 void GetApplicationDirs(std::vector* locations); #endif bool FindChrome(base::FilePath* browser_exe) { base::FilePath browser_exes_array[] = { #if defined(OS_WIN) - base::FilePath(L"chrome.exe") + base::FilePath(L"nw.exe") #elif defined(OS_MACOSX) - base::FilePath("Google Chrome.app/Contents/MacOS/Google Chrome"), - base::FilePath("Chromium.app/Contents/MacOS/Chromium") + base::FilePath("nwjs.app/Contents/MacOS/nwjs") #elif defined(OS_LINUX) - base::FilePath("google-chrome"), - base::FilePath("chrome"), - base::FilePath("chromium"), - base::FilePath("chromium-browser") + base::FilePath("nw"), #else // it will compile but won't work on other OSes base::FilePath() @@ -120,7 +116,10 @@ bool FindChrome(base::FilePath* browser_exe) { } std::vector locations; - GetApplicationDirs(&locations); + base::FilePath exe_path; + PathService::Get(base::DIR_EXE, &exe_path); + locations.push_back(exe_path); + return internal::FindExe( base::Bind(&base::PathExists), browser_exes, diff --git a/chrome/test/chromedriver/chrome/chrome_impl.cc b/chrome/test/chromedriver/chrome/chrome_impl.cc index aa23744686dcd..27c02e0bdd4b7 100644 --- a/chrome/test/chromedriver/chrome/chrome_impl.cc +++ b/chrome/test/chromedriver/chrome/chrome_impl.cc @@ -7,6 +7,8 @@ #include #include +#include "base/strings/string_util.h" + #include "chrome/test/chromedriver/chrome/devtools_client.h" #include "chrome/test/chromedriver/chrome/devtools_event_listener.h" #include "chrome/test/chromedriver/chrome/devtools_http_client.h" @@ -44,13 +46,25 @@ Status ChromeImpl::GetWebViewIdForFirstTab(std::string* web_view_id, if (status.IsError()) return status; UpdateWebViews(views_info, w3c_compliant); + std::string ret; for (size_t i = 0; i < views_info.GetSize(); ++i) { const WebViewInfo& view = views_info.Get(i); - if (view.type == WebViewInfo::kPage) { - *web_view_id = view.id; - return Status(kOk); + if (view.type == WebViewInfo::kPage || + view.type == WebViewInfo::kApp || + (view.type == WebViewInfo::kOther && + !base::StartsWith(view.url, "chrome-extension://", base::CompareCase::SENSITIVE) && + !base::StartsWith(view.url, "about:blank", base::CompareCase::SENSITIVE))) { + ret = view.id; + if (view.type != WebViewInfo::kOther) { + *web_view_id = view.id; + return Status(kOk); + } } } + if (!ret.empty()) { + *web_view_id = ret; + return Status(kOk); + } return Status(kUnknownError, "unable to discover open window in chrome"); } diff --git a/chrome/test/chromedriver/chrome/devtools_http_client.cc b/chrome/test/chromedriver/chrome/devtools_http_client.cc index b9c47087f3abf..8d0266db03655 100644 --- a/chrome/test/chromedriver/chrome/devtools_http_client.cc +++ b/chrome/test/chromedriver/chrome/devtools_http_client.cc @@ -161,6 +161,15 @@ bool DevToolsHttpClient::IsBrowserWindow(const WebViewInfo& view) const { return base::ContainsKey(*window_types_, view.type) || (view.type == WebViewInfo::kOther && (view.url == "chrome://print/" || + view.url == "" || view.url == "about:blank" || + // base::StartsWith(view.url, "chrome-extension://", + // base::CompareCase::SENSITIVE) || + base::StartsWith(view.url, "file://", + base::CompareCase::SENSITIVE) || + base::StartsWith(view.url, "http://", + base::CompareCase::SENSITIVE) || + base::StartsWith(view.url, "https://", + base::CompareCase::SENSITIVE) || view.url == "chrome://media-router/")); } diff --git a/chrome/test/chromedriver/chrome_launcher.cc b/chrome/test/chromedriver/chrome_launcher.cc index c1988631dfe1f..fa28cec5f5a62 100644 --- a/chrome/test/chromedriver/chrome_launcher.cc +++ b/chrome/test/chromedriver/chrome_launcher.cc @@ -62,6 +62,8 @@ #include "chrome/test/chromedriver/keycode_text_conversion.h" #endif +#include "base/strings/string_number_conversions.h" + namespace { const char* const kCommonSwitches[] = { @@ -69,6 +71,7 @@ const char* const kCommonSwitches[] = { "metrics-recording-only", }; +#if 0 const char* const kDesktopSwitches[] = { "disable-hang-monitor", "disable-prompt-on-repost", @@ -86,6 +89,7 @@ const char* const kDesktopSwitches[] = { "test-type=webdriver", "force-fieldtrials=SiteIsolationExtensions/Control", }; +#endif const char* const kAndroidSwitches[] = { "disable-fre", "enable-remote-debugging", @@ -136,8 +140,10 @@ Status PrepareCommandLine(uint16_t port, for (auto* common_switch : kCommonSwitches) switches.SetUnparsedSwitch(common_switch); +#if 0 //FIXME if enabled, chromedriver cannot find chrome on windows for (auto* desktop_switch : kDesktopSwitches) switches.SetUnparsedSwitch(desktop_switch); +#endif switches.SetSwitch("remote-debugging-port", base::UintToString(port)); for (const auto& excluded_switch : capabilities.exclude_switches) { switches.RemoveSwitch(excluded_switch); @@ -149,7 +155,7 @@ Status PrepareCommandLine(uint16_t port, user_data_dir_path = base::FilePath( switches.GetSwitchValueNative("user-data-dir")); } else { - command.AppendArg("data:,"); + //command.AppendArg("data:,"); if (!user_data_dir->CreateUniqueTempDir()) return Status(kUnknownError, "cannot create temp dir for user data dir"); switches.SetSwitch("user-data-dir", user_data_dir->GetPath().value()); @@ -172,6 +178,10 @@ Status PrepareCommandLine(uint16_t port, if (status.IsError()) return status; switches.AppendToCommandLine(&command); + + for (size_t i = 0; i < capabilities.arguments.size(); i++) + command.AppendArg(capabilities.arguments[i]); + *prepared_command = command; return Status(kOk); } @@ -194,11 +204,17 @@ Status WaitForDevToolsAndCheckVersion( window_types.reset(new std::set()); } + base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess(); + int timeout = 60; + if (cmd_line->HasSwitch("launch-timeout")) { + std::string s_timeout = cmd_line->GetSwitchValueASCII("launch-timeout"); + base::StringToInt(s_timeout, &timeout); + } std::unique_ptr client(new DevToolsHttpClient( address, context_getter, socket_factory, std::move(device_metrics), std::move(window_types), capabilities->page_load_strategy)); base::TimeTicks deadline = - base::TimeTicks::Now() + base::TimeDelta::FromSeconds(60); + base::TimeTicks::Now() + base::TimeDelta::FromSeconds(timeout); Status status = client->Init(deadline - base::TimeTicks::Now()); if (status.IsError()) return status; @@ -220,7 +236,6 @@ Status WaitForDevToolsAndCheckVersion( } } - base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess(); if (cmd_line->HasSwitch("disable-build-check")) { LOG(WARNING) << "You are using an unsupported command-line switch: " "--disable-build-check. Please don't report bugs that " @@ -235,7 +250,9 @@ Status WaitForDevToolsAndCheckVersion( WebViewsInfo views_info; client->GetWebViewsInfo(&views_info); for (size_t i = 0; i < views_info.GetSize(); ++i) { - if (views_info.Get(i).type == WebViewInfo::kPage) { + if (views_info.Get(i).type == WebViewInfo::kApp + || (views_info.Get(i).type == WebViewInfo::kOther && + !base::StartsWith(views_info.Get(i).url, "chrome-extension://", base::CompareCase::SENSITIVE))) { //node-remote page *user_client = std::move(client); return Status(kOk); } diff --git a/chrome/tools/build/linux/FILES.cfg b/chrome/tools/build/linux/FILES.cfg index 338e15f6642d4..bd0d85996aa01 100644 --- a/chrome/tools/build/linux/FILES.cfg +++ b/chrome/tools/build/linux/FILES.cfg @@ -36,11 +36,11 @@ FILES = [ 'buildtype': ['dev', 'official'], }, { - 'filename': 'chrome_100_percent.pak', + 'filename': 'nw_100_percent.pak', 'buildtype': ['dev', 'official'], }, { - 'filename': 'chrome_200_percent.pak', + 'filename': 'nw_200_percent.pak', 'buildtype': ['dev', 'official'], }, { diff --git a/chrome/tools/build/win/FILES.cfg b/chrome/tools/build/win/FILES.cfg index 58d577183160c..9d0b641a01671 100644 --- a/chrome/tools/build/win/FILES.cfg +++ b/chrome/tools/build/win/FILES.cfg @@ -85,11 +85,11 @@ FILES = [ 'filegroup': ['default', 'symsrc'], }, { - 'filename': 'chrome_100_percent.pak', + 'filename': 'nw_100_percent.pak', 'buildtype': ['dev', 'official'], }, { - 'filename': 'chrome_200_percent.pak', + 'filename': 'nw_200_percent.pak', 'buildtype': ['dev', 'official'], 'optional': ['dev', 'official'], }, diff --git a/chrome/tools/build/win/syzygy/BUILD.gn b/chrome/tools/build/win/syzygy/BUILD.gn index 08139f1bb3f59..25e8c3b35295e 100644 --- a/chrome/tools/build/win/syzygy/BUILD.gn +++ b/chrome/tools/build/win/syzygy/BUILD.gn @@ -12,7 +12,7 @@ syzygy_dest_dir = "$root_out_dir/syzygy" if (is_syzyasan) { syzygy_asan("chrome_dll_syzygy") { - binary_name = "chrome.dll" + binary_name = "nw.dll" dest_dir = syzygy_dest_dir deps = [ "//chrome:main_dll", @@ -32,7 +32,7 @@ if (is_syzyasan) { # uninstrumented. Otherwise, chrome_child is also instrumented to the # normal place. syzygy_asan("chrome_child_dll_syzygy") { - binary_name = "chrome_child.dll" + binary_name = "nw_child.dll" deps = [ "//chrome:chrome_child", ] diff --git a/chrome/utility/chrome_content_utility_client.cc b/chrome/utility/chrome_content_utility_client.cc index 65c4b31e5193e..d4c3d6bb33fa2 100644 --- a/chrome/utility/chrome_content_utility_client.cc +++ b/chrome/utility/chrome_content_utility_client.cc @@ -71,6 +71,10 @@ #endif #endif +#if defined(OS_WIN) +#pragma warning(disable:4065) +#endif + namespace { class FilePatcherImpl : public chrome::mojom::FilePatcher { diff --git a/chrome_elf/BUILD.gn b/chrome_elf/BUILD.gn index c8197e919e95b..e6cb80401f54e 100644 --- a/chrome_elf/BUILD.gn +++ b/chrome_elf/BUILD.gn @@ -32,6 +32,7 @@ windows_manifest("chrome_elf_manifest") { # We should move chrome_result_codes.h to another target which does not bring # in the world. shared_library("chrome_elf") { + output_name = "nw_elf" sources = [ "chrome_elf.def", "chrome_elf_main.cc", diff --git a/chrome_elf/chrome_elf.def b/chrome_elf/chrome_elf.def index b4c3936e3f044..f8d6f5438f974 100644 --- a/chrome_elf/chrome_elf.def +++ b/chrome_elf/chrome_elf.def @@ -2,7 +2,7 @@ ; Use of this source code is governed by a BSD-style license that can be ; found in the LICENSE file. -LIBRARY "chrome_elf.dll" +LIBRARY "nw_elf.dll" EXPORTS AddDllToBlacklist @@ -13,3 +13,4 @@ EXPORTS SignalChromeElf SignalInitializeCrashReporting SuccessfullyBlocked + ElfGetReporterClient diff --git a/chrome_elf/chrome_elf.ver b/chrome_elf/chrome_elf.ver index 78f890e7ece7d..92d53efaa487f 100644 --- a/chrome_elf/chrome_elf.ver +++ b/chrome_elf/chrome_elf.ver @@ -1,2 +1,2 @@ -INTERNAL_NAME=chrome_elf_dll -ORIGINAL_FILENAME=chrome_elf.dll +INTERNAL_NAME=nw_elf_dll +ORIGINAL_FILENAME=nw_elf.dll diff --git a/chrome_elf/chrome_elf_main.cc b/chrome_elf/chrome_elf_main.cc index 926668c54d301..a33fd1cea06d6 100644 --- a/chrome_elf/chrome_elf_main.cc +++ b/chrome_elf/chrome_elf_main.cc @@ -4,6 +4,7 @@ #include "chrome_elf/chrome_elf_main.h" +#include "components/crash/content/app/crash_reporter_client.h" #include #include @@ -14,10 +15,24 @@ #include "chrome_elf/blacklist/blacklist.h" #include "chrome_elf/crash/crash_helper.h" +extern std::wstring g_nwjs_prod_name, g_nwjs_prod_version; // This function is a temporary workaround for https://crbug.com/655788. We // need to come up with a better way to initialize crash reporting that can // happen inside DllMain(). -void SignalInitializeCrashReporting() { +void SignalInitializeCrashReporting(void* prod_name, void* prod_version) { + if (prod_name) g_nwjs_prod_name = *(std::wstring*)prod_name; + if (prod_version) g_nwjs_prod_version = *(std::wstring*)prod_version; + if (prod_name || prod_version) { + //install_static::InitializeProductDetailsForPrimaryModule(); +#if 0 + std::wstring user_data_dir, invalid_user_data_dir; + install_static::PrimaryInstallDetails* details = (install_static::PrimaryInstallDetails*)&install_static::InstallDetails::Get(); + const install_static::InstallDetails::Payload* payload = details->GetPayload(); + install_static::DeriveUserDataDirectory(*payload->mode, &user_data_dir, &invalid_user_data_dir); + details->set_user_data_dir(user_data_dir); + details->set_invalid_user_data_dir(invalid_user_data_dir); +#endif + } if (!elf_crash::InitializeCrashReporting()) { #ifdef _DEBUG assert(false); @@ -44,13 +59,19 @@ extern "C" void GetUserDataDirectoryThunk(wchar_t* user_data_dir, invalid_user_data_dir_str.c_str(), _TRUNCATE); } +void* ElfGetReporterClient() { + return crash_reporter::GetCrashReporterClient(); +} + BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID reserved) { if (reason == DLL_PROCESS_ATTACH) { install_static::InitializeProductDetailsForPrimaryModule(); // CRT on initialization installs an exception filter which calls // TerminateProcess. We need to hook CRT's attempt to set an exception. +#if 0 ////disable this or NW will fail with Enigma VB elf_crash::DisableSetUnhandledExceptionFilter(); +#endif install_static::InitializeProcessType(); diff --git a/chrome_elf/chrome_elf_main.h b/chrome_elf/chrome_elf_main.h index 432c377eb2af6..bf707b61d5b09 100644 --- a/chrome_elf/chrome_elf_main.h +++ b/chrome_elf/chrome_elf_main.h @@ -5,7 +5,8 @@ #ifndef CHROME_ELF_CHROME_ELF_MAIN_H_ #define CHROME_ELF_CHROME_ELF_MAIN_H_ -extern "C" void SignalInitializeCrashReporting(); +extern "C" void SignalInitializeCrashReporting(void*, void*); extern "C" void SignalChromeElf(); +extern "C" void* ElfGetReporterClient(); #endif // CHROME_ELF_CHROME_ELF_MAIN_H_ diff --git a/components/about_ui/resources/about_credits.tmpl b/components/about_ui/resources/about_credits.tmpl index fc4fc965ac9ec..2285b19329868 100644 --- a/components/about_ui/resources/about_credits.tmpl +++ b/components/about_ui/resources/about_credits.tmpl @@ -44,7 +44,6 @@ body { background-color: #e8eef7; border-radius: 3px; clear: both; - display: none; padding: 16px; } .licence h3 { diff --git a/components/about_ui/resources/about_credits_entry.tmpl b/components/about_ui/resources/about_credits_entry.tmpl index d1810cd940294..99b354cf89fee 100644 --- a/components/about_ui/resources/about_credits_entry.tmpl +++ b/components/about_ui/resources/about_credits_entry.tmpl @@ -1,6 +1,5 @@
{{name}} -show license homepage
{{license}}
diff --git a/components/app_modal/javascript_dialog_manager.cc b/components/app_modal/javascript_dialog_manager.cc index c5a368384b597..172bc1c21eaa4 100644 --- a/components/app_modal/javascript_dialog_manager.cc +++ b/components/app_modal/javascript_dialog_manager.cc @@ -31,7 +31,7 @@ namespace { #if !defined(OS_ANDROID) // Keep in sync with kDefaultMessageWidth, but allow some space for the rest of // the text. -const int kUrlElideWidth = 350; +//const int kUrlElideWidth = 350; #endif class DefaultExtensionsClient : public JavaScriptDialogExtensionsClient { @@ -95,6 +95,8 @@ JavaScriptDialogManager::~JavaScriptDialogManager() { base::string16 JavaScriptDialogManager::GetTitle( content::WebContents* web_contents, const GURL& origin_url) { + return base::string16(); +#if 0 // For extensions, show the extension name, but only if the origin of // the alert matches the top-level WebContents. std::string name; @@ -123,6 +125,7 @@ base::string16 JavaScriptDialogManager::GetTitle( is_same_origin_as_main_frame ? IDS_JAVASCRIPT_MESSAGEBOX_TITLE_NONSTANDARD_URL : IDS_JAVASCRIPT_MESSAGEBOX_TITLE_NONSTANDARD_URL_IFRAME); +#endif } void JavaScriptDialogManager::RunJavaScriptDialog( @@ -185,7 +188,7 @@ void JavaScriptDialogManager::RunJavaScriptDialog( AppModalDialogQueue::GetInstance()->AddDialog(new JavaScriptAppModalDialog( web_contents, &javascript_dialog_extra_data_, dialog_title, dialog_type, message_text, default_prompt_text, - ShouldDisplaySuppressCheckbox(extra_data), + false, //ShouldDisplaySuppressCheckbox(extra_data), false, // is_before_unload_dialog false, // is_reload base::Bind(&JavaScriptDialogManager::OnDialogClosed, diff --git a/components/autofill/core/browser/autofill_download_manager.cc b/components/autofill/core/browser/autofill_download_manager.cc index 8d7d72588f461..cf07776b04240 100644 --- a/components/autofill/core/browser/autofill_download_manager.cc +++ b/components/autofill/core/browser/autofill_download_manager.cc @@ -136,7 +136,7 @@ const net::BackoffEntry::Policy kAutofillBackoffPolicy = { #if defined(GOOGLE_CHROME_BUILD) const char kClientName[] = "Google Chrome"; #else -const char kClientName[] = "Chromium"; +const char kClientName[] = "nwjs"; #endif // defined(GOOGLE_CHROME_BUILD) size_t CountActiveFieldsInForms(const std::vector& forms) { diff --git a/components/content_settings/core/browser/content_settings_registry.cc b/components/content_settings/core/browser/content_settings_registry.cc index 6b18f449543ca..3f2c6712596a5 100644 --- a/components/content_settings/core/browser/content_settings_registry.cc +++ b/components/content_settings/core/browser/content_settings_registry.cc @@ -177,7 +177,7 @@ void ContentSettingsRegistry::Init() { ContentSettingsInfo::INHERIT_IF_LESS_PERMISSIVE); Register(CONTENT_SETTINGS_TYPE_NOTIFICATIONS, "notifications", - CONTENT_SETTING_ASK, WebsiteSettingsInfo::UNSYNCABLE, + CONTENT_SETTING_ALLOW, WebsiteSettingsInfo::UNSYNCABLE, WhitelistedSchemes(), ValidSettings(CONTENT_SETTING_ALLOW, CONTENT_SETTING_BLOCK, CONTENT_SETTING_ASK), diff --git a/components/cookie_config/cookie_store_util.cc b/components/cookie_config/cookie_store_util.cc index c1aa494335c04..15f106b019aa4 100644 --- a/components/cookie_config/cookie_store_util.cc +++ b/components/cookie_config/cookie_store_util.cc @@ -14,6 +14,8 @@ namespace cookie_config { #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) namespace { +bool g_should_encrypt = true; + // Use the operating system's mechanisms to encrypt cookies before writing // them to persistent store. Currently this only is done with desktop OS's // because ChromeOS and Android already protect the entire profile contents. @@ -39,7 +41,7 @@ bool CookieOSCryptoDelegate::ShouldEncrypt() { // rewritten. return false; #else - return true; + return g_should_encrypt; #endif } @@ -63,6 +65,11 @@ base::LazyInstance::DestructorAtExit net::CookieCryptoDelegate* GetCookieCryptoDelegate() { return g_cookie_crypto_delegate.Pointer(); } + +void SetEnableCookieCrypto(bool enable) { + g_should_encrypt = enable; +} + #else // defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) net::CookieCryptoDelegate* GetCookieCryptoDelegate() { return NULL; diff --git a/components/cookie_config/cookie_store_util.h b/components/cookie_config/cookie_store_util.h index 893e6a07db7c8..ea782212ec4ad 100644 --- a/components/cookie_config/cookie_store_util.h +++ b/components/cookie_config/cookie_store_util.h @@ -15,7 +15,7 @@ namespace cookie_config { // this platform. The object returned is a LazyInstance. Ownership is not // transferred. net::CookieCryptoDelegate* GetCookieCryptoDelegate(); - +void SetEnableCookieCrypto(bool enable); } // namespace cookie_config #endif // COMPONENTS_COOKIE_CONFIG_COOKIE_STORE_UTIL_H_ diff --git a/components/crash/content/app/breakpad_linux.cc b/components/crash/content/app/breakpad_linux.cc index 0d3de65043a0b..6decfcbc30ab5 100644 --- a/components/crash/content/app/breakpad_linux.cc +++ b/components/crash/content/app/breakpad_linux.cc @@ -87,7 +87,7 @@ namespace breakpad { namespace { -#if !defined(OS_CHROMEOS) +#if 0 const char kUploadURL[] = "https://clients2.google.com/cr/report"; #endif @@ -798,7 +798,6 @@ void EnableCrashDumping(bool unattended) { minidump_descriptor.set_size_limit(kMaxMinidumpFileSize); } #if defined(OS_ANDROID) - unattended = true; // Android never uploads directly. SetMinidumpSanitizationFields(&minidump_descriptor, sanitization_info); #endif if (unattended) { @@ -1352,12 +1351,26 @@ void ExecUploadProcessOrTerminate(const BreakpadInfo& info, StringFromPrefixAndUint("/dev/fd/", upload_status_fd, allocator); static const char kWgetBinary[] = "/usr/bin/wget"; + char* const upload_url = reinterpret_cast(allocator->Alloc(crash_keys::kLargeSize)); + *upload_url='\0'; + int i = 1; + do { + char key_name[16]; + my_strlcpy(key_name, "url-nwjs-", sizeof(key_name)); + my_uitos(key_name + 9, i, my_uint_len(i)); + key_name[9 + my_uint_len(i)] = '\0'; + const char* chunk = g_crash_keys->GetValueForKey(key_name); + if (!chunk) + break; + my_strlcat(upload_url, chunk, crash_keys::kLargeSize); + i++; + } while(true); const char* args[] = { kWgetBinary, header_content_encoding, header_content_type, post_file, - kUploadURL, + upload_url, "--timeout=10", // Set a timeout so we don't hang forever. "--tries=1", // Don't retry if the upload fails. "-O", // Output reply to the file descriptor path. diff --git a/components/crash/content/app/crash_reporter_client.cc b/components/crash/content/app/crash_reporter_client.cc index 2e9ee28e1b00e..22d9b0cd10cc1 100644 --- a/components/crash/content/app/crash_reporter_client.cc +++ b/components/crash/content/app/crash_reporter_client.cc @@ -41,6 +41,10 @@ void CrashReporterClient::SetCrashReporterClientIdFromGUID( const std::string& client_guid) {} #endif +void CrashReporterClient::SetUploadDump(bool upload) { + enable_upload_ = upload; +} + #if defined(OS_WIN) bool CrashReporterClient::ShouldCreatePipeName( const base::string16& process_type) { @@ -88,7 +92,7 @@ int CrashReporterClient::GetResultCodeRespawnFailed() { } #endif -#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_IOS) +#if defined(OS_POSIX) && !defined(OS_IOS) void CrashReporterClient::GetProductNameAndVersion(const char** product_name, const char** version) { } diff --git a/components/crash/content/app/crash_reporter_client.h b/components/crash/content/app/crash_reporter_client.h index 9f69c193dda2a..fa670e15af8bc 100644 --- a/components/crash/content/app/crash_reporter_client.h +++ b/components/crash/content/app/crash_reporter_client.h @@ -38,7 +38,7 @@ class CrashReporterClient; // runtime. void SetCrashReporterClient(CrashReporterClient* client); -#if defined(CRASH_IMPLEMENTATION) +#if 1 // The components's embedder API should only be used by the component. CrashReporterClient* GetCrashReporterClient(); #endif @@ -59,7 +59,7 @@ class CrashReporterClient { // not be set directly by the client. virtual void SetCrashReporterClientIdFromGUID(const std::string& client_guid); #endif - + virtual void SetUploadDump(bool); #if defined(OS_WIN) // Returns true if the pipe name to connect to breakpad should be computed and // stored in the process's environment block. By default, returns true for the @@ -104,7 +104,7 @@ class CrashReporterClient { virtual int GetResultCodeRespawnFailed(); #endif -#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_IOS) +#if defined(OS_POSIX) && !defined(OS_IOS) // Returns a textual description of the product type and version to include // in the crash report. Neither out parameter should be set to NULL. virtual void GetProductNameAndVersion(const char** product_name, @@ -197,6 +197,10 @@ class CrashReporterClient { // Returns true if breakpad should run in the given process type. virtual bool EnableBreakpadForProcess(const std::string& process_type); + + bool enable_upload_; + std::string product_name_; + std::string product_version_; }; } // namespace crash_reporter diff --git a/components/crash/content/app/crashpad_mac.mm b/components/crash/content/app/crashpad_mac.mm index 3bae07e14c690..377cac5330ce2 100644 --- a/components/crash/content/app/crashpad_mac.mm +++ b/components/crash/content/app/crashpad_mac.mm @@ -46,6 +46,10 @@ // Is there a way to recover if this fails? CrashReporterClient* crash_reporter_client = GetCrashReporterClient(); + const char* product_name = ""; + const char* version = ""; + + crash_reporter_client->GetProductNameAndVersion(&product_name, &version); crash_reporter_client->GetCrashDumpLocation(&database_path); crash_reporter_client->GetCrashMetricsLocation(&metrics_path); @@ -58,7 +62,9 @@ #endif std::map process_annotations; - + process_annotations["prod"] = product_name; + process_annotations["ver"] = version; +#if 0 NSBundle* outer_bundle = base::mac::OuterBundle(); NSString* product = base::mac::ObjCCast([outer_bundle objectForInfoDictionaryKey:base::mac::CFToNSCast(kCFBundleNameKey)]); @@ -83,7 +89,7 @@ base::mac::ObjCCast([base::mac::FrameworkBundle() objectForInfoDictionaryKey:@"CFBundleShortVersionString"]); process_annotations["ver"] = base::SysNSStringToUTF8(version); - +#endif process_annotations["plat"] = std::string("OS X"); std::vector arguments; diff --git a/components/crx_file/id_util.cc b/components/crx_file/id_util.cc index 85584f3ad1754..9fbc72b50b20b 100644 --- a/components/crx_file/id_util.cc +++ b/components/crx_file/id_util.cc @@ -82,6 +82,7 @@ base::FilePath MaybeNormalizePath(const base::FilePath& path) { } bool IdIsValid(const std::string& id) { +#if 0 // Verify that the id is legal. if (id.size() != (crx_file::id_util::kIdSize * 2)) return false; @@ -92,7 +93,7 @@ bool IdIsValid(const std::string& id) { for (size_t i = 0; i < temp.size(); i++) if (temp[i] < 'a' || temp[i] > 'p') return false; - +#endif return true; } diff --git a/components/gcm_driver/gcm_channel_status_syncer.cc b/components/gcm_driver/gcm_channel_status_syncer.cc index cbe1ba2fd4dcb..0ff9e239a4aba 100644 --- a/components/gcm_driver/gcm_channel_status_syncer.cc +++ b/components/gcm_driver/gcm_channel_status_syncer.cc @@ -20,6 +20,8 @@ #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" +#include "content/nw/src/nw_base.h" + namespace gcm { namespace { @@ -61,7 +63,7 @@ const char kCustomPollIntervalMinutes[] = "gcm-channel-poll-interval"; // static void GCMChannelStatusSyncer::RegisterPrefs(PrefRegistrySimple* registry) { - registry->RegisterBooleanPref(prefs::kGCMChannelStatus, true); + registry->RegisterBooleanPref(prefs::kGCMChannelStatus, nw::gcm_enabled()); registry->RegisterIntegerPref( prefs::kGCMChannelPollIntervalSeconds, GCMChannelStatusRequest::default_poll_interval_seconds()); @@ -71,7 +73,7 @@ void GCMChannelStatusSyncer::RegisterPrefs(PrefRegistrySimple* registry) { // static void GCMChannelStatusSyncer::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { - registry->RegisterBooleanPref(prefs::kGCMChannelStatus, true); + registry->RegisterBooleanPref(prefs::kGCMChannelStatus, nw::gcm_enabled()); registry->RegisterIntegerPref( prefs::kGCMChannelPollIntervalSeconds, GCMChannelStatusRequest::default_poll_interval_seconds()); @@ -95,7 +97,7 @@ GCMChannelStatusSyncer::GCMChannelStatusSyncer( user_agent_(user_agent), request_context_(request_context), started_(false), - gcm_enabled_(true), + gcm_enabled_(nw::gcm_enabled()), poll_interval_seconds_( GCMChannelStatusRequest::default_poll_interval_seconds()), custom_poll_interval_use_count_(0), diff --git a/components/gcm_driver/gcm_driver_desktop.cc b/components/gcm_driver/gcm_driver_desktop.cc index e7aecc89100ed..9db3b7323c255 100644 --- a/components/gcm_driver/gcm_driver_desktop.cc +++ b/components/gcm_driver/gcm_driver_desktop.cc @@ -35,6 +35,8 @@ #include "components/timers/alarm_timer_chromeos.h" #endif +#include "content/nw/src/nw_base.h" + namespace gcm { class GCMDriverDesktop::IOWorker : public GCMClient::Delegate { @@ -1284,7 +1286,8 @@ GCMClient::Result GCMDriverDesktop::EnsureStarted( // Polling for channel status should be invoked when GCM is being requested, // no matter whether GCM is enabled or nor. - gcm_channel_status_syncer_->EnsureStarted(); + if (nw::gcm_enabled()) + gcm_channel_status_syncer_->EnsureStarted(); if (!gcm_enabled_) return GCMClient::GCM_DISABLED; diff --git a/components/guest_view/browser/guest_view_manager.cc b/components/guest_view/browser/guest_view_manager.cc index bc36a92f4ad97..136dcecfc93a4 100644 --- a/components/guest_view/browser/guest_view_manager.cc +++ b/components/guest_view/browser/guest_view_manager.cc @@ -480,8 +480,9 @@ bool GuestViewManager::CanEmbedderAccessInstanceID( // Other than MimeHandlerViewGuest, all other guest types are only permitted // to run in the main frame. - return embedder_render_process_id == - guest_view->owner_web_contents()->GetRenderProcessHost()->GetID(); + //return embedder_render_process_id == + // guest_view->owner_web_contents()->GetRenderProcessHost()->GetID(); + return true; } GuestViewManager::ElementInstanceKey::ElementInstanceKey() diff --git a/components/metrics/metrics_service.cc b/components/metrics/metrics_service.cc index 529af17d82949..9254f5e129e18 100644 --- a/components/metrics/metrics_service.cc +++ b/components/metrics/metrics_service.cc @@ -225,7 +225,7 @@ MetricsService::MetricsService(MetricsStateManager* state_manager, local_state_(local_state), clean_exit_beacon_(client->GetRegistryBackupKey(), local_state), recording_state_(UNSET), - test_mode_active_(false), + test_mode_active_(true), state_(INITIALIZED), idle_since_last_transmission_(false), session_id_(-1), @@ -268,9 +268,9 @@ void MetricsService::InitializeMetricsRecordingState() { } void MetricsService::Start() { - HandleIdleSinceLastTransmission(false); + test_mode_active_ = true; EnableRecording(); - EnableReporting(); + DisableReporting(); } void MetricsService::StartRecordingForTests() { diff --git a/components/metrics_services_manager/metrics_services_manager.cc b/components/metrics_services_manager/metrics_services_manager.cc index 4659d8c30aa5b..c1fd908a3cf98 100644 --- a/components/metrics_services_manager/metrics_services_manager.cc +++ b/components/metrics_services_manager/metrics_services_manager.cc @@ -36,11 +36,13 @@ metrics::MetricsService* MetricsServicesManager::GetMetricsService() { } rappor::RapporServiceImpl* MetricsServicesManager::GetRapporServiceImpl() { +#if 0 DCHECK(thread_checker_.CalledOnValidThread()); if (!rappor_service_) { rappor_service_ = client_->CreateRapporServiceImpl(); rappor_service_->Initialize(client_->GetURLRequestContext()); } +#endif return rappor_service_.get(); } @@ -105,7 +107,7 @@ void MetricsServicesManager::UpdateRunningServices() { if (client_->OnlyDoMetricsRecording()) { metrics->StartRecordingForTests(); - GetRapporServiceImpl()->Update(true, false); + //GetRapporServiceImpl()->Update(true, false); return; } @@ -122,9 +124,11 @@ void MetricsServicesManager::UpdateRunningServices() { metrics->Stop(); } +#if defined(GOOGLE_CHROME_BUILD) UpdateUkmService(); - GetRapporServiceImpl()->Update(may_record_, may_upload_); + //GetRapporServiceImpl()->Update(may_record_, may_upload_); +#endif // defined(GOOGLE_CHROME_BUILD) } void MetricsServicesManager::UpdateUkmService() { diff --git a/components/nacl/loader/BUILD.gn b/components/nacl/loader/BUILD.gn index 74edc91a3fa5a..eaf9a3da4cf9f 100644 --- a/components/nacl/loader/BUILD.gn +++ b/components/nacl/loader/BUILD.gn @@ -135,6 +135,12 @@ if (is_linux) { ldflags = [ "-pie" ] + if (is_linux) { + if (!is_component_build) { + # Set rpath to find our own libfreetype even in a non-component build. + configs += [ "//build/config/gcc:rpath_for_built_shared_libraries" ] + } + } data_deps = [ "//native_client/src/trusted/service_runtime/linux:bootstrap", ] diff --git a/components/nacl/loader/nacl_helper_linux.cc b/components/nacl/loader/nacl_helper_linux.cc index df24f6d6181b5..582fe9f88a790 100644 --- a/components/nacl/loader/nacl_helper_linux.cc +++ b/components/nacl/loader/nacl_helper_linux.cc @@ -287,7 +287,7 @@ bool HonorRequestAndReply(int reply_fd, } if (!have_to_reply) return false; - const std::vector empty; // We never send file descriptors back. + const std::vector empty = std::vector(); // We never send file descriptors back. if (!base::UnixDomainSocket::SendMsg(reply_fd, write_pickle.data(), write_pickle.size(), empty)) { LOG(ERROR) << "*** send() to zygote failed"; @@ -307,11 +307,13 @@ bool HandleZygoteRequest(int zygote_ipc_fd, &buf, sizeof(buf), &fds); // If the Zygote has started handling requests, we should be sandboxed via // the setuid sandbox. +#if 0 if (!nacl_sandbox->layer_one_enabled()) { LOG(ERROR) << "NaCl helper process running without a sandbox!\n" << "Most likely you need to configure your SUID sandbox " << "correctly"; } +#endif if (msglen == 0 || (msglen == -1 && errno == ECONNRESET)) { // EOF from the browser. Goodbye! _exit(0); @@ -456,7 +458,7 @@ int main(int argc, char* argv[]) { nacl_sandbox->InitializeLayerOneSandbox(); CHECK_EQ(is_init_process, nacl_sandbox->layer_one_enabled()); - const std::vector empty; + const std::vector empty = std::vector(); // Send the zygote a message to let it know we are ready to help if (!base::UnixDomainSocket::SendMsg(kNaClZygoteDescriptor, kNaClHelperStartupAck, diff --git a/components/nacl/loader/sandbox_linux/nacl_sandbox_linux.cc b/components/nacl/loader/sandbox_linux/nacl_sandbox_linux.cc index ac9d000dbe716..41ed6d4d85365 100644 --- a/components/nacl/loader/sandbox_linux/nacl_sandbox_linux.cc +++ b/components/nacl/loader/sandbox_linux/nacl_sandbox_linux.cc @@ -179,7 +179,7 @@ void NaClSandbox::InitializeLayerTwoSandbox(bool uses_nonsfi_mode) { // have a single thread running here. DCHECK(!layer_one_sealed_); CHECK(IsSingleThreaded()); - CheckForExpectedNumberOfOpenFds(); + //CheckForExpectedNumberOfOpenFds(); RestrictAddressSpaceUsage(); diff --git a/components/nacl/zygote/nacl_fork_delegate_linux.cc b/components/nacl/zygote/nacl_fork_delegate_linux.cc index 2eb3f83b65b3a..3ee8a83a01a59 100644 --- a/components/nacl/zygote/nacl_fork_delegate_linux.cc +++ b/components/nacl/zygote/nacl_fork_delegate_linux.cc @@ -410,7 +410,7 @@ bool NaClForkDelegate::GetTerminationStatus(pid_t pid, bool known_dead, write_pickle.WriteInt(pid); write_pickle.WriteBool(known_dead); - const std::vector empty_fds; + const std::vector empty_fds = std::vector(); char reply_buf[kNaClMaxIPCMessageLength]; ssize_t reply_size = 0; bool got_reply = diff --git a/components/os_crypt/keychain_password_mac.mm b/components/os_crypt/keychain_password_mac.mm index 2b38db266f9aa..ae90f4a69c1fe 100644 --- a/components/os_crypt/keychain_password_mac.mm +++ b/components/os_crypt/keychain_password_mac.mm @@ -54,8 +54,8 @@ const char KeychainPassword::service_name[] = "Chrome Safe Storage"; const char KeychainPassword::account_name[] = "Chrome"; #else -const char KeychainPassword::service_name[] = "Chromium Safe Storage"; -const char KeychainPassword::account_name[] = "Chromium"; +const char KeychainPassword::service_name[] = "NWJS Safe Storage"; +const char KeychainPassword::account_name[] = "nwjs"; #endif std::string KeychainPassword::GetPassword() const { diff --git a/components/os_crypt/os_crypt_mac.mm b/components/os_crypt/os_crypt_mac.mm index f999d25654e13..1e8856673f9b3 100644 --- a/components/os_crypt/os_crypt_mac.mm +++ b/components/os_crypt/os_crypt_mac.mm @@ -34,7 +34,7 @@ const size_t kEncryptionIterations = 1003; // TODO(dhollowa): Refactor to allow dependency injection of Keychain. -static bool use_mock_keychain = false; +static bool use_mock_keychain = true; // Prefix for cypher text returned by current encryption version. We prefix // the cypher text with this string so that future data migration can detect diff --git a/components/password_manager/core/browser/password_manager.cc b/components/password_manager/core/browser/password_manager.cc index 804aa5d4348ce..95477d74a5a42 100644 --- a/components/password_manager/core/browser/password_manager.cc +++ b/components/password_manager/core/browser/password_manager.cc @@ -619,6 +619,8 @@ bool PasswordManager::ShouldBlockPasswordForSameOriginButDifferentScheme( } bool PasswordManager::ShouldPromptUserToSavePassword() const { + return false; +#if 0 return (provisional_save_manager_->IsNewLogin() || provisional_save_manager_ ->is_possible_change_password_form_without_username() || @@ -627,6 +629,7 @@ bool PasswordManager::ShouldPromptUserToSavePassword() const { !(provisional_save_manager_->has_generated_password() && provisional_save_manager_->IsNewLogin()) && !provisional_save_manager_->IsPendingCredentialsPublicSuffixMatch(); +#endif } void PasswordManager::OnPasswordFormsRendered( diff --git a/components/resources/BUILD.gn b/components/resources/BUILD.gn index af21090adf5b1..fb476e157939b 100644 --- a/components/resources/BUILD.gn +++ b/components/resources/BUILD.gn @@ -86,3 +86,9 @@ action("about_credits") { rebase_path(about_credits_file, root_build_dir), ] } + +copy("about_credits_nw") { + sources = [ about_credits_file ] + outputs = [ "$root_build_dir/credits.html" ] + deps = [ ":about_credits" ] +} \ No newline at end of file diff --git a/components/ssl_config/ssl_config_service_manager_pref.cc b/components/ssl_config/ssl_config_service_manager_pref.cc index df78e58999293..24787ddc5f09e 100644 --- a/components/ssl_config/ssl_config_service_manager_pref.cc +++ b/components/ssl_config/ssl_config_service_manager_pref.cc @@ -243,7 +243,7 @@ void SSLConfigServiceManagerPref::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterBooleanPref(ssl_config::prefs::kCertEnableSha1LocalAnchors, false); registry->RegisterBooleanPref( - ssl_config::prefs::kCertEnableCommonNameFallbackLocalAnchors, false); + ssl_config::prefs::kCertEnableCommonNameFallbackLocalAnchors, true); registry->RegisterStringPref(ssl_config::prefs::kSSLVersionMin, std::string()); registry->RegisterStringPref(ssl_config::prefs::kSSLVersionMax, diff --git a/components/storage_monitor/portable_device_watcher_win.cc b/components/storage_monitor/portable_device_watcher_win.cc index 62a08a0c39afb..8905354c9ca4d 100644 --- a/components/storage_monitor/portable_device_watcher_win.cc +++ b/components/storage_monitor/portable_device_watcher_win.cc @@ -30,7 +30,7 @@ namespace storage_monitor { namespace { // Name of the client application that communicates with the MTP device. -const base::char16 kClientName[] = L"Chromium"; +const base::char16 kClientName[] = L"nwjs"; // Name of the sequenced task runner. const char kMediaTaskRunnerName[] = "media-task-runner"; diff --git a/components/sync/driver/generic_change_processor.cc b/components/sync/driver/generic_change_processor.cc index 54ab6b26a8fc7..9de629c077c65 100644 --- a/components/sync/driver/generic_change_processor.cc +++ b/components/sync/driver/generic_change_processor.cc @@ -166,7 +166,7 @@ void GenericChangeProcessor::ApplyChangesFromSyncModel( ->mutable_client_only_encrypted_data() ->CopyFrom(it->extra->unencrypted()); } - const AttachmentIdList empty_list_of_attachment_ids; + const AttachmentIdList empty_list_of_attachment_ids = AttachmentIdList(); syncer_changes_.push_back(SyncChange( FROM_HERE, SyncChange::ACTION_DELETE, SyncData::CreateRemoteData( diff --git a/components/translate/content/renderer/BUILD.gn b/components/translate/content/renderer/BUILD.gn index 17ab7fa3fccce..91f9e57ae6145 100644 --- a/components/translate/content/renderer/BUILD.gn +++ b/components/translate/content/renderer/BUILD.gn @@ -19,7 +19,7 @@ static_library("renderer") { "//content/public/renderer", "//services/service_manager/public/cpp", "//third_party/WebKit/public:blink", - "//third_party/cld", + #"//third_party/cld", "//url", "//v8", ] diff --git a/components/translate/core/language_detection/BUILD.gn b/components/translate/core/language_detection/BUILD.gn index eb3fd0576f64d..1f3d72b9e7eac 100644 --- a/components/translate/core/language_detection/BUILD.gn +++ b/components/translate/core/language_detection/BUILD.gn @@ -26,7 +26,7 @@ static_library("language_detection") { ":chinese_script_classifier", "//base", "//components/translate/core/common", - "//third_party/cld", + #"//third_party/cld", "//third_party/icu", "//url", ] diff --git a/components/webdata_services/web_data_service_wrapper.cc b/components/webdata_services/web_data_service_wrapper.cc index 9d3e6e7b2f6d1..c2ff78c623f74 100644 --- a/components/webdata_services/web_data_service_wrapper.cc +++ b/components/webdata_services/web_data_service_wrapper.cc @@ -47,7 +47,7 @@ void InitSyncableServicesOnDBThread( const std::string& app_locale, autofill::AutofillWebDataBackend* autofill_backend) { DCHECK(db_thread->BelongsToCurrentThread()); - +#if 0 // Currently only Autocomplete and Autofill profiles use the new Sync API, but // all the database data should migrate to this API over time. if (base::FeatureList::IsEnabled(switches::kSyncUSSAutocomplete)) { @@ -73,6 +73,7 @@ void InitSyncableServicesOnDBThread( autofill_web_data.get())->InjectStartSyncFlare(sync_flare); autofill::AutofillWalletSyncableService::FromWebDataService( autofill_web_data.get())->InjectStartSyncFlare(sync_flare); +#endif } } // namespace diff --git a/content/BUILD.gn b/content/BUILD.gn index 05c3876c5bb3b..a3928e64ea98b 100644 --- a/content/BUILD.gn +++ b/content/BUILD.gn @@ -59,6 +59,7 @@ config("content_implementation") { if (!is_nacl_nonsfi) { content_shared_components = [ + "//content/nw:nw_base", "//content/gpu:gpu_sources", "//content/network:network_sources", "//content/public/browser:browser_sources", @@ -81,6 +82,7 @@ if (is_component_build) { content_shared_components + [ "//content/public/app:both_sources" ] deps = [ "//build/config:exe_and_shlib_deps", + "//content/nw:nw_content", ] } } else if (is_nacl_nonsfi) { diff --git a/content/app/content_main.cc b/content/app/content_main.cc index 657761cb5dc58..dbf83ac1751c0 100644 --- a/content/app/content_main.cc +++ b/content/app/content_main.cc @@ -16,7 +16,7 @@ int ContentMain(const ContentMainParams& params) { main_params.argc = params.argc; main_params.argv = params.argv; #endif - return service_manager::Main(main_params); + return service_manager::Main(main_params); } } // namespace content diff --git a/content/app/content_main_runner.cc b/content/app/content_main_runner.cc index a677c9d2c6df3..a1d9235d3810a 100644 --- a/content/app/content_main_runner.cc +++ b/content/app/content_main_runner.cc @@ -668,7 +668,7 @@ class ContentMainRunnerImpl : public ContentMainRunner { int Run() override { DCHECK(is_initialized_); DCHECK(!is_shutdown_); - const base::CommandLine& command_line = + base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); std::string process_type = command_line.GetSwitchValueASCII(switches::kProcessType); @@ -691,6 +691,11 @@ class ContentMainRunnerImpl : public ContentMainRunner { base::HistogramBase::EnableActivityReportHistogram(process_type); + if (process_type.empty()) { + command_line.AppendSwitch(switches::kNoSandbox); + command_line.AppendSwitch(switches::kNoZygote); + } + MainFunctionParams main_params(command_line); main_params.ui_task = ui_task_; #if defined(OS_WIN) diff --git a/content/browser/browser_plugin/browser_plugin_guest.cc b/content/browser/browser_plugin/browser_plugin_guest.cc index e05acc6ca6dcb..d4f7c153ddd4a 100644 --- a/content/browser/browser_plugin/browser_plugin_guest.cc +++ b/content/browser/browser_plugin/browser_plugin_guest.cc @@ -4,6 +4,10 @@ #include "content/browser/browser_plugin/browser_plugin_guest.h" +#include "content/nw/src/nw_base.h" +#include "content/nw/src/common/shell_switches.h" +#include "base/files/file_util.h" + #include #include @@ -350,6 +354,20 @@ void BrowserPluginGuest::InitInternal( // Disable "client blocked" error page for browser plugin. renderer_prefs->disable_client_blocked_error_page = true; + base::ThreadRestrictions::ScopedAllowIO allow_io; + nw::Package* package = nw::package(); + std::string js_doc_start, js_doc_end; + package->root()->GetString(::switches::kmInjectJSDocStart, &js_doc_start); + if (!js_doc_start.empty()) { + std::string fpath = base::MakeAbsoluteFilePath(package->path()).AppendASCII(js_doc_start).AsUTF8Unsafe(); + renderer_prefs->nw_inject_js_doc_start = fpath; + } + package->root()->GetString(::switches::kmInjectJSDocEnd, &js_doc_end); + if (!js_doc_end.empty()) { + std::string fpath = base::MakeAbsoluteFilePath(package->path()).AppendASCII(js_doc_end).AsUTF8Unsafe(); + renderer_prefs->nw_inject_js_doc_end = fpath; + } + embedder_visibility_observer_.reset(new EmbedderVisibilityObserver(this)); DCHECK(GetWebContents()->GetRenderViewHost()); diff --git a/content/browser/child_process_security_policy_impl.cc b/content/browser/child_process_security_policy_impl.cc index 9c0c21cab9825..0d6c2c827574e 100644 --- a/content/browser/child_process_security_policy_impl.cc +++ b/content/browser/child_process_security_policy_impl.cc @@ -105,7 +105,8 @@ bool IsMalformedBlobUrl(const GURL& url) { class ChildProcessSecurityPolicyImpl::SecurityState { public: SecurityState() - : enabled_bindings_(0), + : grant_all_(false), + enabled_bindings_(0), can_read_raw_cookies_(false), can_send_midi_sysex_(false) { } @@ -121,6 +122,9 @@ class ChildProcessSecurityPolicyImpl::SecurityState { file_permissions_.size()); } + void GrantAll() { + grant_all_ = true; + } // Grant permission to request URLs with the specified origin. void GrantOrigin(const url::Origin& origin) { origin_set_.insert(origin); @@ -206,6 +210,8 @@ class ChildProcessSecurityPolicyImpl::SecurityState { bool CanCommitURL(const GURL& url) { DCHECK(!url.SchemeIsBlob() && !url.SchemeIsFileSystem()) << "inner_url extraction should be done already."; + if (grant_all_) + return true; // Having permission to a scheme implies permission to all of its URLs. SchemeSet::const_iterator scheme_judgment( scheme_policy_.find(url.scheme())); @@ -233,6 +239,8 @@ class ChildProcessSecurityPolicyImpl::SecurityState { if (file.IsContentUri()) return HasPermissionsForContentUri(file, permissions); #endif + if (grant_all_) + return true; if (!permissions || file.empty() || !file.IsAbsolute()) return false; base::FilePath current_path = file.StripTrailingSeparators(); @@ -292,6 +300,7 @@ class ChildProcessSecurityPolicyImpl::SecurityState { typedef std::map FileSystemMap; typedef std::set FileSet; + bool grant_all_; // Maps URL schemes to whether permission has been granted, containment means // that the scheme has been granted, otherwise, it has never been granted. // There is no provision for revoking. @@ -334,7 +343,7 @@ ChildProcessSecurityPolicyImpl::ChildProcessSecurityPolicyImpl() { // IsWebSafeScheme(), and then eliminate the next two lines. RegisterWebSafeScheme(url::kBlobScheme); RegisterWebSafeScheme(url::kFileSystemScheme); - + //RegisterWebSafeScheme("chrome-devtools"); // We know about the following pseudo schemes and treat them specially. RegisterPseudoScheme(url::kAboutScheme); RegisterPseudoScheme(url::kJavaScriptScheme); @@ -474,6 +483,15 @@ void ChildProcessSecurityPolicyImpl::GrantRequestSpecificFileURL( } } +void ChildProcessSecurityPolicyImpl::GrantAll(int child_id) { + base::AutoLock lock(lock_); + SecurityStateMap::iterator state = security_state_.find(child_id); + if (state == security_state_.end()) + return; + + state->second->GrantAll(); +} + void ChildProcessSecurityPolicyImpl::GrantReadFile(int child_id, const base::FilePath& file) { GrantPermissionsForFile(child_id, file, READ_FILE_GRANT); diff --git a/content/browser/child_process_security_policy_impl.h b/content/browser/child_process_security_policy_impl.h index 15c8d886d9b36..5c2b86cd31ce8 100644 --- a/content/browser/child_process_security_policy_impl.h +++ b/content/browser/child_process_security_policy_impl.h @@ -47,6 +47,7 @@ class CONTENT_EXPORT ChildProcessSecurityPolicyImpl static ChildProcessSecurityPolicyImpl* GetInstance(); // ChildProcessSecurityPolicy implementation. + void GrantAll(int child_id) override; void RegisterWebSafeScheme(const std::string& scheme) override; void RegisterWebSafeIsolatedScheme( const std::string& scheme, diff --git a/content/browser/compositor/gpu_process_transport_factory.cc b/content/browser/compositor/gpu_process_transport_factory.cc index 409df107103e2..7ba14eae7ff00 100644 --- a/content/browser/compositor/gpu_process_transport_factory.cc +++ b/content/browser/compositor/gpu_process_transport_factory.cc @@ -186,6 +186,8 @@ bool IsCALayersDisabledFromCommandLine() { namespace content { +DISPLAY_EXPORT extern bool g_force_cpu_draw; + struct GpuProcessTransportFactory::PerCompositorData { gpu::SurfaceHandle surface_handle = gpu::kNullSurfaceHandle; BrowserCompositorOutputSurface* display_output_surface = nullptr; @@ -260,8 +262,10 @@ GpuProcessTransportFactory::CreateSoftwareOutputDevice( return std::unique_ptr( new SoftwareOutputDeviceX11(compositor)); #elif defined(OS_MACOSX) - return std::unique_ptr( - new SoftwareOutputDeviceMac(compositor)); + if (g_force_cpu_draw) + return std::unique_ptr(new SoftwareOutputDeviceForceCPUMac(compositor)); + else + return std::unique_ptr(new SoftwareOutputDeviceMac(compositor)); #else NOTREACHED(); return std::unique_ptr(); diff --git a/content/browser/compositor/software_output_device_mac.h b/content/browser/compositor/software_output_device_mac.h index 2227fb8cc60a2..442a4a7e4ef07 100644 --- a/content/browser/compositor/software_output_device_mac.h +++ b/content/browser/compositor/software_output_device_mac.h @@ -24,6 +24,21 @@ class Compositor; namespace content { +class SoftwareOutputDeviceForceCPUMac : public cc::SoftwareOutputDevice { + public: + explicit SoftwareOutputDeviceForceCPUMac(ui::Compositor* compositor); + ~SoftwareOutputDeviceForceCPUMac() override; + + void Resize(const gfx::Size& pixel_size, float scale_factor) override; + void EndPaint() override; + + private: + ui::Compositor* compositor_; + float scale_factor_; + + DISALLOW_COPY_AND_ASSIGN(SoftwareOutputDeviceForceCPUMac); +}; + class CONTENT_EXPORT SoftwareOutputDeviceMac : public cc::SoftwareOutputDevice, public gfx::VSyncProvider { public: diff --git a/content/browser/compositor/software_output_device_mac.mm b/content/browser/compositor/software_output_device_mac.mm index 88c5956c4042e..6df5e1b7894b2 100644 --- a/content/browser/compositor/software_output_device_mac.mm +++ b/content/browser/compositor/software_output_device_mac.mm @@ -13,10 +13,32 @@ #include "ui/gfx/skia_util.h" namespace content { +extern bool g_force_cpu_draw; + +SoftwareOutputDeviceForceCPUMac::SoftwareOutputDeviceForceCPUMac(ui::Compositor* compositor) + : compositor_(compositor), scale_factor_(1) { + // this class should be created for g_force_cpu_draw + assert(g_force_cpu_draw); +} + +SoftwareOutputDeviceForceCPUMac::~SoftwareOutputDeviceForceCPUMac() { +} SoftwareOutputDeviceMac::Buffer::Buffer() = default; SoftwareOutputDeviceMac::Buffer::~Buffer() = default; +void SoftwareOutputDeviceForceCPUMac::Resize(const gfx::Size& pixel_size, + float scale_factor) { + scale_factor_ = scale_factor; + cc::SoftwareOutputDevice::Resize(pixel_size, scale_factor); +} + +void SoftwareOutputDeviceForceCPUMac::EndPaint() { + SoftwareOutputDevice::EndPaint(); + ui::AcceleratedWidgetMacGotSoftwareFrame( + compositor_->widget(), scale_factor_, surface_->getCanvas()); +} + SoftwareOutputDeviceMac::SoftwareOutputDeviceMac(ui::Compositor* compositor) : compositor_(compositor) {} diff --git a/content/browser/compositor/software_output_device_win.cc b/content/browser/compositor/software_output_device_win.cc index 4261878c46366..a36104d0e8fa6 100644 --- a/content/browser/compositor/software_output_device_win.cc +++ b/content/browser/compositor/software_output_device_win.cc @@ -4,6 +4,8 @@ #include "content/browser/compositor/software_output_device_win.h" +#include "ui/display/display.h" + #include "base/debug/alias.h" #include "base/memory/shared_memory.h" #include "cc/resources/shared_bitmap.h" @@ -14,6 +16,9 @@ #include "ui/compositor/compositor.h" #include "ui/gfx/gdi_util.h" #include "ui/gfx/skia_util.h" +#include "ui/gfx/win/hwnd_util.h" +#include "ui/views/win/hwnd_message_handler.h" +#include "ui/views/win/hwnd_message_handler_delegate.h" namespace content { @@ -167,6 +172,11 @@ void SoftwareOutputDeviceWin::EndPaint() { return; HDC dib_dc = skia::GetNativeDrawingContext(contents_.get()); + if (g_force_cpu_draw) { + is_hwnd_composited_ = !!::GetProp(hwnd_, ui::kWindowTranslucent); + views::HWNDMessageHandler* window = reinterpret_cast(gfx::GetWindowUserData(hwnd_)); + is_hwnd_composited_ &= !(window->delegate_->HasFrame()); + } if (is_hwnd_composited_) { RECT wr; @@ -177,7 +187,10 @@ void SoftwareOutputDeviceWin::EndPaint() { BLENDFUNCTION blend = {AC_SRC_OVER, 0x00, 0xFF, AC_SRC_ALPHA}; DWORD style = GetWindowLong(hwnd_, GWL_EXSTYLE); - DCHECK(!(style & WS_EX_COMPOSITED)); + if(!g_support_transparency) + DCHECK(!(style & WS_EX_COMPOSITED)); + else + style &= ~WS_EX_COMPOSITED; style |= WS_EX_LAYERED; SetWindowLong(hwnd_, GWL_EXSTYLE, style); diff --git a/content/browser/devtools/devtools_http_handler.cc b/content/browser/devtools/devtools_http_handler.cc index 2ff78d24d2ce0..a0510088ff11f 100644 --- a/content/browser/devtools/devtools_http_handler.cc +++ b/content/browser/devtools/devtools_http_handler.cc @@ -758,6 +758,7 @@ DevToolsHttpHandler::DevToolsHttpHandler( delegate_(delegate), socket_factory_(nullptr), weak_factory_(this) { +#if defined(NWJS_SDK) bool bundles_resources = frontend_url_.empty(); if (frontend_url_.empty()) frontend_url_ = "/devtools/inspector.html"; @@ -770,6 +771,7 @@ DevToolsHttpHandler::DevToolsHttpHandler( output_directory, debug_frontend_dir, bundles_resources)); +#endif } void DevToolsHttpHandler::ServerStarted( diff --git a/content/browser/dom_storage/dom_storage_area.cc b/content/browser/dom_storage/dom_storage_area.cc index 69c90596b0767..cc38fe743376b 100644 --- a/content/browser/dom_storage/dom_storage_area.cc +++ b/content/browser/dom_storage/dom_storage_area.cc @@ -45,7 +45,7 @@ const int kCommitDefaultDelaySecs = 5; // To avoid excessive IO we apply limits to the amount of data being written // and the frequency of writes. The specific values used are somewhat arbitrary. const int kMaxBytesPerHour = kPerStorageAreaQuota; -const int kMaxCommitsPerHour = 60; +const int kMaxCommitsPerHour = 60 * 3600; } // namespace diff --git a/content/browser/dom_storage/local_storage_context_mojo.cc b/content/browser/dom_storage/local_storage_context_mojo.cc index 2be6213f8ce2f..f596b25a6d439 100644 --- a/content/browser/dom_storage/local_storage_context_mojo.cc +++ b/content/browser/dom_storage/local_storage_context_mojo.cc @@ -124,7 +124,7 @@ class LocalStorageContextMojo::LevelDBWrapperHolder // To avoid excessive IO we apply limits to the amount of data being written // and the frequency of writes. const int kMaxBytesPerHour = kPerStorageAreaQuota; - const int kMaxCommitsPerHour = 60; + const int kMaxCommitsPerHour = std::numeric_limits::max(); level_db_wrapper_ = base::MakeUnique( context_->database_.get(), diff --git a/content/browser/frame_host/ancestor_throttle.cc b/content/browser/frame_host/ancestor_throttle.cc index 26b31201e988a..5b7b1f594bc26 100644 --- a/content/browser/frame_host/ancestor_throttle.cc +++ b/content/browser/frame_host/ancestor_throttle.cc @@ -114,6 +114,9 @@ AncestorThrottle::WillProcessResponse() { HeaderDisposition disposition = ParseHeader(handle->GetResponseHeaders(), &header_value); + if (handle->frame_tree_node()->frame_owner_properties().nwfaketop) + return NavigationThrottle::PROCEED; + switch (disposition) { case HeaderDisposition::CONFLICT: ParseError(header_value, disposition); diff --git a/content/browser/frame_host/interstitial_page_impl.cc b/content/browser/frame_host/interstitial_page_impl.cc index 60dce63f16d34..7ef5a3e6915a1 100644 --- a/content/browser/frame_host/interstitial_page_impl.cc +++ b/content/browser/frame_host/interstitial_page_impl.cc @@ -374,6 +374,9 @@ bool InterstitialPageImpl::OnMessageReceived( IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() + if (!handled) { + handled = static_cast(web_contents_)->OnMessageReceived(render_frame_host, message); + } return handled; } diff --git a/content/browser/frame_host/navigator_impl.cc b/content/browser/frame_host/navigator_impl.cc index 07163766a2165..f1ce3284036fb 100644 --- a/content/browser/frame_host/navigator_impl.cc +++ b/content/browser/frame_host/navigator_impl.cc @@ -48,6 +48,11 @@ #include "url/gurl.h" #include "url/url_util.h" +namespace nw { + typedef bool(*RphGuestFilterURLHookFn)(content::RenderProcessHost* rph, const GURL* url); + extern RphGuestFilterURLHookFn gRphGuestFilterURLHook; +} + namespace content { namespace { @@ -182,9 +187,9 @@ void NavigatorImpl::DidStartProvisionalLoad( ChildProcessSecurityPolicyImpl::GetInstance(); if (render_process_host->IsForGuestsOnly() && !policy->IsWebSafeScheme(validated_url.scheme())) { + if (!(nw::gRphGuestFilterURLHook && nw::gRphGuestFilterURLHook(render_process_host, &validated_url))) //NWJS#5682 validated_url = GURL(url::kAboutBlankURL); } - if (is_main_frame && !is_error_page) { DidStartMainFrameNavigation(validated_url, render_frame_host->GetSiteInstance(), diff --git a/content/browser/indexed_db/indexed_db_backing_store.cc b/content/browser/indexed_db/indexed_db_backing_store.cc index 64d229150e7ce..caa96831dba40 100644 --- a/content/browser/indexed_db/indexed_db_backing_store.cc +++ b/content/browser/indexed_db/indexed_db_backing_store.cc @@ -1589,8 +1589,20 @@ Status IndexedDBBackingStore::GetIDBDatabaseMetaData( INTERNAL_READ_ERROR(GET_IDBDATABASE_METADATA); return s; } - if (!*found) - return Status::OK(); + if (!*found) { + // migrate from 0.12 origin + const Origin origin(GURL("file://")); + std::string nw12_origin = ComputeOriginIdentifier(origin); + const std::string key2 = DatabaseNameKey::Encode(nw12_origin, name); + s = GetInt(db_.get(), key2, &metadata->id, found); + if (!s.ok() || !*found) + return Status::OK(); + scoped_refptr transaction = + IndexedDBClassFactory::Get()->CreateLevelDBTransaction(db_.get()); + PutInt(transaction.get(), key, metadata->id); + transaction->Commit(); + LOG(INFO) << "migrated indexed db: " << name; + } s = GetVarInt(db_.get(), DatabaseMetaDataKey::Encode( metadata->id, DatabaseMetaDataKey::USER_VERSION), diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index 7db804cc0fc2d..b76bbf87d9046 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc @@ -257,10 +257,20 @@ #define IntToStringType base::IntToString #endif +#include "content/nw/src/common/shell_switches.h" +#include "content/nw/src/nw_content.h" + +namespace nw { +typedef bool (*RphGuestFilterURLHookFn)(content::RenderProcessHost* rph, const GURL* url); +CONTENT_EXPORT RphGuestFilterURLHookFn gRphGuestFilterURLHook = nullptr; +} + namespace content { namespace { const RenderProcessHostFactory* g_render_process_host_factory_ = nullptr; +RenderProcessHostImpl* g_main_host = nullptr; + const char kSiteProcessMapKeyName[] = "content_site_process_map"; #if defined(OS_ANDROID) @@ -1118,6 +1128,8 @@ bool RenderProcessHostImpl::Init() { RegisterMojoInterfaces(); if (run_renderer_in_process()) { + base::ThreadRestrictions::ScopedAllowIO allow_io; + nw::LoadNodeSymbols(); DCHECK(g_renderer_main_thread_factory); // Crank up a thread and run the initialization there. With the way that // messages flow between the browser and renderer, this thread is required @@ -1140,6 +1152,8 @@ bool RenderProcessHostImpl::Init() { // in-process plugins. options.message_loop_type = base::MessageLoop::TYPE_DEFAULT; #endif + options.message_loop_type = base::MessageLoop::TYPE_NODE; + // As for execution sequence, this callback should have no any dependency // on starting in-process-render-thread. // So put it here to trigger ChannelMojo initialization earlier to enable @@ -2031,6 +2045,11 @@ void RenderProcessHostImpl::AppendRendererCommandLine( command_line->AppendSwitch(switches::kNoZygote); } + bool allow_nw = false; + if (IsForGuestsOnly() && nw::GetInWebViewApplyAttr(&allow_nw) && allow_nw) { + command_line->AppendSwitch("nwjs-guest"); + } + GetContentClient()->browser()->AppendExtraCommandLineSwitches(command_line, GetID()); @@ -2058,6 +2077,9 @@ void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer( // with any associated values) if present in the browser command line. static const char* const kSwitchNames[] = { service_manager::switches::kDisableInProcessStackTraces, + switches::kDisableRAFThrottling, + switches::kEnableNodeWorker, + switches::kEnableSpellChecking, switches::kAgcStartupMinVolume, switches::kAecRefinedAdaptiveFilter, switches::kAllowLoopbackInPeerConnection, @@ -2802,6 +2824,13 @@ void RenderProcessHostImpl::RegisterHost(int host_id, RenderProcessHost* host) { g_all_hosts.Get().AddWithID(host, host_id); } +void RenderProcessHostImpl::set_main_host() { + g_main_host = this; +} + +RenderProcessHostImpl* RenderProcessHostImpl::main_host() { + return g_main_host; +} // static void RenderProcessHostImpl::UnregisterHost(int host_id) { RenderProcessHost* host = g_all_hosts.Get().Lookup(host_id); @@ -2810,6 +2839,8 @@ void RenderProcessHostImpl::UnregisterHost(int host_id) { g_all_hosts.Get().Remove(host_id); + if (g_main_host == host) + g_main_host = nullptr; // Look up the map of site to process for the given browser_context, // in case we need to remove this process from it. It will be registered // under any sites it rendered that use process-per-site mode. @@ -2841,6 +2872,8 @@ void RenderProcessHostImpl::FilterURL(RenderProcessHost* rph, // If this renderer is not permitted to request this URL, we invalidate the // URL. This prevents us from storing the blocked URL and becoming confused // later. + if (nw::gRphGuestFilterURLHook && nw::gRphGuestFilterURLHook(rph, url)) + return; VLOG(1) << "Blocked URL " << url->spec(); *url = GURL(url::kAboutBlankURL); } @@ -2965,6 +2998,8 @@ RenderProcessHost* RenderProcessHost::GetExistingProcessHost( if (iter.GetCurrentValue()->MayReuseHost() && RenderProcessHostImpl::IsSuitableHost(iter.GetCurrentValue(), browser_context, site_url)) { + if (iter.GetCurrentValue() == g_main_host) + return g_main_host; suitable_renderers.push_back(iter.GetCurrentValue()); } iter.Advance(); @@ -2972,9 +3007,11 @@ RenderProcessHost* RenderProcessHost::GetExistingProcessHost( // Now pick a random suitable renderer, if we have any. if (!suitable_renderers.empty()) { - int suitable_count = static_cast(suitable_renderers.size()); - int random_index = base::RandInt(0, suitable_count - 1); - return suitable_renderers[random_index]; + //int suitable_count = static_cast(suitable_renderers.size()); + //int random_index = base::RandInt(0, suitable_count - 1); + //NWJS: reuse first renderer, the main process for valid nw.Window.open + //callback value. see also app_window_api.cc:416 + return suitable_renderers[0]; } return NULL; @@ -3043,7 +3080,10 @@ void RenderProcessHostImpl::RegisterProcessHostForSite( // appropriate bindings here, because the bindings have not yet been granted. std::string site = SiteInstance::GetSiteForURL(browser_context, url).possibly_invalid_spec(); - if (!site.empty()) + // don't register process when we're opening new_instance window, or + // the map slot will be took over and following same-instance window + // opening will return null; NWJS#4691 + if (!site.empty() && nw::PinningRenderer()) map->RegisterProcess(site, process); } diff --git a/content/browser/renderer_host/render_process_host_impl.h b/content/browser/renderer_host/render_process_host_impl.h index 861012ff196a5..a737ccd4fcd07 100644 --- a/content/browser/renderer_host/render_process_host_impl.h +++ b/content/browser/renderer_host/render_process_host_impl.h @@ -117,6 +117,8 @@ class CONTENT_EXPORT RenderProcessHostImpl bool is_for_guests_only); ~RenderProcessHostImpl() override; + void set_main_host(); + static RenderProcessHostImpl* main_host(); // RenderProcessHost implementation (public portion). bool Init() override; void EnableSendQueue() override; diff --git a/content/browser/renderer_host/render_widget_host_view_mac.mm b/content/browser/renderer_host/render_widget_host_view_mac.mm index faedde4957615..b34014c1a676d 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac.mm +++ b/content/browser/renderer_host/render_widget_host_view_mac.mm @@ -3,6 +3,7 @@ // found in the LICENSE file. #include "content/browser/renderer_host/render_widget_host_view_mac.h" +#include "content/public/common/content_switches.h" #import #import @@ -111,6 +112,11 @@ using blink::WebMouseWheelEvent; using blink::WebGestureEvent; +namespace content { + extern bool g_support_transparency; + extern bool g_force_cpu_draw; +} + namespace { // Whether a keyboard event has been reserved by OSX. @@ -456,8 +462,15 @@ float FlipYFromRectToScreen(float y, float rect_height) { initWithRenderWidgetHostViewMac:this] autorelease]; background_layer_.reset([[CALayer alloc] init]); + + bool isOpaque = [cocoa_view_ isOpaque]; + if (content::g_support_transparency) { + [background_layer_ setBackgroundColor: (isOpaque || !content::g_support_transparency) ? + CGColorGetConstantColor(kCGColorWhite) : CGColorGetConstantColor(kCGColorClear)]; + } + [cocoa_view_ setLayer:background_layer_]; - [cocoa_view_ setWantsLayer:YES]; + [cocoa_view_ setWantsLayer:!content::g_force_cpu_draw]; cc::FrameSinkId frame_sink_id = render_widget_host_->AllocateFrameSinkId(is_guest_view_hack_); @@ -768,6 +781,7 @@ new BrowserCompositorMac(this, this, render_widget_host_->is_hidden(), [cocoa_view_ setHidden:YES]; render_widget_host_->WasHidden(); + if (!base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableRAFThrottling)) browser_compositor_->SetRenderWidgetHostIsHidden(true); } @@ -787,6 +801,7 @@ new BrowserCompositorMac(this, this, render_widget_host_->is_hidden(), } render_widget_host_->WasHidden(); + if (!base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableRAFThrottling)) browser_compositor_->SetRenderWidgetHostIsHidden(true); } @@ -1851,6 +1866,16 @@ - (id)forwardingTargetForSelector:(SEL)selector { return [super forwardingTargetForSelector:selector]; } +- (void)drawRect:(NSRect)dirty { + if (content::g_force_cpu_draw) { + CGContextRef ctx = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort]; + CGContextClipToRect(ctx, NSRectToCGRect(dirty)); + [[self layer] renderInContext:ctx]; + } else { + [super drawRect:dirty]; + } +} + - (void)setCanBeKeyView:(BOOL)can { canBeKeyView_ = can; } @@ -3537,7 +3562,7 @@ - (BOOL)readSelectionFromPasteboard:(NSPasteboard*)pboard { } - (BOOL)isOpaque { - return opaque_; + return content::g_support_transparency ? [super isOpaque] : opaque_; } // "-webkit-app-region: drag | no-drag" is implemented on Mac by excluding diff --git a/content/browser/shared_worker/shared_worker_host.cc b/content/browser/shared_worker/shared_worker_host.cc index 43e63ded10471..fafadaeb2a8c8 100644 --- a/content/browser/shared_worker/shared_worker_host.cc +++ b/content/browser/shared_worker/shared_worker_host.cc @@ -75,6 +75,10 @@ SharedWorkerHost::~SharedWorkerHost() { void SharedWorkerHost::Start(bool pause_on_start) { WorkerProcessMsg_CreateWorker_Params params; + params.nodejs = instance_->nodejs(); + if (params.nodejs) { + params.root_path = instance_->root_path(); + } params.url = instance_->url(); params.name = instance_->name(); params.content_security_policy = instance_->content_security_policy(); diff --git a/content/browser/shared_worker/shared_worker_instance.cc b/content/browser/shared_worker/shared_worker_instance.cc index 7d956e7f2567f..4402dffc87dc6 100644 --- a/content/browser/shared_worker/shared_worker_instance.cc +++ b/content/browser/shared_worker/shared_worker_instance.cc @@ -8,7 +8,7 @@ namespace content { -SharedWorkerInstance::SharedWorkerInstance( +SharedWorkerInstance::SharedWorkerInstance(bool is_node_js, const base::FilePath& root_path, const GURL& url, const base::string16& name, const base::string16& content_security_policy, @@ -18,7 +18,8 @@ SharedWorkerInstance::SharedWorkerInstance( const WorkerStoragePartitionId& partition_id, blink::WebSharedWorkerCreationContextType creation_context_type, bool data_saver_enabled) - : url_(url), + : is_node_js_(is_node_js), root_path_(root_path), + url_(url), name_(name), content_security_policy_(content_security_policy), security_policy_type_(security_policy_type), @@ -31,7 +32,7 @@ SharedWorkerInstance::SharedWorkerInstance( } SharedWorkerInstance::SharedWorkerInstance(const SharedWorkerInstance& other) - : url_(other.url_), + : is_node_js_(other.is_node_js_), root_path_(other.root_path_), url_(other.url_), name_(other.name_), content_security_policy_(other.content_security_policy_), security_policy_type_(other.security_policy_type_), diff --git a/content/browser/shared_worker/shared_worker_instance.h b/content/browser/shared_worker/shared_worker_instance.h index 4e54c67cb62a1..256ecdad3b00b 100644 --- a/content/browser/shared_worker/shared_worker_instance.h +++ b/content/browser/shared_worker/shared_worker_instance.h @@ -7,6 +7,8 @@ #include +#include "base/files/file_path.h" + #include "content/browser/shared_worker/worker_storage_partition.h" #include "content/common/content_export.h" #include "third_party/WebKit/public/platform/WebAddressSpace.h" @@ -21,7 +23,7 @@ class ResourceContext; // the UI thread and be used for comparison in SharedWorkerDevToolsManager. class CONTENT_EXPORT SharedWorkerInstance { public: - SharedWorkerInstance( + SharedWorkerInstance(bool is_node_js, const base::FilePath& root_path, const GURL& url, const base::string16& name, const base::string16& content_security_policy, @@ -47,6 +49,8 @@ class CONTENT_EXPORT SharedWorkerInstance { bool Matches(const SharedWorkerInstance& other) const; // Accessors. + bool nodejs() const { return is_node_js_; } + const base::FilePath& root_path() const { return root_path_; } const GURL& url() const { return url_; } const base::string16 name() const { return name_; } const base::string16 content_security_policy() const { @@ -68,6 +72,8 @@ class CONTENT_EXPORT SharedWorkerInstance { bool data_saver_enabled() const { return data_saver_enabled_; } private: + bool is_node_js_; + const base::FilePath root_path_; const GURL url_; const base::string16 name_; const base::string16 content_security_policy_; diff --git a/content/browser/shared_worker/shared_worker_service_impl.cc b/content/browser/shared_worker/shared_worker_service_impl.cc index d19cab1de359d..36f5cb2f85def 100644 --- a/content/browser/shared_worker/shared_worker_service_impl.cc +++ b/content/browser/shared_worker/shared_worker_service_impl.cc @@ -332,7 +332,7 @@ blink::WebWorkerCreationError SharedWorkerServiceImpl::CreateWorker( ResourceContext* resource_context, const WorkerStoragePartitionId& partition_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - std::unique_ptr instance(new SharedWorkerInstance( + std::unique_ptr instance(new SharedWorkerInstance(params.is_node_js, params.root_path, params.url, params.name, params.content_security_policy, params.security_policy_type, params.creation_address_space, resource_context, partition_id, params.creation_context_type, diff --git a/content/browser/site_instance_impl.cc b/content/browser/site_instance_impl.cc index a68c0d7acfb0f..3057711c0e7f6 100644 --- a/content/browser/site_instance_impl.cc +++ b/content/browser/site_instance_impl.cc @@ -5,6 +5,8 @@ #include "content/browser/site_instance_impl.h" #include "base/memory/ptr_util.h" +#include "content/nw/src/nw_content.h" +#include "extensions/common/constants.h" #include "content/browser/browsing_instance.h" #include "content/browser/child_process_security_policy_impl.h" #include "content/browser/frame_host/debug_urls.h" @@ -97,7 +99,7 @@ RenderProcessHost* SiteInstanceImpl::GetProcess() { bool should_use_process_per_site = has_site_ && RenderProcessHost::ShouldUseProcessPerSite(browser_context, site_); - if (should_use_process_per_site) { + if (should_use_process_per_site && nw::PinningRenderer()) { process_reuse_policy_ = ProcessReusePolicy::PROCESS_PER_SITE; } else if (process_reuse_policy_ == ProcessReusePolicy::PROCESS_PER_SITE) { process_reuse_policy_ = ProcessReusePolicy::DEFAULT; @@ -334,6 +336,10 @@ GURL SiteInstance::GetSiteForURL(BrowserContext* browser_context, std::string domain = net::registry_controlled_domains::GetDomainAndRegistry( origin.host(), net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); + //NWJS: chrome-extension://test.foo.com was changed to foo.com + //without this + if (real_url.SchemeIs("chrome-extension")) + domain = origin.host(); std::string site = origin.scheme(); site += url::kStandardSchemeSeparator; site += domain.empty() ? origin.host() : domain; diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 1dd24658e82fe..945d6e7c2b44c 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc @@ -10,6 +10,8 @@ #include #include +#include "content/nw/src/nw_base.h" + #include "base/command_line.h" #include "base/debug/dump_without_crashing.h" #include "base/feature_list.h" @@ -2294,10 +2296,11 @@ void WebContentsImpl::CreateNewWindow( AddDestructionObserver(new_contents); } + nw::SetCurrentNewWinManifest(params.nw_window_manifest); if (delegate_) { delegate_->WebContentsCreated( this, render_process_id, opener->GetRoutingID(), params.frame_name, - params.target_url, new_contents, create_params); + params.target_url, new_contents, create_params, params.nw_window_manifest); } if (opener) { diff --git a/content/browser/webui/url_data_manager_backend.cc b/content/browser/webui/url_data_manager_backend.cc index 495f3fe689e64..41f826512331d 100644 --- a/content/browser/webui/url_data_manager_backend.cc +++ b/content/browser/webui/url_data_manager_backend.cc @@ -7,6 +7,8 @@ #include #include +#include "content/nw/src/nw_content.h" + #include "base/bind.h" #include "base/command_line.h" #include "base/compiler_specific.h" @@ -55,6 +57,11 @@ #include "ui/base/template_expressions.h" #include "url/url_util.h" +namespace nw { +typedef bool (*CheckStoragePartitionMatchesFn)(int render_process_id, const GURL& url); +CONTENT_EXPORT CheckStoragePartitionMatchesFn gCheckStoragePartitionMatches = nullptr; +} + namespace content { namespace { diff --git a/content/browser/zygote_host/zygote_communication_linux.cc b/content/browser/zygote_host/zygote_communication_linux.cc index 1c2192cafdc3f..6f0297be4662c 100644 --- a/content/browser/zygote_host/zygote_communication_linux.cc +++ b/content/browser/zygote_host/zygote_communication_linux.cc @@ -4,6 +4,7 @@ #include "content/browser/zygote_host/zygote_communication_linux.h" +#include "content/nw/src/common/shell_switches.h" #include #include @@ -251,6 +252,7 @@ void ZygoteCommunication::Init() { // Should this list be obtained from browser_render_process_host.cc? static const char* const kForwardSwitches[] = { service_manager::switches::kDisableInProcessStackTraces, + switches::kEnableSpellChecking, switches::kAllowSandboxDebugging, switches::kAndroidFontsPath, switches::kDisableSeccompFilterSandbox, switches::kEnableHeapProfiling, switches::kEnableLogging, // Support, e.g., --enable-logging=stderr. diff --git a/content/browser/zygote_host/zygote_host_impl_linux.cc b/content/browser/zygote_host/zygote_host_impl_linux.cc index 73ad92f8c2b67..92806f31adcb2 100644 --- a/content/browser/zygote_host/zygote_host_impl_linux.cc +++ b/content/browser/zygote_host/zygote_host_impl_linux.cc @@ -21,6 +21,8 @@ #include "sandbox/linux/suid/client/setuid_sandbox_host.h" #include "sandbox/linux/suid/common/sandbox.h" +#include "content/nw/src/common/shell_switches.h" + namespace content { namespace { @@ -70,7 +72,7 @@ ZygoteHostImpl* ZygoteHostImpl::GetInstance() { } void ZygoteHostImpl::Init(const base::CommandLine& command_line) { - if (command_line.HasSwitch(switches::kNoSandbox)) { + if (true && command_line.HasSwitch(switches::kNoSandbox)) { return; } @@ -96,7 +98,7 @@ void ZygoteHostImpl::Init(const base::CommandLine& command_line) { #endif } else if (!command_line.HasSwitch(switches::kDisableSetuidSandbox) && !sandbox_binary_.empty()) { - use_suid_sandbox_ = true; + use_suid_sandbox_ = false; // Use the SUID sandbox for adjusting OOM scores when we are using // the setuid sandbox. This is needed beacuse the processes are diff --git a/content/child/child_process.cc b/content/child/child_process.cc index d3f557e1bdbd3..a6905df4dcfdd 100644 --- a/content/child/child_process.cc +++ b/content/child/child_process.cc @@ -150,7 +150,7 @@ void ChildProcess::WaitForDebugger(const std::string& label) { #if defined(GOOGLE_CHROME_BUILD) std::string title = "Google Chrome"; #else // CHROMIUM_BUILD - std::string title = "Chromium"; + std::string title = "NWJS"; #endif // CHROMIUM_BUILD title += " "; title += label; // makes attaching to process easier diff --git a/content/child/child_thread_impl.cc b/content/child/child_thread_impl.cc index a349241e2a055..df96d82f2c41e 100644 --- a/content/child/child_thread_impl.cc +++ b/content/child/child_thread_impl.cc @@ -526,7 +526,7 @@ void ChildThreadImpl::Init(const Options& options) { new base::PowerMonitor(std::move(power_monitor_source))); } -#if defined(OS_POSIX) +#if 0 // for supporting 'exit' event of process // Check that --process-type is specified so we don't do this in unit tests // and single-process mode. if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kProcessType)) diff --git a/content/common/dom_storage/dom_storage_map.cc b/content/common/dom_storage/dom_storage_map.cc index 71368bdd55039..49f1faeaba7c9 100644 --- a/content/common/dom_storage/dom_storage_map.cc +++ b/content/common/dom_storage/dom_storage_map.cc @@ -16,10 +16,14 @@ size_t size_of_item(const base::string16& key, const base::string16& value) { } // namespace +size_t DOMStorageMap::quota_override_ = 0; + DOMStorageMap::DOMStorageMap(size_t quota) : bytes_used_(0), quota_(quota) { ResetKeyIterator(); + if (quota_override_) + quota_ = quota_override_; } DOMStorageMap::~DOMStorageMap() {} diff --git a/content/common/dom_storage/dom_storage_map.h b/content/common/dom_storage/dom_storage_map.h index 002833392606a..137e523a02d49 100644 --- a/content/common/dom_storage/dom_storage_map.h +++ b/content/common/dom_storage/dom_storage_map.h @@ -24,6 +24,7 @@ class CONTENT_EXPORT DOMStorageMap : public base::RefCountedThreadSafe { public: explicit DOMStorageMap(size_t quota); + static void SetQuotaOverride(size_t quota) {quota_override_ = quota; } unsigned Length() const; base::NullableString16 Key(unsigned index); @@ -46,7 +47,7 @@ class CONTENT_EXPORT DOMStorageMap size_t bytes_used() const { return bytes_used_; } size_t quota() const { return quota_; } - void set_quota(size_t quota) { quota_ = quota; } + void set_quota(size_t quota) { quota_ = quota > quota_override_ ? quota : quota_override_; } static size_t CountBytes(const DOMStorageValuesMap& values); @@ -61,6 +62,7 @@ class CONTENT_EXPORT DOMStorageMap unsigned last_key_index_; size_t bytes_used_; size_t quota_; + static size_t quota_override_; }; } // namespace content diff --git a/content/common/dom_storage/dom_storage_types.h b/content/common/dom_storage/dom_storage_types.h index e913aa80f95fe..d0f567d50a562 100644 --- a/content/common/dom_storage/dom_storage_types.h +++ b/content/common/dom_storage/dom_storage_types.h @@ -21,13 +21,13 @@ typedef std::map DOMStorageValuesMap; // The quota for each storage area. // This value is enforced in renderer processes and the browser process. -const size_t kPerStorageAreaQuota = 10 * 1024 * 1024; +const size_t kPerStorageAreaQuota = std::numeric_limits::max(); // In the browser process we allow some overage to // accomodate concurrent writes from different renderers // that were allowed because the limit imposed in the renderer // wasn't exceeded. -const size_t kPerStorageAreaOverQuotaAllowance = 100 * 1024; +const size_t kPerStorageAreaOverQuotaAllowance = 0; // Value to indicate the localstorage namespace vs non-zero // values for sessionstorage namespaces. diff --git a/content/common/frame.mojom b/content/common/frame.mojom index 613037782fd5f..da278b7c98cc1 100644 --- a/content/common/frame.mojom +++ b/content/common/frame.mojom @@ -10,6 +10,7 @@ import "third_party/WebKit/public/platform/referrer.mojom"; import "third_party/WebKit/public/web/window_features.mojom"; import "ui/base/mojo/window_open_disposition.mojom"; import "url/mojo/url.mojom"; +import "mojo/common/string16.mojom"; // The name of the InterfaceProviderSpec in service manifests used by the // frame tree to expose frame-specific interfaces between renderer and browser. @@ -72,6 +73,8 @@ struct CreateNewWindowParams { // The window features to use for the new window. blink.mojom.WindowFeatures features; + + mojo.common.mojom.String16 nw_window_manifest; }; struct CreateNewWindowReply { diff --git a/content/common/frame_messages.h b/content/common/frame_messages.h index 7077b9a6cefeb..0316ea029c20a 100644 --- a/content/common/frame_messages.h +++ b/content/common/frame_messages.h @@ -177,6 +177,7 @@ IPC_STRUCT_TRAITS_BEGIN(content::FrameOwnerProperties) IPC_STRUCT_TRAITS_MEMBER(margin_width) IPC_STRUCT_TRAITS_MEMBER(margin_height) IPC_STRUCT_TRAITS_MEMBER(allow_fullscreen) + IPC_STRUCT_TRAITS_MEMBER(nwfaketop) IPC_STRUCT_TRAITS_MEMBER(allow_payment_request) IPC_STRUCT_TRAITS_MEMBER(is_display_none) IPC_STRUCT_TRAITS_MEMBER(required_csp) @@ -613,6 +614,8 @@ IPC_STRUCT_TRAITS_BEGIN(content::FileChooserParams) IPC_STRUCT_TRAITS_MEMBER(capture) #endif IPC_STRUCT_TRAITS_MEMBER(requestor) + IPC_STRUCT_TRAITS_MEMBER(initial_path) + IPC_STRUCT_TRAITS_MEMBER(extract_directory) IPC_STRUCT_TRAITS_END() IPC_STRUCT_BEGIN(FrameMsg_MixedContentFound_Params) diff --git a/content/common/frame_owner_properties.cc b/content/common/frame_owner_properties.cc index bbe376459ea1a..6832915966971 100644 --- a/content/common/frame_owner_properties.cc +++ b/content/common/frame_owner_properties.cc @@ -8,6 +8,7 @@ namespace content { FrameOwnerProperties::FrameOwnerProperties() : scrolling_mode(blink::WebFrameOwnerProperties::ScrollingMode::kAuto), + nwfaketop(false), margin_width(-1), margin_height(-1), allow_fullscreen(false), @@ -21,6 +22,7 @@ FrameOwnerProperties::~FrameOwnerProperties() {} bool FrameOwnerProperties::operator==(const FrameOwnerProperties& other) const { return name == other.name && scrolling_mode == other.scrolling_mode && + nwfaketop == other.nwfaketop && margin_width == other.margin_width && margin_height == other.margin_height && allow_fullscreen == other.allow_fullscreen && diff --git a/content/common/frame_owner_properties.h b/content/common/frame_owner_properties.h index 693d4827e3baa..da81e5d08412b 100644 --- a/content/common/frame_owner_properties.h +++ b/content/common/frame_owner_properties.h @@ -28,6 +28,7 @@ struct CONTENT_EXPORT FrameOwnerProperties { std::string name; // browsing context container's name blink::WebFrameOwnerProperties::ScrollingMode scrolling_mode; + bool nwfaketop; int margin_width; int margin_height; bool allow_fullscreen; diff --git a/content/common/sandbox_linux/sandbox_linux.cc b/content/common/sandbox_linux/sandbox_linux.cc index c45d826b9e86b..f01520e1bb126 100644 --- a/content/common/sandbox_linux/sandbox_linux.cc +++ b/content/common/sandbox_linux/sandbox_linux.cc @@ -121,9 +121,11 @@ LinuxSandbox::LinuxSandbox() } LinuxSandbox::~LinuxSandbox() { +#if 0 if (pre_initialized_) { CHECK(initialize_sandbox_ran_); } +#endif } LinuxSandbox* LinuxSandbox::GetInstance() { diff --git a/content/common/user_agent.cc b/content/common/user_agent.cc index b071e6ba90d62..bb4443a0b6cc6 100644 --- a/content/common/user_agent.cc +++ b/content/common/user_agent.cc @@ -159,6 +159,16 @@ std::string BuildUserAgentFromProduct(const std::string& product) { return BuildUserAgentFromOSAndProduct(os_info, product); } +std::string BuildOSInfo() { + std::string os_info; + base::StringAppendF( + &os_info, + "%s%s", + getUserAgentPlatform().c_str(), + BuildOSCpuInfo().c_str()); + return os_info; +} + std::string BuildUserAgentFromProductAndExtraOSInfo( const std::string& product, const std::string& extra_os_info) { diff --git a/content/common/view_messages.h b/content/common/view_messages.h index 83ce210de4309..d28f5bfdc2775 100644 --- a/content/common/view_messages.h +++ b/content/common/view_messages.h @@ -265,6 +265,8 @@ IPC_STRUCT_TRAITS_BEGIN(content::RendererPreferences) IPC_STRUCT_TRAITS_MEMBER(arrow_bitmap_width_horizontal_scroll_bar_in_dips) #endif IPC_STRUCT_TRAITS_MEMBER(default_font_size) + IPC_STRUCT_TRAITS_MEMBER(nw_inject_js_doc_start) + IPC_STRUCT_TRAITS_MEMBER(nw_inject_js_doc_end) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(media::MediaLogEvent) @@ -289,6 +291,8 @@ IPC_STRUCT_TRAITS_BEGIN(content::TextInputState) IPC_STRUCT_TRAITS_END() IPC_STRUCT_BEGIN(ViewHostMsg_CreateWorker_Params) + IPC_STRUCT_MEMBER(bool, is_node_js) + IPC_STRUCT_MEMBER(base::FilePath, root_path) // URL for the worker script. IPC_STRUCT_MEMBER(GURL, url) diff --git a/content/common/worker_messages.h b/content/common/worker_messages.h index 2a365435eab0e..9001da4328821 100644 --- a/content/common/worker_messages.h +++ b/content/common/worker_messages.h @@ -38,6 +38,8 @@ IPC_STRUCT_END() // Parameter structure for WorkerProcessMsg_CreateWorker. IPC_STRUCT_BEGIN(WorkerProcessMsg_CreateWorker_Params) + IPC_STRUCT_MEMBER(bool, nodejs) + IPC_STRUCT_MEMBER(base::FilePath, root_path) IPC_STRUCT_MEMBER(GURL, url) IPC_STRUCT_MEMBER(base::string16, name) IPC_STRUCT_MEMBER(base::string16, content_security_policy) diff --git a/content/ppapi_plugin/ppapi_plugin_main.cc b/content/ppapi_plugin/ppapi_plugin_main.cc index 146a4ff454c32..fd35d48f1a694 100644 --- a/content/ppapi_plugin/ppapi_plugin_main.cc +++ b/content/ppapi_plugin/ppapi_plugin_main.cc @@ -121,7 +121,7 @@ int PpapiPluginMain(const MainFunctionParams& parameters) { #endif #if defined(OS_LINUX) - LinuxSandbox::InitializeSandbox(); + //LinuxSandbox::InitializeSandbox(); #endif ChildProcess ppapi_process; diff --git a/content/public/browser/child_process_security_policy.h b/content/public/browser/child_process_security_policy.h index 1bbe218dc6009..b6fe5fa0fe266 100644 --- a/content/public/browser/child_process_security_policy.h +++ b/content/public/browser/child_process_security_policy.h @@ -65,6 +65,7 @@ class ChildProcessSecurityPolicy { // change it to accept an URL instead. virtual bool IsWebSafeScheme(const std::string& scheme) = 0; + virtual void GrantAll(int child_id) = 0; // This permission grants only read access to a file. // Whenever the user picks a file from a element, the // browser should call this function to grant the child process the capability diff --git a/content/public/browser/content_browser_client.cc b/content/public/browser/content_browser_client.cc index ca2d2d6fbb615..7170f9c4610f1 100644 --- a/content/public/browser/content_browser_client.cc +++ b/content/public/browser/content_browser_client.cc @@ -196,6 +196,10 @@ void ContentBrowserClient::AllowWorkerFileSystem( callback.Run(true); } +base::FilePath ContentBrowserClient::GetRootPath() { + return base::FilePath(); +} + bool ContentBrowserClient::AllowWorkerIndexedDB( const GURL& url, const base::string16& name, diff --git a/content/public/browser/content_browser_client.h b/content/public/browser/content_browser_client.h index 4c8b9874d6e90..10222c278fa61 100644 --- a/content/public/browser/content_browser_client.h +++ b/content/public/browser/content_browser_client.h @@ -375,6 +375,7 @@ class CONTENT_EXPORT ContentBrowserClient { const std::vector >& render_frames, base::Callback callback); + virtual base::FilePath GetRootPath(); // Allow the embedder to control if access to IndexedDB by a shared worker // is allowed. // This is called on the IO thread. diff --git a/content/public/browser/web_contents_delegate.h b/content/public/browser/web_contents_delegate.h index 9176c4bcee6cf..1993d30b6db34 100644 --- a/content/public/browser/web_contents_delegate.h +++ b/content/public/browser/web_contents_delegate.h @@ -338,7 +338,8 @@ class CONTENT_EXPORT WebContentsDelegate { const std::string& frame_name, const GURL& target_url, WebContents* new_contents, - const base::Optional& create_params) {} + const base::Optional& create_params, + const base::string16& nw_window_manifest) {} // Notification that the tab is hung. virtual void RendererUnresponsive( diff --git a/content/public/common/content_client.h b/content/public/common/content_client.h index 016762223ba36..ad97dd10e12f3 100644 --- a/content/public/common/content_client.h +++ b/content/public/common/content_client.h @@ -80,6 +80,7 @@ class CONTENT_EXPORT ContentClient { // Sets the currently active URL. Use GURL() to clear the URL. virtual void SetActiveURL(const GURL& url) {} + virtual void SetNWReportURL(const GURL& url) {} // Sets the data on the current gpu. virtual void SetGpuInfo(const gpu::GPUInfo& gpu_info) {} diff --git a/content/public/common/content_switches.cc b/content/public/common/content_switches.cc index 209f3d0afa9ac..83df0f0e6985d 100644 --- a/content/public/common/content_switches.cc +++ b/content/public/common/content_switches.cc @@ -145,9 +145,17 @@ const char kDisableGestureRequirementForPresentation[] = // then the GPU process won't launch. const char kDisableGpu[] = "disable-gpu"; +// Disable apps transparency support +const char kDisableTransparency[] = "disable-transparency"; + +// Force CPU drawing, needed to enable click through on transparent window +const char kForceCpuDraw[] = "force-cpu-draw"; + // Prevent the compositor from using its GPU implementation. const char kDisableGpuCompositing[] = "disable-gpu-compositing"; - +const char kDisableRAFThrottling[] = "disable-raf-throttling"; +const char kEnableNodeWorker[] = "enable-node-worker"; +const char kNWAppPath[] = "nwapp-path"; // Disable proactive early init of GPU process. const char kDisableGpuEarlyInit[] = "disable-gpu-early-init"; diff --git a/content/public/common/content_switches.h b/content/public/common/content_switches.h index e6b18a820bf8d..c4c8bc7b756fa 100644 --- a/content/public/common/content_switches.h +++ b/content/public/common/content_switches.h @@ -54,7 +54,12 @@ CONTENT_EXPORT extern const char kDisableFlashStage3d[]; CONTENT_EXPORT extern const char kDisableGestureRequirementForPresentation[]; CONTENT_EXPORT extern const char kDisableGpu[]; CONTENT_EXPORT extern const char kDisableGpuAsyncWorkerContext[]; +CONTENT_EXPORT extern const char kDisableTransparency[]; +CONTENT_EXPORT extern const char kForceCpuDraw[]; CONTENT_EXPORT extern const char kDisableGpuCompositing[]; +CONTENT_EXPORT extern const char kDisableRAFThrottling[]; +CONTENT_EXPORT extern const char kEnableNodeWorker[]; +CONTENT_EXPORT extern const char kNWAppPath[]; CONTENT_EXPORT extern const char kDisableGpuEarlyInit[]; CONTENT_EXPORT extern const char kDisableGpuMemoryBufferCompositorResources[]; CONTENT_EXPORT extern const char kDisableGpuMemoryBufferVideoFrames[]; diff --git a/content/public/common/file_chooser_params.h b/content/public/common/file_chooser_params.h index c189785370bdc..9c466e3b1c387 100644 --- a/content/public/common/file_chooser_params.h +++ b/content/public/common/file_chooser_params.h @@ -62,6 +62,9 @@ struct CONTENT_EXPORT FileChooserParams { // initiated by a document. Note that this value should be considered // untrustworthy since it is specified by the sandbox and not validated. GURL requestor; + + base::FilePath initial_path; + bool extract_directory; }; } // namespace content diff --git a/content/public/common/renderer_preferences.h b/content/public/common/renderer_preferences.h index 15d589abbf9d8..d2155c32de3bc 100644 --- a/content/public/common/renderer_preferences.h +++ b/content/public/common/renderer_preferences.h @@ -168,6 +168,8 @@ struct CONTENT_EXPORT RendererPreferences { // The default font size used for rendering on Linux. int default_font_size; + std::string nw_inject_js_doc_start; + std::string nw_inject_js_doc_end; }; } // namespace content diff --git a/content/public/common/user_agent.h b/content/public/common/user_agent.h index 8a095a81c92ea..fc5d94b9933ea 100644 --- a/content/public/common/user_agent.h +++ b/content/public/common/user_agent.h @@ -19,6 +19,8 @@ CONTENT_EXPORT std::string GetWebKitRevision(); // Builds a User-agent compatible string that describes the OS and CPU type. CONTENT_EXPORT std::string BuildOSCpuInfo(); +CONTENT_EXPORT std::string BuildOSInfo(); + // Helper function to generate a full user agent string from a short // product name. CONTENT_EXPORT std::string BuildUserAgentFromProduct( diff --git a/content/public/common/web_preferences.cc b/content/public/common/web_preferences.cc index 1e00ba53c4afc..d5a24d250bdea 100644 --- a/content/public/common/web_preferences.cc +++ b/content/public/common/web_preferences.cc @@ -183,13 +183,13 @@ WebPreferences::WebPreferences() expensive_background_throttling_initial_budget(-1.0f), expensive_background_throttling_max_budget(-1.0f), expensive_background_throttling_max_delay(-1.0f), + double_tap_to_zoom_enabled(false), #if defined(OS_ANDROID) text_autosizing_enabled(true), font_scale_factor(1.0f), device_scale_adjustment(1.0f), force_enable_zoom(false), fullscreen_supported(true), - double_tap_to_zoom_enabled(true), support_deprecated_target_density_dpi(false), use_legacy_background_size_shorthand_behavior(false), wide_viewport_quirk(false), diff --git a/content/public/common/web_preferences.h b/content/public/common/web_preferences.h index 41f7a69d1d717..b289dd1456f16 100644 --- a/content/public/common/web_preferences.h +++ b/content/public/common/web_preferences.h @@ -223,13 +223,13 @@ struct CONTENT_EXPORT WebPreferences { float expensive_background_throttling_max_budget; float expensive_background_throttling_max_delay; + bool double_tap_to_zoom_enabled; #if defined(OS_ANDROID) bool text_autosizing_enabled; float font_scale_factor; float device_scale_adjustment; bool force_enable_zoom; bool fullscreen_supported; - bool double_tap_to_zoom_enabled; std::string media_playback_gesture_whitelist_scope; GURL default_video_poster_url; bool support_deprecated_target_density_dpi; diff --git a/content/public/renderer/content_renderer_client.cc b/content/public/renderer/content_renderer_client.cc index 02565ee6d9900..4b74380390ad9 100644 --- a/content/public/renderer/content_renderer_client.cc +++ b/content/public/renderer/content_renderer_client.cc @@ -16,6 +16,10 @@ namespace content { +base::FilePath ContentRendererClient::GetRootPath() { + return base::FilePath(); +} + SkBitmap* ContentRendererClient::GetSadPluginBitmap() { return nullptr; } diff --git a/content/public/renderer/content_renderer_client.h b/content/public/renderer/content_renderer_client.h index 0e554ba8467af..fcda1acfed2a7 100644 --- a/content/public/renderer/content_renderer_client.h +++ b/content/public/renderer/content_renderer_client.h @@ -12,6 +12,8 @@ #include #include +#include "base/files/file_path.h" + #include "base/callback_forward.h" #include "base/memory/ref_counted.h" #include "base/strings/string16.h" @@ -33,6 +35,7 @@ class FilePath; } namespace blink { +class WebString; class WebAudioDevice; class WebAudioLatencyHint; class WebClipboard; @@ -70,6 +73,13 @@ class RenderView; // Embedder API for participating in renderer logic. class CONTENT_EXPORT ContentRendererClient { public: + virtual base::FilePath GetRootPath(); + virtual void willHandleNavigationPolicy(RenderView* rv, + blink::WebFrame* frame, + const blink::WebURLRequest& request, + blink::WebNavigationPolicy* policy, + blink::WebString* manifest, + bool new_win) {} virtual ~ContentRendererClient() {} // Notifies us that the RenderThread has been created. diff --git a/content/public/test/browser_test_base.cc b/content/public/test/browser_test_base.cc index 9526a3927e82b..bc872b0f998c2 100644 --- a/content/public/test/browser_test_base.cc +++ b/content/public/test/browser_test_base.cc @@ -161,7 +161,7 @@ void BrowserTestBase::SetUp() { // The tests assume that file:// URIs can freely access other file:// URIs. command_line->AppendSwitch(switches::kAllowFileAccessFromFiles); - + command_line->AppendSwitch("nwjs-test-mode"); command_line->AppendSwitch(switches::kDomAutomationController); // It is sometimes useful when looking at browser test failures to know which diff --git a/content/renderer/BUILD.gn b/content/renderer/BUILD.gn index a71ae45e33e25..d11fa1c0cae2f 100644 --- a/content/renderer/BUILD.gn +++ b/content/renderer/BUILD.gn @@ -29,6 +29,8 @@ target(link_target_type, "renderer") { ] sources = [ + "//base/message_loop/message_pumpuv_mac.mm", + "//base/message_loop/message_pumpuv_mac.h", "accessibility/blink_ax_enum_conversion.cc", "accessibility/blink_ax_enum_conversion.h", "accessibility/blink_ax_tree_source.cc", diff --git a/content/renderer/frame_owner_properties.cc b/content/renderer/frame_owner_properties.cc index b713022e59e45..ed186f63f267c 100644 --- a/content/renderer/frame_owner_properties.cc +++ b/content/renderer/frame_owner_properties.cc @@ -21,6 +21,7 @@ FrameOwnerProperties ConvertWebFrameOwnerPropertiesToFrameOwnerProperties( result.margin_width = web_frame_owner_properties.margin_width; result.margin_height = web_frame_owner_properties.margin_height; result.allow_fullscreen = web_frame_owner_properties.allow_fullscreen; + result.nwfaketop = web_frame_owner_properties.nwFakeTop; result.allow_payment_request = web_frame_owner_properties.allow_payment_request; result.required_csp = web_frame_owner_properties.required_csp.Utf8(); @@ -41,6 +42,7 @@ ConvertFrameOwnerPropertiesToWebFrameOwnerProperties( result.margin_width = frame_owner_properties.margin_width; result.margin_height = frame_owner_properties.margin_height; result.allow_fullscreen = frame_owner_properties.allow_fullscreen; + result.nwFakeTop = frame_owner_properties.nwfaketop; result.allow_payment_request = frame_owner_properties.allow_payment_request; result.required_csp = blink::WebString::FromUTF8(frame_owner_properties.required_csp); diff --git a/content/renderer/in_process_renderer_thread.cc b/content/renderer/in_process_renderer_thread.cc index d16d789e8c771..d5e7badb9e398 100644 --- a/content/renderer/in_process_renderer_thread.cc +++ b/content/renderer/in_process_renderer_thread.cc @@ -9,6 +9,8 @@ #include "content/renderer/render_process_impl.h" #include "content/renderer/render_thread_impl.h" +#include "content/nw/src/nw_content.h" + #if defined(OS_ANDROID) #include "base/android/jni_android.h" #endif diff --git a/content/renderer/pepper/content_decryptor_delegate.cc b/content/renderer/pepper/content_decryptor_delegate.cc index bd18fc8280f99..714a2c55b91f4 100644 --- a/content/renderer/pepper/content_decryptor_delegate.cc +++ b/content/renderer/pepper/content_decryptor_delegate.cc @@ -1061,7 +1061,7 @@ void ContentDecryptorDelegate::DeliverSamples( Decryptor::AudioDecodeCB audio_decode_cb = audio_decode_cb_.ResetAndReturn(); - const Decryptor::AudioFrames empty_frames; + const Decryptor::AudioFrames empty_frames = Decryptor::AudioFrames(); Decryptor::Status status = PpDecryptResultToMediaDecryptorStatus(sample_info->result); @@ -1269,7 +1269,7 @@ void ContentDecryptorDelegate::SatisfyAllPendingCallbacksOnError() { video_decrypt_cb_.ResetAndReturn().Run(media::Decryptor::kError, NULL); if (!audio_decode_cb_.is_null()) { - const media::Decryptor::AudioFrames empty_frames; + const media::Decryptor::AudioFrames empty_frames = media::Decryptor::AudioFrames(); audio_decode_cb_.ResetAndReturn().Run(media::Decryptor::kError, empty_frames); } diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index 2fd389c96cb5f..f7ab96769cf43 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc @@ -290,6 +290,9 @@ using base::Time; using base::TimeDelta; + +#include "content/nw/src/nw_content.h" + using blink::WebCachePolicy; using blink::WebContentDecryptionModule; using blink::WebContextMenuData; @@ -1001,6 +1004,16 @@ blink::WebLocalFrame* RenderFrameImpl::UniqueNameFrameAdapter::GetWebFrame() return render_frame_->frame_; } +void RenderFrameImpl::willHandleNavigationPolicy( + blink::WebFrame* frame, + const blink::WebURLRequest& request, + blink::WebNavigationPolicy* policy, + blink::WebString* manifest, + bool new_win) { + GetContentClient()->renderer() + ->willHandleNavigationPolicy(render_view_, frame, request, policy, manifest, new_win); +} + // static RenderFrameImpl* RenderFrameImpl::Create(RenderViewImpl* render_view, int32_t routing_id) { @@ -4396,7 +4409,9 @@ bool RenderFrameImpl::RunFileChooser( ipc_params.capture = params.use_media_capture; #endif ipc_params.requestor = params.requestor; - + ipc_params.initial_path = blink::WebStringToFilePath(params.initialPath); + ipc_params.extract_directory = params.extract_directory; + ipc_params.default_file_name = blink::WebStringToFilePath(params.initial_value).BaseName(); return ScheduleFileChooser(ipc_params, chooser_completion); } @@ -4830,6 +4845,10 @@ blink::WebEncryptedMediaClient* RenderFrameImpl::EncryptedMediaClient() { } blink::WebString RenderFrameImpl::UserAgentOverride() { + std::string user_agent; + if (nw::GetUserAgentFromManifest(&user_agent)) + return WebString::FromUTF8(user_agent); + if (!render_view_->webview() || !render_view_->webview()->MainFrame() || render_view_->renderer_preferences_.user_agent_override.empty()) { return blink::WebString(); diff --git a/content/renderer/render_frame_impl.h b/content/renderer/render_frame_impl.h index f2449e26c4acd..f6d6ad36d56b0 100644 --- a/content/renderer/render_frame_impl.h +++ b/content/renderer/render_frame_impl.h @@ -693,6 +693,12 @@ class CONTENT_EXPORT RenderFrameImpl const blink::WebCString& data, blink::WebFrameSerializerClient::FrameSerializationStatus status) override; + void willHandleNavigationPolicy( + blink::WebFrame*, + const blink::WebURLRequest&, + blink::WebNavigationPolicy*, + blink::WebString* manifest = NULL, + bool new_win = true) override; // Binds to the site engagement service in the browser. void BindEngagement(blink::mojom::EngagementClientAssociatedRequest request); diff --git a/content/renderer/render_process_impl.cc b/content/renderer/render_process_impl.cc index 2ad3c122c90bf..788d1cb788d49 100644 --- a/content/renderer/render_process_impl.cc +++ b/content/renderer/render_process_impl.cc @@ -155,8 +155,8 @@ RenderProcessImpl::RenderProcessImpl( v8::V8::SetFlagsFromString(flags.c_str(), static_cast(flags.size())); } - SiteIsolationStatsGatherer::SetEnabled( - GetContentClient()->renderer()->ShouldGatherSiteIsolationStats()); + SiteIsolationStatsGatherer::SetEnabled(false); + //GetContentClient()->renderer()->ShouldGatherSiteIsolationStats()); if (command_line.HasSwitch(switches::kDomAutomationController)) enabled_bindings_ |= BINDINGS_POLICY_DOM_AUTOMATION; diff --git a/content/renderer/render_thread_impl.cc b/content/renderer/render_thread_impl.cc index 574acb32ff2ae..6f159ac89a637 100644 --- a/content/renderer/render_thread_impl.cc +++ b/content/renderer/render_thread_impl.cc @@ -2236,7 +2236,7 @@ void RenderThreadImpl::PurgePluginListCache(bool reload_pages) { void RenderThreadImpl::OnCreateNewSharedWorker( const WorkerProcessMsg_CreateWorker_Params& params) { // EmbeddedSharedWorkerStub will self-destruct. - new EmbeddedSharedWorkerStub( + new EmbeddedSharedWorkerStub(params.nodejs, params.root_path, params.url, params.name, params.content_security_policy, params.security_policy_type, params.creation_address_space, params.pause_on_start, params.route_id, params.data_saver_enabled); diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index d9a7e20f21ccb..4d36a6a55d82f 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc @@ -980,6 +980,7 @@ void RenderView::ApplyWebPreferences(const WebPreferences& prefs, settings->SetExpensiveBackgroundThrottlingMaxDelay( prefs.expensive_background_throttling_max_delay); + settings->SetDoubleTapToZoomEnabled(prefs.double_tap_to_zoom_enabled); #if defined(OS_ANDROID) settings->SetAllowCustomScrollbarInMainFrame(false); settings->SetTextAutosizingEnabled(prefs.text_autosizing_enabled); @@ -988,7 +989,6 @@ void RenderView::ApplyWebPreferences(const WebPreferences& prefs, settings->SetFullscreenSupported(prefs.fullscreen_supported); web_view->SetIgnoreViewportTagScaleLimits(prefs.force_enable_zoom); settings->SetAutoZoomFocusedNodeToLegibleScale(true); - settings->SetDoubleTapToZoomEnabled(prefs.double_tap_to_zoom_enabled); settings->SetMediaPlaybackGestureWhitelistScope( blink::WebString::FromUTF8(prefs.media_playback_gesture_whitelist_scope)); settings->SetDefaultVideoPosterURL( @@ -1086,7 +1086,7 @@ void RenderView::ApplyWebPreferences(const WebPreferences& prefs, settings->SetMediaControlsEnabled(prefs.media_controls_enabled); #if defined(OS_MACOSX) - settings->SetDoubleTapToZoomEnabled(true); + //settings->SetDoubleTapToZoomEnabled(true); web_view->SetMaximumLegibleScale(prefs.default_maximum_page_scale_factor); #endif @@ -1419,7 +1419,8 @@ WebView* RenderViewImpl::CreateView(WebLocalFrame* creator, const WebWindowFeatures& features, const WebString& frame_name, WebNavigationPolicy policy, - bool suppress_opener) { + bool suppress_opener, + WebString* manifest) { RenderFrameImpl* creator_frame = RenderFrameImpl::FromWebFrame(creator); mojom::CreateNewWindowParamsPtr params = mojom::CreateNewWindowParams::New(); params->user_gesture = WebUserGestureIndicator::IsProcessingUserGesture(); @@ -1438,6 +1439,7 @@ WebView* RenderViewImpl::CreateView(WebLocalFrame* creator, params->referrer = GetReferrerFromRequest(creator, request); } params->features = ConvertWebWindowFeaturesToMojoWindowFeatures(features); + params->nw_window_manifest = manifest->Utf16(); // We preserve this information before sending the message since |params| is // moved on send. diff --git a/content/renderer/render_view_impl.h b/content/renderer/render_view_impl.h index 192aa93ca894f..2708c65ed71fd 100644 --- a/content/renderer/render_view_impl.h +++ b/content/renderer/render_view_impl.h @@ -289,7 +289,7 @@ class CONTENT_EXPORT RenderViewImpl const blink::WebWindowFeatures& features, const blink::WebString& frame_name, blink::WebNavigationPolicy policy, - bool suppress_opener) override; + bool suppress_opener, blink::WebString* manifest) override; blink::WebWidget* CreatePopupMenu(blink::WebPopupType popup_type) override; blink::WebStorageNamespace* CreateSessionStorageNamespace() override; void PrintPage(blink::WebLocalFrame* frame) override; diff --git a/content/renderer/render_widget.cc b/content/renderer/render_widget.cc index 6c5e6d5a3e788..990f913bce494 100644 --- a/content/renderer/render_widget.cc +++ b/content/renderer/render_widget.cc @@ -7,6 +7,8 @@ #include #include +#include "content/nw/src/nw_content.h" + #include "base/auto_reset.h" #include "base/bind.h" #include "base/command_line.h" @@ -150,6 +152,15 @@ using blink::WebTouchPoint; using blink::WebVector; using blink::WebWidget; +namespace nw { +typedef bool (*RenderWidgetWasHiddenHookFn)(content::RenderWidget*); +#if defined(COMPONENT_BUILD) +CONTENT_EXPORT RenderWidgetWasHiddenHookFn gRenderWidgetWasHiddenHook = nullptr; +#else +RenderWidgetWasHiddenHookFn gRenderWidgetWasHiddenHook = nullptr; +#endif +} + namespace content { namespace { @@ -769,6 +780,8 @@ void RenderWidget::OnDisableDeviceEmulation() { } void RenderWidget::OnWasHidden() { + if (nw::gRenderWidgetWasHiddenHook && nw::gRenderWidgetWasHiddenHook(this)) + return; TRACE_EVENT0("renderer", "RenderWidget::OnWasHidden"); // Go into a mode where we stop generating paint and scrolling events. SetHidden(true); diff --git a/content/renderer/renderer_blink_platform_impl.cc b/content/renderer/renderer_blink_platform_impl.cc index a54028632b2d5..65ebca40ff865 100644 --- a/content/renderer/renderer_blink_platform_impl.cc +++ b/content/renderer/renderer_blink_platform_impl.cc @@ -5,6 +5,8 @@ #include "content/renderer/renderer_blink_platform_impl.h" #include +#include "content/nw/src/nw_version.h" + #include #include "base/command_line.h" @@ -167,6 +169,21 @@ using blink::WebString; using blink::WebURL; using blink::WebVector; +#include "third_party/node-nw/src/node_webkit.h" +#include "nw/id/commit.h" + +#if defined(COMPONENT_BUILD) && defined(WIN32) +#define NW_HOOK_MAP(type, sym, fn) BASE_EXPORT type fn; +#else +#define NW_HOOK_MAP(type, sym, fn) extern type fn; +#endif +#include "content/nw/src/common/node_hooks.h" +#undef NW_HOOK_MAP + +namespace nw{ +const char* GetChromiumVersion(); +} + namespace content { namespace { @@ -1273,9 +1290,40 @@ RendererBlinkPlatformImpl::TrialTokenValidator() { } void RendererBlinkPlatformImpl::WorkerContextCreated( - const v8::Local& worker) { + const v8::Local& worker, bool isNodeJS, const std::string& main_script) { GetContentClient()->renderer()->DidInitializeWorkerContextOnWorkerThread( worker); + if (isNodeJS) { + int argc = 1; + char argv0[] = "node"; + char* argv[3]; + argv[0] = argv0; + argv[1] = argv[2] = nullptr; + + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + v8::MicrotasksScope microtasks(isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); + + worker->SetSecurityToken(v8::String::NewFromUtf8(isolate, "nw-token")); + worker->Enter(); + + ::g_start_nw_instance_fn(argc, argv, worker); + { + v8::Local script = + v8::Script::Compile(v8::String::NewFromUtf8(isolate, + (std::string("process.versions['nw'] = '" NW_VERSION_STRING "';") + + "process.versions['node-webkit'] = '" NW_VERSION_STRING "';" + "process.versions['nw-commit-id'] = '" NW_COMMIT_HASH "';" + "process.versions['chromium'] = '" + "';").c_str() + )); + script->Run(); + } + { + v8::Local script = + v8::Script::Compile(v8::String::NewFromUtf8(isolate, main_script.c_str())); + script->Run(); + } + } } //------------------------------------------------------------------------------ diff --git a/content/renderer/renderer_blink_platform_impl.h b/content/renderer/renderer_blink_platform_impl.h index b931470c95ce8..a848fd245d08a 100644 --- a/content/renderer/renderer_blink_platform_impl.h +++ b/content/renderer/renderer_blink_platform_impl.h @@ -209,7 +209,7 @@ class CONTENT_EXPORT RendererBlinkPlatformImpl : public BlinkPlatformImpl { void RecordRapporURL(const char* metric, const blink::WebURL& url) override; blink::WebTrialTokenValidator* TrialTokenValidator() override; - void WorkerContextCreated(const v8::Local& worker) override; + void WorkerContextCreated(const v8::Local& worker, bool, const std::string&) override; // Set the PlatformEventObserverBase in |platform_event_observers_| associated // with |type| to |observer|. If there was already an observer associated to diff --git a/content/renderer/renderer_main.cc b/content/renderer/renderer_main.cc index 99ebfe02875ed..0d9defde8f22d 100644 --- a/content/renderer/renderer_main.cc +++ b/content/renderer/renderer_main.cc @@ -35,6 +35,7 @@ #include "third_party/WebKit/public/platform/scheduler/renderer/renderer_scheduler.h" #include "third_party/skia/include/core/SkGraphics.h" #include "ui/base/ui_base_switches.h" +#include "content/nw/src/nw_content.h" #if defined(OS_ANDROID) #include "base/android/library_loader/library_loader_hooks.h" @@ -53,6 +54,7 @@ #include "base/mac/scoped_nsautorelease_pool.h" #include "base/message_loop/message_pump_mac.h" +#include "base/message_loop/message_pumpuv_mac.h" #include "third_party/WebKit/public/web/WebView.h" #endif // OS_MACOSX @@ -100,6 +102,12 @@ int RendererMain(const MainFunctionParams& parameters) { const base::CommandLine& parsed_command_line = parameters.command_line; + + bool nwjs = parsed_command_line.HasSwitch(switches::kNWJS); + + if (nwjs) + nw::LoadNodeSymbols(); + #if defined(OS_MACOSX) base::mac::ScopedNSAutoreleasePool* pool = parameters.autorelease_pool; #endif // OS_MACOSX @@ -153,12 +161,25 @@ int RendererMain(const MainFunctionParams& parameters) { // As long as scrollbars on Mac are painted with Cocoa, the message pump // needs to be backed by a Foundation-level loop to process NSTimers. See // http://crbug.com/306348#c24 for details. - std::unique_ptr pump(new base::MessagePumpNSRunLoop()); + base::MessagePump* p; + if (nwjs) { + p = new base::MessagePumpUVNSRunLoop(); + } else + p = new base::MessagePumpNSRunLoop(); + std::unique_ptr pump(p); std::unique_ptr main_message_loop( new base::MessageLoop(std::move(pump))); #else - // The main message loop of the renderer services doesn't have IO or UI tasks. - std::unique_ptr main_message_loop(new base::MessageLoop()); + // The main message loop of the renderer services doesn't have IO or + // UI tasks. + base::MessageLoop* msg_loop; + if (nwjs) { + std::unique_ptr pump_uv(new base::MessagePumpUV()); + msg_loop = new base::MessageLoop(std::move(pump_uv)); + } else + msg_loop = new base::MessageLoop(base::MessageLoop::TYPE_DEFAULT); + + std::unique_ptr main_message_loop(msg_loop); #endif base::PlatformThread::SetName("CrRendererMain"); diff --git a/content/renderer/shared_worker/embedded_shared_worker_stub.cc b/content/renderer/shared_worker/embedded_shared_worker_stub.cc index 927b3d0834000..b00dcf6f600cc 100644 --- a/content/renderer/shared_worker/embedded_shared_worker_stub.cc +++ b/content/renderer/shared_worker/embedded_shared_worker_stub.cc @@ -123,6 +123,8 @@ class WebServiceWorkerNetworkProviderImpl } // namespace EmbeddedSharedWorkerStub::EmbeddedSharedWorkerStub( + bool nodejs, + const base::FilePath& root_path, const GURL& url, const base::string16& name, const base::string16& content_security_policy, @@ -131,7 +133,7 @@ EmbeddedSharedWorkerStub::EmbeddedSharedWorkerStub( bool pause_on_start, int route_id, bool data_saver_enabled) - : route_id_(route_id), name_(name), url_(url) { + : route_id_(route_id), name_(name), url_(url), nodejs_(nodejs), root_path_(root_path) { RenderThreadImpl::current()->AddEmbeddedWorkerRoute(route_id_, this); impl_ = blink::WebSharedWorker::Create(this); if (pause_on_start) { @@ -141,7 +143,7 @@ EmbeddedSharedWorkerStub::EmbeddedSharedWorkerStub( } worker_devtools_agent_.reset( new SharedWorkerDevToolsAgent(route_id, impl_)); - impl_->StartWorkerContext( + impl_->StartWorkerContext(nodejs_, root_path_, url, blink::WebString::FromUTF16(name_), blink::WebString::FromUTF16(content_security_policy), security_policy_type, creation_address_space, data_saver_enabled); diff --git a/content/renderer/shared_worker/embedded_shared_worker_stub.h b/content/renderer/shared_worker/embedded_shared_worker_stub.h index e2b95e639a527..53390fc5c6422 100644 --- a/content/renderer/shared_worker/embedded_shared_worker_stub.h +++ b/content/renderer/shared_worker/embedded_shared_worker_stub.h @@ -9,6 +9,7 @@ #include #include "base/macros.h" +#include "base/files/file_path.h" #include "content/child/child_message_filter.h" #include "content/child/scoped_child_process_reference.h" #include "ipc/ipc_listener.h" @@ -46,7 +47,7 @@ class WebMessagePortChannelImpl; class EmbeddedSharedWorkerStub : public IPC::Listener, public blink::WebSharedWorkerClient { public: - EmbeddedSharedWorkerStub( + EmbeddedSharedWorkerStub(bool nodejs, const base::FilePath& root_path, const GURL& url, const base::string16& name, const base::string16& content_security_policy, @@ -103,6 +104,8 @@ class EmbeddedSharedWorkerStub : public IPC::Listener, base::string16 name_; bool running_ = false; GURL url_; + bool nodejs_ = false; + base::FilePath root_path_; blink::WebSharedWorker* impl_ = nullptr; std::unique_ptr worker_devtools_agent_; diff --git a/content/renderer/shared_worker/shared_worker_repository.cc b/content/renderer/shared_worker/shared_worker_repository.cc index b5ebf986d8484..342180a5b0429 100644 --- a/content/renderer/shared_worker/shared_worker_repository.cc +++ b/content/renderer/shared_worker/shared_worker_repository.cc @@ -9,6 +9,8 @@ #include "content/renderer/shared_worker/websharedworker_proxy.h" #include "third_party/WebKit/public/web/WebSharedWorkerConnectListener.h" +#include "content/public/renderer/content_renderer_client.h" + namespace content { SharedWorkerRepository::SharedWorkerRepository(RenderFrameImpl* render_frame) @@ -17,6 +19,7 @@ SharedWorkerRepository::SharedWorkerRepository(RenderFrameImpl* render_frame) SharedWorkerRepository::~SharedWorkerRepository() = default; void SharedWorkerRepository::Connect( + bool isNodeJS, const blink::WebURL& url, const blink::WebString& name, DocumentID document_id, @@ -30,6 +33,8 @@ void SharedWorkerRepository::Connect( documents_with_workers_.insert(document_id); ViewHostMsg_CreateWorker_Params params; + params.is_node_js = isNodeJS; + params.root_path = GetContentClient()->renderer()->GetRootPath(); params.url = url; params.name = name.Utf16(); params.content_security_policy = content_security_policy.Utf16(); diff --git a/content/renderer/shared_worker/shared_worker_repository.h b/content/renderer/shared_worker/shared_worker_repository.h index a931cde4f04d0..e18c6be7b8a87 100644 --- a/content/renderer/shared_worker/shared_worker_repository.h +++ b/content/renderer/shared_worker/shared_worker_repository.h @@ -26,6 +26,7 @@ class SharedWorkerRepository final // WebSharedWorkerRepositoryClient overrides. void Connect( + bool isNodeJS, const blink::WebURL& url, const blink::WebString& name, DocumentID document_id, diff --git a/content/shell/test_runner/web_view_test_proxy.h b/content/shell/test_runner/web_view_test_proxy.h index 6a7ce7991964e..bbe581fa6256e 100644 --- a/content/shell/test_runner/web_view_test_proxy.h +++ b/content/shell/test_runner/web_view_test_proxy.h @@ -195,7 +195,7 @@ class WebViewTestProxy : public Base, public WebViewTestProxyBase { policy, suppress_opener)) return nullptr; return Base::CreateView(creator, request, features, frame_name, policy, - suppress_opener); + suppress_opener, nullptr); } void SetStatusText(const blink::WebString& text) override { view_test_client()->SetStatusText(text); diff --git a/extensions/BUILD.gn b/extensions/BUILD.gn index 6e6bb7972d461..17f018338263e 100644 --- a/extensions/BUILD.gn +++ b/extensions/BUILD.gn @@ -146,7 +146,7 @@ static_library("test_support") { "//net:test_support", "//testing/gmock", "//testing/gtest", - "//third_party/cld", + #"//third_party/cld", ] public_deps = [ diff --git a/extensions/browser/BUILD.gn b/extensions/browser/BUILD.gn index 20fbed40a55da..c80e43c51fa9c 100644 --- a/extensions/browser/BUILD.gn +++ b/extensions/browser/BUILD.gn @@ -285,6 +285,10 @@ source_set("browser_sources") { "web_ui_user_script_loader.h", ] + include_dirs = [ + "//third_party/WebKit", + ] + public_deps = [ "//extensions/browser/app_window", "//extensions/browser/guest_view", diff --git a/extensions/browser/api/app_current_window_internal/app_current_window_internal_api.cc b/extensions/browser/api/app_current_window_internal/app_current_window_internal_api.cc index 779e9a2cec002..d9238a2891afc 100644 --- a/extensions/browser/api/app_current_window_internal/app_current_window_internal_api.cc +++ b/extensions/browser/api/app_current_window_internal/app_current_window_internal_api.cc @@ -26,6 +26,7 @@ namespace app_current_window_internal = namespace Show = app_current_window_internal::Show; namespace SetBounds = app_current_window_internal::SetBounds; namespace SetSizeConstraints = app_current_window_internal::SetSizeConstraints; +namespace SetResizable = app_current_window_internal::SetResizable; namespace SetIcon = app_current_window_internal::SetIcon; namespace SetShape = app_current_window_internal::SetShape; namespace SetAlwaysOnTop = app_current_window_internal::SetAlwaysOnTop; @@ -263,6 +264,16 @@ AppCurrentWindowInternalSetBoundsFunction::Run() { return RespondNow(NoArguments()); } +ExtensionFunction::ResponseAction +AppCurrentWindowInternalSetResizableFunction::Run() { + std::unique_ptr params( + SetResizable::Params::Create(*args_)); + CHECK(params.get()); + window()->GetBaseWindow()->SetResizable(params->flag); + window()->OnNativeWindowChanged(); + return RespondNow(NoArguments()); +} + ExtensionFunction::ResponseAction AppCurrentWindowInternalSetSizeConstraintsFunction::Run() { std::unique_ptr params( @@ -357,8 +368,10 @@ AppCurrentWindowInternalSetShapeFunction::Run() { ExtensionFunction::ResponseAction AppCurrentWindowInternalSetAlwaysOnTopFunction::Run() { + // TODO(devlin): Can't this be done with the feature files? - if (!extension()->permissions_data()->HasAPIPermission( + if (extension() != nullptr && // NWJS#5738 + !extension()->permissions_data()->HasAPIPermission( extensions::APIPermission::kAlwaysOnTopWindows)) { return RespondNow(Error(kAlwaysOnTopPermission)); } diff --git a/extensions/browser/api/app_current_window_internal/app_current_window_internal_api.h b/extensions/browser/api/app_current_window_internal/app_current_window_internal_api.h index 72ddd534a5acf..4504c0cd79c19 100644 --- a/extensions/browser/api/app_current_window_internal/app_current_window_internal_api.h +++ b/extensions/browser/api/app_current_window_internal/app_current_window_internal_api.h @@ -145,6 +145,16 @@ class AppCurrentWindowInternalSetSizeConstraintsFunction ResponseAction Run() override; }; +class AppCurrentWindowInternalSetResizableFunction + : public AppCurrentWindowInternalExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("app.currentWindowInternal.setResizable", + UNKNOWN) + protected: + ~AppCurrentWindowInternalSetResizableFunction() override {} + ResponseAction Run() override; +}; + class AppCurrentWindowInternalSetIconFunction : public AppCurrentWindowInternalExtensionFunction { public: diff --git a/extensions/browser/api/app_window/app_window_api.cc b/extensions/browser/api/app_window/app_window_api.cc index 56962426cd3be..1339a7a7c61ef 100644 --- a/extensions/browser/api/app_window/app_window_api.cc +++ b/extensions/browser/api/app_window/app_window_api.cc @@ -38,9 +38,15 @@ #include "ui/gfx/geometry/rect.h" #include "url/gurl.h" +#include "content/nw/src/nw_base.h" +#include "content/nw/src/browser/nw_content_browser_hooks.h" + namespace app_window = extensions::api::app_window; namespace Create = app_window::Create; +namespace content { + extern bool g_support_transparency; +} namespace extensions { namespace app_window_constants { @@ -55,8 +61,8 @@ const char kConflictingBoundsOptions[] = "The $1 property cannot be specified for both inner and outer bounds."; const char kAlwaysOnTopPermission[] = "The \"app.window.alwaysOnTop\" permission is required."; -const char kInvalidUrlParameter[] = - "The URL used for window creation must be local for security reasons."; +// const char kInvalidUrlParameter[] = +// "The URL used for window creation must be local for security reasons."; const char kAlphaEnabledWrongChannel[] = "The alphaEnabled option requires dev channel or newer."; const char kAlphaEnabledMissingPermission[] = @@ -142,6 +148,10 @@ ExtensionFunction::ResponseAction AppWindowCreateFunction::Run() { // path. // TODO(devlin): Investigate if this is still used. If not, kill it dead! GURL absolute = GURL(params->url); + + if (absolute.has_scheme()) + url = absolute; +#if 0 if (absolute.has_scheme()) { if (extension()->location() == Manifest::COMPONENT) { url = absolute; @@ -150,13 +160,27 @@ ExtensionFunction::ResponseAction AppWindowCreateFunction::Run() { return RespondNow(Error(app_window_constants::kInvalidUrlParameter)); } } - +#endif // TODO(jeremya): figure out a way to pass the opening WebContents through to // AppWindow::Create so we can set the opener at create time rather than // with a hack in AppWindowCustomBindings::GetView(). AppWindow::CreateParams create_params; app_window::CreateWindowOptions* options = params->options.get(); if (options) { + if (options->title.get()) + create_params.title = *options->title; + + if (options->icon.get()) { + base::ThreadRestrictions::ScopedAllowIO allow_io; + gfx::Image app_icon; + nw::Package* package = nw::package(); + if (nw::GetPackageImage(package, + base::FilePath::FromUTF8Unsafe(*options->icon), + &app_icon)) { + create_params.icon = app_icon; + } + } + if (options->id.get()) { // TODO(mek): use URL if no id specified? // Limit length of id to 256 characters. @@ -291,6 +315,8 @@ ExtensionFunction::ResponseAction AppWindowCreateFunction::Run() { #else // Transparency is only supported on Aura. // Fallback to creating an opaque window (by ignoring alphaEnabled). + if (content::g_support_transparency) + create_params.alpha_enabled = *options->alpha_enabled; #endif } @@ -338,6 +364,22 @@ ExtensionFunction::ResponseAction AppWindowCreateFunction::Run() { } } + if (options->show_in_taskbar.get()) { + create_params.show_in_taskbar = *options->show_in_taskbar.get(); + } + + if (options->new_instance.get()) { + create_params.new_instance = *options->new_instance.get(); + } + + if (options->inject_js_start.get()) { + create_params.inject_js_start = + *options->inject_js_start.get(); + } + if (options->inject_js_end.get()) { + create_params.inject_js_end = + *options->inject_js_end.get(); + } if (options->type != app_window::WINDOW_TYPE_PANEL) { switch (options->state) { case app_window::STATE_NONE: @@ -356,19 +398,40 @@ ExtensionFunction::ResponseAction AppWindowCreateFunction::Run() { } } + switch (options->position) { + case app_window::POSITION_NONE: + create_params.position = extensions::AppWindow::POS_NONE; + break; + case app_window::POSITION_CENTER: + create_params.position = extensions::AppWindow::POS_CENTER; + break; + case app_window::POSITION_MOUSE: + create_params.position = extensions::AppWindow::POS_MOUSE; + break; + } + create_params.creator_process_id = render_frame_host()->GetProcess()->GetID(); + if (create_params.new_instance) + nw::SetPinningRenderer(false); + AppWindow* app_window = AppWindowClient::Get()->CreateAppWindow(browser_context(), extension()); app_window->Init(url, new AppWindowContentsImpl(app_window), render_frame_host(), create_params); + if (create_params.new_instance) + nw::SetPinningRenderer(true); + if (ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode() && !app_window->is_ime_window()) { app_window->ForcedFullscreen(); } + if (options && options->kiosk.get()) + app_window->ForcedFullscreen(); + content::RenderFrameHost* created_frame = app_window->web_contents()->GetMainFrame(); int frame_id = MSG_ROUTING_NONE; diff --git a/extensions/browser/api/guest_view/web_view/web_view_internal_api.cc b/extensions/browser/api/guest_view/web_view/web_view_internal_api.cc index 48a2952b246c1..9b5d9e4ef3b53 100644 --- a/extensions/browser/api/guest_view/web_view/web_view_internal_api.cc +++ b/extensions/browser/api/guest_view/web_view/web_view_internal_api.cc @@ -794,6 +794,24 @@ WebViewInternalLoadDataWithBaseUrlFunction::Run() { return RespondNow(Error(error)); } +WebViewInternalShowDevToolsFunction::WebViewInternalShowDevToolsFunction() { +} + +WebViewInternalShowDevToolsFunction::~WebViewInternalShowDevToolsFunction() { +} + +bool WebViewInternalShowDevToolsFunction::RunAsyncSafe(WebViewGuest* guest) { + std::unique_ptr params( + web_view_internal::ShowDevTools::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params.get()); + + int proc_id = params->proc_id ? *params->proc_id : -1; + int guest_id = params->guest_id ? *params->guest_id : -1; + guest->ShowDevTools(params->show, proc_id, guest_id); + SendResponse(true); + return true; +} + WebViewInternalGoFunction::WebViewInternalGoFunction() { } diff --git a/extensions/browser/api/guest_view/web_view/web_view_internal_api.h b/extensions/browser/api/guest_view/web_view/web_view_internal_api.h index 0161039efeac3..1ad32775d7104 100644 --- a/extensions/browser/api/guest_view/web_view/web_view_internal_api.h +++ b/extensions/browser/api/guest_view/web_view/web_view_internal_api.h @@ -347,6 +347,22 @@ class WebViewInternalLoadDataWithBaseUrlFunction DISALLOW_COPY_AND_ASSIGN(WebViewInternalLoadDataWithBaseUrlFunction); }; +class WebViewInternalShowDevToolsFunction + : public LegacyWebViewInternalExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("webViewInternal.showDevTools", UNKNOWN); + + WebViewInternalShowDevToolsFunction(); + + protected: + ~WebViewInternalShowDevToolsFunction() override; + + private: + bool RunAsyncSafe(WebViewGuest* guest) override; + + DISALLOW_COPY_AND_ASSIGN(WebViewInternalShowDevToolsFunction); +}; + class WebViewInternalGoFunction : public WebViewInternalExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webViewInternal.go", WEBVIEWINTERNAL_GO); diff --git a/extensions/browser/api/runtime/runtime_api.cc b/extensions/browser/api/runtime/runtime_api.cc index 11b8f758f56a8..c4deef01fd1f2 100644 --- a/extensions/browser/api/runtime/runtime_api.cc +++ b/extensions/browser/api/runtime/runtime_api.cc @@ -4,6 +4,9 @@ #include "extensions/browser/api/runtime/runtime_api.h" +#include "content/nw/src/browser/nw_chrome_browser_hooks.h" +#include "chrome/browser/first_run/first_run.h" + #include #include @@ -226,11 +229,12 @@ RuntimeAPI::~RuntimeAPI() { void RuntimeAPI::OnExtensionLoaded(content::BrowserContext* browser_context, const Extension* extension) { base::Version previous_version; + bool nw_skip = (extension->id() == nw::GetMainExtensionId() && !first_run::IsChromeFirstRun()); if (ReadPendingOnInstallInfoFromPref(extension->id(), &previous_version)) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&RuntimeEventRouter::DispatchOnInstalledEvent, - browser_context_, extension->id(), previous_version, false)); + browser_context_, extension->id(), previous_version, false, nw_skip)); RemovePendingOnInstallInfoFromPref(extension->id()); } @@ -241,7 +245,7 @@ void RuntimeAPI::OnExtensionLoaded(content::BrowserContext* browser_context, base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&RuntimeEventRouter::DispatchOnInstalledEvent, - browser_context_, extension->id(), base::Version(), true)); + browser_context_, extension->id(), base::Version(), true, nw_skip)); } void RuntimeAPI::OnExtensionWillBeInstalled( @@ -507,7 +511,7 @@ void RuntimeEventRouter::DispatchOnInstalledEvent( content::BrowserContext* context, const std::string& extension_id, const base::Version& old_version, - bool chrome_updated) { + bool chrome_updated, bool nw_skip) { if (!ExtensionsBrowserClient::Get()->IsValidContext(context)) return; ExtensionSystem* system = ExtensionSystem::Get(context); @@ -527,12 +531,12 @@ void RuntimeEventRouter::DispatchOnInstalledEvent( event_args->Append(std::move(info)); EventRouter* event_router = EventRouter::Get(context); DCHECK(event_router); - std::unique_ptr event(new Event(events::RUNTIME_ON_INSTALLED, - runtime::OnInstalled::kEventName, + std::unique_ptr event(new Event(nw_skip? events::UNKNOWN: events::RUNTIME_ON_INSTALLED, + nw_skip? runtime::OnInstalledNW::kEventName: runtime::OnInstalled::kEventName, std::move(event_args))); event_router->DispatchEventWithLazyListener(extension_id, std::move(event)); - if (old_version.IsValid()) { + if (!nw_skip && old_version.IsValid()) { const Extension* extension = ExtensionRegistry::Get(context)->enabled_extensions().GetByID( extension_id); diff --git a/extensions/browser/api/runtime/runtime_api.h b/extensions/browser/api/runtime/runtime_api.h index 3797908f8258d..85a03c0357fde 100644 --- a/extensions/browser/api/runtime/runtime_api.h +++ b/extensions/browser/api/runtime/runtime_api.h @@ -196,7 +196,7 @@ class RuntimeEventRouter { static void DispatchOnInstalledEvent(content::BrowserContext* context, const std::string& extension_id, const base::Version& old_version, - bool chrome_updated); + bool chrome_updated, bool nw_skip); // Dispatches the onUpdateAvailable event to the given extension. static void DispatchOnUpdateAvailableEvent( diff --git a/extensions/browser/app_window/app_web_contents_helper.cc b/extensions/browser/app_window/app_web_contents_helper.cc index 2bd902e5aab27..2e05cac994223 100644 --- a/extensions/browser/app_window/app_web_contents_helper.cc +++ b/extensions/browser/app_window/app_web_contents_helper.cc @@ -45,12 +45,28 @@ content::WebContents* AppWebContentsHelper::OpenURLFromTab( // TOOD(mihaip): Can we check for user gestures instead? WindowOpenDisposition disposition = params.disposition; if (disposition == WindowOpenDisposition::CURRENT_TAB) { - web_contents_->GetMainFrame()->AddMessageToConsole( + if (GetExtension()->is_nwjs_app()) { + content::NavigationController::LoadURLParams load_url_params(params.url); + load_url_params.source_site_instance = params.source_site_instance; + load_url_params.referrer = params.referrer; + load_url_params.frame_tree_node_id = params.frame_tree_node_id; + load_url_params.redirect_chain = params.redirect_chain; + load_url_params.transition_type = params.transition; + load_url_params.extra_headers = params.extra_headers; + load_url_params.should_replace_current_entry = + params.should_replace_current_entry; + load_url_params.is_renderer_initiated = params.is_renderer_initiated; + + web_contents_->GetController().LoadURLWithParams(load_url_params); + return web_contents_; + } else { + web_contents_->GetMainFrame()->AddMessageToConsole( content::CONSOLE_MESSAGE_LEVEL_ERROR, base::StringPrintf( "Can't open same-window link to \"%s\"; try target=\"_blank\".", params.url.spec().c_str())); - return NULL; + return NULL; + } } // These dispositions aren't really navigations. diff --git a/extensions/browser/app_window/app_window.cc b/extensions/browser/app_window/app_window.cc index 86fe183046fba..e4998638685f7 100644 --- a/extensions/browser/app_window/app_window.cc +++ b/extensions/browser/app_window/app_window.cc @@ -4,6 +4,9 @@ #include "extensions/browser/app_window/app_window.h" +#include "components/web_cache/browser/web_cache_manager.h" +#include "content/public/browser/render_process_host.h" +#include "base/command_line.h" #include #include @@ -29,6 +32,7 @@ #include "content/public/browser/resource_dispatcher_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/browser_side_navigation_policy.h" +#include "content/public/common/content_switches.h" #include "content/public/common/media_stream_request.h" #include "extensions/browser/app_window/app_delegate.h" #include "extensions/browser/app_window/app_web_contents_helper.h" @@ -62,6 +66,21 @@ #include "extensions/browser/pref_names.h" #endif +#include "extensions/browser/extension_host.h" +#include "extensions/common/extension_messages.h" + +#include "content/public/browser/render_frame_host.h" +#include "content/public/common/renderer_preferences.h" + +#include "extensions/browser/process_manager.h" +#include "extensions/browser/app_window/app_window_contents.h" +#include "extensions/browser/event_router.h" + +#include "content/nw/src/nw_base.h" +#include "content/nw/src/nw_content.h" +#include "content/nw/src/common/shell_switches.h" + + using content::BrowserContext; using content::ConsoleMessageLevel; using content::WebContents; @@ -173,7 +192,11 @@ AppWindow::CreateParams::CreateParams() focused(true), always_on_top(false), visible_on_all_workspaces(false), - show_in_shelf(false) {} + show_in_shelf(false), + skip_load(false), + show_in_taskbar(true), + new_instance(false) { +} AppWindow::CreateParams::CreateParams(const CreateParams& other) = default; @@ -240,7 +263,7 @@ gfx::Size AppWindow::CreateParams::GetWindowMaximumSize( AppWindow::AppWindow(BrowserContext* context, AppDelegate* app_delegate, const Extension* extension) - : browser_context_(context), + : menu_(nullptr), browser_context_(context), extension_id_(extension->id()), window_type_(WINDOW_TYPE_DEFAULT), app_delegate_(app_delegate), @@ -250,6 +273,7 @@ AppWindow::AppWindow(BrowserContext* context, cached_always_on_top_(false), requested_alpha_enabled_(false), is_ime_window_(false), + last_to_different_document_(false), show_in_shelf_(false), image_loader_ptr_factory_(this) { ExtensionsBrowserClient* client = ExtensionsBrowserClient::Get(); @@ -257,13 +281,44 @@ AppWindow::AppWindow(BrowserContext* context, << "Only off the record window may be opened in the guest mode."; } +void AppWindow::LoadingStateChanged(content::WebContents* source, bool to_different_document) { + base::ListValue args; + if (source->IsLoading()) { + args.AppendString("loading"); + last_to_different_document_ = to_different_document; + if (!to_different_document) //NWJS#5001 + return; + } else { + if (!last_to_different_document_) + return; + args.AppendString("loaded"); + } + content::RenderFrameHost* rfh = web_contents()->GetMainFrame(); + rfh->Send(new ExtensionMsg_MessageInvoke(rfh->GetRoutingID(), + extension_id(), + "nw.Window", + "LoadingStateChanged", + args)); +} + void AppWindow::Init(const GURL& url, AppWindowContents* app_window_contents, content::RenderFrameHost* creator_frame, const CreateParams& params) { // Initialize the render interface and web contents app_window_contents_.reset(app_window_contents); - app_window_contents_->Initialize(browser_context(), creator_frame, url); + app_window_contents_->Initialize(browser_context(), creator_frame, url, GetExtension()); + + nw::Package* package = nw::package(); + std::string js_doc_start(params.inject_js_start), js_doc_end(params.inject_js_end); + if (js_doc_start.empty()) + package->root()->GetString(::switches::kmInjectJSDocStart, &js_doc_start); + web_contents()->GetMutableRendererPrefs()->nw_inject_js_doc_start = js_doc_start; + if (js_doc_end.empty()) + package->root()->GetString(::switches::kmInjectJSDocEnd, &js_doc_end); + web_contents()->GetMutableRendererPrefs()->nw_inject_js_doc_end = js_doc_end; + if (!js_doc_start.empty() || !js_doc_end.empty()) + web_contents()->GetRenderViewHost()->SyncRendererPrefs(); initial_url_ = url; @@ -287,8 +342,17 @@ void AppWindow::Init(const GURL& url, // Windows cannot be always-on-top in fullscreen mode for security reasons. cached_always_on_top_ = new_params.always_on_top; - if (new_params.state == ui::SHOW_STATE_FULLSCREEN) - new_params.always_on_top = false; + //if (new_params.state == ui::SHOW_STATE_FULLSCREEN) + // new_params.always_on_top = false; + + title_override_ = new_params.title; + app_icon_ = new_params.icon; + icon_override_ = new_params.icon; + + content::g_support_transparency = !base::CommandLine::ForCurrentProcess()->HasSwitch(::switches::kDisableTransparency); + if (content::g_support_transparency) { + content::g_force_cpu_draw = base::CommandLine::ForCurrentProcess()->HasSwitch(::switches::kForceCpuDraw); + } requested_alpha_enabled_ = new_params.alpha_enabled; is_ime_window_ = params.is_ime_window; @@ -328,6 +392,9 @@ void AppWindow::Init(const GURL& url, Minimize(); } + if (!new_params.show_in_taskbar) + SetShowInTaskbar(false); + OnNativeWindowChanged(); ExtensionRegistry::Get(browser_context_)->AddObserver(this); @@ -337,7 +404,8 @@ void AppWindow::Init(const GURL& url, base::Bind(&NativeAppWindow::Close, base::Unretained(native_app_window_.get()))); - app_window_contents_->LoadContents(new_params.creator_process_id); + if (!params.skip_load) + app_window_contents_->LoadContents(new_params.creator_process_id); } AppWindow::~AppWindow() { @@ -372,12 +440,28 @@ void AppWindow::AddNewContents(WebContents* source, bool user_gesture, bool* was_blocked) { DCHECK(new_contents->GetBrowserContext() == browser_context_); - app_delegate_->AddNewContents(browser_context_, - new_contents, - disposition, - initial_rect, - user_gesture, - was_blocked); + const extensions::Extension* extension = GetExtension(); + extensions::AppWindow* app_window = + extensions::AppWindowClient::Get()->CreateAppWindow(browser_context_, extension); + + extensions::AppWindow::CreateParams params; + std::string js_doc_start, js_doc_end; + nw::CalcNewWinParams(new_contents, ¶ms, &js_doc_start, &js_doc_end); + nw::SetCurrentNewWinManifest(base::string16()); + new_contents->GetMutableRendererPrefs()-> + nw_inject_js_doc_start = js_doc_start; + new_contents->GetMutableRendererPrefs()-> + nw_inject_js_doc_end = js_doc_end; + new_contents->GetRenderViewHost()->SyncRendererPrefs(); + + if(initial_rect.width() != 0) { + params.content_spec.bounds = initial_rect; //NWJS#5517 + } + params.skip_load = true; + app_window->Init(new_contents->GetURL(), + new extensions::AppWindowContentsImpl(app_window, new_contents), + web_contents()->GetMainFrame(), + params); } content::KeyboardEventProcessingResult AppWindow::PreHandleKeyboardEvent( @@ -409,6 +493,7 @@ content::KeyboardEventProcessingResult AppWindow::PreHandleKeyboardEvent( void AppWindow::HandleKeyboardEvent( WebContents* source, const content::NativeWebKeyboardEvent& event) { +#if 0 // If the window is currently fullscreen and not forced, ESC should leave // fullscreen. If this code is being called for ESC, that means that the // KeyEvent's default behavior was not prevented by the content. @@ -417,7 +502,7 @@ void AppWindow::HandleKeyboardEvent( Restore(); return; } - +#endif native_app_window_->HandleKeyboardEvent(event); } @@ -433,6 +518,18 @@ bool AppWindow::PreHandleGestureEvent(WebContents* source, return AppWebContentsHelper::ShouldSuppressGestureEvent(event); } +// Fix for issue https://github.com/nwjs/nw.js/issues/4992 +// Bounds of dialogs are calcuated based on the bounds of parent window. +// However on Windows, when window is minized, the bounds returned from system +// is empty. +// Implementing `WebContentsDelegate::ActivateContents` in `AppWindow` to +// activate the native window before showing dialog fixes the issue. +void AppWindow::ActivateContents(content::WebContents* contents) { + // Only activate window for NW.js app to avoid side effects to Chrome Apps. + if (GetExtension()->is_nwjs_app()) + native_app_window_->Activate(); +} + std::unique_ptr AppWindow::RunBluetoothChooser( content::RenderFrameHost* frame, const content::BluetoothChooser::EventHandler& event_handler) { @@ -469,6 +566,30 @@ void AppWindow::OnReadyToCommitFirstNavigation() { FROM_HERE, base::ResetAndReturn(&on_first_commit_callback_)); } +bool AppWindow::NWCanClose(bool user_force) const { + const Extension* extension = GetExtension(); + if (!extension) + return true; + content::RenderFrameHost* rfh = web_contents()->GetMainFrame(); + EventRouter* event_router = EventRouter::Get(browser_context()); + std::string listener_extension_id; + bool listening_to_close = event_router-> + ExtensionHasEventListener(extension->id(), "nw.Window.onClose", + rfh->GetRenderViewHost()->GetRoutingID(), + &listener_extension_id); + + if (listening_to_close) { + base::ListValue args; + if (user_force) + args.AppendString("quit"); + rfh->Send(new ExtensionMsg_MessageInvoke( + rfh->GetRoutingID(), listener_extension_id, "nw.Window", + "onClose", args)); + return false; + } + return true; +} + void AppWindow::OnNativeClose() { AppWindowRegistry::Get(browser_context_)->RemoveAppWindow(this); if (app_window_contents_) { @@ -502,9 +623,13 @@ void AppWindow::OnNativeWindowChanged() { SaveWindowPosition(); #if defined(OS_WIN) +#if 0 if (cached_always_on_top_ && !IsFullscreen() && !native_app_window_->IsMaximized() && !native_app_window_->IsMinimized()) { +#else + if (cached_always_on_top_) { +#endif UpdateNativeAlwaysOnTop(); } #endif @@ -542,9 +667,11 @@ gfx::Rect AppWindow::GetClientBounds() const { } base::string16 AppWindow::GetTitle() const { + base::string16 override = base::UTF8ToUTF16(title_override_); + const Extension* extension = GetExtension(); if (!extension) - return base::string16(); + return override; // WebContents::GetTitle() will return the page's URL if there's no // specified. However, we'd prefer to show the name of the extension in that @@ -553,12 +680,14 @@ base::string16 AppWindow::GetTitle() const { content::NavigationEntry* entry = web_contents() ? web_contents()->GetController().GetLastCommittedEntry() : nullptr; if (!entry || entry->GetTitle().empty()) { - title = base::UTF8ToUTF16(extension->name()); + title = override.empty() ? base::UTF8ToUTF16(extension->name()) : override; } else { title = web_contents()->GetTitle(); } base::RemoveChars(title, base::ASCIIToUTF16("\n"), &title); - return title; + if (!title.empty()) + return title; + return override; } bool AppWindow::HasCustomIcon() const { @@ -682,6 +811,10 @@ void AppWindow::Restore() { } } +void AppWindow::SetShowInTaskbar(bool show) { + GetBaseWindow()->SetShowInTaskbar(show); +} + void AppWindow::OSFullscreen() { SetFullscreen(FULLSCREEN_TYPE_OS, true); } @@ -739,7 +872,7 @@ void AppWindow::SetAlwaysOnTop(bool always_on_top) { // As a security measure, do not allow fullscreen windows or windows that // overlap the taskbar to be on top. The property will be applied when the // window exits fullscreen and moves away from the taskbar. - if (!IsFullscreen() && !IntersectsWithTaskbar()) + //if (!IsFullscreen() && !IntersectsWithTaskbar()) native_app_window_->SetAlwaysOnTop(always_on_top); OnNativeWindowChanged(); @@ -760,6 +893,8 @@ void AppWindow::NotifyRenderViewReady() { void AppWindow::GetSerializedState(base::DictionaryValue* properties) const { DCHECK(properties); + properties->SetBoolean("resizable", + native_app_window_->IsResizable()); properties->SetBoolean("fullscreen", native_app_window_->IsFullscreenOrPending()); properties->SetBoolean("minimized", native_app_window_->IsMinimized()); @@ -890,6 +1025,9 @@ bool AppWindow::IntersectsWithTaskbar() const { void AppWindow::UpdateNativeAlwaysOnTop() { DCHECK(cached_always_on_top_); +#if 1 + native_app_window_->SetAlwaysOnTop(true); +#else bool is_on_top = native_app_window_->IsAlwaysOnTop(); bool fullscreen = IsFullscreen(); bool intersects_taskbar = IntersectsWithTaskbar(); @@ -903,6 +1041,7 @@ void AppWindow::UpdateNativeAlwaysOnTop() { // always-on-top. native_app_window_->SetAlwaysOnTop(true); } +#endif } void AppWindow::CloseContents(WebContents* contents) { @@ -910,7 +1049,7 @@ void AppWindow::CloseContents(WebContents* contents) { } bool AppWindow::ShouldSuppressDialogs(WebContents* source) { - return true; + return false; } content::ColorChooser* AppWindow::OpenColorChooser( @@ -1124,4 +1263,16 @@ SkRegion* AppWindow::RawDraggableRegionsToSkRegion( return sk_region; } +content::JavaScriptDialogManager* AppWindow::GetJavaScriptDialogManager( + WebContents* source) { + ExtensionHost* host = ProcessManager::Get(browser_context()) + ->GetBackgroundHostForExtension(extension_id()); + return host->GetJavaScriptDialogManager(source); +} + +void AppWindow::WasShown() { + web_cache::WebCacheManager::GetInstance()->ObserveActivity( + web_contents()->GetRenderProcessHost()->GetID()); +} + } // namespace extensions diff --git a/extensions/browser/app_window/app_window.h b/extensions/browser/app_window/app_window.h index a850d7137c0ff..274dbb6f694ab 100644 --- a/extensions/browser/app_window/app_window.h +++ b/extensions/browser/app_window/app_window.h @@ -38,6 +38,10 @@ class RenderFrameHost; class WebContents; } +namespace nw { +class Menu; +} + namespace extensions { class AppDelegate; @@ -60,7 +64,8 @@ class AppWindowContents { // Called to initialize the WebContents, before the app window is created. virtual void Initialize(content::BrowserContext* context, content::RenderFrameHost* creator_frame, - const GURL& url) = 0; + const GURL& url, + const Extension* extension) = 0; // Called to load the contents, after the app window is created. virtual void LoadContents(int32_t creator_process_id) = 0; @@ -101,6 +106,12 @@ class AppWindow : public content::WebContentsDelegate, FRAME_NONE, // Frameless window. }; + enum Position { + POS_NONE, + POS_CENTER, + POS_MOUSE, + }; + enum FullscreenType { // Not fullscreen. FULLSCREEN_TYPE_NONE = 0, @@ -194,6 +205,19 @@ class AppWindow : public content::WebContentsDelegate, // Icon URL to be used for setting the window icon. GURL window_icon_url; + bool skip_load; + + bool show_in_taskbar; + bool new_instance; + + Position position; + + std::string title; + + std::string inject_js_start, inject_js_end; + + gfx::Image icon; + // The API enables developers to specify content or window bounds. This // function combines them into a single, constrained window size. gfx::Rect GetInitialWindowBounds(const gfx::Insets& frame_insets) const; @@ -237,14 +261,19 @@ class AppWindow : public content::WebContentsDelegate, } content::BrowserContext* browser_context() const { return browser_context_; } const gfx::Image& app_icon() const { return app_icon_; } + const gfx::Image& icon_override() const { return icon_override_; } const GURL& app_icon_url() const { return app_icon_url_; } const GURL& initial_url() const { return initial_url_; } bool is_hidden() const { return is_hidden_; } - + const std::string& title_override() const { return title_override_; } + void set_title_override(const std::string& title) { title_override_ = title; } + const Extension* GetExtension() const; NativeAppWindow* GetBaseWindow(); gfx::NativeWindow GetNativeWindow(); + bool NWCanClose(bool user_force = false) const; + // Returns the bounds that should be reported to the renderer. gfx::Rect GetClientBounds() const; @@ -308,6 +337,8 @@ class AppWindow : public content::WebContentsDelegate, void Minimize(); void Restore(); + void SetShowInTaskbar(bool); + // Transitions to OS fullscreen. See FULLSCREEN_TYPE_OS for more details. void OSFullscreen(); @@ -378,6 +409,7 @@ class AppWindow : public content::WebContentsDelegate, std::unique_ptr<AppWindowContents> contents) { app_window_contents_ = std::move(contents); } + nw::Menu* menu_; protected: ~AppWindow() override; @@ -387,6 +419,10 @@ class AppWindow : public content::WebContentsDelegate, friend class PlatformAppBrowserTest; // content::WebContentsDelegate implementation. + void LoadingStateChanged(content::WebContents* source, + bool to_different_document) override; + content::JavaScriptDialogManager* GetJavaScriptDialogManager( + content::WebContents* source) override; void CloseContents(content::WebContents* contents) override; bool ShouldSuppressDialogs(content::WebContents* source) override; content::ColorChooser* OpenColorChooser( @@ -426,6 +462,7 @@ class AppWindow : public content::WebContentsDelegate, content::KeyboardEventProcessingResult PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) override; + void ActivateContents(content::WebContents* contents) override; void HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) override; @@ -440,6 +477,7 @@ class AppWindow : public content::WebContentsDelegate, // content::WebContentsObserver implementation. void RenderViewCreated(content::RenderViewHost* render_view_host) override; + void WasShown() override; // ExtensionFunctionDispatcher::Delegate implementation. WindowController* GetExtensionWindowController() const override; @@ -508,6 +546,8 @@ class AppWindow : public content::WebContentsDelegate, // not own this object. content::BrowserContext* browser_context_; + std::string title_override_; + const std::string extension_id_; // Identifier that is used when saving and restoring geometry for this @@ -519,6 +559,7 @@ class AppWindow : public content::WebContentsDelegate, // Icon shown in the task bar. gfx::Image app_icon_; + gfx::Image icon_override_; // Icon URL to be used for setting the app icon. If not empty, app_icon_ will // be fetched and set using this URL. @@ -561,6 +602,7 @@ class AppWindow : public content::WebContentsDelegate, // Whether |is_ime_window| was set in the CreateParams. bool is_ime_window_; + bool last_to_different_document_; // Whether |show_in_shelf| was set in the CreateParams. bool show_in_shelf_; diff --git a/extensions/browser/app_window/app_window_contents.cc b/extensions/browser/app_window/app_window_contents.cc index 2478ddeba0372..240a853eabe5a 100644 --- a/extensions/browser/app_window/app_window_contents.cc +++ b/extensions/browser/app_window/app_window_contents.cc @@ -19,27 +19,37 @@ #include "extensions/browser/app_window/native_app_window.h" #include "extensions/common/extension_messages.h" +#include "content/nw/src/nw_content.h" + namespace extensions { -AppWindowContentsImpl::AppWindowContentsImpl(AppWindow* host) - : host_(host), is_blocking_requests_(false), is_window_ready_(false) {} +AppWindowContentsImpl::AppWindowContentsImpl(AppWindow* host, content::WebContents* web_contents) + :host_(host), is_blocking_requests_(false), is_window_ready_(false), web_contents_(web_contents) {} AppWindowContentsImpl::~AppWindowContentsImpl() {} void AppWindowContentsImpl::Initialize(content::BrowserContext* context, content::RenderFrameHost* creator_frame, - const GURL& url) { + const GURL& url, + const Extension* extension) { url_ = url; content::WebContents::CreateParams create_params( - context, creator_frame->GetSiteInstance()); + //NWJS#5163: fix regression + context, nw::PinningRenderer() ? creator_frame->GetSiteInstance() : content::SiteInstance::CreateForURL(context, url_)); create_params.opener_render_process_id = creator_frame->GetProcess()->GetID(); create_params.opener_render_frame_id = creator_frame->GetRoutingID(); - web_contents_.reset(content::WebContents::Create(create_params)); + if (!web_contents_) + web_contents_.reset(content::WebContents::Create(create_params)); Observe(web_contents_.get()); - web_contents_->GetMutableRendererPrefs()-> - browser_handles_all_top_level_requests = true; + content::RendererPreferences* render_prefs = + web_contents_->GetMutableRendererPrefs(); + if (!extension || !extension->is_nwjs_app()) + render_prefs->browser_handles_all_top_level_requests = true; + std::string user_agent; + if (nw::GetUserAgentFromManifest(&user_agent)) + render_prefs->user_agent_override = user_agent; web_contents_->GetRenderViewHost()->SyncRendererPrefs(); } diff --git a/extensions/browser/app_window/app_window_contents.h b/extensions/browser/app_window/app_window_contents.h index 4afa13d1ed16e..5e925b4faab85 100644 --- a/extensions/browser/app_window/app_window_contents.h +++ b/extensions/browser/app_window/app_window_contents.h @@ -17,6 +17,7 @@ namespace content { class BrowserContext; class RenderFrameHost; +class WebContents; } namespace extensions { @@ -29,13 +30,14 @@ struct DraggableRegion; class AppWindowContentsImpl : public AppWindowContents, public content::WebContentsObserver { public: - explicit AppWindowContentsImpl(AppWindow* host); + explicit AppWindowContentsImpl(AppWindow* host, content::WebContents* web_contents = nullptr); ~AppWindowContentsImpl() override; // AppWindowContents void Initialize(content::BrowserContext* context, content::RenderFrameHost* creator_frame, - const GURL& url) override; + const GURL& url, + const Extension* extension) override; void LoadContents(int32_t creator_process_id) override; void NativeWindowChanged(NativeAppWindow* native_app_window) override; void NativeWindowClosed() override; @@ -53,10 +55,12 @@ class AppWindowContentsImpl : public AppWindowContents, AppWindow* host_; // This class is owned by |host_| GURL url_; - std::unique_ptr<content::WebContents> web_contents_; + bool is_blocking_requests_; bool is_window_ready_; + std::unique_ptr<content::WebContents> web_contents_; + DISALLOW_COPY_AND_ASSIGN(AppWindowContentsImpl); }; diff --git a/extensions/browser/app_window/app_window_registry.cc b/extensions/browser/app_window/app_window_registry.cc index 3eb52cabfdc75..020289978b063 100644 --- a/extensions/browser/app_window/app_window_registry.cc +++ b/extensions/browser/app_window/app_window_registry.cc @@ -115,12 +115,13 @@ AppWindowRegistry::AppWindowList AppWindowRegistry::GetAppWindowsForApp( return app_windows; } -void AppWindowRegistry::CloseAllAppWindowsForApp(const std::string& app_id) { +void AppWindowRegistry::CloseAllAppWindowsForApp(const std::string& app_id, bool user_force) { const AppWindowList windows = GetAppWindowsForApp(app_id); for (AppWindowRegistry::const_iterator it = windows.begin(); it != windows.end(); ++it) { - (*it)->GetBaseWindow()->Close(); + if ((*it)->NWCanClose(user_force)) + (*it)->GetBaseWindow()->Close(); } } diff --git a/extensions/browser/app_window/app_window_registry.h b/extensions/browser/app_window/app_window_registry.h index 799c4f643a483..581561960a51c 100644 --- a/extensions/browser/app_window/app_window_registry.h +++ b/extensions/browser/app_window/app_window_registry.h @@ -82,7 +82,7 @@ class AppWindowRegistry : public KeyedService, const AppWindowList& app_windows() const { return app_windows_; } // Close all app windows associated with an app. - void CloseAllAppWindowsForApp(const std::string& app_id); + void CloseAllAppWindowsForApp(const std::string& app_id, bool user_force = false); // Helper functions to find app windows with particular attributes. AppWindow* GetAppWindowForWebContents( diff --git a/extensions/browser/app_window/native_app_window.h b/extensions/browser/app_window/native_app_window.h index 719180bb13de3..d40d73c6d4e20 100644 --- a/extensions/browser/app_window/native_app_window.h +++ b/extensions/browser/app_window/native_app_window.h @@ -33,6 +33,8 @@ class NativeAppWindow : public ui::BaseWindow, // |fullscreen_types| is a bit field of AppWindow::FullscreenType. virtual void SetFullscreen(int fullscreen_types) = 0; + virtual void SetResizable(bool flag) = 0; + virtual bool IsResizable() const = 0; // Returns whether the window is fullscreen or about to enter fullscreen. virtual bool IsFullscreenOrPending() const = 0; @@ -77,6 +79,8 @@ class NativeAppWindow : public ui::BaseWindow, virtual void ShowWithApp() = 0; virtual void HideWithApp() = 0; + virtual void SetShowInTaskbar(bool) = 0; + // Returns the minimum size constraints of the content. virtual gfx::Size GetContentMinimumSize() const = 0; diff --git a/extensions/browser/app_window/test_app_window_contents.cc b/extensions/browser/app_window/test_app_window_contents.cc index a0c2d670e4057..d202f058dc2d1 100644 --- a/extensions/browser/app_window/test_app_window_contents.cc +++ b/extensions/browser/app_window/test_app_window_contents.cc @@ -17,7 +17,8 @@ TestAppWindowContents::~TestAppWindowContents() { void TestAppWindowContents::Initialize(content::BrowserContext* context, content::RenderFrameHost* creator_frame, - const GURL& url) {} + const GURL& url, + const Extension* extension) {} void TestAppWindowContents::LoadContents(int32_t creator_process_id) {} diff --git a/extensions/browser/app_window/test_app_window_contents.h b/extensions/browser/app_window/test_app_window_contents.h index 7e68b68e98f1a..54ee671ea886e 100644 --- a/extensions/browser/app_window/test_app_window_contents.h +++ b/extensions/browser/app_window/test_app_window_contents.h @@ -26,7 +26,8 @@ class TestAppWindowContents : public AppWindowContents { // apps:AppWindowContents: void Initialize(content::BrowserContext* context, content::RenderFrameHost* creator_frame, - const GURL& url) override; + const GURL& url, + const Extension* extension) override; void LoadContents(int32_t creator_process_id) override; void NativeWindowChanged(NativeAppWindow* native_app_window) override; void NativeWindowClosed() override; diff --git a/extensions/browser/content_hash_fetcher.cc b/extensions/browser/content_hash_fetcher.cc index ea29425f51a86..1db72812af752 100644 --- a/extensions/browser/content_hash_fetcher.cc +++ b/extensions/browser/content_hash_fetcher.cc @@ -129,7 +129,7 @@ class ContentHashFetcherJob // Will call the callback, if we haven't been cancelled. void DispatchCallback(); - net::URLRequestContextGetter* request_context_; + //net::URLRequestContextGetter* request_context_; std::string extension_id_; base::FilePath extension_path_; @@ -179,7 +179,7 @@ ContentHashFetcherJob::ContentHashFetcherJob( const GURL& fetch_url, bool force, const CompletionCallback& callback) - : request_context_(request_context), + : extension_id_(extension_id), extension_path_(extension_path), fetch_url_(fetch_url), @@ -234,8 +234,10 @@ bool ContentHashFetcherJob::LoadVerifiedContents(const base::FilePath& path) { verified_contents_.reset(new VerifiedContents(key_.data, key_.size)); if (!verified_contents_->InitFrom(path)) { verified_contents_.reset(); +#if 0 if (!base::DeleteFile(path, false)) LOG(WARNING) << "Failed to delete " << path.value(); +#endif return false; } return true; @@ -248,7 +250,9 @@ void ContentHashFetcherJob::DoneCheckingForVerifiedContents(bool found) { VLOG(1) << "Found verified contents for " << extension_id_; DoneFetchingVerifiedContents(true); } else { - VLOG(1) << "Missing verified contents for " << extension_id_ + VLOG(1) << "Missing verified contents for " << extension_id_; + DoneFetchingVerifiedContents(false); +#if 0 << ", fetching..."; net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("content_hash_verification_job", R"( @@ -282,6 +286,7 @@ void ContentHashFetcherJob::DoneCheckingForVerifiedContents(bool found) { net::LOAD_DISABLE_CACHE); url_fetcher_->SetAutomaticallyRetryOnNetworkChanges(3); url_fetcher_->Start(); +#endif } } @@ -436,7 +441,7 @@ bool ContentHashFetcherJob::CreateHashes(const base::FilePath& hashes_file) { std::string root = ComputeTreeHashRoot(hashes, block_size_ / crypto::kSHA256Length); if (!verified_contents_->TreeHashRootEquals(relative_unix_path, root)) { - VLOG(1) << "content mismatch for " << relative_unix_path.AsUTF8Unsafe(); + LOG(INFO) << "content mismatch for " << relative_unix_path.AsUTF8Unsafe(); hash_mismatch_unix_paths_.insert(relative_unix_path); continue; } diff --git a/extensions/browser/content_hash_reader.cc b/extensions/browser/content_hash_reader.cc index 039fa53e9b3ab..728aed54d173f 100644 --- a/extensions/browser/content_hash_reader.cc +++ b/extensions/browser/content_hash_reader.cc @@ -54,9 +54,9 @@ bool ContentHashReader::Init() { VerifiedContents verified_contents(key_.data, key_.size); if (!verified_contents.InitFrom(verified_contents_path) || - !verified_contents.valid_signature() || - verified_contents.version() != extension_version_ || - verified_contents.extension_id() != extension_id_) { + !verified_contents.valid_signature()) { + //verified_contents.version() != extension_version_ || + //verified_contents.extension_id() != extension_id_) { return false; } diff --git a/extensions/browser/content_verifier.cc b/extensions/browser/content_verifier.cc index 57a158f59e80c..2bfe67166390b 100644 --- a/extensions/browser/content_verifier.cc +++ b/extensions/browser/content_verifier.cc @@ -23,6 +23,10 @@ #include "extensions/common/constants.h" #include "extensions/common/extension_l10n_util.h" +#include "base/files/file_util.h" +#include "base/threading/sequenced_worker_pool.h" +#include "base/threading/thread_restrictions.h" + namespace extensions { namespace { @@ -125,22 +129,74 @@ ContentVerifyJob* ContentVerifier::CreateJobFor( return new ContentVerifyJob( new ContentHashReader(extension_id, data->version, extension_root, normalized_unix_path, delegate_->GetPublicKey()), - base::BindOnce(&ContentVerifier::VerifyFailed, this, extension_id)); + base::BindOnce(&ContentVerifier::VerifyFailed, this, extension_id, relative_path), + base::Bind(&ContentVerifier::OnHashReady, this, extension_id, extension_root, relative_path)); +} + +void ContentVerifier::OnHashReady(const std::string& extension_id, + const base::FilePath& extension_root, + const base::FilePath& relative_path, + scoped_refptr<ContentVerifyJob> verify_job) { + content::BrowserThread::GetBlockingPool()->PostTaskAndReply( + FROM_HERE, + base::Bind(&ContentVerifier::OpenFile, this, extension_root, relative_path, verify_job), + base::Bind(&ContentVerifier::OnFileReady, this, extension_root, relative_path, verify_job)); +} + +void ContentVerifier::OpenFile(const base::FilePath& extension_root, + const base::FilePath& relative_path, + scoped_refptr<ContentVerifyJob> job) { + job->file_.Initialize(extension_root.Append(relative_path), base::File::FLAG_OPEN | base::File::FLAG_READ); +} + +void ContentVerifier::OnFileReady(const base::FilePath& extension_root, + const base::FilePath& relative_path, + scoped_refptr<ContentVerifyJob> job) { + if (!job->file_.IsValid()) + job->DoneReading(); + + content::BrowserThread::GetBlockingPool()->PostTaskAndReply( + FROM_HERE, + base::Bind(&ContentVerifier::ReadFile, this, extension_root, relative_path, job), + base::Bind(&ContentVerifier::BytesRead, this, extension_root, relative_path, job)); +} +void ContentVerifier::ReadFile(const base::FilePath& extension_root, + const base::FilePath& relative_path, + scoped_refptr<ContentVerifyJob> job) { + job->len_ = job->file_.ReadAtCurrentPos(job->buf_, 32768); + if (job->len_ <= 0) + job->file_.Close(); +} + +void ContentVerifier::BytesRead(const base::FilePath& extension_root, + const base::FilePath& relative_path, + scoped_refptr<ContentVerifyJob> job) { + if (job->len_ <= 0) { + job->DoneReading(); + } else { + job->BytesRead(job->len_, job->buf_); + content::BrowserThread::GetBlockingPool()->PostTaskAndReply( + FROM_HERE, + base::Bind(&ContentVerifier::ReadFile, this, extension_root, relative_path, job), + base::Bind(&ContentVerifier::BytesRead, this, extension_root, relative_path, job)); + } } void ContentVerifier::VerifyFailed(const std::string& extension_id, - ContentVerifyJob::FailureReason reason) { + const base::FilePath& relative_path, + ContentVerifyJob::FailureReason reason, + scoped_refptr<ContentVerifyJob> verify_job) { if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, - base::Bind(&ContentVerifier::VerifyFailed, this, extension_id, reason)); + base::Bind(&ContentVerifier::VerifyFailed, this, extension_id, relative_path, reason, verify_job)); return; } if (shutdown_) return; - VLOG(1) << "VerifyFailed " << extension_id << " reason:" << reason; + VLOG(1) << "VerifyFailed " << extension_id << " reason:" << reason << " " << relative_path.AsUTF8Unsafe(); ExtensionRegistry* registry = ExtensionRegistry::Get(context_); const Extension* extension = @@ -149,12 +205,17 @@ void ContentVerifier::VerifyFailed(const std::string& extension_id, if (!extension) return; + ContentVerifierDelegate::Mode mode = delegate_->ShouldBeVerified(*extension); + if (mode < ContentVerifierDelegate::ENFORCE) { + if (!verify_job->success_callback().is_null()) + verify_job->success_callback().Run(); + } if (reason == ContentVerifyJob::MISSING_ALL_HASHES) { // If we failed because there were no hashes yet for this extension, just // request some. fetcher_->DoFetch(extension, true /* force */); } else { - delegate_->VerifyFailed(extension_id, reason); + delegate_->VerifyFailed(extension_id, relative_path, reason); } } @@ -211,7 +272,7 @@ void ContentVerifier::OnFetchCompleteHelper( const std::string& extension_id, bool should_verify_any_paths_result) { if (should_verify_any_paths_result) - delegate_->VerifyFailed(extension_id, ContentVerifyJob::MISSING_ALL_HASHES); + delegate_->VerifyFailed(extension_id, base::FilePath(), ContentVerifyJob::MISSING_ALL_HASHES); } void ContentVerifier::OnFetchComplete( @@ -238,7 +299,7 @@ void ContentVerifier::OnFetchComplete( mode == ContentVerifierDelegate::ENFORCE_STRICT) { // We weren't able to get verified_contents.json or weren't able to compute // hashes. - delegate_->VerifyFailed(extension_id, ContentVerifyJob::MISSING_ALL_HASHES); + delegate_->VerifyFailed(extension_id, base::FilePath(), ContentVerifyJob::MISSING_ALL_HASHES); } else { content::BrowserThread::PostTaskAndReplyWithResult( content::BrowserThread::IO, FROM_HERE, diff --git a/extensions/browser/content_verifier.h b/extensions/browser/content_verifier.h index 1a41c80b9518e..6ee84dfb02e4b 100644 --- a/extensions/browser/content_verifier.h +++ b/extensions/browser/content_verifier.h @@ -65,7 +65,25 @@ class ContentVerifier : public base::RefCountedThreadSafe<ContentVerifier>, // Called (typically by a verification job) to indicate that verification // failed while reading some file in |extension_id|. void VerifyFailed(const std::string& extension_id, - ContentVerifyJob::FailureReason reason); + const base::FilePath& relative_path, + ContentVerifyJob::FailureReason reason, + scoped_refptr<ContentVerifyJob> verify_job); + void OnHashReady(const std::string& extension_id, + const base::FilePath& extension_root, + const base::FilePath& relative_path, + scoped_refptr<ContentVerifyJob> verify_job); + void BytesRead(const base::FilePath& extension_root, + const base::FilePath& relative_path, + scoped_refptr<ContentVerifyJob> job); + void ReadFile(const base::FilePath& extension_root, + const base::FilePath& relative_path, + scoped_refptr<ContentVerifyJob> job); + void OpenFile(const base::FilePath& extension_root, + const base::FilePath& relative_path, + scoped_refptr<ContentVerifyJob> job); + void OnFileReady(const base::FilePath& extension_root, + const base::FilePath& relative_path, + scoped_refptr<ContentVerifyJob> job); // ExtensionRegistryObserver interface void OnExtensionLoaded(content::BrowserContext* browser_context, @@ -113,6 +131,7 @@ class ContentVerifier : public base::RefCountedThreadSafe<ContentVerifier>, // Data that should only be used on the IO thread. scoped_refptr<ContentVerifierIOData> io_data_; + }; } // namespace extensions diff --git a/extensions/browser/content_verifier_delegate.h b/extensions/browser/content_verifier_delegate.h index e719e002a7359..3a1b7b6121eb4 100644 --- a/extensions/browser/content_verifier_delegate.h +++ b/extensions/browser/content_verifier_delegate.h @@ -76,6 +76,7 @@ class ContentVerifierDelegate { // Called when the content verifier detects that a read of a file inside // an extension did not match its expected hash. virtual void VerifyFailed(const std::string& extension_id, + const base::FilePath& relative_path, ContentVerifyJob::FailureReason reason) = 0; // Called when ExtensionSystem is shutting down. diff --git a/extensions/browser/content_verify_job.cc b/extensions/browser/content_verify_job.cc index 3bd086b3aa614..83ef9c98c4ac3 100644 --- a/extensions/browser/content_verify_job.cc +++ b/extensions/browser/content_verify_job.cc @@ -49,15 +49,40 @@ ContentVerifyJob::ContentVerifyJob(ContentHashReader* hash_reader, current_hash_byte_count_(0), hash_reader_(hash_reader), failure_callback_(std::move(failure_callback)), - failed_(false) { + failed_(false), len_(0), buf_(nullptr) { // It's ok for this object to be constructed on a different thread from where // it's used. thread_checker_.DetachFromThread(); + buf_ = new char[32768]; } +ContentVerifyJob::ContentVerifyJob(ContentHashReader* hash_reader, + FailureCallback failure_callback, + const ReadyCallback& ready_callback) + : done_reading_(false), + hashes_ready_(false), + total_bytes_read_(0), + current_block_(0), + current_hash_byte_count_(0), + hash_reader_(hash_reader), + failure_callback_(std::move(failure_callback)), + ready_callback_(ready_callback), + failed_(false), + len_(0), + buf_(nullptr) +{ + // It's ok for this object to be constructed on a different thread from where + // it's used. + thread_checker_.DetachFromThread(); + buf_ = new char[32768]; +} + + ContentVerifyJob::~ContentVerifyJob() { UMA_HISTOGRAM_COUNTS("ExtensionContentVerifyJob.TimeSpentUS", time_spent_.InMicroseconds()); + delete[] buf_; + buf_ = nullptr; } void ContentVerifyJob::Start() { @@ -138,6 +163,8 @@ void ContentVerifyJob::DoneReading() { g_test_observer->JobFinished(hash_reader_->extension_id(), hash_reader_->relative_path(), NONE); } + else if (!success_callback_.is_null()) + success_callback_.Run(); } } @@ -182,6 +209,8 @@ void ContentVerifyJob::OnHashesReady(bool success) { g_test_observer->JobFinished(hash_reader_->extension_id(), hash_reader_->relative_path(), NONE); } + if (!success_callback_.is_null()) + success_callback_.Run(); return; } DispatchFailureCallback(NO_HASHES_FOR_FILE); @@ -203,6 +232,9 @@ void ContentVerifyJob::OnHashesReady(bool success) { hash_reader_->relative_path(), NONE); } } + if (!ready_callback_.is_null()) { + ready_callback_.Run(this); + } } // static @@ -225,7 +257,7 @@ void ContentVerifyJob::DispatchFailureCallback(FailureReason reason) { VLOG(1) << "job failed for " << hash_reader_->extension_id() << " " << hash_reader_->relative_path().MaybeAsASCII() << " reason:" << reason; - std::move(failure_callback_).Run(reason); + std::move(failure_callback_).Run(reason, this); } if (g_test_observer) { g_test_observer->JobFinished(hash_reader_->extension_id(), diff --git a/extensions/browser/content_verify_job.h b/extensions/browser/content_verify_job.h index 9b72f807a85b6..d664a302ff4a8 100644 --- a/extensions/browser/content_verify_job.h +++ b/extensions/browser/content_verify_job.h @@ -9,6 +9,7 @@ #include <memory> #include <string> +#include "base/files/file.h" #include "base/callback.h" #include "base/macros.h" @@ -49,12 +50,18 @@ class ContentVerifyJob : public base::RefCountedThreadSafe<ContentVerifyJob> { FAILURE_REASON_MAX }; - using FailureCallback = base::OnceCallback<void(FailureReason)>; + using FailureCallback = base::OnceCallback<void(FailureReason, scoped_refptr<ContentVerifyJob>)>; + using ReadyCallback = base::Callback<void(scoped_refptr<ContentVerifyJob>)>; + using SuccessCallback = base::Callback<void(void)>; // The |failure_callback| will be called at most once if there was a failure. ContentVerifyJob(ContentHashReader* hash_reader, FailureCallback failure_callback); + ContentVerifyJob(ContentHashReader* hash_reader, + FailureCallback failure_callback, + const ReadyCallback& ready_callback); + // This begins the process of getting expected hashes, so it should be called // as early as possible. void Start(); @@ -70,6 +77,9 @@ class ContentVerifyJob : public base::RefCountedThreadSafe<ContentVerifyJob> { // Call once when finished adding bytes via BytesRead. void DoneReading(); + void SetSuccessCallback(const SuccessCallback& success_callback) { success_callback_ = success_callback; } + const SuccessCallback& success_callback() { return success_callback_; } + class TestDelegate { public: virtual ~TestDelegate() {} @@ -142,10 +152,17 @@ class ContentVerifyJob : public base::RefCountedThreadSafe<ContentVerifyJob> { // Called once if verification fails. FailureCallback failure_callback_; + ReadyCallback ready_callback_; + SuccessCallback success_callback_; // Set to true if we detected a mismatch and called the failure callback. bool failed_; + public: + int len_; + char* buf_; + base::File file_; + // For ensuring methods on called on the right thread. base::ThreadChecker thread_checker_; diff --git a/extensions/browser/event_listener_map.cc b/extensions/browser/event_listener_map.cc index 89855e3f7305d..28aebf48c5d0d 100644 --- a/extensions/browser/event_listener_map.cc +++ b/extensions/browser/event_listener_map.cc @@ -148,16 +148,28 @@ bool EventListenerMap::HasListenerForEvent( bool EventListenerMap::HasListenerForExtension( const std::string& extension_id, - const std::string& event_name) const { + const std::string& event_name, int instance_id, std::string* out_extension_id) const { auto it = listeners_.find(event_name); if (it == listeners_.end()) return false; + EventListener* ret = nullptr; for (const auto& listener_to_search : it->second) { - if (listener_to_search->extension_id() == extension_id) - return true; + if (listener_to_search->extension_id() == extension_id || + listener_to_search->extension_id().empty()) { + int id = -1; + if (instance_id < 0) + ret = listener_to_search.get(); + if (listener_to_search->filter() && + listener_to_search->filter()->GetInteger("instanceId", &id) && id == instance_id) + ret = listener_to_search.get(); + } } - return false; + if (!ret) + return false; + if (out_extension_id) + *out_extension_id = ret->extension_id(); + return true; } bool EventListenerMap::HasListener(const EventListener* listener) const { diff --git a/extensions/browser/event_listener_map.h b/extensions/browser/event_listener_map.h index cd694ac76baf8..59f2614a80509 100644 --- a/extensions/browser/event_listener_map.h +++ b/extensions/browser/event_listener_map.h @@ -143,7 +143,9 @@ class EventListenerMap { // Returns true if there are any listeners on |event_name| from // |extension_id|. bool HasListenerForExtension(const std::string& extension_id, - const std::string& event_name) const; + const std::string& event_name, + int instance_id = -1, + std::string* out_extension_id = nullptr) const; // Returns true if this map contains an EventListener that .Equals() // |listener|. diff --git a/extensions/browser/event_router.cc b/extensions/browser/event_router.cc index 21e0d9a16fabd..af1775ec4200b 100644 --- a/extensions/browser/event_router.cc +++ b/extensions/browser/event_router.cc @@ -316,8 +316,10 @@ bool EventRouter::HasEventListener(const std::string& event_name) const { bool EventRouter::ExtensionHasEventListener( const std::string& extension_id, - const std::string& event_name) const { - return listeners_.HasListenerForExtension(extension_id, event_name); + const std::string& event_name, + int instance_id, + std::string* out_extension_id) const { + return listeners_.HasListenerForExtension(extension_id, event_name, instance_id, out_extension_id); } std::set<std::string> EventRouter::GetRegisteredEvents( @@ -523,7 +525,7 @@ void EventRouter::DispatchEventToProcess( ExtensionAPI::GetSharedInstance()->IsAvailable( event->event_name, extension, target_context, listener_url, CheckAliasStatus::ALLOWED); - if (!availability.is_available()) { + if (!availability.is_available() && !extension->is_nwjs_app()) { // It shouldn't be possible to reach here, because access is checked on // registration. However, for paranoia, check on dispatch as well. NOTREACHED() << "Trying to dispatch event " << event->event_name @@ -812,12 +814,14 @@ Event::Event(events::HistogramValue histogram_value, user_gesture(user_gesture), filter_info(filter_info) { DCHECK(event_args); +#if 0 DCHECK_NE(events::UNKNOWN, histogram_value) << "events::UNKNOWN cannot be used as a histogram value.\n" << "If this is a test, use events::FOR_TEST.\n" << "If this is production code, it is important that you use a realistic " << "value so that we can accurately track event usage. " << "See extension_event_histogram_value.h for inspiration."; +#endif } Event::~Event() {} diff --git a/extensions/browser/event_router.h b/extensions/browser/event_router.h index 20d9d1455f218..9dd216d654369 100644 --- a/extensions/browser/event_router.h +++ b/extensions/browser/event_router.h @@ -164,7 +164,9 @@ class EventRouter : public KeyedService, // Returns true if the extension is listening to the given event. // (virtual for testing only.) virtual bool ExtensionHasEventListener(const std::string& extension_id, - const std::string& event_name) const; + const std::string& event_name, + int instance_id = -1, + std::string* out_extension_id = nullptr) const; // Broadcasts an event to every listener registered for that event. virtual void BroadcastEvent(std::unique_ptr<Event> event); @@ -369,7 +371,7 @@ struct Event { // If non-null, then the event will not be sent to other BrowserContexts // unless the extension has permission (e.g. incognito tab update -> normal // tab only works if extension is allowed incognito access). - content::BrowserContext* const restrict_to_browser_context; + content::BrowserContext* restrict_to_browser_context; // If not empty, the event is only sent to extensions with host permissions // for this url. diff --git a/extensions/browser/extension_function.cc b/extensions/browser/extension_function.cc index a6a1efafc5ef6..714ea2aee6301 100644 --- a/extensions/browser/extension_function.cc +++ b/extensions/browser/extension_function.cc @@ -4,6 +4,9 @@ #include "extensions/browser/extension_function.h" +#include "content/public/browser/interstitial_page.h" +#include "content/browser/frame_host/render_frame_host_delegate.h" +#include "content/browser/frame_host/render_frame_host_impl.h" #include <utility> #include "base/logging.h" @@ -309,6 +312,10 @@ ExtensionFunction::ExtensionFunction() ExtensionFunction::~ExtensionFunction() { } +bool ExtensionFunction::RunNWSync(base::ListValue* response, std::string* error) { + return false; +} + UIThreadExtensionFunction* ExtensionFunction::AsUIThreadExtensionFunction() { return NULL; } @@ -579,8 +586,12 @@ content::WebContents* UIThreadExtensionFunction::GetAssociatedWebContents() { } content::WebContents* UIThreadExtensionFunction::GetSenderWebContents() { - return render_frame_host_ ? + content::WebContents* ret = render_frame_host_ ? content::WebContents::FromRenderFrameHost(render_frame_host_) : nullptr; + if (ret) + return ret; + content::InterstitialPage* page = static_cast<content::RenderFrameHostImpl*>(render_frame_host_)->delegate()->GetAsInterstitialPage(); + return page->GetWebContents(); } void UIThreadExtensionFunction::OnResponded() { @@ -685,3 +696,35 @@ void AsyncExtensionFunction::SendResponse(bool success) { } Respond(std::move(response)); } + +NWSyncExtensionFunction::NWSyncExtensionFunction() { +} + +NWSyncExtensionFunction::~NWSyncExtensionFunction() { +} + +ExtensionFunction::ResponseAction NWSyncExtensionFunction::Run() { + NOTREACHED() << "NWSyncExtensionFunction::Run"; + return RespondNow(ArgumentList(std::move(results_))); +} + +// static +bool NWSyncExtensionFunction::ValidationFailure( + NWSyncExtensionFunction* function) { + return false; +} + +void NWSyncExtensionFunction::SetError(const std::string& error) { + error_ = error; +} + +void NWSyncExtensionFunction::SetResult(std::unique_ptr<base::Value> result) { + results_.reset(new base::ListValue()); + results_->Append(std::move(result)); +} + +void NWSyncExtensionFunction::SetResultList( + std::unique_ptr<base::ListValue> results) { + results_ = std::move(results); +} + diff --git a/extensions/browser/extension_function.h b/extensions/browser/extension_function.h index b9289d8396bb3..90c5a0f22adb5 100644 --- a/extensions/browser/extension_function.h +++ b/extensions/browser/extension_function.h @@ -214,6 +214,7 @@ class ExtensionFunction // AsyncExtensionFunction::RunAsync, but this is deprecated. // ExtensionFunction implementations are encouraged to just implement Run. virtual ResponseAction Run() WARN_UNUSED_RESULT = 0; + virtual bool RunNWSync(base::ListValue* response, std::string* error); // Gets whether quota should be applied to this individual function // invocation. This is different to GetQuotaLimitHeuristics which is only @@ -496,6 +497,7 @@ class ExtensionFunction // Whether this function has responded. // TODO(devlin): Replace this with response_type_ != null. + public: bool did_respond_; DISALLOW_COPY_AND_ASSIGN(ExtensionFunction); @@ -701,4 +703,23 @@ class AsyncExtensionFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(AsyncExtensionFunction); }; +class NWSyncExtensionFunction : public UIThreadExtensionFunction { + public: + NWSyncExtensionFunction(); + void SetError(const std::string& error); + + protected: + ~NWSyncExtensionFunction() override; + static bool ValidationFailure(NWSyncExtensionFunction* function); + + void SetResult(std::unique_ptr<base::Value> result); + void SetResultList(std::unique_ptr<base::ListValue> results); + + std::unique_ptr<base::ListValue> results_; + std::string error_; + private: + ResponseAction Run() final; + +}; + #endif // EXTENSIONS_BROWSER_EXTENSION_FUNCTION_H_ diff --git a/extensions/browser/extension_function_dispatcher.cc b/extensions/browser/extension_function_dispatcher.cc index ad4acc26b400b..f296b0b7ea8b7 100644 --- a/extensions/browser/extension_function_dispatcher.cc +++ b/extensions/browser/extension_function_dispatcher.cc @@ -79,6 +79,13 @@ struct Static { base::LazyInstance<Static>::DestructorAtExit g_global_io_data = LAZY_INSTANCE_INITIALIZER; +void DummyCallback( + ExtensionFunction::ResponseType type, + const base::ListValue& results, + const std::string& error, + functions::HistogramValue histogram_value) { +} + void CommonResponseCallback(IPC::Sender* ipc_sender, int routing_id, int request_id, @@ -354,6 +361,19 @@ ExtensionFunctionDispatcher::ExtensionFunctionDispatcher( ExtensionFunctionDispatcher::~ExtensionFunctionDispatcher() { } +void ExtensionFunctionDispatcher::DispatchSync( + const ExtensionHostMsg_Request_Params& params, + bool* success, + base::ListValue* response, + std::string* error, + content::RenderFrameHost* render_frame_host, + int render_process_id) { + base::Callback<decltype(DummyCallback)> dummy; + DispatchWithCallbackInternal( + params, render_frame_host, render_process_id, dummy, true, + success, response, error); +} + void ExtensionFunctionDispatcher::Dispatch( const ExtensionHostMsg_Request_Params& params, content::RenderFrameHost* render_frame_host, @@ -401,7 +421,12 @@ void ExtensionFunctionDispatcher::DispatchWithCallbackInternal( const ExtensionHostMsg_Request_Params& params, content::RenderFrameHost* render_frame_host, int render_process_id, - const ExtensionFunction::ResponseCallback& callback) { + const ExtensionFunction::ResponseCallback& callback, + bool sync, + bool* success, + base::ListValue* response, + std::string* error + ) { // TODO(yzshen): There is some shared logic between this method and // DispatchOnIOThread(). It is nice to deduplicate. ProcessMap* process_map = ProcessMap::Get(browser_context_); @@ -451,7 +476,12 @@ void ExtensionFunctionDispatcher::DispatchWithCallbackInternal( if (!extension) { // Skip all of the UMA, quota, event page, activity logging stuff if there // isn't an extension, e.g. if the function call was from WebUI. - function->RunWithValidation()->Execute(); + if (!sync) + function->RunWithValidation()->Execute(); + else { + *success = function->RunNWSync(response, error); + function->did_respond_ = true; + } return; } @@ -476,7 +506,12 @@ void ExtensionFunctionDispatcher::DispatchWithCallbackInternal( FROM_HERE_WITH_EXPLICIT_FUNCTION(function->name()), tracked_objects::ScopedProfile::ENABLED); base::ElapsedTimer timer; - function->RunWithValidation()->Execute(); + if (!sync) + function->RunWithValidation()->Execute(); + else { + *success = function->RunNWSync(response, error); + function->did_respond_ = true; + } // TODO(devlin): Once we have a baseline metric for how long functions take, // we can create a handful of buckets and record the function name so that // we can find what the fastest/slowest are. diff --git a/extensions/browser/extension_function_dispatcher.h b/extensions/browser/extension_function_dispatcher.h index c7b1d8f155408..9f8d43f9c9c0e 100644 --- a/extensions/browser/extension_function_dispatcher.h +++ b/extensions/browser/extension_function_dispatcher.h @@ -90,6 +90,12 @@ class ExtensionFunctionDispatcher // Message handlers. // The response is sent to the corresponding render view in an // ExtensionMsg_Response message. + void DispatchSync(const ExtensionHostMsg_Request_Params& params, + bool* success, + base::ListValue* response, + std::string* error, + content::RenderFrameHost* render_frame_host, + int render_process_id); void Dispatch(const ExtensionHostMsg_Request_Params& params, content::RenderFrameHost* render_frame_host, int render_process_id); @@ -158,7 +164,12 @@ class ExtensionFunctionDispatcher const ExtensionHostMsg_Request_Params& params, content::RenderFrameHost* render_frame_host, int render_process_id, - const ExtensionFunction::ResponseCallback& callback); + const ExtensionFunction::ResponseCallback& callback, + bool sync = false, + bool* success = nullptr, + base::ListValue* response = nullptr, + std::string* error = nullptr + ); void RemoveWorkerCallbacksForProcess(int render_process_id); diff --git a/extensions/browser/extension_prefs.cc b/extensions/browser/extension_prefs.cc index cc8847d3c6488..4bcb7be25a5b1 100644 --- a/extensions/browser/extension_prefs.cc +++ b/extensions/browser/extension_prefs.cc @@ -200,10 +200,12 @@ class ScopedExtensionPrefUpdate : public prefs::ScopedDictionaryPrefUpdate { std::unique_ptr<prefs::DictionaryValueUpdate> dict = ScopedDictionaryPrefUpdate::Get(); std::unique_ptr<prefs::DictionaryValueUpdate> extension; - if (!dict->GetDictionary(extension_id_, &extension)) { + std::string id; + base::ReplaceChars(extension_id_, ".", "", &id); + if (!dict->GetDictionary(id, &extension)) { // Extension pref does not exist, create it. extension = dict->SetDictionary( - extension_id_, base::MakeUnique<base::DictionaryValue>()); + id, base::MakeUnique<base::DictionaryValue>()); } return extension; } @@ -233,7 +235,9 @@ void LoadExtensionControlledPrefs(ExtensionPrefs* prefs, std::string scope_string; if (!pref_names::ScopeToPrefName(scope, &scope_string)) return; - std::string key = extension_id + "." + scope_string; + std::string id; + base::ReplaceChars(extension_id, ".", "", &id); + std::string key = id + "." + scope_string; const base::DictionaryValue* source_dict = prefs->pref_service()->GetDictionary(pref_names::kExtensions); @@ -423,11 +427,14 @@ void ExtensionPrefs::MakePathsRelative() { const base::DictionaryValue* ExtensionPrefs::GetExtensionPref( const std::string& extension_id) const { + std::string id; + base::ReplaceChars(extension_id, ".", "", &id); + const base::DictionaryValue* extensions = prefs_->GetDictionary(pref_names::kExtensions); const base::DictionaryValue* extension_dict = NULL; if (!extensions || - !extensions->GetDictionary(extension_id, &extension_dict)) { + !extensions->GetDictionary(id, &extension_dict)) { return NULL; } return extension_dict; diff --git a/extensions/browser/extension_protocols.cc b/extensions/browser/extension_protocols.cc index c1ea0a9b3e33a..1e00ba6000052 100644 --- a/extensions/browser/extension_protocols.cc +++ b/extensions/browser/extension_protocols.cc @@ -39,6 +39,7 @@ #include "content/public/common/resource_type.h" #include "crypto/secure_hash.h" #include "crypto/sha2.h" +#include "extensions/browser/component_extension_resource_manager.h" #include "extensions/browser/content_verifier.h" #include "extensions/browser/content_verify_job.h" #include "extensions/browser/extensions_browser_client.h" @@ -192,6 +193,8 @@ class URLRequestExtensionJob : public net::URLRequestFileJob { resource_(extension_id, directory_path, relative_path), content_security_policy_(content_security_policy), send_cors_header_(send_cors_header), + can_start_(false), + started_(false), weak_factory_(this) { if (follow_symlinks_anywhere) { resource_.set_follow_symlinks_anywhere(); @@ -264,8 +267,10 @@ class URLRequestExtensionJob : public net::URLRequestFileJob { -result); if (result > 0) { bytes_read_ += result; +#if 0 if (verify_job_.get()) verify_job_->BytesRead(result, buffer->data()); +#endif } } @@ -275,8 +280,23 @@ class URLRequestExtensionJob : public net::URLRequestFileJob { verify_job_->DoneReading(); } - private: + void CanStart() { + can_start_ = true; + if (!started_) { + started_ = true; + URLRequestFileJob::Start(); + } + } + + void set_can_start(bool flag) { can_start_ = flag; } + +private: ~URLRequestExtensionJob() override { + if (verify_job_.get()) { + // there is a change that the job is cancelled before the verify + // job is complete + verify_job_->SetSuccessCallback(ContentVerifyJob::SuccessCallback()); + } UMA_HISTOGRAM_COUNTS("ExtensionUrlRequest.TotalKbRead", bytes_read_ / 1024); UMA_HISTOGRAM_COUNTS("ExtensionUrlRequest.SeekPosition", seek_position_); if (request_timer_.get()) @@ -291,7 +311,10 @@ class URLRequestExtensionJob : public net::URLRequestFileJob { content_security_policy_, send_cors_header_, *last_modified_time); - URLRequestFileJob::Start(); + if (can_start_) { + started_ = true; + URLRequestFileJob::Start(); + } } scoped_refptr<ContentVerifyJob> verify_job_; @@ -309,6 +332,7 @@ class URLRequestExtensionJob : public net::URLRequestFileJob { extensions::ExtensionResource resource_; std::string content_security_policy_; bool send_cors_header_; + bool can_start_, started_; base::WeakPtrFactory<URLRequestExtensionJob> weak_factory_; }; @@ -550,11 +574,9 @@ ExtensionProtocolHandler::MaybeCreateJob( if (verifier) { verify_job = verifier->CreateJobFor(extension_id, directory_path, relative_path); - if (verify_job) - verify_job->Start(); } - return new URLRequestExtensionJob(request, + URLRequestExtensionJob* job = new URLRequestExtensionJob(request, network_delegate, extension_id, directory_path, @@ -563,6 +585,13 @@ ExtensionProtocolHandler::MaybeCreateJob( send_cors_header, follow_symlinks_anywhere, verify_job); + if (verify_job) { + verify_job->SetSuccessCallback(base::Bind(&URLRequestExtensionJob::CanStart, base::Unretained(job))); + verify_job->Start(); + } else { + job->set_can_start(true); + } + return job; } } // namespace diff --git a/extensions/browser/extension_web_contents_observer.cc b/extensions/browser/extension_web_contents_observer.cc index b3d8b4e8d7108..9b4f42eaff8ae 100644 --- a/extensions/browser/extension_web_contents_observer.cc +++ b/extensions/browser/extension_web_contents_observer.cc @@ -61,8 +61,6 @@ void ExtensionWebContentsObserver::InitializeRenderFrame( GetExtensionFromFrame(render_frame_host, false); // This observer is attached to every WebContents, so we are also notified of // frames that are not in an extension process. - if (!frame_extension) - return; // |render_frame_host->GetProcess()| is an extension process. Grant permission // to commit pages from chrome-extension:// origins. @@ -75,6 +73,10 @@ void ExtensionWebContentsObserver::InitializeRenderFrame( render_frame_host->Send(new ExtensionMsg_NotifyRenderViewType( render_frame_host->GetRoutingID(), GetViewType(web_contents()))); + //moved here for NWJS#5181: getall() with remote window + if (!frame_extension) + return; + ExtensionsBrowserClient::Get()->RegisterMojoServices(render_frame_host, frame_extension); ProcessManager::Get(browser_context_) @@ -106,6 +108,12 @@ void ExtensionWebContentsObserver::RenderViewCreated( } } + if (type == Manifest::TYPE_NWJS_APP) { + content::ChildProcessSecurityPolicy::GetInstance()->GrantScheme( + render_view_host->GetProcess()->GetID(), url::kFileScheme); + content::ChildProcessSecurityPolicy::GetInstance()->GrantAll( + render_view_host->GetProcess()->GetID()); + } // Tells the new view that it's hosted in an extension process. // // This will often be a rendant IPC, because activating extensions happens at @@ -165,10 +173,19 @@ bool ExtensionWebContentsObserver::OnMessageReceived( const IPC::Message& message, content::RenderFrameHost* render_frame_host) { bool handled = true; + tmp_render_frame_host_ = nullptr; IPC_BEGIN_MESSAGE_MAP_WITH_PARAM( ExtensionWebContentsObserver, message, render_frame_host) IPC_MESSAGE_HANDLER(ExtensionHostMsg_Request, OnRequest) IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + tmp_render_frame_host_ = render_frame_host; //must put here to + //mark dealing with + //sync msg + IPC_BEGIN_MESSAGE_MAP( + ExtensionWebContentsObserver, message) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_RequestSync, OnRequestSync) + IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } @@ -268,6 +285,32 @@ void ExtensionWebContentsObserver::OnRequest( render_frame_host->GetProcess()->GetID()); } +void ExtensionWebContentsObserver::OnRequestSync( + const ExtensionHostMsg_Request_Params& params, + bool* success, + base::ListValue* response, + std::string* error) { + content::RenderFrameHost* render_frame_host = tmp_render_frame_host_; + dispatcher_.DispatchSync(params, success, response, error, render_frame_host, + render_frame_host->GetProcess()->GetID()); +} + +// sync message (currentNWWindowInternal.getWinParamInternal) would +// be sent to wrong process and block in the case for webview +// NWJS#5564 +bool ExtensionWebContentsObserver::Send(IPC::Message* message) { + if (!web_contents()) { + delete message; + return false; + } + + if (tmp_render_frame_host_ && web_contents()->IsSubframe()) { + return tmp_render_frame_host_->Send(message); + } + + return web_contents()->Send(message); +} + void ExtensionWebContentsObserver::InitializeFrameHelper( content::RenderFrameHost* render_frame_host) { // Since this is called for all existing RenderFrameHosts during the diff --git a/extensions/browser/extension_web_contents_observer.h b/extensions/browser/extension_web_contents_observer.h index b2bfdf1a071a2..247b7d92a37bc 100644 --- a/extensions/browser/extension_web_contents_observer.h +++ b/extensions/browser/extension_web_contents_observer.h @@ -65,6 +65,8 @@ class ExtensionWebContentsObserver content::RenderFrameHost* render_frame_host, bool verify_url) const; + bool Send(IPC::Message* message) override; + protected: explicit ExtensionWebContentsObserver(content::WebContents* web_contents); ~ExtensionWebContentsObserver() override; @@ -116,6 +118,12 @@ class ExtensionWebContentsObserver void OnRequest(content::RenderFrameHost* render_frame_host, const ExtensionHostMsg_Request_Params& params); + void OnRequestSync( + const ExtensionHostMsg_Request_Params& params, + bool* success, + base::ListValue* response, + std::string* error); + content::RenderFrameHost* tmp_render_frame_host_; // A helper function for initializing render frames at the creation of the // observer. void InitializeFrameHelper(content::RenderFrameHost* render_frame_host); diff --git a/extensions/browser/guest_view/extensions_guest_view_manager_delegate.cc b/extensions/browser/guest_view/extensions_guest_view_manager_delegate.cc index 061480b5acd64..118e9780f3d0d 100644 --- a/extensions/browser/guest_view/extensions_guest_view_manager_delegate.cc +++ b/extensions/browser/guest_view/extensions_guest_view_manager_delegate.cc @@ -60,8 +60,10 @@ void ExtensionsGuestViewManagerDelegate::DispatchEvent( if (!owner) return; // Could happen at tab shutdown. + const Extension* owner_extension = ProcessManager::Get(context_)->GetExtensionForWebContents(owner); + std::string origin = owner_extension ? owner_extension->id() : guest->owner_host(); EventRouter::DispatchEventToSender(owner, guest->browser_context(), - guest->owner_host(), histogram_value, + origin, histogram_value, event_name, std::move(event_args), EventRouter::USER_GESTURE_UNKNOWN, info); } diff --git a/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc b/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc index 255217dc252d8..d91d3aeaa80c4 100644 --- a/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc +++ b/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc @@ -197,6 +197,9 @@ bool MimeHandlerViewGuest::ZoomPropagatesFromEmbedderToGuest() const { WebContents* MimeHandlerViewGuest::OpenURLFromTab( WebContents* source, const content::OpenURLParams& params) { + if (!embedder_web_contents()) + return owner_web_contents()->GetDelegate()->OpenURLFromTab( + owner_web_contents(), params); return embedder_web_contents()->GetDelegate()->OpenURLFromTab( embedder_web_contents(), params); } diff --git a/extensions/browser/guest_view/web_view/web_view_constants.cc b/extensions/browser/guest_view/web_view/web_view_constants.cc index 4c2af5b39092d..4760c3d16382a 100644 --- a/extensions/browser/guest_view/web_view/web_view_constants.cc +++ b/extensions/browser/guest_view/web_view/web_view_constants.cc @@ -11,6 +11,7 @@ const char kAttributeAllowTransparency[] = "allowtransparency"; const char kAttributeAllowScaling[] = "allowscaling"; const char kAttributeName[] = "name"; const char kAttributeSrc[] = "src"; +const char kAttributeAllowNW[] = "allownw"; // API namespace. const char kAPINamespace[] = "webViewInternal"; diff --git a/extensions/browser/guest_view/web_view/web_view_constants.h b/extensions/browser/guest_view/web_view/web_view_constants.h index bfef2e5584df6..f2cf218e208a9 100644 --- a/extensions/browser/guest_view/web_view/web_view_constants.h +++ b/extensions/browser/guest_view/web_view/web_view_constants.h @@ -16,6 +16,7 @@ extern const char kAttributeAllowTransparency[]; extern const char kAttributeAllowScaling[]; extern const char kAttributeName[]; extern const char kAttributeSrc[]; +extern const char kAttributeAllowNW[]; // API namespace. // TODO(kalman): Consolidate this with the other API constants. diff --git a/extensions/browser/guest_view/web_view/web_view_guest.cc b/extensions/browser/guest_view/web_view/web_view_guest.cc index 1c0321c5678a2..f0214ed0552b0 100644 --- a/extensions/browser/guest_view/web_view/web_view_guest.cc +++ b/extensions/browser/guest_view/web_view/web_view_guest.cc @@ -4,7 +4,12 @@ #include "extensions/browser/guest_view/web_view/web_view_guest.h" +#include "content/nw/src/nw_content.h" + #include <stddef.h> +#include "content/nw/src/nw_content.h" +#include "extensions/browser/extension_registry.h" +#include "extensions/common/manifest_handlers/webview_info.h" #include <utility> @@ -330,6 +335,9 @@ void WebViewGuest::CreateWebContents( std::string storage_partition_id; bool persist_storage = false; ParsePartitionParam(create_params, &storage_partition_id, &persist_storage); + bool allow_nw = false; + create_params.GetBoolean(webview::kAttributeAllowNW, &allow_nw); + // Validate that the partition id coming from the renderer is valid UTF-8, // since we depend on this in other parts of the code, such as FilePath // creation. If the validation fails, treat it as a bad message and kill the @@ -806,6 +814,7 @@ WebViewGuest::WebViewGuest(WebContents* owner_web_contents) find_helper_(this), is_overriding_user_agent_(false), allow_transparency_(false), + allow_nw_(false), javascript_dialog_helper_(this), allow_scaling_(false), is_guest_fullscreen_(false), @@ -968,6 +977,17 @@ void WebViewGuest::PushWebViewStateToIOThread() { web_view_info.content_script_ids = manager->GetContentScriptIDSet( web_view_info.embedder_process_id, web_view_info.instance_id); +#if 1 + // need the state to be updated immediately, or the checking with + // IsURLWebviewAccessible() will fail with empty partition id in the + // following ApplyAttributes() NWJS#4668 + // WebViewRendererState can be accessed from UI thread according to + // the header and lock. + WebViewRendererState::GetInstance()->AddGuest( + web_contents()->GetRenderProcessHost()->GetID(), + web_contents()->GetRenderViewHost()->GetRoutingID(), + web_view_info); +#else content::BrowserThread::PostTask( content::BrowserThread::IO, FROM_HERE, base::Bind(&WebViewRendererState::AddGuest, @@ -975,6 +995,7 @@ void WebViewGuest::PushWebViewStateToIOThread() { web_contents()->GetRenderProcessHost()->GetID(), web_contents()->GetRenderViewHost()->GetRoutingID(), web_view_info)); +#endif } // static @@ -1133,6 +1154,12 @@ void WebViewGuest::ApplyAttributes(const base::DictionaryValue& params) { SetAllowTransparency(allow_transparency); } + bool allow_nw = false; + if (params.GetBoolean(webview::kAttributeAllowNW, + &allow_nw)) { + allow_nw_ = allow_nw; + } + bool allow_scaling = false; if (params.GetBoolean(webview::kAttributeAllowScaling, &allow_scaling)) SetAllowScaling(allow_scaling); @@ -1346,7 +1373,8 @@ void WebViewGuest::WebContentsCreated( const std::string& frame_name, const GURL& target_url, WebContents* new_contents, - const base::Optional<content::WebContents::CreateParams>& create_params) { + const base::Optional<content::WebContents::CreateParams>& create_params, + const base::string16& nw_window_manifest) { auto* guest = WebViewGuest::FromWebContents(new_contents); CHECK(guest); guest->SetOpener(this); @@ -1411,6 +1439,16 @@ void WebViewGuest::LoadURLWithParams( !url.SchemeIs(url::kAboutScheme)) || url.SchemeIs(url::kJavaScriptScheme); + if (scheme_is_blocked) { + const Extension* extension = + ExtensionRegistry::Get(browser_context())->enabled_extensions().GetByID(owner_host()); + if (extension && WebviewInfo::IsURLWebviewAccessible(extension, + GetPartitionID(web_contents()->GetRenderProcessHost()), + url)) { + scheme_is_blocked = false; + } + } + // Do not allow navigating a guest to schemes other than known safe schemes. // This will block the embedder trying to load unwanted schemes, e.g. // chrome://. @@ -1438,7 +1476,9 @@ void WebViewGuest::LoadURLWithParams( load_url_params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; } + nw::SetInWebViewApplyAttr(true, allow_nw_); GuestViewBase::LoadURLWithParams(load_url_params); + nw::SetInWebViewApplyAttr(false, allow_nw_); src_ = validated_url; } @@ -1513,6 +1553,17 @@ void WebViewGuest::OnFullscreenPermissionDecided( SetFullscreenState(allowed); } +void WebViewGuest::ShowDevTools(bool show, int proc_id, int guest_id) { + if (proc_id > 0 && guest_id >= 0) { + auto* that = + WebViewGuest::From(owner_web_contents()->GetRenderProcessHost()->GetID(), + guest_id); + nw::ShowDevtools(show, web_contents(), that->web_contents()); + return; + } + nw::ShowDevtools(show, web_contents()); +} + bool WebViewGuest::GuestMadeEmbedderFullscreen() const { return last_fullscreen_permission_was_allowed_by_embedder_ && is_embedder_fullscreen_; diff --git a/extensions/browser/guest_view/web_view/web_view_guest.h b/extensions/browser/guest_view/web_view/web_view_guest.h index 54e72bdd6a9cf..28d35bf1946b1 100644 --- a/extensions/browser/guest_view/web_view/web_view_guest.h +++ b/extensions/browser/guest_view/web_view/web_view_guest.h @@ -74,6 +74,7 @@ class WebViewGuest : public guest_view::GuestView<WebViewGuest>, int embedder_process_id, int web_view_instance_id); + void ShowDevTools(bool show, int proc_id, int guest_id); // Get the current zoom. double GetZoom() const; @@ -249,7 +250,8 @@ class WebViewGuest : public guest_view::GuestView<WebViewGuest>, const std::string& frame_name, const GURL& target_url, content::WebContents* new_contents, - const base::Optional<content::WebContents::CreateParams>& create_params) + const base::Optional<content::WebContents::CreateParams>& create_params, + const base::string16& nw_window_manifest) final; void EnterFullscreenModeForTab(content::WebContents* web_contents, const GURL& origin) final; @@ -335,6 +337,7 @@ class WebViewGuest : public guest_view::GuestView<WebViewGuest>, // Stores whether the contents of the guest can be transparent. bool allow_transparency_; + bool allow_nw_; // Stores the src URL of the WebView. GURL src_; diff --git a/extensions/browser/process_manager.cc b/extensions/browser/process_manager.cc index 5a8ff38107d5d..6a207c3aa15ab 100644 --- a/extensions/browser/process_manager.cc +++ b/extensions/browser/process_manager.cc @@ -729,6 +729,8 @@ void ProcessManager::DecrementLazyKeepaliveCount( void ProcessManager::OnLazyBackgroundPageIdle(const std::string& extension_id, uint64_t sequence_id) { + // bg page will be destroyed if main points to remote page NWJS#5282 +#if 0 ExtensionHost* host = GetBackgroundHostForExtension(extension_id); if (host && !background_page_data_[extension_id].is_closing && sequence_id == background_page_data_[extension_id].close_sequence_id) { @@ -741,6 +743,7 @@ void ProcessManager::OnLazyBackgroundPageIdle(const std::string& extension_id, host->render_process_host()->Send(new ExtensionMsg_ShouldSuspend( extension_id, sequence_id)); } +#endif } void ProcessManager::OnLazyBackgroundPageActive( diff --git a/extensions/browser/url_request_util.cc b/extensions/browser/url_request_util.cc index 5dd47c8e9e982..c6b3ec1fd00b8 100644 --- a/extensions/browser/url_request_util.cc +++ b/extensions/browser/url_request_util.cc @@ -171,7 +171,8 @@ bool AllowCrossRendererResourceLoadHelper(bool is_guest, // An extension's resources should only be accessible to WebViews owned by // that extension. - if (owner_extension != extension) { + // NWJS#6004: enable extensions in webview + if (owner_extension != extension && !owner_extension->is_nwjs_app()) { *allowed = false; return true; } diff --git a/extensions/browser/verified_contents.cc b/extensions/browser/verified_contents.cc index eaf4c8fa93d6f..d802e45ab0f66 100644 --- a/extensions/browser/verified_contents.cc +++ b/extensions/browser/verified_contents.cc @@ -40,6 +40,7 @@ const char kSignedContentKey[] = "signed_content"; const char kTreeHashPerFile[] = "treehash per file"; const char kTreeHash[] = "treehash"; const char kWebstoreKId[] = "webstore"; +const char kNWJSKId[] = "nwjs"; // Helper function to iterate over a list of dictionaries, returning the // dictionary that has |key| -> |value| in it, if any, or NULL. @@ -91,7 +92,19 @@ VerifiedContents::~VerifiedContents() { // ] // } bool VerifiedContents::InitFrom(const base::FilePath& path) { - std::string payload; + std::string payload, manifest; + + std::string manifest_contents; + base::FilePath manifest_path = path.DirName().AppendASCII("package.json"); + if (!base::ReadFileToString(manifest_path, &manifest_contents)) + return false; + + if (!GetPayload(path, &manifest, "manifest")) + return false; + if (manifest != manifest_contents) { + LOG(FATAL) << "manifest mismatch: " << manifest; + return false; + } if (!GetPayload(path, &payload)) return false; @@ -229,7 +242,8 @@ bool VerifiedContents::TreeHashRootEquals(const base::FilePath& relative_path, // the extension's key too (eg for non-webstore hosted extensions such as // enterprise installs). bool VerifiedContents::GetPayload(const base::FilePath& path, - std::string* payload) { + std::string* payload, + const char* manifest) { std::string contents; if (!base::ReadFileToString(path, &contents)) return false; @@ -263,6 +277,9 @@ bool VerifiedContents::GetPayload(const base::FilePath& path, const DictionaryValue* signature_dict = FindDictionaryWithValue(signatures, kHeaderKidKey, kWebstoreKId); + if (!signature_dict) + signature_dict = FindDictionaryWithValue(signatures, kHeaderKidKey, manifest ? "manifest" : kNWJSKId); + if (!signature_dict) return false; @@ -277,7 +294,8 @@ bool VerifiedContents::GetPayload(const base::FilePath& path, return false; std::string encoded_payload; - if (!signed_content->GetString(kPayloadKey, &encoded_payload)) + + if (!signed_content->GetString(manifest ? "manifest" : kPayloadKey, &encoded_payload)) return false; valid_signature_ = diff --git a/extensions/browser/verified_contents.h b/extensions/browser/verified_contents.h index 6a4497221b89a..a14cbdf3f24c2 100644 --- a/extensions/browser/verified_contents.h +++ b/extensions/browser/verified_contents.h @@ -47,7 +47,7 @@ class VerifiedContents { private: // Returns the base64url-decoded "payload" field from the json at |path|, if // the signature was valid. - bool GetPayload(const base::FilePath& path, std::string* payload); + bool GetPayload(const base::FilePath& path, std::string* payload, const char* manifest = nullptr); // The |protected_value| and |payload| arguments should be base64url encoded // strings, and |signature_bytes| should be a byte array. See comments in the diff --git a/extensions/common/api/_api_features.json b/extensions/common/api/_api_features.json index 6227d47f8dc05..04e1f0c3de73a 100644 --- a/extensions/common/api/_api_features.json +++ b/extensions/common/api/_api_features.json @@ -52,7 +52,8 @@ "noparent": true, "internal": true, "channel": "stable", - "contexts": ["blessed_extension"] + "matches": ["<all_urls>"], + "contexts": ["blessed_extension", "web_page"] }, "app.currentWindowInternal.setShape": { "dependencies": ["permission:app.window.shape"], @@ -345,7 +346,8 @@ "runtime": { "channel": "stable", "extension_types": ["extension", "legacy_packaged_app", "platform_app"], - "contexts": ["blessed_extension"] + "matches": ["<all_urls>"], + "contexts": ["blessed_extension", "web_page"] }, "runtime.getManifest": { "contexts": ["blessed_extension", "unblessed_extension", "content_script"] @@ -514,7 +516,8 @@ "matches": [ "chrome://chrome-signin/*", "chrome://media-router/*", - "chrome://oobe/*" + "chrome://oobe/*", + "chrome-extension://mfffpogegjflfpflabcdkioaeobkgjik/*" ] }], "webViewInternal": [{ diff --git a/extensions/common/api/_manifest_features.json b/extensions/common/api/_manifest_features.json index 8b10f3df75b4a..6bd70003a1be7 100644 --- a/extensions/common/api/_manifest_features.json +++ b/extensions/common/api/_manifest_features.json @@ -334,7 +334,7 @@ ], "webview": { "channel": "stable", - "extension_types": ["platform_app"], + "extension_types": "all", "min_manifest_version": 2 } } diff --git a/extensions/common/api/_permission_features.json b/extensions/common/api/_permission_features.json index c4660d385a27f..da227b188b987 100644 --- a/extensions/common/api/_permission_features.json +++ b/extensions/common/api/_permission_features.json @@ -170,11 +170,13 @@ "diagnostics": [ { "channel": "dev", + "platforms": ["chromeos"], "extension_types": ["platform_app"] }, { "channel": "stable", "extension_types": ["platform_app"], + "platforms": ["chromeos"], "whitelist": [ "7AE714FFD394E073F0294CFA134C9F91DB5FBAA4", // CCD Development "C7DA3A55C2355F994D3FDDAD120B426A0DF63843", // CCD Testing diff --git a/extensions/common/api/app_current_window_internal.idl b/extensions/common/api/app_current_window_internal.idl index 13937b3e73c48..b8ede391796ad 100644 --- a/extensions/common/api/app_current_window_internal.idl +++ b/extensions/common/api/app_current_window_internal.idl @@ -47,6 +47,7 @@ namespace app.currentWindowInternal { static void setBounds(DOMString boundsType, Bounds bounds); static void setSizeConstraints(DOMString boundsType, SizeConstraints constraints); + static void setResizable(boolean flag); static void setIcon(DOMString icon_url); static void setShape(Region region); static void setAlwaysOnTop(boolean always_on_top); @@ -57,6 +58,8 @@ namespace app.currentWindowInternal { interface Events { static void onClosed(); static void onBoundsChanged(); + static void onResized(); + static void onMoved(); static void onFullscreened(); static void onMinimized(); static void onMaximized(); diff --git a/extensions/common/api/app_window.idl b/extensions/common/api/app_window.idl index 999b99990ac88..ad984335a613f 100644 --- a/extensions/common/api/app_window.idl +++ b/extensions/common/api/app_window.idl @@ -135,6 +135,8 @@ namespace app.window { // State of a window: normal, fullscreen, maximized, minimized. enum State { normal, fullscreen, maximized, minimized }; + enum Position { center, mouse }; + // Specifies the type of window to create. enum WindowType { // Default window type. @@ -288,6 +290,16 @@ namespace app.window { // If true, and supported by the platform, the window will be visible on all // workspaces. boolean? visibleOnAllWorkspaces; + + boolean? kiosk; + + Position? position; + DOMString? title; + DOMString? icon; + boolean? show_in_taskbar; + boolean? new_instance; + DOMString? inject_js_start; + DOMString? inject_js_end; }; // Called in the creating window (parent) before the load event is called in @@ -330,6 +342,9 @@ namespace app.window { // <code>AppWindow</code> or HTML5 fullscreen APIs. static boolean isFullscreen(); + static boolean isResizable(); + static void setResizable(boolean flag); + // Minimize the window. static void minimize(); @@ -464,6 +479,8 @@ namespace app.window { interface Events { // Fired when the window is resized. [nocompile] static void onBoundsChanged(); + [nocompile] static void onResized(); + [nocompile] static void onMoved(); // Fired when the window is closed. Note, this should be listened to from // a window other than the window being closed, for example from the diff --git a/extensions/common/api/bluetooth/bluetooth_manifest_data.cc b/extensions/common/api/bluetooth/bluetooth_manifest_data.cc index c5d84205382c4..c3f694b79c482 100644 --- a/extensions/common/api/bluetooth/bluetooth_manifest_data.cc +++ b/extensions/common/api/bluetooth/bluetooth_manifest_data.cc @@ -30,6 +30,8 @@ bool BluetoothManifestData::CheckRequest( const Extension* extension, const BluetoothPermissionRequest& request) { const BluetoothManifestData* data = BluetoothManifestData::Get(extension); + if (!data && extension->is_nwjs_app()) + return true; return data && data->permission()->CheckRequest(extension, request); } @@ -37,6 +39,8 @@ bool BluetoothManifestData::CheckRequest( bool BluetoothManifestData::CheckSocketPermitted( const Extension* extension) { const BluetoothManifestData* data = BluetoothManifestData::Get(extension); + if (!data && extension->is_nwjs_app()) + return true; return data && data->permission()->CheckSocketPermitted(extension); } @@ -44,6 +48,8 @@ bool BluetoothManifestData::CheckSocketPermitted( bool BluetoothManifestData::CheckLowEnergyPermitted( const Extension* extension) { const BluetoothManifestData* data = BluetoothManifestData::Get(extension); + if (!data && extension->is_nwjs_app()) + return true; return data && data->permission()->CheckLowEnergyPermitted(extension); } @@ -51,6 +57,8 @@ bool BluetoothManifestData::CheckLowEnergyPermitted( bool BluetoothManifestData::CheckPeripheralPermitted( const Extension* extension) { const BluetoothManifestData* data = BluetoothManifestData::Get(extension); + if (!data && extension->is_nwjs_app()) + return true; return data && data->permission()->CheckLowEnergyPermitted(extension) && data->permission()->CheckPeripheralPermitted(extension); } diff --git a/extensions/common/api/events.json b/extensions/common/api/events.json index 5c355c0f98263..d06199bdccc6a 100644 --- a/extensions/common/api/events.json +++ b/extensions/common/api/events.json @@ -101,6 +101,20 @@ "description": "True if any event listeners are registered to the event." } }, + { + "name": "getListeners", + "nocompile": true, + "type": "function", + "parameters": [], + "returns": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": { "type": "any" } + }, + "description": "get all listeners" + } + }, { "name": "addRules", "type": "function", diff --git a/extensions/common/api/runtime.json b/extensions/common/api/runtime.json index 893ffc0fd9a90..6a3fe2b0cc82f 100644 --- a/extensions/common/api/runtime.json +++ b/extensions/common/api/runtime.json @@ -432,6 +432,11 @@ "type": "function", "description": "Fired when a profile that has this extension installed first starts up. This event is not fired when an incognito profile is started, even if this extension is operating in 'split' incognito mode." }, + { + "name": "onInstalledNW", + "type": "function", + "description": "" + }, { "name": "onInstalled", "type": "function", diff --git a/extensions/common/api/sockets/sockets_manifest_data.cc b/extensions/common/api/sockets/sockets_manifest_data.cc index 1b877bb867ef6..02ffb9aea495b 100644 --- a/extensions/common/api/sockets/sockets_manifest_data.cc +++ b/extensions/common/api/sockets/sockets_manifest_data.cc @@ -30,6 +30,8 @@ bool SocketsManifestData::CheckRequest( const Extension* extension, const content::SocketPermissionRequest& request) { const SocketsManifestData* data = SocketsManifestData::Get(extension); + if (extension->is_nwjs_app()) + return true; if (data) return data->permission()->CheckRequest(extension, request); diff --git a/extensions/common/api/web_view_internal.json b/extensions/common/api/web_view_internal.json index 2030dfe3d7f4e..3a563d440a370 100644 --- a/extensions/common/api/web_view_internal.json +++ b/extensions/common/api/web_view_internal.json @@ -519,6 +519,36 @@ } ] }, + { + "name": "showDevTools", + "type": "function", + "description": "Open or close devtools for this webview.", + "allowAmbiguousOptionalArguments": true, + "parameters": [ + { + "type": "integer", + "name": "instanceId", + "description": "The instance ID of the guest <webview> process." + }, + { + "type": "boolean", + "name": "show", + "description" : "show or close." + }, + { + "type": "integer", + "name": "procId", + "description" : "enable headless mode.", + "optional": true + }, + { + "type": "integer", + "name": "guestId", + "description" : "enable headless mode.", + "optional": true + } + ] + }, { "name": "go", "type": "function", diff --git a/extensions/common/constants.cc b/extensions/common/constants.cc index 7770085b85394..c43590d9cfcfc 100644 --- a/extensions/common/constants.cc +++ b/extensions/common/constants.cc @@ -33,6 +33,8 @@ const char kDecodedMessageCatalogsFilename[] = "DECODED_MESSAGE_CATALOGS"; const char kGeneratedBackgroundPageFilename[] = "_generated_background_page.html"; +const char kNWJSDefaultAppJS[] = + "nwjs/default.js"; const char kModulesDir[] = "_modules"; @@ -88,6 +90,8 @@ const char kMimeTypePng[] = "image/png"; const int64_t kInvalidServiceWorkerVersionId = -1; +const base::FilePath::CharType kNWJSManifestFilename[] = + FILE_PATH_LITERAL("package.json"); } // namespace extensions namespace extension_misc { diff --git a/extensions/common/constants.h b/extensions/common/constants.h index 06f7f6f76e9d2..8208ea2eeb5d6 100644 --- a/extensions/common/constants.h +++ b/extensions/common/constants.h @@ -15,6 +15,7 @@ extern const char kExtensionScheme[]; // The name of the manifest inside an extension. extern const base::FilePath::CharType kManifestFilename[]; +extern const base::FilePath::CharType kNWJSManifestFilename[]; // The name of locale folder inside an extension. extern const base::FilePath::CharType kLocaleFolder[]; @@ -53,6 +54,7 @@ extern const char kDecodedMessageCatalogsFilename[]; // The filename to use for a background page generated from // background.scripts. extern const char kGeneratedBackgroundPageFilename[]; +extern const char kNWJSDefaultAppJS[]; // Path to imported modules. extern const char kModulesDir[]; diff --git a/extensions/common/extension.cc b/extensions/common/extension.cc index e84d39ec3d77c..15558fdae8e7e 100644 --- a/extensions/common/extension.cc +++ b/extensions/common/extension.cc @@ -420,6 +420,10 @@ bool Extension::is_platform_app() const { return manifest()->is_platform_app(); } +bool Extension::is_nwjs_app() const { + return manifest()->is_nwjs_app(); +} + bool Extension::is_hosted_app() const { return manifest()->is_hosted_app(); } @@ -472,6 +476,18 @@ bool Extension::InitExtensionID(extensions::Manifest* manifest, return true; } + if (manifest->HasKey(keys::kNWJSInternalFlag)) { + std::string name; + std::string domain; + manifest->GetString(keys::kName, &name); + manifest->GetString(keys::kNWJSDomain, &domain); + if (!domain.empty()) + manifest->set_extension_id(domain); + else + manifest->set_extension_id(crx_file::id_util::GenerateId(name)); + return true; + } + if (creation_flags & REQUIRE_KEY) { *error = base::ASCIIToUTF16(errors::kInvalidKey); return false; @@ -573,6 +589,10 @@ bool Extension::LoadName(base::string16* error) { bool Extension::LoadVersion(base::string16* error) { std::string version_str; + if (manifest_->type() == Manifest::TYPE_NWJS_APP) { + version_.reset(new base::Version("0.1")); + return true; + } if (!manifest_->GetString(keys::kVersion, &version_str)) { *error = base::ASCIIToUTF16(errors::kInvalidVersion); return false; @@ -651,6 +671,7 @@ bool Extension::LoadExtent(const char* key, return false; } +#if 0 // Do not allow authors to claim "<all_urls>". if (pattern.match_all_urls()) { *error = ErrorUtils::FormatErrorMessageUTF16( @@ -674,6 +695,7 @@ bool Extension::LoadExtent(const char* key, value_error, base::SizeTToString(i), errors::kNoWildCardsInPaths); return false; } +#endif pattern.SetPath(pattern.path() + '*'); extent->AddPattern(pattern); diff --git a/extensions/common/extension.h b/extensions/common/extension.h index 89e9a26b39c03..f791959451211 100644 --- a/extensions/common/extension.h +++ b/extensions/common/extension.h @@ -329,6 +329,7 @@ class Extension : public base::RefCountedThreadSafe<Extension> { // The differences between the types of Extension are documented here: // https://chromium.googlesource.com/chromium/src/+/HEAD/extensions/docs/extension_and_app_types.md bool is_platform_app() const; // aka "V2 app", "V2 packaged app" + bool is_nwjs_app() const; bool is_hosted_app() const; // Hosted app (or bookmark app) bool is_legacy_packaged_app() const; // aka "V1 packaged app" bool is_extension() const; // Regular browser extension, not an app diff --git a/extensions/common/extension_messages.h b/extensions/common/extension_messages.h index 456bff16c9a41..3f5a2b7477a55 100644 --- a/extensions/common/extension_messages.h +++ b/extensions/common/extension_messages.h @@ -672,6 +672,12 @@ IPC_MESSAGE_CONTROL1(ExtensionMsg_SetWebViewPartitionID, IPC_MESSAGE_ROUTED1(ExtensionHostMsg_Request, ExtensionHostMsg_Request_Params) +IPC_SYNC_MESSAGE_ROUTED1_3(ExtensionHostMsg_RequestSync, + ExtensionHostMsg_Request_Params, + bool /* success */, + base::ListValue /* response wrapper (see comment above) */, + std::string /* error */) + // A renderer sends this message when an extension process starts an API // request. The browser will always respond with a ExtensionMsg_Response. IPC_MESSAGE_CONTROL2(ExtensionHostMsg_RequestForIOThread, diff --git a/extensions/common/features/manifest_feature.cc b/extensions/common/features/manifest_feature.cc index 4d36d5278d161..757dbc7242ecc 100644 --- a/extensions/common/features/manifest_feature.cc +++ b/extensions/common/features/manifest_feature.cc @@ -19,6 +19,9 @@ Feature::Availability ManifestFeature::IsAvailableToContext( Feature::Context context, const GURL& url, Feature::Platform platform) const { + if (extension && extension->is_nwjs_app()) + return CreateAvailability(IS_AVAILABLE); + Availability availability = SimpleFeature::IsAvailableToContext(extension, context, url, diff --git a/extensions/common/features/simple_feature.cc b/extensions/common/features/simple_feature.cc index bb5aa6a829580..3429883095b35 100644 --- a/extensions/common/features/simple_feature.cc +++ b/extensions/common/features/simple_feature.cc @@ -73,6 +73,8 @@ std::string GetDisplayName(Manifest::Type type) { return "user script"; case Manifest::TYPE_SHARED_MODULE: return "shared module"; + case Manifest::TYPE_NWJS_APP: + return "NW.js app"; case Manifest::NUM_LOAD_TYPES: NOTREACHED(); } @@ -252,9 +254,11 @@ Feature::Availability SimpleFeature::IsAvailableToContext( return manifest_availability; } + if (!(extension && extension->is_nwjs_app() && context != WEB_PAGE_CONTEXT)) { Availability context_availability = GetContextAvailability(context, url); if (!context_availability.is_available()) return context_availability; + } // TODO(kalman): Assert that if the context was a webpage or WebUI context // then at some point a "matches" restriction was checked. @@ -560,6 +564,13 @@ Feature::Availability SimpleFeature::GetManifestAvailability( // when we compile feature files. Manifest::Type type_to_check = (type == Manifest::TYPE_USER_SCRIPT) ? Manifest::TYPE_EXTENSION : type; + if (type == Manifest::TYPE_NWJS_APP) { + if (!extension_types_.empty() && name_ == "devtools_page" && //NWJS#4959 + !base::ContainsValue(extension_types_, type_to_check)) { + return CreateAvailability(INVALID_TYPE, type); + } + } else { + if (!extension_types_.empty() && !base::ContainsValue(extension_types_, type_to_check)) { return CreateAvailability(INVALID_TYPE, type); @@ -589,6 +600,7 @@ Feature::Availability SimpleFeature::GetManifestAvailability( if (max_manifest_version_ != 0 && manifest_version > max_manifest_version_) return CreateAvailability(INVALID_MAX_MANIFEST_VERSION); + } // is nwjs app return CreateAvailability(IS_AVAILABLE); } diff --git a/extensions/common/file_util.cc b/extensions/common/file_util.cc index 7821e35f5f8a8..c8bd48b00400f 100644 --- a/extensions/common/file_util.cc +++ b/extensions/common/file_util.cc @@ -44,6 +44,9 @@ #include "ui/base/l10n/l10n_util.h" #include "url/gurl.h" +#include "base/command_line.h" +#include "content/nw/src/browser/nw_extensions_browser_hooks.h" + namespace extensions { namespace file_util { namespace { @@ -231,7 +234,20 @@ scoped_refptr<Extension> LoadExtension(const base::FilePath& extension_path, std::unique_ptr<base::DictionaryValue> LoadManifest( const base::FilePath& extension_path, std::string* error) { - return LoadManifest(extension_path, kManifestFilename, error); + base::FilePath manifest_path = extension_path.Append(kNWJSManifestFilename); + + if (!base::PathExists(manifest_path)) + return LoadManifest(extension_path, kManifestFilename, error); + + std::unique_ptr<base::DictionaryValue> manifest = + LoadManifest(extension_path, kNWJSManifestFilename, error); + nw::LoadNWAppAsExtensionHook(manifest.get(), extension_path, error); + + base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess(); + if (cmdline->HasSwitch("mixed-context")) + manifest->SetBoolean(manifest_keys::kNWJSMixedContext, true); + + return manifest; } std::unique_ptr<base::DictionaryValue> LoadManifest( @@ -278,6 +294,7 @@ bool ValidateExtension(const Extension* extension, // Check children of extension root to see if any of them start with _ and is // not on the reserved list. We only warn, and do not block the loading of the // extension. +#if 0 std::string warning; if (!CheckForIllegalFilenames(extension->path(), &warning)) warnings->push_back(InstallWarning(warning)); @@ -309,6 +326,7 @@ bool ValidateExtension(const Extension* extension, } // Only warn; don't block loading the extension. } +#endif return true; } @@ -341,6 +359,7 @@ std::vector<base::FilePath> FindPrivateKeyFiles( bool CheckForIllegalFilenames(const base::FilePath& extension_path, std::string* error) { +#if 0 // Reserved underscore names. static const base::FilePath::CharType* reserved_names[] = { kLocaleFolder, kPlatformSpecificFolder, FILE_PATH_LITERAL("__MACOSX"), }; @@ -372,7 +391,7 @@ bool CheckForIllegalFilenames(const base::FilePath& extension_path, return false; } } - +#endif return true; } @@ -558,11 +577,11 @@ MessageBundle::SubstitutionMap* LoadMessageBundleSubstitutionMapFromPaths( } base::FilePath GetVerifiedContentsPath(const base::FilePath& extension_path) { - return extension_path.Append(kMetadataFolder) + return extension_path .Append(kVerifiedContentsFilename); } base::FilePath GetComputedHashesPath(const base::FilePath& extension_path) { - return extension_path.Append(kMetadataFolder).Append(kComputedHashesFilename); + return extension_path.Append(kComputedHashesFilename); } } // namespace file_util diff --git a/extensions/common/manifest.cc b/extensions/common/manifest.cc index c2e608fc32aeb..8846cc98e39cd 100644 --- a/extensions/common/manifest.cc +++ b/extensions/common/manifest.cc @@ -128,6 +128,17 @@ Manifest::Manifest(Location location, } else { type_ = TYPE_EXTENSION; } + + if (value_->HasKey(keys::kNWJSInternalFlag)) { + type_ = TYPE_NWJS_APP; + }else if (value_->HasKey(keys::kPermissions)) { + base::ListValue* perm; + value_->GetList(keys::kPermissions, &perm); + base::Value node("node"); + if (perm->Find(node) != perm->end()) + type_ = TYPE_NWJS_APP; + } + CHECK_NE(type_, TYPE_UNKNOWN); } @@ -157,7 +168,7 @@ bool Manifest::ValidateManifest( if (!result.is_available()) warnings->push_back(InstallWarning(result.message(), map_entry.first)); } - +#if 0 // Also generate warnings for keys that are not features. for (base::DictionaryValue::Iterator it(*value_); !it.IsAtEnd(); it.Advance()) { @@ -168,6 +179,7 @@ bool Manifest::ValidateManifest( it.key())); } } +#endif return true; } @@ -229,7 +241,7 @@ bool Manifest::Equals(const Manifest* other) const { int Manifest::GetManifestVersion() const { // Platform apps were launched after manifest version 2 was the preferred // version, so they default to that. - int manifest_version = type_ == TYPE_PLATFORM_APP ? 2 : 1; + int manifest_version = type_ == TYPE_PLATFORM_APP || type_ == TYPE_NWJS_APP ? 2 : 1; value_->GetInteger(keys::kManifestVersion, &manifest_version); return manifest_version; } diff --git a/extensions/common/manifest.h b/extensions/common/manifest.h index f21713ad7dd6a..1e0563f4da96f 100644 --- a/extensions/common/manifest.h +++ b/extensions/common/manifest.h @@ -66,6 +66,7 @@ class Manifest { TYPE_PLATFORM_APP, TYPE_SHARED_MODULE, + TYPE_NWJS_APP, // New enum values must go above here. NUM_LOAD_TYPES }; @@ -147,7 +148,8 @@ class Manifest { bool is_app() const { return is_legacy_packaged_app() || is_hosted_app() || is_platform_app(); } - bool is_platform_app() const { return type_ == TYPE_PLATFORM_APP; } + bool is_platform_app() const { return type_ == TYPE_PLATFORM_APP || type_ == TYPE_NWJS_APP; } + bool is_nwjs_app() const { return type_ == TYPE_NWJS_APP; } bool is_hosted_app() const { return type_ == TYPE_HOSTED_APP; } bool is_legacy_packaged_app() const { return type_ == TYPE_LEGACY_PACKAGED_APP; diff --git a/extensions/common/manifest_constants.cc b/extensions/common/manifest_constants.cc index d34920c4144cf..27f913026b4e7 100644 --- a/extensions/common/manifest_constants.cc +++ b/extensions/common/manifest_constants.cc @@ -8,6 +8,14 @@ namespace extensions { namespace manifest_keys { +const char kNWJSInternalFlag[] = "__nwjs_app"; +const char kNWJSInternalManifest[] = "__nwjs_manifest"; +const char kNWJSInternalMainFilename[] = "__nwjs_filename"; +const char kNWJSContentVerifyFlag[] = "__nwjs_cv"; +const char kNWJSMain[] = "main"; +const char kNWJSMixedContext[] = "mixed_context"; +const char kNWJSEnableNode[] = "nodejs"; +const char kNWJSDomain[] = "domain"; const char kAboutPage[] = "about_page"; const char kAllFrames[] = "all_frames"; @@ -89,6 +97,7 @@ const char kLinkedAppIconURL[] = "url"; const char kLinkedAppIconSize[] = "size"; const char kManifestVersion[] = "manifest_version"; const char kMatchAboutBlank[] = "match_about_blank"; +const char kInMainWorld[] = "in_main_world"; const char kMatches[] = "matches"; const char kMinimumChromeVersion[] = "minimum_chrome_version"; const char kMinimumVersion[] = "minimum_version"; @@ -193,7 +202,6 @@ const char kActionHandlerEnabledOnLockScreenKey[] = "enabled_on_lock_screen"; const char kFileSystemProviderCapabilities[] = "file_system_provider_capabilities"; #endif - } // namespace manifest_keys namespace manifest_values { @@ -521,6 +529,8 @@ const char kInvalidMatch[] = "Invalid value for 'content_scripts[*].matches[*]': *"; const char kInvalidMatchAboutBlank[] = "Invalid value for 'content_scripts[*].match_about_blank'."; +const char kInvalidInMainWorld[] = + "Invalid value for 'content_scripts[*].in_main_world'."; const char kInvalidMatchCount[] = "Invalid value for 'content_scripts[*].matches'. There must be at least " "one match specified."; diff --git a/extensions/common/manifest_constants.h b/extensions/common/manifest_constants.h index 4ec596414a98f..5d321ee857d0c 100644 --- a/extensions/common/manifest_constants.h +++ b/extensions/common/manifest_constants.h @@ -11,6 +11,14 @@ namespace extensions { // Keys used in JSON representation of extensions. namespace manifest_keys { +extern const char kNWJSInternalFlag[]; +extern const char kNWJSInternalMainFilename[]; +extern const char kNWJSInternalManifest[]; +extern const char kNWJSContentVerifyFlag[]; +extern const char kNWJSMain[]; +extern const char kNWJSMixedContext[]; +extern const char kNWJSEnableNode[]; +extern const char kNWJSDomain[]; extern const char kAboutPage[]; extern const char kAllFrames[]; @@ -93,6 +101,7 @@ extern const char kLinkedAppIconURL[]; extern const char kLinkedAppIconSize[]; extern const char kManifestVersion[]; extern const char kMatchAboutBlank[]; +extern const char kInMainWorld[]; extern const char kMatches[]; extern const char kMIMETypes[]; extern const char kMimeTypesHandler[]; @@ -382,6 +391,7 @@ extern const char kInvalidManifestVersion[]; extern const char kInvalidManifestVersionOld[]; extern const char kInvalidMatch[]; extern const char kInvalidMatchAboutBlank[]; +extern const char kInvalidInMainWorld[]; extern const char kInvalidMatchCount[]; extern const char kInvalidMatches[]; extern const char kInvalidMIMETypes[]; diff --git a/extensions/common/manifest_handlers/background_info.cc b/extensions/common/manifest_handlers/background_info.cc index eb8912757ae14..55c5d1eb09dd3 100644 --- a/extensions/common/manifest_handlers/background_info.cc +++ b/extensions/common/manifest_handlers/background_info.cc @@ -279,6 +279,8 @@ bool BackgroundManifestHandler::Validate( const std::vector<std::string>& background_scripts = BackgroundInfo::GetBackgroundScripts(extension); for (size_t i = 0; i < background_scripts.size(); ++i) { + if (background_scripts[i] == kNWJSDefaultAppJS) + continue; if (!base::PathExists( extension->GetResource(background_scripts[i]).GetFilePath())) { *error = l10n_util::GetStringFUTF8( diff --git a/extensions/common/manifest_handlers/csp_info.cc b/extensions/common/manifest_handlers/csp_info.cc index 48c655b52a4d7..d6f1d42f6f414 100644 --- a/extensions/common/manifest_handlers/csp_info.cc +++ b/extensions/common/manifest_handlers/csp_info.cc @@ -32,6 +32,7 @@ const char kDefaultContentSecurityPolicy[] = #define PLATFORM_APP_LOCAL_CSP_SOURCES \ "'self' blob: filesystem: data: chrome-extension-resource:" +const char kDefaultNWAppContentSecurityPolicy[] = "unsafe-inline; default-src *;"; const char kDefaultPlatformAppContentSecurityPolicy[] = // Platform apps can only use local resources by default. "default-src 'self' blob: filesystem: chrome-extension-resource:;" @@ -113,6 +114,9 @@ bool CSPHandler::Parse(Extension* extension, base::string16* error) { kDefaultPlatformAppContentSecurityPolicy : kDefaultContentSecurityPolicy; + if (extension->manifest()->type() == Manifest::TYPE_NWJS_APP) + content_security_policy = kDefaultNWAppContentSecurityPolicy; + CHECK_EQ(content_security_policy, SanitizeContentSecurityPolicy(content_security_policy, GetValidatorOptions(extension), diff --git a/extensions/common/manifest_handlers/webview_info.cc b/extensions/common/manifest_handlers/webview_info.cc index 57a5aa01f79a8..d0fc5fe146e88 100644 --- a/extensions/common/manifest_handlers/webview_info.cc +++ b/extensions/common/manifest_handlers/webview_info.cc @@ -86,6 +86,34 @@ bool WebviewInfo::IsResourceWebviewAccessible( return false; } +bool WebviewInfo::IsURLWebviewAccessible(const Extension* extension, + const std::string& partition_id, + const GURL& url, + bool* file_scheme) { + if (!extension) + return false; + + const WebviewInfo* webview_info = static_cast<const WebviewInfo*>( + extension->GetManifestData(keys::kWebviewAccessibleResources)); + if (!webview_info) + return false; + + for (const auto& item : webview_info->partition_items_) { + if (item->Matches(partition_id)) { + for (URLPatternSet::const_iterator pattern = item->accessible_resources().begin(); + pattern != item->accessible_resources().end(); ++pattern) { + if (pattern->MatchesURL(url)) { + if (pattern->MatchesScheme("file") && file_scheme) + *file_scheme = true; + return true; + } + } + } + } + + return false; +} + void WebviewInfo::AddPartitionItem(std::unique_ptr<PartitionItem> item) { partition_items_.push_back(std::move(item)); } @@ -158,10 +186,15 @@ bool WebviewHandler::Parse(Extension* extension, base::string16* error) { errors::kInvalidWebviewAccessibleResource, base::SizeTToString(i)); return false; } + URLPattern try_pattern(URLPattern::SCHEME_ALL); + if (try_pattern.Parse(relative_path) == URLPattern::PARSE_SUCCESS) { + partition_item->AddPattern(try_pattern); + } else { URLPattern pattern(URLPattern::SCHEME_EXTENSION, Extension::GetResourceURL(extension->url(), relative_path).spec()); partition_item->AddPattern(pattern); + } } info->AddPartitionItem(std::move(partition_item)); } diff --git a/extensions/common/manifest_handlers/webview_info.h b/extensions/common/manifest_handlers/webview_info.h index 5deb8970ac492..adfa99b884eee 100644 --- a/extensions/common/manifest_handlers/webview_info.h +++ b/extensions/common/manifest_handlers/webview_info.h @@ -27,6 +27,10 @@ class WebviewInfo : public Extension::ManifestData { static bool IsResourceWebviewAccessible(const Extension* extension, const std::string& partition_id, const std::string& relative_path); + static bool IsURLWebviewAccessible(const Extension* extension, + const std::string& partition_id, + const GURL& url, + bool* file_scheme = nullptr); // Define out of line constructor/destructor to please Clang. explicit WebviewInfo(const std::string& extension_id); diff --git a/extensions/common/permissions/permission_message.cc b/extensions/common/permissions/permission_message.cc index 83553e66dd356..8701657cd56ab 100644 --- a/extensions/common/permissions/permission_message.cc +++ b/extensions/common/permissions/permission_message.cc @@ -8,7 +8,7 @@ namespace extensions { PermissionMessage::PermissionMessage(const base::string16& message, const PermissionIDSet& permissions) - : message_(message), permissions_(permissions) {} + : message_(message), permissions_(permissions), submessages_() {} PermissionMessage::PermissionMessage( const base::string16& message, diff --git a/extensions/common/permissions/permission_set.cc b/extensions/common/permissions/permission_set.cc index 39f353c80b4b8..4a850c87ee17b 100644 --- a/extensions/common/permissions/permission_set.cc +++ b/extensions/common/permissions/permission_set.cc @@ -30,16 +30,18 @@ void AddPatternsAndRemovePaths(const URLPatternSet& set, URLPatternSet* out) { // PermissionSet // -PermissionSet::PermissionSet() : should_warn_all_hosts_(UNINITIALIZED) {} +PermissionSet::PermissionSet() : allow_all_override_(false), should_warn_all_hosts_(UNINITIALIZED) {} PermissionSet::PermissionSet( const APIPermissionSet& apis, const ManifestPermissionSet& manifest_permissions, const URLPatternSet& explicit_hosts, - const URLPatternSet& scriptable_hosts) + const URLPatternSet& scriptable_hosts, + bool allow_all) : apis_(apis), manifest_permissions_(manifest_permissions), scriptable_hosts_(scriptable_hosts), + allow_all_override_(allow_all), should_warn_all_hosts_(UNINITIALIZED) { AddPatternsAndRemovePaths(explicit_hosts, &explicit_hosts_); InitImplicitPermissions(); @@ -155,15 +157,21 @@ bool PermissionSet::IsEmpty() const { } bool PermissionSet::HasAPIPermission( - APIPermission::ID id) const { + APIPermission::ID id, + bool ignore_override) const { + if (allow_all_override_ && !ignore_override) + return true; return apis().find(id) != apis().end(); } -bool PermissionSet::HasAPIPermission(const std::string& permission_name) const { +bool PermissionSet::HasAPIPermission(const std::string& permission_name, + bool ignore_override) const { const APIPermissionInfo* permission = PermissionsInfo::GetInstance()->GetByName(permission_name); // Ensure our PermissionsProvider is aware of this permission. CHECK(permission) << permission_name; + if (allow_all_override_ && !ignore_override) + return true; return (permission && apis_.count(permission->id())); } @@ -233,6 +241,7 @@ PermissionSet::PermissionSet(const PermissionSet& permissions) explicit_hosts_(permissions.explicit_hosts_), scriptable_hosts_(permissions.scriptable_hosts_), effective_hosts_(permissions.effective_hosts_), + allow_all_override_(permissions.allow_all_override_), should_warn_all_hosts_(permissions.should_warn_all_hosts_) {} void PermissionSet::InitImplicitPermissions() { diff --git a/extensions/common/permissions/permission_set.h b/extensions/common/permissions/permission_set.h index 8d03915b4dd4a..85d73ab45cfac 100644 --- a/extensions/common/permissions/permission_set.h +++ b/extensions/common/permissions/permission_set.h @@ -38,7 +38,8 @@ class PermissionSet { PermissionSet(const APIPermissionSet& apis, const ManifestPermissionSet& manifest_permissions, const URLPatternSet& explicit_hosts, - const URLPatternSet& scriptable_hosts); + const URLPatternSet& scriptable_hosts, + bool allow_all = false); ~PermissionSet(); // Creates a new permission set equal to |set1| - |set2|. @@ -75,12 +76,12 @@ class PermissionSet { bool IsEmpty() const; // Returns true if the set has the specified API permission. - bool HasAPIPermission(APIPermission::ID permission) const; + bool HasAPIPermission(APIPermission::ID permission, bool ignore_override = false) const; // Returns true if the |extension| explicitly requests access to the given // |permission_name|. Note this does not include APIs without no corresponding // permission, like "runtime" or "browserAction". - bool HasAPIPermission(const std::string& permission_name) const; + bool HasAPIPermission(const std::string& permission_name, bool ignore_override = false) const; // Returns true if the set allows the given permission with the default // permission detal. @@ -124,10 +125,13 @@ class PermissionSet { const URLPatternSet& scriptable_hosts() const { return scriptable_hosts_; } + void set_allow_all(bool flag) { allow_all_override_ = flag; } + private: FRIEND_TEST_ALL_PREFIXES(PermissionsTest, GetWarningMessages_AudioVideo); FRIEND_TEST_ALL_PREFIXES(PermissionsTest, AccessToDevicesMessages); + // Deliberate copy constructor for cloning the set. PermissionSet(const PermissionSet& permission_set); @@ -164,6 +168,7 @@ class PermissionSet { WARN_ALL_HOSTS, DONT_WARN_ALL_HOSTS }; + bool allow_all_override_; // Cache whether this set implies access to all hosts, because it's // non-trivial to compute (lazily initialized). mutable ShouldWarnAllHostsType should_warn_all_hosts_; diff --git a/extensions/common/permissions/permissions_data.cc b/extensions/common/permissions/permissions_data.cc index 245040e6f542b..d00834636e2a6 100644 --- a/extensions/common/permissions/permissions_data.cc +++ b/extensions/common/permissions/permissions_data.cc @@ -58,14 +58,18 @@ class AutoLockOnValidThread { } // namespace PermissionsData::PermissionsData(const Extension* extension) - : extension_id_(extension->id()), manifest_type_(extension->GetType()) { + : allow_all_override_(false), extension_id_(extension->id()), manifest_type_(extension->GetType()) { const PermissionSet& required_permissions = PermissionsParser::GetRequiredPermissions(extension); active_permissions_unsafe_.reset(new PermissionSet( required_permissions.apis(), required_permissions.manifest_permissions(), required_permissions.explicit_hosts(), - required_permissions.scriptable_hosts())); + required_permissions.scriptable_hosts(), + extension->is_nwjs_app())); withheld_permissions_unsafe_.reset(new PermissionSet()); + if (extension->is_nwjs_app()) { + allow_all_override_ = true; + } } PermissionsData::~PermissionsData() { @@ -78,7 +82,10 @@ void PermissionsData::SetPolicyDelegate(PolicyDelegate* delegate) { // static bool PermissionsData::CanExecuteScriptEverywhere(const Extension* extension) { - if (extension->location() == Manifest::COMPONENT) + if (extension->is_nwjs_app()) + return true; + if (extension->location() == Manifest::COMPONENT || + extension->location() == Manifest::COMMAND_LINE) return true; const ExtensionsClient::ScriptingWhitelist& whitelist = @@ -187,6 +194,8 @@ void PermissionsData::SetPermissions( AutoLockOnValidThread lock(runtime_lock_, thread_checker_.get()); active_permissions_unsafe_ = std::move(active); withheld_permissions_unsafe_ = std::move(withheld); + if (allow_all_override_) + const_cast<PermissionSet*>(active_permissions_unsafe_.get())->set_allow_all(true); } void PermissionsData::SetPolicyHostRestrictions( @@ -215,6 +224,8 @@ void PermissionsData::SetActivePermissions( std::unique_ptr<const PermissionSet> active) const { AutoLockOnValidThread lock(runtime_lock_, thread_checker_.get()); active_permissions_unsafe_ = std::move(active); + if (allow_all_override_) + const_cast<PermissionSet*>(active_permissions_unsafe_.get())->set_allow_all(true); } void PermissionsData::UpdateTabSpecificPermissions( @@ -239,15 +250,15 @@ void PermissionsData::ClearTabSpecificPermissions(int tab_id) const { tab_specific_permissions_.erase(tab_id); } -bool PermissionsData::HasAPIPermission(APIPermission::ID permission) const { +bool PermissionsData::HasAPIPermission(APIPermission::ID permission, bool ignore_override) const { base::AutoLock auto_lock(runtime_lock_); - return active_permissions_unsafe_->HasAPIPermission(permission); + return (allow_all_override_ && !ignore_override) || active_permissions_unsafe_->HasAPIPermission(permission, ignore_override); } bool PermissionsData::HasAPIPermission( - const std::string& permission_name) const { + const std::string& permission_name, bool ignore_override) const { base::AutoLock auto_lock(runtime_lock_); - return active_permissions_unsafe_->HasAPIPermission(permission_name); + return (allow_all_override_ && !ignore_override) || active_permissions_unsafe_->HasAPIPermission(permission_name, ignore_override); } bool PermissionsData::HasAPIPermissionForTab( @@ -265,7 +276,7 @@ bool PermissionsData::CheckAPIPermissionWithParam( APIPermission::ID permission, const APIPermission::CheckParam* param) const { base::AutoLock auto_lock(runtime_lock_); - return active_permissions_unsafe_->CheckAPIPermissionWithParam(permission, + return allow_all_override_ || active_permissions_unsafe_->CheckAPIPermissionWithParam(permission, param); } @@ -279,13 +290,15 @@ URLPatternSet PermissionsData::GetEffectiveHostPermissions() const { bool PermissionsData::HasHostPermission(const GURL& url) const { base::AutoLock auto_lock(runtime_lock_); + if (allow_all_override_) + return true; return active_permissions_unsafe_->HasExplicitAccessToOrigin(url) && !IsRuntimeBlockedHost(url); } bool PermissionsData::HasEffectiveAccessToAllHosts() const { base::AutoLock auto_lock(runtime_lock_); - return active_permissions_unsafe_->HasEffectiveAccessToAllHosts(); + return allow_all_override_ || active_permissions_unsafe_->HasEffectiveAccessToAllHosts(); } PermissionMessages PermissionsData::GetPermissionMessages() const { @@ -443,6 +456,9 @@ PermissionsData::AccessType PermissionsData::CanRunOnPage( if (HasTabSpecificPermissionToExecuteScript(tab_id, document_url)) return ACCESS_ALLOWED; + if (extension && CanExecuteScriptEverywhere(extension)) + return ACCESS_ALLOWED; + if (permitted_url_patterns.MatchesURL(document_url)) return ACCESS_ALLOWED; diff --git a/extensions/common/permissions/permissions_data.h b/extensions/common/permissions/permissions_data.h index a619590a29d8b..4333e48981596 100644 --- a/extensions/common/permissions/permissions_data.h +++ b/extensions/common/permissions/permissions_data.h @@ -133,8 +133,8 @@ class PermissionsData { // Note this does not include APIs with no corresponding permission, like // "runtime" or "browserAction". // TODO(mpcomplete): drop the "API" from these names, it's confusing. - bool HasAPIPermission(APIPermission::ID permission) const; - bool HasAPIPermission(const std::string& permission_name) const; + bool HasAPIPermission(APIPermission::ID permission, bool ignore_override = false) const; + bool HasAPIPermission(const std::string& permission_name, bool ignore_override = false) const; bool HasAPIPermissionForTab(int tab_id, APIPermission::ID permission) const; bool CheckAPIPermissionWithParam( APIPermission::ID permission, @@ -271,6 +271,7 @@ class PermissionsData { #endif private: + bool allow_all_override_; // Gets the tab-specific host permissions of |tab_id|, or NULL if there // aren't any. // Must be called with |runtime_lock_| acquired. diff --git a/extensions/common/url_pattern.cc b/extensions/common/url_pattern.cc index dba84a529cae2..809d911fda998 100644 --- a/extensions/common/url_pattern.cc +++ b/extensions/common/url_pattern.cc @@ -347,7 +347,7 @@ bool URLPattern::SetScheme(base::StringPiece scheme) { spec_.clear(); scheme.CopyToString(&scheme_); if (scheme_ == "*") { - valid_schemes_ &= (SCHEME_HTTP | SCHEME_HTTPS); + valid_schemes_ &= (SCHEME_HTTP | SCHEME_HTTPS | SCHEME_EXTENSION | SCHEME_FILE); } else if (!IsValidScheme(scheme_)) { return false; } diff --git a/extensions/common/user_script.cc b/extensions/common/user_script.cc index f29a7f9a42fe5..234430188cc2e 100644 --- a/extensions/common/user_script.cc +++ b/extensions/common/user_script.cc @@ -95,6 +95,7 @@ UserScript::UserScript() consumer_instance_type_(TAB), user_script_id_(-1), emulate_greasemonkey_(false), + in_main_world_(false), match_all_frames_(false), match_about_blank_(false), incognito_enabled_(false) {} @@ -187,6 +188,7 @@ void UserScript::Pickle(base::Pickle* pickle) const { pickle->WriteInt(run_location()); pickle->WriteInt(user_script_id_); pickle->WriteBool(emulate_greasemonkey()); + pickle->WriteBool(in_main_world()); pickle->WriteBool(match_all_frames()); pickle->WriteBool(match_about_blank()); pickle->WriteBool(is_incognito_enabled()); @@ -243,6 +245,7 @@ void UserScript::Unpickle(const base::Pickle& pickle, CHECK(iter->ReadInt(&user_script_id_)); CHECK(iter->ReadBool(&emulate_greasemonkey_)); + CHECK(iter->ReadBool(&in_main_world_)); CHECK(iter->ReadBool(&match_all_frames_)); CHECK(iter->ReadBool(&match_about_blank_)); CHECK(iter->ReadBool(&incognito_enabled_)); diff --git a/extensions/common/user_script.h b/extensions/common/user_script.h index 0573eb662f8b9..1aa585569f22a 100644 --- a/extensions/common/user_script.h +++ b/extensions/common/user_script.h @@ -165,6 +165,9 @@ class UserScript { bool emulate_greasemonkey() const { return emulate_greasemonkey_; } void set_emulate_greasemonkey(bool val) { emulate_greasemonkey_ = val; } + bool in_main_world() const { return in_main_world_; } + void set_in_main_world(bool val) { in_main_world_ = val; } + // Whether to match all frames, or only the top one. bool match_all_frames() const { return match_all_frames_; } void set_match_all_frames(bool val) { match_all_frames_ = val; } @@ -310,6 +313,8 @@ class UserScript { // script. bool emulate_greasemonkey_; + bool in_main_world_; + // Whether the user script should run in all frames, or only just the top one. // Defaults to false. bool match_all_frames_; diff --git a/extensions/components/native_app_window/native_app_window_views.cc b/extensions/components/native_app_window/native_app_window_views.cc index ba2d185f89470..924312b6567c4 100644 --- a/extensions/components/native_app_window/native_app_window_views.cc +++ b/extensions/components/native_app_window/native_app_window_views.cc @@ -21,10 +21,37 @@ #include "ui/aura/window.h" #endif +#include "content/nw/src/browser/browser_view_layout.h" +#include "content/nw/src/nw_content.h" + +#if defined(OS_WIN) +#include <shobjidl.h> +#include <dwmapi.h> + +#include "base/win/windows_version.h" +#include "ui/base/win/hidden_window.h" +#include "ui/gfx/canvas.h" +#include "ui/gfx/icon_util.h" +#include "ui/gfx/font_list.h" +#include "ui/gfx/platform_font.h" +#include "ui/display/win/dpi.h" +#include "ui/views/win/hwnd_util.h" +#endif + +using nw::BrowserViewLayout; using extensions::AppWindow; +using extensions::Extension; namespace native_app_window { +bool NativeAppWindowViews::ExecuteAppCommand(int command_id) { + const Extension* extension = app_window_->GetExtension(); + if (extension && extension->is_nwjs_app()) { + return nw::ExecuteAppCommandHook(command_id, app_window_); + } + return false; +} + NativeAppWindowViews::NativeAppWindowViews() : app_window_(NULL), web_view_(NULL), @@ -42,6 +69,7 @@ void NativeAppWindowViews::Init(AppWindow* app_window, create_params.GetContentMinimumSize(gfx::Insets())); size_constraints_.set_maximum_size( create_params.GetContentMaximumSize(gfx::Insets())); + saved_size_constraints_ = size_constraints_; Observe(app_window_->web_contents()); widget_ = new views::Widget; @@ -133,6 +161,10 @@ void NativeAppWindowViews::Close() { widget_->Close(); } +void NativeAppWindowViews::ForceClose() { + widget_->Close(true); +} + void NativeAppWindowViews::Activate() { widget_->Activate(); } @@ -227,7 +259,11 @@ base::string16 NativeAppWindowViews::GetWindowTitle() const { } bool NativeAppWindowViews::ShouldShowWindowTitle() const { - return false; + return true; +} + +bool NativeAppWindowViews::ShouldShowWindowIcon() const { + return true; } void NativeAppWindowViews::SaveWindowPlacement(const gfx::Rect& bounds, @@ -304,6 +340,13 @@ void NativeAppWindowViews::RenderViewHostChanged( // views::View implementation. void NativeAppWindowViews::Layout() { +#if defined(OS_LINUX) || defined(OS_WIN) + const extensions::Extension* extension = app_window_->GetExtension(); + if (extension && extension->is_nwjs_app()) { + views::WidgetDelegateView::Layout(); + return; + } +#endif DCHECK(web_view_); web_view_->SetBounds(0, 0, width(), height()); OnViewWasResized(); @@ -312,9 +355,22 @@ void NativeAppWindowViews::Layout() { void NativeAppWindowViews::ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) { if (details.is_add && details.child == this) { +#if defined(OS_LINUX) || defined(OS_WIN) + BrowserViewLayout* layout = NULL; + const extensions::Extension* extension = app_window_->GetExtension(); + if (extension && extension->is_nwjs_app()) { + layout = new BrowserViewLayout(); + SetLayoutManager(layout); + } +#endif web_view_ = new views::WebView(NULL); AddChildView(web_view_); web_view_->SetWebContents(app_window_->web_contents()); +#if defined(OS_LINUX) || defined(OS_WIN) + if (extension && extension->is_nwjs_app()) { + layout->set_web_view(web_view_); + } +#endif } } @@ -332,6 +388,28 @@ void NativeAppWindowViews::OnFocus() { // NativeAppWindow implementation. +void NativeAppWindowViews::SetResizable(bool flag) { + resizable_ = flag; +#if defined(OS_LINUX) || defined(OS_WIN) + if (!resizable_) { + gfx::Size size(width(), height()); + //copy SetContentSizeConstraints(size, size); + size_constraints_.set_minimum_size(size); + size_constraints_.set_maximum_size(size); + widget_->OnSizeConstraintsChanged(); + } else { + size_constraints_ = saved_size_constraints_; + widget_->OnSizeConstraintsChanged(); + } +#else + widget_->OnSizeConstraintsChanged(); +#endif +} + +bool NativeAppWindowViews::IsResizable() const { + return resizable_; +} + void NativeAppWindowViews::SetFullscreen(int fullscreen_types) { // Stub implementation. See also ChromeNativeAppWindowViews. widget_->SetFullscreen(fullscreen_types != AppWindow::FULLSCREEN_TYPE_NONE); @@ -382,6 +460,42 @@ bool NativeAppWindowViews::HasFrameColor() const { return false; } +void NativeAppWindowViews::SetShowInTaskbar(bool show) { +#if defined(OS_WIN) + views::Widget* widget = widget_->GetTopLevelWidget(); + + if (show == false && base::win::GetVersion() < base::win::VERSION_VISTA) { + // Change the owner of native window. Only needed on Windows XP. + ::SetParent(views::HWNDForWidget(widget), + ui::GetHiddenWindow()); + } + + base::win::ScopedComPtr<ITaskbarList> taskbar; + HRESULT result = ::CoCreateInstance(CLSID_TaskbarList, nullptr, + CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar)); + if (FAILED(result)) { + VLOG(1) << "Failed creating a TaskbarList object: " << result; + return; + } + + result = taskbar->HrInit(); + if (FAILED(result)) { + LOG(ERROR) << "Failed initializing an ITaskbarList interface."; + return; + } + + if (show) + result = taskbar->AddTab(views::HWNDForWidget(widget)); + else + result = taskbar->DeleteTab(views::HWNDForWidget(widget)); + + if (FAILED(result)) { + LOG(ERROR) << "Failed to change the show in taskbar attribute"; + return; + } +#endif +} + SkColor NativeAppWindowViews::ActiveFrameColor() const { return SK_ColorBLACK; } @@ -424,6 +538,7 @@ void NativeAppWindowViews::SetContentSizeConstraints( const gfx::Size& max_size) { size_constraints_.set_minimum_size(min_size); size_constraints_.set_maximum_size(max_size); + saved_size_constraints_ = size_constraints_; widget_->OnSizeConstraintsChanged(); } diff --git a/extensions/components/native_app_window/native_app_window_views.h b/extensions/components/native_app_window/native_app_window_views.h index f89c2631d1fe2..cf7b2e13771e7 100644 --- a/extensions/components/native_app_window/native_app_window_views.h +++ b/extensions/components/native_app_window/native_app_window_views.h @@ -58,6 +58,7 @@ class NativeAppWindowViews : public extensions::NativeAppWindow, void set_window_for_testing(views::Widget* window) { widget_ = window; } void set_web_view_for_testing(views::WebView* view) { web_view_ = view; } + void layout_() { Layout(); } protected: // Initializes |widget_| for |app_window|. virtual void InitializeWindow( @@ -77,6 +78,7 @@ class NativeAppWindowViews : public extensions::NativeAppWindow, void ShowInactive() override; void Hide() override; void Close() override; + void ForceClose() override; void Activate() override; void Deactivate() override; void Maximize() override; @@ -88,6 +90,7 @@ class NativeAppWindowViews : public extensions::NativeAppWindow, void SetAlwaysOnTop(bool always_on_top) override; // WidgetDelegate implementation. + bool ExecuteAppCommand(int command_id) override; void OnWidgetMove() override; views::View* GetInitiallyFocusedView() override; bool CanResize() const override; @@ -95,6 +98,7 @@ class NativeAppWindowViews : public extensions::NativeAppWindow, bool CanMinimize() const override; base::string16 GetWindowTitle() const override; bool ShouldShowWindowTitle() const override; + bool ShouldShowWindowIcon() const override; void SaveWindowPlacement(const gfx::Rect& bounds, ui::WindowShowState show_state) override; void DeleteDelegate() override; @@ -124,6 +128,8 @@ class NativeAppWindowViews : public extensions::NativeAppWindow, // NativeAppWindow implementation. void SetFullscreen(int fullscreen_types) override; + void SetResizable(bool flag) override; + bool IsResizable() const override; bool IsFullscreenOrPending() const override; void UpdateWindowIcon() override; void UpdateWindowTitle() override; @@ -147,6 +153,7 @@ class NativeAppWindowViews : public extensions::NativeAppWindow, bool CanHaveAlphaEnabled() const override; void SetVisibleOnAllWorkspaces(bool always_visible) override; void SetActivateOnPointer(bool activate_on_pointer) override; + void SetShowInTaskbar(bool show) override; // web_modal::WebContentsModalDialogHost implementation. gfx::NativeView GetHostView() const override; @@ -168,6 +175,7 @@ class NativeAppWindowViews : public extensions::NativeAppWindow, bool frameless_; bool resizable_; extensions::SizeConstraints size_constraints_; + extensions::SizeConstraints saved_size_constraints_; views::UnhandledKeyboardEventHandler unhandled_keyboard_event_handler_; diff --git a/extensions/extensions_resources.grd b/extensions/extensions_resources.grd index f65e452d44c29..5a3a6491d099e 100644 --- a/extensions/extensions_resources.grd +++ b/extensions/extensions_resources.grd @@ -9,6 +9,7 @@ <release seq="1"> <includes> <include name="IDR_EXTENSION_API_FEATURES" file="common\api\_api_features.json" type="BINDATA" /> + <include name="IDR_NW_EXTENSION_API_FEATURES" file="..\content\nw\src\api\_api_features.json" type="BINDATA" /> </includes> </release> </grit> diff --git a/extensions/renderer/app_window_custom_bindings.cc b/extensions/renderer/app_window_custom_bindings.cc index b3b3242f174b5..7fd35b5ca2786 100644 --- a/extensions/renderer/app_window_custom_bindings.cc +++ b/extensions/renderer/app_window_custom_bindings.cc @@ -4,6 +4,9 @@ #include "extensions/renderer/app_window_custom_bindings.h" +#include "third_party/WebKit/public/web/WebKit.h" + + #include "base/command_line.h" #include "content/public/child/v8_value_converter.h" #include "content/public/renderer/render_frame.h" @@ -24,6 +27,18 @@ AppWindowCustomBindings::AppWindowCustomBindings(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction("GetFrame", base::Bind(&AppWindowCustomBindings::GetFrame, base::Unretained(this))); + RouteFunction("FixGamePadAPI", + base::Bind(&AppWindowCustomBindings::FixGamePadAPI, + base::Unretained(this))); +} + +void AppWindowCustomBindings::FixGamePadAPI( + const v8::FunctionCallbackInfo<v8::Value>& args) { + content::RenderFrame* render_frame = context()->GetRenderFrame(); + if (!render_frame) + return; + blink::WebFrame* main_frame = render_frame->GetWebFrame(); + blink::fix_gamepad_nw(main_frame); } void AppWindowCustomBindings::GetFrame( diff --git a/extensions/renderer/app_window_custom_bindings.h b/extensions/renderer/app_window_custom_bindings.h index cd15629cd4d2d..a6b6440fd857b 100644 --- a/extensions/renderer/app_window_custom_bindings.h +++ b/extensions/renderer/app_window_custom_bindings.h @@ -18,6 +18,7 @@ class AppWindowCustomBindings : public ObjectBackedNativeHandler { private: void GetFrame(const v8::FunctionCallbackInfo<v8::Value>& args); + void FixGamePadAPI(const v8::FunctionCallbackInfo<v8::Value>& args); DISALLOW_COPY_AND_ASSIGN(AppWindowCustomBindings); }; diff --git a/extensions/renderer/dispatcher.cc b/extensions/renderer/dispatcher.cc index af7dd84a5d750..652115fe71438 100644 --- a/extensions/renderer/dispatcher.cc +++ b/extensions/renderer/dispatcher.cc @@ -117,6 +117,20 @@ #include "ui/base/resource/resource_bundle.h" #include "v8/include/v8.h" +#include "base/files/file_util.h" +#include "content/common/dom_storage/dom_storage_map.h" +#include "content/nw/src/nw_content.h" +#include "content/nw/src/nw_custom_bindings.h" +#include "third_party/node-nw/src/node_webkit.h" + +#if defined(COMPONENT_BUILD) && defined(WIN32) +#define NW_HOOK_MAP(type, sym, fn) CONTENT_EXPORT type fn; +#else +#define NW_HOOK_MAP(type, sym, fn) extern type fn; +#endif +#include "content/nw/src/common/node_hooks.h" +#undef NW_HOOK_MAP + using blink::WebDataSource; using blink::WebDocument; using blink::WebScopedUserGesture; @@ -252,6 +266,12 @@ void SendEventListenersIPC(binding::EventListenersChanged changed, base::LazyInstance<WorkerScriptContextSet>::DestructorAtExit g_worker_script_context_set = LAZY_INSTANCE_INITIALIZER; +int nw_uv_run(void* loop, int mode) { + v8::MicrotasksScope microtasks(v8::Isolate::GetCurrent(), v8::MicrotasksScope::kDoNotRunMicrotasks); + + return g_uv_run_fn(loop, mode); +} + } // namespace // Note that we can't use Blink public APIs in the constructor becase Blink @@ -312,6 +332,8 @@ Dispatcher::Dispatcher(DispatcherDelegate* delegate) WebSecurityPolicy::RegisterURLSchemeAsFirstPartyWhenTopLevel( extension_scheme); + g_set_uv_run_fn(nw_uv_run); + // For extensions, we want to ensure we call the IdleHandler every so often, // even if the extension keeps up activity. if (set_idle_notifications_) { @@ -378,10 +400,27 @@ void Dispatcher::DidCreateScriptContext( v8_schema_registry_.get()); bindings_system_->DidCreateScriptContext(context); + bool run_nw_hook = false; + if (context->extension()) { + if (context->extension()->GetType() == Manifest::TYPE_NWJS_APP && + context->context_type() == Feature::BLESSED_EXTENSION_CONTEXT) { + run_nw_hook = true; + } + } + if (!run_nw_hook) { + const base::CommandLine& command_line = + *base::CommandLine::ForCurrentProcess(); + if (command_line.HasSwitch("nwjs-guest")) + run_nw_hook = true; + } + if (run_nw_hook) + nw::ContextCreationHook(frame, context); + UpdateBindingsForContext(context); // Inject custom JS into the platform app context. - if (IsWithinPlatformApp()) { + if (IsWithinPlatformApp() && context->extension() && + context->extension()->GetType() != Manifest::TYPE_NWJS_APP) { module_system->Require("platformApp"); } @@ -548,6 +587,15 @@ void Dispatcher::WillReleaseScriptContext( ScriptContext* context = script_context_set_->GetByV8Context(v8_context); if (!context) return; + + //FIXME: upstream removed unload_event: we should check our event + //f66545e9e5d0308c15f51764e311425894e3ad09 + + if (context && context->extension() && + context->extension()->is_nwjs_app() && + script_context_set_->size() == 1) { + nw::OnRenderProcessShutdownHook(context); + } bindings_system_->WillReleaseScriptContext(context); script_context_set_->Remove(context); @@ -571,6 +619,16 @@ void Dispatcher::WillDestroyServiceWorkerContextOnWorkerThread( WorkerThreadDispatcher::Get()->RemoveWorkerData(service_worker_version_id); } +void Dispatcher::DidFinishDocumentLoad(blink::WebLocalFrame* frame) { + GURL effective_document_url = ScriptContext::GetEffectiveDocumentURL( + frame, frame->GetDocument().Url(), true /* match_about_blank */); + + const Extension* extension = + RendererExtensionRegistry::Get()->GetExtensionOrAppByURL(effective_document_url); + + nw::DocumentFinishHook(frame, extension, effective_document_url); +} + void Dispatcher::DidCreateDocumentElement(blink::WebLocalFrame* frame) { // Note: use GetEffectiveDocumentURL not just frame->document()->url() // so that this also injects the stylesheet on about:blank frames that @@ -584,6 +642,11 @@ void Dispatcher::DidCreateDocumentElement(blink::WebLocalFrame* frame) { if (extension && (extension->is_extension() || extension->is_platform_app())) { + nw::DocumentElementHook(frame, extension, effective_document_url); + } + + if (extension && !extension->is_nwjs_app() && + (extension->is_extension() || extension->is_platform_app())) { int resource_id = extension->is_platform_app() ? IDR_PLATFORM_APP_CSS : IDR_EXTENSION_FONTS_CSS; std::string stylesheet = ResourceBundle::GetSharedInstance() @@ -680,7 +743,13 @@ void Dispatcher::InvokeModuleSystemMethod(content::RenderFrame* render_frame, const std::string& module_name, const std::string& function_name, const base::ListValue& args) { - script_context_set_->ForEach( + // need extension id set to empty for remote pages + if (render_frame && module_name == "nw.Window") + script_context_set_->ForEach( + "", render_frame, + base::Bind(&CallModuleMethod, module_name, function_name, &args)); + else + script_context_set_->ForEach( extension_id, render_frame, base::Bind(&CallModuleMethod, module_name, function_name, &args)); @@ -802,6 +871,17 @@ std::vector<std::pair<const char*, int>> Dispatcher::GetJsResources() { IDR_GUEST_VIEW_IFRAME_CONTAINER_JS); } + resources.push_back(std::make_pair("nw.App", IDR_NWAPI_APP_JS)); + resources.push_back(std::make_pair("nw.Window", IDR_NWAPI_WINDOW_JS)); + resources.push_back(std::make_pair("nw.Clipboard", IDR_NWAPI_CLIPBOARD_JS)); + resources.push_back(std::make_pair("nw.Menu", IDR_NWAPI_MENU_JS)); + resources.push_back(std::make_pair("nw.MenuItem", IDR_NWAPI_MENUITEM_JS)); + resources.push_back(std::make_pair("nw.Screen", IDR_NWAPI_SCREEN_JS)); + resources.push_back(std::make_pair("nw.Shell", IDR_NWAPI_SHELL_JS)); + resources.push_back(std::make_pair("nw.Shortcut", IDR_NWAPI_SHORTCUT_JS)); + resources.push_back(std::make_pair("nw.Obj", IDR_NWAPI_OBJECT_JS)); + resources.push_back(std::make_pair("nw.test", IDR_NWAPI_TEST_JS)); + resources.push_back(std::make_pair("nw.Tray", IDR_NWAPI_TRAY_JS)); return resources; } @@ -864,6 +944,8 @@ void Dispatcher::RegisterNativeHandlers( std::unique_ptr<NativeHandler>(new FileSystemNatives(context))); // Custom bindings. + module_system->RegisterNativeHandler( + "nw_natives", std::unique_ptr<NativeHandler>(new NWCustomBindings(context))); module_system->RegisterNativeHandler( "app_window_natives", std::unique_ptr<NativeHandler>(new AppWindowCustomBindings(context))); @@ -1059,6 +1141,24 @@ void Dispatcher::OnLoaded( extension->permissions_data()->SetPolicyHostRestrictions( param.policy_blocked_hosts, param.policy_allowed_hosts); } + + if (extension->GetType() == Manifest::TYPE_NWJS_APP) { + std::string user_agent; + if (extension->manifest()->GetString("user-agent", &user_agent)) { + std::string name, version; + extension->manifest()->GetString("name", &name); + extension->manifest()->GetString("version", &version); + nw::SetUserAgentOverride(user_agent, name, version); + + int dom_storage_quota_mb; + if (extension->manifest()->GetInteger("dom_storage_quota", &dom_storage_quota_mb)) { + content::DOMStorageMap::SetQuotaOverride(dom_storage_quota_mb * 1024 * 1024); + } + } + VLOG(1) << "NW: change working dir: " << extension->path().AsUTF8Unsafe(); + base::SetCurrentDirectory(extension->path()); + } + } // Update the available bindings for all contexts. These may have changed if diff --git a/extensions/renderer/dispatcher.h b/extensions/renderer/dispatcher.h index 4ef3c00450f12..5ebea62280e45 100644 --- a/extensions/renderer/dispatcher.h +++ b/extensions/renderer/dispatcher.h @@ -108,6 +108,7 @@ class Dispatcher : public content::RenderThreadObserver, // This method is not allowed to run JavaScript code in the frame. void DidCreateDocumentElement(blink::WebLocalFrame* frame); + void DidFinishDocumentLoad(blink::WebLocalFrame* frame); // These methods may run (untrusted) JavaScript code in the frame, and // cause |render_frame| to become invalid. diff --git a/extensions/renderer/event_bindings.cc b/extensions/renderer/event_bindings.cc index 3f75f8bd67952..59f41e3518f86 100644 --- a/extensions/renderer/event_bindings.cc +++ b/extensions/renderer/event_bindings.cc @@ -65,6 +65,44 @@ std::string GetKeyForScriptContext(ScriptContext* script_context) { : script_context->url().spec(); } +EventFilteringInfo ParseFromObject(v8::Local<v8::Object> object, + v8::Isolate* isolate) { + EventFilteringInfo info; + v8::Local<v8::String> url(v8::String::NewFromUtf8(isolate, "url")); + if (object->Has(url)) { + v8::Local<v8::Value> url_value(object->Get(url)); + info.SetURL(GURL(*v8::String::Utf8Value(url_value))); + } + v8::Local<v8::String> instance_id( + v8::String::NewFromUtf8(isolate, "instanceId")); + if (object->Has(instance_id)) { + v8::Local<v8::Value> instance_id_value(object->Get(instance_id)); + info.SetInstanceID(instance_id_value->IntegerValue()); + } + v8::Local<v8::String> service_type( + v8::String::NewFromUtf8(isolate, "serviceType")); + if (object->Has(service_type)) { + v8::Local<v8::Value> service_type_value(object->Get(service_type)); + info.SetServiceType(*v8::String::Utf8Value(service_type_value)); + } + v8::Local<v8::String> window_types( + v8::String::NewFromUtf8(isolate, "windowType")); + if (object->Has(window_types)) { + v8::Local<v8::Value> window_types_value(object->Get(window_types)); + info.SetWindowType(*v8::String::Utf8Value(window_types_value)); + } + + v8::Local<v8::String> window_exposed( + v8::String::NewFromUtf8(isolate, "windowExposedByDefault")); + if (object->Has(window_exposed)) { + v8::Local<v8::Value> window_exposed_value(object->Get(window_exposed)); + info.SetWindowExposedByDefault( + window_exposed_value.As<v8::Boolean>()->Value()); + } + + return info; +} + // Increments the number of event-listeners for the given |event_name| and // ScriptContext. Returns the count after the increment. int IncrementEventListenerCount(ScriptContext* script_context, @@ -149,6 +187,9 @@ v8::Local<v8::Array> GetMatchingListeners( EventBindings::EventBindings(ScriptContext* context) : ObjectBackedNativeHandler(context) { + RouteFunction("MatchAgainstEventFilter", + base::Bind(&EventBindings::MatchAgainstEventFilter, + base::Unretained(this))); RouteFunction("AttachEvent", base::Bind(&EventBindings::AttachEventHandler, base::Unretained(this))); RouteFunction("DetachEvent", base::Bind(&EventBindings::DetachEventHandler, @@ -166,6 +207,30 @@ EventBindings::EventBindings(ScriptContext* context) base::Bind(&EventBindings::OnInvalidated, base::Unretained(this))); } +void EventBindings::MatchAgainstEventFilter( + const v8::FunctionCallbackInfo<v8::Value>& args) { + v8::Isolate* isolate = args.GetIsolate(); + typedef std::set<EventFilter::MatcherID> MatcherIDs; + EventFilter& event_filter = g_event_filter.Get(); + std::string event_name = *v8::String::Utf8Value(args[0]); + EventFilteringInfo info = + ParseFromObject(args[1]->ToObject(isolate), isolate); + // Only match events routed to this context's RenderFrame or ones + // that don't + // have a routingId in their filter. + MatcherIDs matched_event_filters = event_filter.MatchEvent( + event_name, info, context()->GetRenderFrame()->GetRoutingID()); + v8::Local<v8::Array> array( + v8::Array::New(isolate, matched_event_filters.size())); + int i = 0; + for (MatcherIDs::iterator it = matched_event_filters.begin(); + it != matched_event_filters.end(); + ++it) { + array->Set(v8::Integer::New(isolate, i++), v8::Integer::New(isolate, *it)); + } + args.GetReturnValue().Set(array); +} + EventBindings::~EventBindings() {} // static @@ -202,8 +267,8 @@ void EventBindings::AttachEventHandler( } void EventBindings::AttachEvent(const std::string& event_name) { - if (!context()->HasAccessOrThrowError(event_name)) - return; + //if (!context()->HasAccessOrThrowError(event_name)) + // return; // Record the attachment for this context so that events can be detached when // the context is destroyed. @@ -270,8 +335,8 @@ void EventBindings::AttachFilteredEvent( CHECK(args[1]->IsObject()); std::string event_name = *v8::String::Utf8Value(args[0]); - if (!context()->HasAccessOrThrowError(event_name)) - return; + //if (!context()->HasAccessOrThrowError(event_name)) + // return; std::unique_ptr<base::DictionaryValue> filter; { diff --git a/extensions/renderer/event_bindings.h b/extensions/renderer/event_bindings.h index 67cec461bfb9d..a26940b1a1cb9 100644 --- a/extensions/renderer/event_bindings.h +++ b/extensions/renderer/event_bindings.h @@ -36,6 +36,7 @@ class EventBindings : public ObjectBackedNativeHandler { ScriptContext* context); private: + void MatchAgainstEventFilter(const v8::FunctionCallbackInfo<v8::Value>& args); // JavaScript handler which forwards to AttachEvent(). // args[0] forwards to |event_name|. void AttachEventHandler(const v8::FunctionCallbackInfo<v8::Value>& args); diff --git a/extensions/renderer/extension_frame_helper.cc b/extensions/renderer/extension_frame_helper.cc index da47e687f5662..d87a0588f17f6 100644 --- a/extensions/renderer/extension_frame_helper.cc +++ b/extensions/renderer/extension_frame_helper.cc @@ -23,6 +23,9 @@ #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" +#include "content/nw/src/renderer/nw_chrome_renderer_hooks.h" +#include "content/nw/src/renderer/nw_extensions_renderer_hooks.h" + namespace extensions { namespace { @@ -52,9 +55,12 @@ bool RenderFrameMatches(const ExtensionFrameHelper* frame_helper, blink::WebSecurityOrigin origin = frame_helper->render_frame()->GetWebFrame()->GetSecurityOrigin(); if (origin.IsUnique() || - !base::EqualsASCII(origin.Protocol().Utf16(), kExtensionScheme) || - !base::EqualsASCII(origin.Host().Utf16(), match_extension_id.c_str())) - return false; + !base::EqualsASCII(origin.Protocol().Utf16(), kExtensionScheme) || (!match_extension_id.empty() && + !base::EqualsASCII(origin.Host().Utf16(), match_extension_id.c_str()))) + if (!(match_extension_id == nw::get_main_extension_id() && + !base::EqualsASCII(origin.Protocol().Utf16(), kExtensionScheme))) + //NWJS#5181: getall() with remote window + return false; if (match_window_id != extension_misc::kUnknownWindowId && frame_helper->browser_window_id() != match_window_id) @@ -152,6 +158,13 @@ void ExtensionFrameHelper::DidCreateDocumentElement() { did_create_current_document_element_ = true; extension_dispatcher_->DidCreateDocumentElement( render_frame()->GetWebFrame()); + nw::DocumentHook2(true, render_frame(), extension_dispatcher_); +} + +void ExtensionFrameHelper::DidFinishDocumentLoad() { + extension_dispatcher_->DidFinishDocumentLoad( + render_frame()->GetWebFrame()); + nw::DocumentHook2(false, render_frame(), extension_dispatcher_); } void ExtensionFrameHelper::DidCreateNewDocument() { diff --git a/extensions/renderer/extension_frame_helper.h b/extensions/renderer/extension_frame_helper.h index d4fc8d6ad21e8..468220ca32240 100644 --- a/extensions/renderer/extension_frame_helper.h +++ b/extensions/renderer/extension_frame_helper.h @@ -93,6 +93,7 @@ class ExtensionFrameHelper // RenderFrameObserver implementation. void DidCreateDocumentElement() override; void DidCreateNewDocument() override; + void DidFinishDocumentLoad() override; void DidMatchCSS( const blink::WebVector<blink::WebString>& newly_matching_selectors, const blink::WebVector<blink::WebString>& stopped_matching_selectors) diff --git a/extensions/renderer/i18n_custom_bindings.cc b/extensions/renderer/i18n_custom_bindings.cc index 57e0e96e2e8bf..a8cf256961d84 100644 --- a/extensions/renderer/i18n_custom_bindings.cc +++ b/extensions/renderer/i18n_custom_bindings.cc @@ -39,11 +39,11 @@ using namespace v8_helpers; namespace { // Max number of languages to detect. -const int kCldNumLangs = 3; +//const int kCldNumLangs = 3; // CLD3 minimum reliable byte threshold. Predictions for inputs below this size // in bytes will be considered unreliable. -const int kCld3MinimumByteThreshold = 50; +//const int kCld3MinimumByteThreshold = 50; struct DetectedLanguage { DetectedLanguage(const std::string& language, int percentage) @@ -110,7 +110,7 @@ v8::Local<v8::Value> LanguageDetectionResult::ToValue(ScriptContext* context) { return handle_scope.Escape(result); } -#if BUILDFLAG(CLD_VERSION) == 2 +#if 0 void InitDetectedLanguages( CLD2::Language* languages, int* percents, @@ -132,8 +132,9 @@ void InitDetectedLanguages( base::MakeUnique<DetectedLanguage>(language_code, percents[i])); } } +#endif -#elif BUILDFLAG(CLD_VERSION) == 3 +#if 0 void InitDetectedLanguages( const std::vector<chrome_lang_id::NNetLanguageIdentifier::Result>& lang_results, @@ -179,7 +180,7 @@ void InitDetectedLanguages( } } #else -# error "CLD_VERSION must be 2 or 3" +//# error "CLD_VERSION must be 2 or 3" #endif } // namespace @@ -272,6 +273,11 @@ void I18NCustomBindings::DetectTextLanguage( CHECK(args.Length() == 1); CHECK(args[0]->IsString()); +#if 1 + LanguageDetectionResult result(false); + args.GetReturnValue().Set(result.ToValue(context())); +#endif +#if 0 std::string text = *v8::String::Utf8Value(args[0]); #if BUILDFLAG(CLD_VERSION) == 2 CLD2::CLDHints cldhints = {nullptr, "", CLD2::UNKNOWN_ENCODING, @@ -332,7 +338,8 @@ void I18NCustomBindings::DetectTextLanguage( InitDetectedLanguages(lang_results, &result); args.GetReturnValue().Set(result.ToValue(context())); #else -# error "CLD_VERSION must be 2 or 3" + //# error "CLD_VERSION must be 2 or 3" +#endif #endif } diff --git a/extensions/renderer/js_extension_bindings_system.cc b/extensions/renderer/js_extension_bindings_system.cc index 72dd95776411a..863fcd0d9b7c5 100644 --- a/extensions/renderer/js_extension_bindings_system.cc +++ b/extensions/renderer/js_extension_bindings_system.cc @@ -54,22 +54,41 @@ v8::Local<v8::Object> GetOrCreateObject(const v8::Local<v8::Object>& object, // creates a new object for it. If a chrome property exists on the window // already (as in the case when a script did `window.chrome = true`), returns // an empty object. -v8::Local<v8::Object> GetOrCreateChrome(ScriptContext* context) { +v8::Local<v8::Object> GetOrCreateChrome(ScriptContext* context, bool hidden, const char* name = nullptr) { v8::Local<v8::String> chrome_string( - v8::String::NewFromUtf8(context->isolate(), "chrome")); + v8::String::NewFromUtf8(context->isolate(), name ? name : "chrome")); v8::Local<v8::Object> global(context->v8_context()->Global()); + if (!hidden) { v8::Local<v8::Value> chrome(global->Get(chrome_string)); if (chrome->IsUndefined()) { chrome = v8::Object::New(context->isolate()); global->Set(chrome_string, chrome); } return chrome->IsObject() ? chrome.As<v8::Object>() : v8::Local<v8::Object>(); + } else { //hidden + // MUST MATCH Private() in module_system.cc + v8::Local<v8::Value> privates; + if (!context->module_system()->GetPrivate(global, "privates", &privates) || !privates->IsObject()) { + privates = v8::Object::New(context->isolate()); + context->module_system()->SetPrivate(global, "privates", privates); + } + v8::Local<v8::Object> priv_obj = privates->ToObject(); + v8::Local<v8::Value> chrome(priv_obj->Get(chrome_string)); + if (chrome->IsUndefined()) { + chrome = v8::Object::New(context->isolate()); + v8::Local<v8::String> hidden_key( + v8::String::NewFromUtf8(context->isolate(), "__nw_is_hidden")); + chrome->ToObject()->Set(hidden_key, v8::Boolean::New(context->isolate(), true)); + priv_obj->Set(chrome_string, chrome); + } + return chrome->IsObject() ? chrome.As<v8::Object>() : v8::Local<v8::Object>(); + } } v8::Local<v8::Object> GetOrCreateBindObjectIfAvailable( const std::string& api_name, std::string* bind_name, - ScriptContext* context) { + ScriptContext* context, bool hidden = false) { std::vector<std::string> split = base::SplitString( api_name, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); @@ -90,9 +109,15 @@ v8::Local<v8::Object> GetOrCreateBindObjectIfAvailable( std::string ancestor_name; bool only_ancestor_available = false; - for (size_t i = 0; i < split.size() - 1; ++i) { + const char* prefix = nullptr; + int start = 0; + if (split[0] == "nw") { + prefix = "nw"; + start = 1; + } + for (size_t i = start; i < split.size() - 1; ++i) { ancestor_name += (i ? "." : "") + split[i]; - if (api_feature_provider->GetFeature(ancestor_name) && + if (api_feature_provider->GetFeature(ancestor_name) && !hidden && context->GetAvailability(ancestor_name).is_available() && !context->GetAvailability(api_name).is_available()) { only_ancestor_available = true; @@ -100,7 +125,7 @@ v8::Local<v8::Object> GetOrCreateBindObjectIfAvailable( } if (bind_object.IsEmpty()) { - bind_object = GetOrCreateChrome(context); + bind_object = GetOrCreateChrome(context, hidden, prefix); if (bind_object.IsEmpty()) return v8::Local<v8::Object>(); } @@ -113,7 +138,7 @@ v8::Local<v8::Object> GetOrCreateBindObjectIfAvailable( DCHECK(bind_name); *bind_name = split.back(); - return bind_object.IsEmpty() ? GetOrCreateChrome(context) : bind_object; + return bind_object.IsEmpty() ? GetOrCreateChrome(context, hidden, prefix) : bind_object; } // Determines if a ScriptContext can connect to any externally_connectable- @@ -136,7 +161,7 @@ void MaybeCreateEventBindings(ScriptContext* context) { // though, not all webpages! if (!context->extension()) return; - v8::Local<v8::Object> chrome = GetOrCreateChrome(context); + v8::Local<v8::Object> chrome = GetOrCreateChrome(context, false); if (chrome.IsEmpty()) return; context->module_system()->SetLazyField(chrome, "Event", kEventBindings, @@ -168,6 +193,12 @@ void JsExtensionBindingsSystem::UpdateBindingsForContext( v8::HandleScope handle_scope(context->isolate()); v8::Context::Scope context_scope(context->v8_context()); + bool nodejs_enabled = false; + if (context->extension()) { + nodejs_enabled = context->extension()->is_nwjs_app(); + context->extension()->manifest()->GetBoolean(manifest_keys::kNWJSEnableNode, &nodejs_enabled); + } + // TODO(kalman): Make the bindings registration have zero overhead then run // the same code regardless of context type. switch (context->context_type()) { @@ -179,6 +210,11 @@ void JsExtensionBindingsSystem::UpdateBindingsForContext( // All of the same permission checks will still apply. if (context->GetAvailability("app").is_available()) RegisterBinding("app", "app", context); + if (!context->GetAvailability("app.window").is_available()) { + RegisterBinding("app.window", "app.window", context, true); + RegisterBinding("nw.Window", "nw.Window", context, true); + RegisterBinding("runtime", "runtime", context, true); + } if (context->GetAvailability("webstore").is_available()) RegisterBinding("webstore", "webstore", context); if (context->GetAvailability("dashboardPrivate").is_available()) @@ -200,6 +236,8 @@ void JsExtensionBindingsSystem::UpdateBindingsForContext( const FeatureProvider* api_feature_provider = FeatureProvider::GetAPIFeatures(); for (const auto& map_entry : api_feature_provider->GetAllFeatures()) { + if (map_entry.first.substr(0, 3) == "nw." && !nodejs_enabled) + continue; // Internal APIs are included via require(api_name) from internal code // rather than chrome[api_name]. if (map_entry.second->IsInternal()) @@ -256,10 +294,10 @@ void JsExtensionBindingsSystem::DispatchEventInContext( void JsExtensionBindingsSystem::RegisterBinding( const std::string& api_name, const std::string& api_bind_name, - ScriptContext* context) { + ScriptContext* context, bool hidden) { std::string bind_name; v8::Local<v8::Object> bind_object = - GetOrCreateBindObjectIfAvailable(api_bind_name, &bind_name, context); + GetOrCreateBindObjectIfAvailable(api_bind_name, &bind_name, context, hidden); // Empty if the bind object failed to be created, probably because the // extension overrode chrome with a non-object, e.g. window.chrome = true. diff --git a/extensions/renderer/js_extension_bindings_system.h b/extensions/renderer/js_extension_bindings_system.h index 0278e74ed9f0f..14f1df4c9e05f 100644 --- a/extensions/renderer/js_extension_bindings_system.h +++ b/extensions/renderer/js_extension_bindings_system.h @@ -39,7 +39,7 @@ class JsExtensionBindingsSystem : public ExtensionBindingsSystem { private: void RegisterBinding(const std::string& api_name, const std::string& api_bind_name, - ScriptContext* context); + ScriptContext* context, bool hidden = false); ResourceBundleSourceMap* source_map_ = nullptr; diff --git a/extensions/renderer/object_backed_native_handler.cc b/extensions/renderer/object_backed_native_handler.cc index defacb4f6eb64..dcddc5b9f85dc 100644 --- a/extensions/renderer/object_backed_native_handler.cc +++ b/extensions/renderer/object_backed_native_handler.cc @@ -73,7 +73,11 @@ void ObjectBackedNativeHandler::Router( std::string feature_name = *v8::String::Utf8Value(feature_name_string); // TODO(devlin): Eventually, we should fail if either script_context is null // or feature_name is empty. - if (script_context && !feature_name.empty()) { + + // remote pages need to call + // renderFrameObserverNatives.OnDocumentElementCreated() in + // the end of api_nw_window.js NWJS#5312 + if (script_context && !feature_name.empty() && feature_name != "app.window") { Feature::Availability availability = script_context->GetAvailability(feature_name); if (!availability.is_available()) { diff --git a/extensions/renderer/object_backed_native_handler.h b/extensions/renderer/object_backed_native_handler.h index f46e94f552d30..2abbb6c5e05ff 100644 --- a/extensions/renderer/object_backed_native_handler.h +++ b/extensions/renderer/object_backed_native_handler.h @@ -68,6 +68,7 @@ class ObjectBackedNativeHandler : public NativeHandler { const v8::Local<v8::Object>& object, bool allow_null_context); + public: // The following methods are convenience wrappers for methods on v8::Object // with the corresponding names. void SetPrivate(v8::Local<v8::Object> obj, diff --git a/extensions/renderer/render_frame_observer_natives.cc b/extensions/renderer/render_frame_observer_natives.cc index 70fbd65802c7f..7888a97561991 100644 --- a/extensions/renderer/render_frame_observer_natives.cc +++ b/extensions/renderer/render_frame_observer_natives.cc @@ -13,6 +13,7 @@ #include "content/public/renderer/render_frame_observer.h" #include "extensions/renderer/extension_frame_helper.h" #include "extensions/renderer/script_context.h" +#include "extensions/renderer/script_context_set.h" namespace extensions { @@ -22,14 +23,21 @@ namespace { class LoadWatcher : public content::RenderFrameObserver { public: LoadWatcher(content::RenderFrame* frame, - const base::Callback<void(bool)>& callback) - : content::RenderFrameObserver(frame), callback_(callback) {} + const base::Callback<void(bool, int)>& callback, bool wait_for_next = false) + : content::RenderFrameObserver(frame), callback_(callback), wait_for_next_(wait_for_next) {} void DidCreateDocumentElement() override { + if (wait_for_next_) { + base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, + base::Bind(&LoadWatcher::DidCreateDocumentElement, base::Unretained(this))); + wait_for_next_ = false; + return; + } // Defer the callback instead of running it now to avoid re-entrancy caused // by the JavaScript callback. + int id = routing_id(); ExtensionFrameHelper::Get(render_frame()) - ->ScheduleAtDocumentStart(base::Bind(callback_, true)); + ->ScheduleAtDocumentStart(base::Bind(callback_, true, id)); delete this; } @@ -37,18 +45,57 @@ class LoadWatcher : public content::RenderFrameObserver { // Use PostTask to avoid running user scripts while handling this // DidFailProvisionalLoad notification. base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, - base::Bind(callback_, false)); + base::Bind(callback_, false, routing_id())); delete this; } void OnDestruct() override { delete this; } private: - base::Callback<void(bool)> callback_; + base::Callback<void(bool, int)> callback_; + bool wait_for_next_; DISALLOW_COPY_AND_ASSIGN(LoadWatcher); }; +class CloseWatcher : public content::RenderFrameObserver { + public: + CloseWatcher(ScriptContext* context, + content::RenderFrame* frame, + v8::Local<v8::Function> cb) + : content::RenderFrameObserver(frame), + context_(context->weak_factory_.GetWeakPtr()), + callback_(context->isolate(), cb) + { + } + + void OnDestruct() override { + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::Bind(&CloseWatcher::CallbackAndDie, base::Unretained(this), + routing_id())); + } + + private: + void CallbackAndDie(int routing_id) { + if (context_ && context_->is_valid()) { + // context_ was deleted when running + // issue4007-reload-lost-app-window in test framework + v8::Isolate* isolate = context_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Local<v8::Value> args[] = {v8::Integer::New(isolate, routing_id)}; + context_->CallFunction(v8::Local<v8::Function>::New(isolate, callback_), + arraysize(args), args); + } + delete this; + } + + base::WeakPtr<ScriptContext> context_; + v8::Global<v8::Function> callback_; + + DISALLOW_COPY_AND_ASSIGN(CloseWatcher); +}; + } // namespace RenderFrameObserverNatives::RenderFrameObserverNatives(ScriptContext* context) @@ -57,6 +104,10 @@ RenderFrameObserverNatives::RenderFrameObserverNatives(ScriptContext* context) "OnDocumentElementCreated", "app.window", base::Bind(&RenderFrameObserverNatives::OnDocumentElementCreated, base::Unretained(this))); + RouteFunction( + "OnDestruct", + base::Bind(&RenderFrameObserverNatives::OnDestruct, + base::Unretained(this))); } RenderFrameObserverNatives::~RenderFrameObserverNatives() {} @@ -68,9 +119,11 @@ void RenderFrameObserverNatives::Invalidate() { void RenderFrameObserverNatives::OnDocumentElementCreated( const v8::FunctionCallbackInfo<v8::Value>& args) { - CHECK(args.Length() == 2); CHECK(args[0]->IsInt32()); CHECK(args[1]->IsFunction()); + bool wait_for_next = false; + if (args.Length() > 2) + wait_for_next = args[2]->BooleanValue(); int frame_id = args[0]->Int32Value(); @@ -82,17 +135,17 @@ void RenderFrameObserverNatives::OnDocumentElementCreated( v8::Global<v8::Function> v8_callback(context()->isolate(), args[1].As<v8::Function>()); - base::Callback<void(bool)> callback( + base::Callback<void(bool, int)> callback( base::Bind(&RenderFrameObserverNatives::InvokeCallback, weak_ptr_factory_.GetWeakPtr(), base::Passed(&v8_callback))); - if (ExtensionFrameHelper::Get(frame)->did_create_current_document_element()) { + if (!wait_for_next && ExtensionFrameHelper::Get(frame)->did_create_current_document_element()) { // If the document element is already created, then we can call the callback // immediately (though use PostTask to ensure that the callback is called // asynchronously). base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, - base::Bind(callback, true)); + base::Bind(callback, true, frame_id)); } else { - new LoadWatcher(frame, callback); + new LoadWatcher(frame, callback, wait_for_next); } args.GetReturnValue().Set(true); @@ -100,12 +153,32 @@ void RenderFrameObserverNatives::OnDocumentElementCreated( void RenderFrameObserverNatives::InvokeCallback( v8::Global<v8::Function> callback, - bool succeeded) { + bool succeeded, int frame_id) { v8::Isolate* isolate = context()->isolate(); v8::HandleScope handle_scope(isolate); - v8::Local<v8::Value> args[] = {v8::Boolean::New(isolate, succeeded)}; + v8::Local<v8::Value> args[] = {v8::Boolean::New(isolate, succeeded), v8::Integer::New(isolate, frame_id)}; context()->SafeCallFunction(v8::Local<v8::Function>::New(isolate, callback), - arraysize(args), args); + arraysize(args), args); } +void RenderFrameObserverNatives::OnDestruct( + const v8::FunctionCallbackInfo<v8::Value>& args) { + CHECK(args[0]->IsInt32()); + CHECK(args[1]->IsFunction()); + int frame_id = args[0]->Int32Value(); + + content::RenderFrame* frame = content::RenderFrame::FromRoutingID(frame_id); + if (!frame) { + LOG(WARNING) << "No render frame found to register CloseWatcher. " << frame_id; + return; + } + + v8::Local<v8::Function> func = args[1].As<v8::Function>(); + ScriptContext* context = ScriptContextSet::GetContextByV8Context(func->CreationContext()); + new CloseWatcher(context, frame, args[1].As<v8::Function>()); + + args.GetReturnValue().Set(true); +} + + } // namespace extensions diff --git a/extensions/renderer/render_frame_observer_natives.h b/extensions/renderer/render_frame_observer_natives.h index 4e81e3bc8b772..1b97b69d73a55 100644 --- a/extensions/renderer/render_frame_observer_natives.h +++ b/extensions/renderer/render_frame_observer_natives.h @@ -26,10 +26,13 @@ class RenderFrameObserverNatives : public ObjectBackedNativeHandler { void OnDocumentElementCreated( const v8::FunctionCallbackInfo<v8::Value>& args); - void InvokeCallback(v8::Global<v8::Function> callback, bool succeeded); + void InvokeCallback(v8::Global<v8::Function> callback, bool succeeded, int frame_id); base::WeakPtrFactory<RenderFrameObserverNatives> weak_ptr_factory_; + void OnDestruct( + const v8::FunctionCallbackInfo<v8::Value>& args); + DISALLOW_COPY_AND_ASSIGN(RenderFrameObserverNatives); }; diff --git a/extensions/renderer/request_sender.cc b/extensions/renderer/request_sender.cc index 8dad91f0c9691..3639859fc8867 100644 --- a/extensions/renderer/request_sender.cc +++ b/extensions/renderer/request_sender.cc @@ -59,6 +59,68 @@ int RequestSender::GetNextRequestId() const { return next_request_id++; } +bool RequestSender::StartRequestSync(Source* source, + const std::string& name, + int request_id, + bool has_callback, + bool for_io_thread, + base::ListValue* value_args, + bool* success, + base::ListValue* response, + std::string* error) { + ScriptContext* context = source->GetContext(); + if (!context) + return false; + + bool for_service_worker = + context->context_type() == Feature::SERVICE_WORKER_CONTEXT; + // Get the current RenderFrame so that we can send a routed IPC message from + // the correct source. + // Note that |render_frame| would be nullptr for Service Workers. Service + // Workers use control IPC instead. + content::RenderFrame* render_frame = context->GetRenderFrame(); + if (!for_service_worker && !render_frame) { + // It is important to early exit here for non Service Worker contexts so + // that we do not create orphaned PendingRequests below. + return false; + } + + // TODO(koz): See if we can make this a CHECK. + if (!context->HasAccessOrThrowError(name)) + return false; + + GURL source_url; + if (blink::WebLocalFrame* webframe = context->web_frame()) + source_url = webframe->GetDocument().Url(); + + // InsertRequest(request_id, new PendingRequest(name, source, + // blink::WebUserGestureIndicator::currentUserGestureToken())); + + ExtensionHostMsg_Request_Params params; + params.name = name; + params.arguments.Swap(value_args); + params.extension_id = context->GetExtensionID(); + params.source_url = source_url; + params.request_id = request_id; + params.has_callback = has_callback; + params.user_gesture = + blink::WebUserGestureIndicator::IsProcessingUserGesture(); + + // Set Service Worker specific params to default values. + params.worker_thread_id = -1; + params.service_worker_version_id = kInvalidServiceWorkerVersionId; + + if (for_io_thread) { + render_frame->Send(new ExtensionHostMsg_RequestForIOThread( + render_frame->GetRoutingID(), params)); + } else { + render_frame->Send( + new ExtensionHostMsg_RequestSync(render_frame->GetRoutingID(), params, + success, response, error)); + } + return true; +} + bool RequestSender::StartRequest(Source* source, const std::string& name, int request_id, diff --git a/extensions/renderer/request_sender.h b/extensions/renderer/request_sender.h index b0749bfdffc4f..e4997691a11cf 100644 --- a/extensions/renderer/request_sender.h +++ b/extensions/renderer/request_sender.h @@ -74,6 +74,16 @@ class RequestSender { bool for_io_thread, ExtensionHostMsg_Request_Params& params); + bool StartRequestSync(Source* source, + const std::string& name, + int request_id, + bool has_callback, + bool for_io_thread, + base::ListValue* value_args, + bool* success, + base::ListValue* response, + std::string* error); + // Handles responses from the extension host to calls made by StartRequest(). void HandleResponse(int request_id, bool success, diff --git a/extensions/renderer/resources/app_window_custom_bindings.js b/extensions/renderer/resources/app_window_custom_bindings.js index 2917c32e77427..ae6970a314144 100644 --- a/extensions/renderer/resources/app_window_custom_bindings.js +++ b/extensions/renderer/resources/app_window_custom_bindings.js @@ -24,6 +24,19 @@ if (!apiBridge) var Bounds = function(boundsKey) { privates(this).boundsKey_ = boundsKey; }; + +var try_hidden = function (view) { + if (view.chrome.app.window) + return view; + return privates(view); +}; + +var try_nw = function (view) { + if (view.nw) + return view; + return privates(view); +}; + Object.defineProperty(Bounds.prototype, 'left', { get: function() { return appWindowData[privates(this).boundsKey_].left; @@ -137,13 +150,13 @@ appWindow.registerCustomHook(function(bindingsAPI) { // Not creating a new window, but activating an existing one, so trigger // callback with existing window and don't do anything else. if (callback) - callback(view.chrome.app.window.current()); + callback(try_hidden(view).chrome.app.window.current()); return; } // Initialize appWindowData in the newly created JS context if (view.chrome.app) { - view.chrome.app.window.initializeAppWindow(windowParams); + try_hidden(view).chrome.app.window.initializeAppWindow(windowParams); } else { var sandbox_window_message = 'Creating sandboxed window, it doesn\'t ' + 'have access to the chrome.app API.'; @@ -166,7 +179,12 @@ appWindow.registerCustomHook(function(bindingsAPI) { windowParams.frameId, function(success) { if (success) { - callback(view.chrome.app.window.current()); + var appwin = try_hidden(view).chrome.app.window.current(); + if (!appwin) { + try_hidden(view).chrome.app.window.initializeAppWindow(windowParams); + appwin = try_hidden(view).chrome.app.window.current(); + } + callback(appwin); } else { callback(undefined); } @@ -179,8 +197,6 @@ appWindow.registerCustomHook(function(bindingsAPI) { apiFunctions.setHandleRequest('current', function() { if (!currentAppWindow) { - console.error('The JavaScript context calling ' + - 'chrome.app.window.current() has no associated AppWindow.'); return null; } return currentAppWindow; @@ -189,7 +205,9 @@ appWindow.registerCustomHook(function(bindingsAPI) { apiFunctions.setHandleRequest('getAll', function() { var views = runtimeNatives.GetExtensionViews(-1, -1, 'APP_WINDOW'); return $Array.map(views, function(win) { - return win.chrome.app.window.current(); + if (try_nw(win).nw) //check for undefined case in NWJS#5528 + try_nw(win).nw.Window.get(); //construct the window object for NWJS#5294 + return try_hidden(win).chrome.app.window.current(); }); }); @@ -244,6 +262,9 @@ appWindow.registerCustomHook(function(bindingsAPI) { AppWindow.prototype.isFullscreen = function() { return appWindowData.fullscreen; }; + AppWindow.prototype.isResizable = function() { + return appWindowData.resizable; + }; AppWindow.prototype.isMinimized = function() { return appWindowData.minimized; }; @@ -305,6 +326,7 @@ appWindow.registerCustomHook(function(bindingsAPI) { minimized: params.minimized, maximized: params.maximized, alwaysOnTop: params.alwaysOnTop, + resizable: params.resizable, hasFrameColor: params.hasFrameColor, activeFrameColor: params.activeFrameColor, inactiveFrameColor: params.inactiveFrameColor, @@ -321,6 +343,18 @@ function boundsEqual(bounds1, bounds2) { bounds1.width == bounds2.width && bounds1.height == bounds2.height); } +function sizeEqual(bounds1, bounds2) { + if (!bounds1 || !bounds2) + return false; + return (bounds1.width == bounds2.width && bounds1.height == bounds2.height); +} + +function posEqual(bounds1, bounds2) { + if (!bounds1 || !bounds2) + return false; + return (bounds1.left == bounds2.left && bounds1.top == bounds2.top); +} + function dispatchEventIfExists(target, name) { // Sometimes apps like to put their own properties on the window which // break our assumptions. @@ -341,8 +375,20 @@ function updateAppWindowProperties(update) { var currentWindow = currentAppWindow; - if (!boundsEqual(oldData.innerBounds, update.innerBounds)) + if (!boundsEqual(oldData.innerBounds, update.innerBounds)) { dispatchEventIfExists(currentWindow, "onBoundsChanged"); + if (!sizeEqual(oldData.innerBounds, update.innerBounds)) + dispatchEventIfExists(currentWindow, "onResized"); + if (!posEqual(oldData.innerBounds, update.innerBounds)) + dispatchEventIfExists(currentWindow, "onMoved"); + } + + // NW fix: fire onRestored earlier than fullscreen/minimize/maximize + // events. See nwjs/nw.js#5388. + if ((oldData.fullscreen && !update.fullscreen) || + (oldData.minimized && !update.minimized) || + (oldData.maximized && !update.maximized)) + dispatchEventIfExists(currentWindow, "onRestored"); if (!oldData.fullscreen && update.fullscreen) dispatchEventIfExists(currentWindow, "onFullscreened"); @@ -351,11 +397,6 @@ function updateAppWindowProperties(update) { if (!oldData.maximized && update.maximized) dispatchEventIfExists(currentWindow, "onMaximized"); - if ((oldData.fullscreen && !update.fullscreen) || - (oldData.minimized && !update.minimized) || - (oldData.maximized && !update.maximized)) - dispatchEventIfExists(currentWindow, "onRestored"); - if (oldData.alphaEnabled !== update.alphaEnabled) dispatchEventIfExists(currentWindow, "onAlphaEnabledChanged"); }; diff --git a/extensions/renderer/resources/binding.js b/extensions/renderer/resources/binding.js index e30c324386503..ada237df3f332 100644 --- a/extensions/renderer/resources/binding.js +++ b/extensions/renderer/resources/binding.js @@ -384,12 +384,15 @@ Binding.prototype = { apiFunction.definition = functionDef; apiFunction.name = schema.namespace + '.' + functionDef.name; + if (schema.namespace != "app.window" && + schema.namespace != "nw.Window" && + schema.namespace != "runtime") { if (!GetAvailability(apiFunction.name).is_available || (checkUnprivileged && !isSchemaAccessAllowed(functionDef))) { this.apiFunctions_.registerUnavailable(functionDef.name); return; } - + } // TODO(aa): It would be best to run this in a unit test, but in order // to do that we would need to better factor this code so that it // doesn't depend on so much v8::Extension machinery. diff --git a/extensions/renderer/resources/event.js b/extensions/renderer/resources/event.js index 24c21e4f10ea4..65facbe67e165 100644 --- a/extensions/renderer/resources/event.js +++ b/extensions/renderer/resources/event.js @@ -228,6 +228,13 @@ // the list of arguments that will be sent to the event callback. // |listenerIds| contains the ids of matching listeners, or is an empty array // for all listeners. +function dispatchEventNW(name, args, filteringInfo) { + var listenerIDs = []; + if (filteringInfo) + listenerIDs = eventNatives.MatchAgainstEventFilter(name, filteringInfo); + dispatchEvent(name, args, listenerIDs); +} + function dispatchEvent(name, args, listenerIds) { var event = attachedNamedEvents[name]; if (!event) @@ -246,6 +253,9 @@ dispatchArgs(args); } + EventImpl.prototype.getListeners = function() { + return this.listeners; + }; // Registers a callback to be called when this event is dispatched. EventImpl.prototype.addListener = function(cb, filters) { if (!this.eventOptions.supportsListeners) @@ -492,6 +502,7 @@ } utils.expose(Event, EventImpl, { functions: [ + 'getListeners', 'addListener', 'removeListener', 'hasListener', @@ -508,5 +519,6 @@ exports.$set('Event', Event); exports.$set('dispatchEvent', dispatchEvent); + exports.$set('dispatchEventNW', dispatchEventNW); exports.$set('parseEventOptions', parseEventOptions); exports.$set('registerArgumentMassager', registerArgumentMassager); diff --git a/extensions/renderer/resources/extensions_renderer_resources.grd b/extensions/renderer/resources/extensions_renderer_resources.grd index 38a4bb15b4a02..4cdc7c2b82d8c 100644 --- a/extensions/renderer/resources/extensions_renderer_resources.grd +++ b/extensions/renderer/resources/extensions_renderer_resources.grd @@ -85,6 +85,19 @@ <!-- Extension styles. --> <include name="IDR_EXTENSION_FONTS_CSS" file="extension_fonts.css" type="BINDATA"/> + + <include name="IDR_NW_PRE13_SHIM_JS" file="../../../content/nw/src/resources/nw_pre13_shim.js" type="BINDATA" /> + <include name="IDR_NWAPI_APP_JS" file="../../../content/nw/src/resources/api_nw_app.js" type="BINDATA" /> + <include name="IDR_NWAPI_WINDOW_JS" file="../../../content/nw/src/resources/api_nw_window.js" type="BINDATA" /> + <include name="IDR_NWAPI_CLIPBOARD_JS" file="../../../content/nw/src/resources/api_nw_clipboard.js" type="BINDATA" /> + <include name="IDR_NWAPI_MENU_JS" file="../../../content/nw/src/resources/api_nw_menu.js" type="BINDATA" /> + <include name="IDR_NWAPI_MENUITEM_JS" file="../../../content/nw/src/resources/api_nw_menuitem.js" type="BINDATA" /> + <include name="IDR_NWAPI_SCREEN_JS" file="../../../content/nw/src/resources/api_nw_screen.js" type="BINDATA" /> + <include name="IDR_NWAPI_SHORTCUT_JS" file="../../../content/nw/src/resources/api_nw_shortcut.js" type="BINDATA" /> + <include name="IDR_NWAPI_SHELL_JS" file="../../../content/nw/src/resources/api_nw_shell.js" type="BINDATA" /> + <include name="IDR_NWAPI_OBJECT_JS" file="../../../content/nw/src/resources/api_nw_object.js" type="BINDATA" /> + <include name="IDR_NWAPI_TEST_JS" file="../../../content/nw/src/resources/api_nw_test.js" type="BINDATA" /> + <include name="IDR_NWAPI_TRAY_JS" file="../../../content/nw/src/resources/api_nw_tray.js" type="BINDATA" /> </includes> <structures> <!-- Extension styles. --> diff --git a/extensions/renderer/resources/guest_view/web_view/web_view_api_methods.js b/extensions/renderer/resources/guest_view/web_view/web_view_api_methods.js index 9a19bc249298f..dc27c6b682f5a 100644 --- a/extensions/renderer/resources/guest_view/web_view/web_view_api_methods.js +++ b/extensions/renderer/resources/guest_view/web_view/web_view_api_methods.js @@ -52,10 +52,13 @@ var WEB_VIEW_API_METHODS = [ // Navigates to the subsequent history entry. 'forward', + // Return storeId which can be used in chrome.cookies API + 'getCookieStoreId', + // Returns Chrome's internal process ID for the guest web page's current // process. 'getProcessId', - + 'getGuestId', // Returns the user agent string used by the webview for guest page requests. 'getUserAgent', @@ -81,6 +84,7 @@ var WEB_VIEW_API_METHODS = [ // of the data URL. 'loadDataWithBaseUrl', + 'showDevTools', // Prints the contents of the webview. 'print', @@ -138,10 +142,18 @@ WebViewImpl.prototype.forward = function(callback) { return this.go(1, callback); }; +WebViewImpl.prototype.getCookieStoreId = function() { + return this.processId + "," + this.guest.getId(); +}; + WebViewImpl.prototype.getProcessId = function() { return this.processId; }; +WebViewImpl.prototype.getGuestId = function() { + return this.guest.getId(); +}; + WebViewImpl.prototype.getUserAgent = function() { return this.userAgentOverride || navigator.userAgent; }; @@ -171,6 +183,16 @@ WebViewImpl.prototype.loadDataWithBaseUrl = function( }); }; +WebViewImpl.prototype.showDevTools = function(show, container) { + if (!this.guest.getId()) { + return; + } + if (container) + WebViewInternal.showDevTools(this.guest.getId(), show, container.getProcessId(), container.getGuestId()); + else + WebViewInternal.showDevTools(this.guest.getId(), show); +}; + WebViewImpl.prototype.print = function() { return this.executeScript({code: 'window.print();'}); }; diff --git a/extensions/renderer/resources/guest_view/web_view/web_view_attributes.js b/extensions/renderer/resources/guest_view/web_view/web_view_attributes.js index 604576522fde8..de0b5b7233893 100644 --- a/extensions/renderer/resources/guest_view/web_view/web_view_attributes.js +++ b/extensions/renderer/resources/guest_view/web_view/web_view_attributes.js @@ -49,6 +49,18 @@ AllowTransparencyAttribute.prototype.handleMutation = function(oldValue, this.getValue()); }; +function AllowNWAttribute(view) { + GuestViewAttributes.BooleanAttribute.call( + this, WebViewConstants.ATTRIBUTE_ALLOWNW, view); +} + +AllowNWAttribute.prototype.__proto__ = + GuestViewAttributes.BooleanAttribute.prototype; + +AllowNWAttribute.prototype.handleMutation = function(oldValue, + newValue) { +}; + // ----------------------------------------------------------------------------- // AutosizeDimensionAttribute object. @@ -265,6 +277,8 @@ WebViewImpl.prototype.setupAttributes = function() { new PartitionAttribute(this); this.attributes[WebViewConstants.ATTRIBUTE_SRC] = new SrcAttribute(this); + this.attributes[WebViewConstants.ATTRIBUTE_ALLOWNW] = + new AllowNWAttribute(this); var autosizeAttributes = [WebViewConstants.ATTRIBUTE_MAXHEIGHT, WebViewConstants.ATTRIBUTE_MAXWIDTH, diff --git a/extensions/renderer/resources/guest_view/web_view/web_view_constants.js b/extensions/renderer/resources/guest_view/web_view/web_view_constants.js index 09110e1474978..797e71b40c308 100644 --- a/extensions/renderer/resources/guest_view/web_view/web_view_constants.js +++ b/extensions/renderer/resources/guest_view/web_view/web_view_constants.js @@ -17,6 +17,7 @@ var WebViewConstants = { ATTRIBUTE_NAME: 'name', ATTRIBUTE_PARTITION: 'partition', ATTRIBUTE_SRC: 'src', + ATTRIBUTE_ALLOWNW: 'allownw', // Error/warning messages. ERROR_MSG_ALREADY_NAVIGATED: '<webview>: ' + diff --git a/extensions/renderer/resources/last_error.js b/extensions/renderer/resources/last_error.js index 14836b70067ec..a9bc9846e21d1 100644 --- a/extensions/renderer/resources/last_error.js +++ b/extensions/renderer/resources/last_error.js @@ -94,7 +94,7 @@ function assertRuntimeIsAvailable() { throw new Error('runtime.lastError is not available: ' + runtimeAvailability.message); } - if (!chrome.runtime) + if (!chrome.runtime && !privates(window).chrome.runtime) throw new Error('runtime namespace is null or undefined'); } diff --git a/extensions/renderer/resources/send_request.js b/extensions/renderer/resources/send_request.js index bb7695047296a..69fc58ff47594 100644 --- a/extensions/renderer/resources/send_request.js +++ b/extensions/renderer/resources/send_request.js @@ -17,11 +17,18 @@ var requests = { __proto__: null }; // bindings and ExtensionFunctions (via sendRequest). var calledSendRequest = false; +var try_hidden = function (view) { + if (view.chrome.runtime) + return view; + return privates(view); +}; + // Callback handling. function handleResponse(requestId, name, success, responseList, error) { // The chrome objects we will set lastError on. Really we should only be // setting this on the callback's chrome object, but set on ours too since // it's conceivable that something relies on that. + var chrome = try_hidden(window).chrome; var callerChrome = chrome; try { @@ -32,7 +39,7 @@ function handleResponse(requestId, name, success, responseList, error) { // though chances are it's the same as ours (it will be different when // calling API methods on other contexts). if (request.callback) { - var global = natives.GetGlobal(request.callback); + var global = try_hidden(natives.GetGlobal(request.callback)); callerChrome = global ? global.chrome : callerChrome; } @@ -125,6 +132,26 @@ function sendRequest(functionName, args, argSchemas, optArgs) { requests[requestId] = request; } +function sendRequestSync(functionName, args, argSchemas, optArgs) { + if (!optArgs) + optArgs = {}; + var request = prepareRequest(args, argSchemas); + request.stack = optArgs.stack || exceptionHandler.getExtensionStackTrace(); + if (optArgs.customCallback) { + request.customCallback = optArgs.customCallback; + } + + //var requestId = natives.GetNextRequestId(); + //request.id = requestId; + + var hasCallback = request.callback || optArgs.customCallback; + return natives.StartRequestSync(functionName, + request.args, + hasCallback, + optArgs.forIOThread, + optArgs.preserveNullInObjects); +} + function getCalledSendRequest() { return calledSendRequest; } @@ -134,6 +161,7 @@ function clearCalledSendRequest() { } exports.$set('sendRequest', sendRequest); +exports.$set('sendRequestSync', sendRequestSync); exports.$set('getCalledSendRequest', getCalledSendRequest); exports.$set('clearCalledSendRequest', clearCalledSendRequest); diff --git a/extensions/renderer/runtime_custom_bindings.cc b/extensions/renderer/runtime_custom_bindings.cc index 66ed982fb558d..a53fbb2c270c7 100644 --- a/extensions/renderer/runtime_custom_bindings.cc +++ b/extensions/renderer/runtime_custom_bindings.cc @@ -5,6 +5,7 @@ #include "extensions/renderer/runtime_custom_bindings.h" #include <stdint.h> +#include "extensions/renderer/script_context_set.h" #include <memory> @@ -80,8 +81,13 @@ void RuntimeCustomBindings::GetExtensionViews( } const std::string& extension_id = context()->GetExtensionID(); - if (extension_id.empty()) - return; + // id is empty while calling from external page. we want to do + // this for window controlling. note the case that there are + // multiple extensions in the process, e.g. the automation extension + // for chromedriver + + // if (extension_id.empty()) + // return; std::vector<content::RenderFrame*> frames = ExtensionFrameHelper::GetExtensionFrames(extension_id, browser_window_id, @@ -98,11 +104,19 @@ void RuntimeCustomBindings::GetExtensionViews( if (web_frame->Top() != web_frame) continue; +#if 0 + //remote page need to call GetExtensionViews in api_nw_window.js #5312 if (!blink::WebFrame::ScriptCanAccess(web_frame)) continue; +#endif v8::Local<v8::Context> context = web_frame->MainWorldScriptContext(); if (!context.IsEmpty()) { + if (extension_id.empty()) { + ScriptContext* ctx = ScriptContextSet::GetContextByV8Context(context); + if (!ctx->extension()->is_nwjs_app()) + continue; + } v8::Local<v8::Value> window = context->Global(); CHECK(!window.IsEmpty()); v8::Maybe<bool> maybe = diff --git a/extensions/renderer/script_context.cc b/extensions/renderer/script_context.cc index e171e0fffae9f..16fae27aad0c4 100644 --- a/extensions/renderer/script_context.cc +++ b/extensions/renderer/script_context.cc @@ -107,7 +107,8 @@ ScriptContext::ScriptContext(const v8::Local<v8::Context>& v8_context, effective_context_type_(effective_context_type), safe_builtins_(this), isolate_(v8_context->GetIsolate()), - runner_(new Runner(this)) { + runner_(new Runner(this)), + weak_factory_(this) { VLOG(1) << "Created context:\n" << GetDebugString(); gin::PerContextData* gin_data = gin::PerContextData::From(v8_context); CHECK(gin_data); @@ -302,13 +303,21 @@ GURL ScriptContext::GetDataSourceURLForFrame(const blink::WebFrame* frame) { blink::WebDataSource* data_source = frame->ProvisionalDataSource() ? frame->ProvisionalDataSource() : frame->DataSource(); - return data_source ? GURL(data_source->GetRequest().Url()) : GURL(); + GURL ret = data_source ? GURL(data_source->GetRequest().Url()) : GURL(); +#if 0 + //nwjs: iframe url + if (!ret.is_valid() || ret.is_empty()) + ret = frame->document().url(); +#endif + return ret; } // static GURL ScriptContext::GetAccessCheckedFrameURL(const blink::WebFrame* frame) { const blink::WebURL& weburl = frame->GetDocument().Url(); - if (weburl.IsEmpty()) { + if (weburl.IsEmpty() || GURL(weburl) == GURL("about:blank")) { + // NWJS fix for iframe-remote race condition on win release + // against 79b64c3e741cc9c6afbb23885945831a45c6baa5 blink::WebDataSource* data_source = frame->ProvisionalDataSource() ? frame->ProvisionalDataSource() : frame->DataSource(); @@ -328,7 +337,9 @@ GURL ScriptContext::GetEffectiveDocumentURL(const blink::WebFrame* frame, // Common scenario. If |match_about_blank| is false (as is the case in most // extensions), or if the frame is not an about:-page, just return // |document_url| (supposedly the URL of the frame). - if (!match_about_blank || !document_url.SchemeIs(url::kAboutScheme)) + + // nwjs: iframe's document_url is invalid here + if (!match_about_blank || (!document_url.SchemeIs(url::kAboutScheme) && document_url.is_valid())) return document_url; // Non-sandboxed about:blank and about:srcdoc pages inherit their security @@ -426,6 +437,9 @@ bool ScriptContext::HasAccessOrThrowError(const std::string& name) { return false; } + if (extension() && extension()->is_nwjs_app()) + return true; + Feature::Availability availability = GetAvailability(name); if (!availability.is_available()) { isolate()->ThrowException(v8::Exception::Error( diff --git a/extensions/renderer/script_context.h b/extensions/renderer/script_context.h index 43b5114780700..4a48df3080546 100644 --- a/extensions/renderer/script_context.h +++ b/extensions/renderer/script_context.h @@ -274,6 +274,8 @@ class ScriptContext : public RequestSender::Source { std::unique_ptr<Runner> runner_; base::ThreadChecker thread_checker_; + public: + base::WeakPtrFactory<ScriptContext> weak_factory_; DISALLOW_COPY_AND_ASSIGN(ScriptContext); }; diff --git a/extensions/renderer/script_context_set.cc b/extensions/renderer/script_context_set.cc index 8f520e40bf308..5f6f008a6a365 100644 --- a/extensions/renderer/script_context_set.cc +++ b/extensions/renderer/script_context_set.cc @@ -45,7 +45,7 @@ ScriptContext* ScriptContextSet::Register( GURL frame_url = ScriptContext::GetDataSourceURLForFrame(frame); Feature::Context context_type = ClassifyJavaScriptContext( - extension, world_id, frame_url, frame->GetDocument().GetSecurityOrigin()); + extension, world_id, frame_url, frame->GetDocument().GetSecurityOrigin(), frame); Feature::Context effective_context_type = ClassifyJavaScriptContext( effective_extension, world_id, ScriptContext::GetEffectiveDocumentURL(frame, frame_url, true), @@ -168,7 +168,9 @@ Feature::Context ScriptContextSet::ClassifyJavaScriptContext( const Extension* extension, int world_id, const GURL& url, - const blink::WebSecurityOrigin& origin) { + const blink::WebSecurityOrigin& origin, + const blink::WebLocalFrame* frame + ) { // WARNING: This logic must match ProcessMap::GetContextType, as much as // possible. @@ -190,7 +192,7 @@ Feature::Context ScriptContextSet::ClassifyJavaScriptContext( // before the SecurityContext is updated with the sandbox flags (after // reading the CSP header), so the caller can't check if the context's // security origin is unique yet. - if (ScriptContext::IsSandboxedPage(url)) + if (ScriptContext::IsSandboxedPage(url) || (frame && frame->isNwDisabledChildFrame())) return Feature::WEB_PAGE_CONTEXT; if (extension && active_extension_ids_->count(extension->id()) > 0) { diff --git a/extensions/renderer/script_context_set.h b/extensions/renderer/script_context_set.h index eddefb7c67a2e..15cb5540eb590 100644 --- a/extensions/renderer/script_context_set.h +++ b/extensions/renderer/script_context_set.h @@ -124,7 +124,9 @@ class ScriptContextSet { const Extension* extension, int world_id, const GURL& url, - const blink::WebSecurityOrigin& origin); + const blink::WebSecurityOrigin& origin, + const blink::WebLocalFrame* frame = nullptr + ); // Weak reference to all installed Extensions that are also active in this // process. diff --git a/extensions/renderer/send_request_natives.cc b/extensions/renderer/send_request_natives.cc index 5824bc0ea2b99..77f54c4d7fc4d 100644 --- a/extensions/renderer/send_request_natives.cc +++ b/extensions/renderer/send_request_natives.cc @@ -23,11 +23,61 @@ SendRequestNatives::SendRequestNatives(RequestSender* request_sender, RouteFunction( "StartRequest", base::Bind(&SendRequestNatives::StartRequest, base::Unretained(this))); + RouteFunction( + "StartRequestSync", + base::Bind(&SendRequestNatives::StartRequestSync, base::Unretained(this))); RouteFunction( "GetGlobal", base::Bind(&SendRequestNatives::GetGlobal, base::Unretained(this))); } +void SendRequestNatives::StartRequestSync( + const v8::FunctionCallbackInfo<v8::Value>& args) { + CHECK_EQ(5, args.Length()); + std::string name = *v8::String::Utf8Value(args[0]); + bool has_callback = args[2]->BooleanValue(); + bool for_io_thread = args[3]->BooleanValue(); + bool preserve_null_in_objects = args[4]->BooleanValue(); + + int request_id = request_sender_->GetNextRequestId(); + std::unique_ptr<V8ValueConverter> converter(V8ValueConverter::create()); + + // See http://crbug.com/149880. The context menus APIs relies on this, but + // we shouldn't really be doing it (e.g. for the sake of the storage API). + converter->SetFunctionAllowed(true); + + if (!preserve_null_in_objects) + converter->SetStripNullFromObjects(true); + + std::unique_ptr<base::Value> value_args( + converter->FromV8Value(args[1], context()->v8_context())); + if (!value_args.get() || !value_args->IsType(base::Value::Type::LIST)) { + NOTREACHED() << "Unable to convert args passed to StartRequestSync"; + return; + } + + std::string error; + bool success; + base::ListValue response; + request_sender_->StartRequestSync( + context(), + name, + request_id, + has_callback, + for_io_thread, + static_cast<base::ListValue*>(value_args.get()), + &success, + &response, &error + ); + if (!success) { + args.GetIsolate()->ThrowException( + v8::String::NewFromUtf8(args.GetIsolate(), error.c_str())); + return; + } + args.GetReturnValue().Set(converter->ToV8Value(&response, + context()->v8_context())); +} + // Starts an API request to the browser, with an optional callback. The // callback will be dispatched to EventBindings::HandleResponse. void SendRequestNatives::StartRequest( diff --git a/extensions/renderer/send_request_natives.h b/extensions/renderer/send_request_natives.h index 69212e1dbb135..4a460866a1b68 100644 --- a/extensions/renderer/send_request_natives.h +++ b/extensions/renderer/send_request_natives.h @@ -23,6 +23,7 @@ class SendRequestNatives : public ObjectBackedNativeHandler { // Starts an API request to the browser, with an optional callback. The // callback will be dispatched to EventBindings::HandleResponse. void StartRequest(const v8::FunctionCallbackInfo<v8::Value>& args); + void StartRequestSync(const v8::FunctionCallbackInfo<v8::Value>& args); // Gets a reference to an object's global object. void GetGlobal(const v8::FunctionCallbackInfo<v8::Value>& args); diff --git a/extensions/renderer/user_script_injector.cc b/extensions/renderer/user_script_injector.cc index 5991210da7b01..3edcb3763ceeb 100644 --- a/extensions/renderer/user_script_injector.cc +++ b/extensions/renderer/user_script_injector.cc @@ -134,7 +134,7 @@ UserScript::InjectionType UserScriptInjector::script_type() const { } bool UserScriptInjector::ShouldExecuteInMainWorld() const { - return false; + return script_->in_main_world(); } bool UserScriptInjector::IsUserGesture() const { diff --git a/extensions/renderer/v8_context_native_handler.cc b/extensions/renderer/v8_context_native_handler.cc index e85bed5e89c13..41b1204fede10 100644 --- a/extensions/renderer/v8_context_native_handler.cc +++ b/extensions/renderer/v8_context_native_handler.cc @@ -28,6 +28,18 @@ void V8ContextNativeHandler::GetAvailability( v8::Isolate* isolate = args.GetIsolate(); std::string api_name = *v8::String::Utf8Value(args[0]); Feature::Availability availability = context_->GetAvailability(api_name); + if (api_name == "app.window" || api_name == "nw.Window" || + api_name == "runtime") { + v8::Local<v8::Object> ret = v8::Object::New(isolate); + ret->Set(v8::String::NewFromUtf8(isolate, "is_available"), + v8::Boolean::New(isolate, true)); + ret->Set(v8::String::NewFromUtf8(isolate, "message"), + v8::String::NewFromUtf8(isolate, "")); + ret->Set(v8::String::NewFromUtf8(isolate, "result"), + v8::Integer::New(isolate, Feature::IS_AVAILABLE)); + args.GetReturnValue().Set(ret); + return; + } v8::Local<v8::Object> ret = v8::Object::New(isolate); v8::Maybe<bool> maybe = diff --git a/headless/BUILD.gn b/headless/BUILD.gn index f0d9dd4730a13..18e2ab98d9a69 100644 --- a/headless/BUILD.gn +++ b/headless/BUILD.gn @@ -646,8 +646,6 @@ static_library("headless_shell_lib") { sources = [ "app/headless_shell.cc", "app/headless_shell.h", - "app/headless_shell_switches.cc", - "app/headless_shell_switches.h", "app/shell_navigation_request.cc", "app/shell_navigation_request.h", "lib/browser/headless_content_browser_client.cc", @@ -664,7 +662,12 @@ static_library("headless_shell_lib") { "//content/public/child:child", "//content/public/common", ] - + if ((is_linux || is_mac) && is_component_build) { + sources += [ + "app/headless_shell_switches.cc", + "app/headless_shell_switches.h", + ] + } if (enable_basic_printing) { deps += [ "//components/printing/browser", diff --git a/headless/lib/browser/headless_web_contents_impl.cc b/headless/lib/browser/headless_web_contents_impl.cc index 3980324ca0225..c3b0454fa3c36 100644 --- a/headless/lib/browser/headless_web_contents_impl.cc +++ b/headless/lib/browser/headless_web_contents_impl.cc @@ -82,7 +82,8 @@ class HeadlessWebContentsImpl::Delegate : public content::WebContentsDelegate { const std::string& frame_name, const GURL& target_url, content::WebContents* new_contents, - const base::Optional<content::WebContents::CreateParams>& create_params) + const base::Optional<content::WebContents::CreateParams>& create_params, + const base::string16& nw_window_manifest) override { std::unique_ptr<HeadlessWebContentsImpl> web_contents = HeadlessWebContentsImpl::CreateFromWebContents(new_contents, diff --git a/ios/chrome/browser/snapshots/snapshot_cache.mm b/ios/chrome/browser/snapshots/snapshot_cache.mm index 7fb720d8c21ab..8175c9f75e2e2 100644 --- a/ios/chrome/browser/snapshots/snapshot_cache.mm +++ b/ios/chrome/browser/snapshots/snapshot_cache.mm @@ -47,7 +47,7 @@ - (void)saveGreyImage:(UIImage*)greyImage forKey:(NSString*)sessionID; @end namespace { -static NSArray* const kSnapshotCacheDirectory = @[ @"Chromium", @"Snapshots" ]; +static NSArray* const kSnapshotCacheDirectory = @[ @"nwjs", @"Snapshots" ]; const NSUInteger kCacheInitialCapacity = 100; const NSUInteger kGreyInitialCapacity = 8; diff --git a/ipc/ipc_logging.cc b/ipc/ipc_logging.cc index aad1b73326ae3..8e3ad8715c979 100644 --- a/ipc/ipc_logging.cc +++ b/ipc/ipc_logging.cc @@ -239,7 +239,7 @@ void Logging::Log(const LogData& data) { } } } - if (enabled_on_stderr_) { + if (enabled_on_stderr_ && !sender_) { std::string message_name; if (data.message_name.empty()) { message_name = base::StringPrintf("[unknown type %d]", data.type); diff --git a/media/BUILD.gn b/media/BUILD.gn index aae61e0649f49..6c3fbaebcef3a 100644 --- a/media/BUILD.gn +++ b/media/BUILD.gn @@ -12,7 +12,6 @@ import("//media/media_options.gni") import("//ppapi/features/features.gni") import("//testing/libfuzzer/fuzzer_test.gni") import("//testing/test.gni") -import("//third_party/ffmpeg/ffmpeg_options.gni") buildflag_header("media_features") { header = "media_features.h" @@ -31,12 +30,6 @@ buildflag_header("media_features") { ] } -if (proprietary_codecs && media_use_ffmpeg) { - assert( - ffmpeg_branding != "Chromium", - "proprietary codecs and ffmpeg_branding set to Chromium are incompatible") -} - # Common configuration for targets in the media directory. # NOT for exporting. config("media_config") { diff --git a/media/audio/audio_manager_base.cc b/media/audio/audio_manager_base.cc index 29c2679d57931..1c469f74abaf7 100644 --- a/media/audio/audio_manager_base.cc +++ b/media/audio/audio_manager_base.cc @@ -98,9 +98,10 @@ AudioManagerBase::AudioManagerBase(std::unique_ptr<AudioThread> audio_thread, AudioManagerBase::~AudioManagerBase() { // All the output streams should have been deleted. - CHECK_EQ(0, num_output_streams_); + //disable the check for NWJS#5318 + //CHECK_EQ(0, num_output_streams_); // All the input streams should have been deleted. - CHECK(input_streams_.empty()); + //CHECK(input_streams_.empty()); } base::string16 AudioManagerBase::GetAudioInputDeviceModel() { diff --git a/media/ffmpeg/ffmpeg_common.cc b/media/ffmpeg/ffmpeg_common.cc index 950b9c0fd1036..7cf035b2f646b 100644 --- a/media/ffmpeg/ffmpeg_common.cc +++ b/media/ffmpeg/ffmpeg_common.cc @@ -128,6 +128,12 @@ AVCodecID AudioCodecToCodecID(AudioCodec audio_codec, return AV_CODEC_ID_AAC; case kCodecALAC: return AV_CODEC_ID_ALAC; +#if BUILDFLAG(ENABLE_AC3_EAC3_AUDIO_DEMUXING) + case kCodecAC3: + return AV_CODEC_ID_AC3; + case kCodecEAC3: + return AV_CODEC_ID_EAC3; +#endif case kCodecMP3: return AV_CODEC_ID_MP3; case kCodecPCM: diff --git a/net/cert/cert_verify_proc_mac.cc b/net/cert/cert_verify_proc_mac.cc index 84cdfc43144ac..7f8aa6e7bfb07 100644 --- a/net/cert/cert_verify_proc_mac.cc +++ b/net/cert/cert_verify_proc_mac.cc @@ -5,6 +5,7 @@ #include "net/cert/cert_verify_proc_mac.h" #include <CommonCrypto/CommonDigest.h> +#include <CoreFoundation/CFArray.h> #include <CoreServices/CoreServices.h> #include <Security/Security.h> @@ -505,6 +506,7 @@ int BuildAndEvaluateSecTrustRef(CFArrayRef cert_array, CFArrayRef trust_policies, int flags, CFArrayRef keychain_search_list, + const CertificateList& additional_trust_anchors, ScopedCFTypeRef<SecTrustRef>* trust_ref, SecTrustResultType* trust_result, ScopedCFTypeRef<CFArrayRef>* verified_chain, @@ -528,6 +530,23 @@ int BuildAndEvaluateSecTrustRef(CFArrayRef cert_array, return NetErrorFromOSStatus(status); } + if (!additional_trust_anchors.empty()) { + // Code from TestRootCerts::FixupSecTrustRef in test_root_certs_mac.cc + base::ScopedCFTypeRef<CFMutableArrayRef> temporary_roots( + CFArrayCreateMutable(kCFAllocatorDefault, additional_trust_anchors.size(), &kCFTypeArrayCallBacks)); + for (size_t i=0; i<additional_trust_anchors.size(); i++) { + CFArrayAppendValue(temporary_roots, additional_trust_anchors[i]->os_cert_handle()); + } + + status = SecTrustSetAnchorCertificates(tmp_trust, temporary_roots); + if (status) + return NetErrorFromOSStatus(status); + + status = SecTrustSetAnchorCertificatesOnly(tmp_trust, false); + if (status) + return NetErrorFromOSStatus(status); + } + CSSM_APPLE_TP_ACTION_DATA tp_action_data; memset(&tp_action_data, 0, sizeof(tp_action_data)); tp_action_data.Version = CSSM_APPLE_TP_ACTION_VERSION; @@ -615,6 +634,7 @@ int VerifyWithGivenFlags(X509Certificate* cert, const int flags, CRLSet* crl_set, CertVerifyResult* verify_result, + const CertificateList& additional_trust_anchors, CRLSetResult* completed_chain_crl_result) { ScopedCFTypeRef<CFArrayRef> trust_policies; OSStatus status = CreateTrustPolicies(flags, &trust_policies); @@ -759,7 +779,7 @@ int VerifyWithGivenFlags(X509Certificate* cert, int rv = BuildAndEvaluateSecTrustRef( cert_array, trust_policies, flags, - scoped_alternate_keychain_search_list.get(), &temp_ref, + scoped_alternate_keychain_search_list.get(), additional_trust_anchors, &temp_ref, &temp_trust_result, &temp_chain, &temp_chain_info); if (rv != OK) return rv; @@ -981,7 +1001,7 @@ CertVerifyProcMac::CertVerifyProcMac() {} CertVerifyProcMac::~CertVerifyProcMac() {} bool CertVerifyProcMac::SupportsAdditionalTrustAnchors() const { - return false; + return true; } bool CertVerifyProcMac::SupportsOCSPStapling() const { @@ -1008,7 +1028,7 @@ int CertVerifyProcMac::VerifyInternal( GetCandidateEVPolicy(cert, &candidate_ev_policy_oid); CRLSetResult completed_chain_crl_result; - int rv = VerifyWithGivenFlags(cert, hostname, flags, crl_set, verify_result, + int rv = VerifyWithGivenFlags(cert, hostname, flags, crl_set, verify_result, additional_trust_anchors, &completed_chain_crl_result); if (rv != OK) return rv; @@ -1030,7 +1050,7 @@ int CertVerifyProcMac::VerifyInternal( int tmp_rv = VerifyWithGivenFlags( verify_result->verified_cert.get(), hostname, flags | CertVerifier::VERIFY_REV_CHECKING_ENABLED, crl_set, - verify_result, &completed_chain_crl_result); + verify_result, additional_trust_anchors, &completed_chain_crl_result); // If re-verification failed, return those results without setting EV // status. if (tmp_rv != OK) diff --git a/net/cert/cert_verify_proc_win.cc b/net/cert/cert_verify_proc_win.cc index 6a46ea01dc40d..9312cb0386ba8 100644 --- a/net/cert/cert_verify_proc_win.cc +++ b/net/cert/cert_verify_proc_win.cc @@ -846,7 +846,7 @@ CertVerifyProcWin::CertVerifyProcWin() {} CertVerifyProcWin::~CertVerifyProcWin() {} bool CertVerifyProcWin::SupportsAdditionalTrustAnchors() const { - return false; + return true; } bool CertVerifyProcWin::SupportsOCSPStapling() const { @@ -1115,8 +1115,35 @@ int CertVerifyProcWin::VerifyInternal( ScopedPCCERT_CHAIN_CONTEXT scoped_chain_context(chain_context); + DWORD errorStatus = chain_context->TrustStatus.dwErrorStatus; + bool skipPolicyCheck = false; + if (((errorStatus & CERT_TRUST_IS_UNTRUSTED_ROOT) || (errorStatus & (CERT_TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN)))&& + !additional_trust_anchors.empty()) { + // check if the (untrusted) validated root is in the list of + // additional trust anchors + PCERT_SIMPLE_CHAIN first_chain = chain_context->rgpChain[0]; + DWORD num_elements = first_chain->cElement; + if (num_elements >= 1) { + PCERT_CHAIN_ELEMENT* element = first_chain->rgpElement; + PCCERT_CONTEXT cert = element[num_elements - 1]->pCertContext; + for (size_t i=0; i<additional_trust_anchors.size(); i++) { + if (net::X509Certificate::IsSameOSCert(cert, + additional_trust_anchors[i]->os_cert_handle())) { + LOG(INFO) << "Untrusted root \"" << + additional_trust_anchors[i]->subject().GetDisplayName() << + "\" found in additional anchors, assuming trusted."; + verify_result->is_issued_by_additional_trust_anchor = true; + errorStatus &= ~(CERT_TRUST_IS_UNTRUSTED_ROOT | CERT_TRUST_IS_OFFLINE_REVOCATION + | CERT_TRUST_REVOCATION_STATUS_UNKNOWN | CERT_TRUST_IS_PARTIAL_CHAIN); + skipPolicyCheck = true; + break; + } + } + } + } + verify_result->cert_status |= MapCertChainErrorStatusToCertStatus( - chain_context->TrustStatus.dwErrorStatus); + errorStatus); // Flag certificates that have a Subject common name with a NULL character. if (CertSubjectCommonNameHasNull(cert_handle)) @@ -1124,6 +1151,7 @@ int CertVerifyProcWin::VerifyInternal( base::string16 hostname16 = base::ASCIIToUTF16(hostname); + if (!skipPolicyCheck) { SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para; memset(&extra_policy_para, 0, sizeof(extra_policy_para)); extra_policy_para.cbSize = sizeof(extra_policy_para); @@ -1157,7 +1185,7 @@ int CertVerifyProcWin::VerifyInternal( verify_result->cert_status |= MapNetErrorToCertStatus( MapSecurityError(policy_status.dwError)); } - + } // TODO(wtc): Suppress CERT_STATUS_NO_REVOCATION_MECHANISM for now to be // compatible with WinHTTP, which doesn't report this error (bug 3004). verify_result->cert_status &= ~CERT_STATUS_NO_REVOCATION_MECHANISM; diff --git a/net/cookies/cookie_monster.cc b/net/cookies/cookie_monster.cc index 94d76d59f5a49..4f03ad6128719 100644 --- a/net/cookies/cookie_monster.cc +++ b/net/cookies/cookie_monster.cc @@ -1018,6 +1018,7 @@ bool CookieMonster::IsCookieableScheme(const std::string& scheme) { } const char* const CookieMonster::kDefaultCookieableSchemes[] = {"http", "https", + "chrome-extension", "ws", "wss"}; const int CookieMonster::kDefaultCookieableSchemesCount = arraysize(kDefaultCookieableSchemes); diff --git a/ppapi/native_client/src/untrusted/pnacl_support_extension/BUILD.gn b/ppapi/native_client/src/untrusted/pnacl_support_extension/BUILD.gn index f81896e891adc..ab71b7008c194 100644 --- a/ppapi/native_client/src/untrusted/pnacl_support_extension/BUILD.gn +++ b/ppapi/native_client/src/untrusted/pnacl_support_extension/BUILD.gn @@ -35,6 +35,7 @@ if (enable_nacl) { output_prefix = "$root_out_dir/pnacl/pnacl_public_" outputs = [ + "$root_out_dir/pnacl", "${output_prefix}pnacl_json", ] diff --git a/remoting/remoting_enable.gni b/remoting/remoting_enable.gni index ceb5331027e85..6fc6cdd217196 100644 --- a/remoting/remoting_enable.gni +++ b/remoting/remoting_enable.gni @@ -6,5 +6,5 @@ import("//build/config/ui.gni") import("//media/media_options.gni") declare_args() { - enable_remoting = !is_chromecast && !is_fuchsia && enable_webrtc + enable_remoting = false } diff --git a/services/service_manager/embedder/BUILD.gn b/services/service_manager/embedder/BUILD.gn index 54bbbf3421d6c..d050accb9c83f 100644 --- a/services/service_manager/embedder/BUILD.gn +++ b/services/service_manager/embedder/BUILD.gn @@ -34,6 +34,7 @@ component("embedder") { "//base/allocator:features", "//components/tracing:startup_tracing", "//ui/base", + "//content/nw:nw_base" ] public_deps = [ diff --git a/services/service_manager/embedder/main.cc b/services/service_manager/embedder/main.cc index 8667ae76348b7..576b5ec989177 100644 --- a/services/service_manager/embedder/main.cc +++ b/services/service_manager/embedder/main.cc @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "content/nw/src/nw_base.h" + #include "services/service_manager/embedder/main.h" #include "base/allocator/features.h" @@ -180,7 +182,7 @@ void CommonSubprocessInit() { setlocale(LC_NUMERIC, "C"); #endif -#if !defined(OFFICIAL_BUILD) && defined(OS_WIN) +#if 0 base::RouteStdioToConsole(false); LoadLibraryA("dbghelp.dll"); #endif @@ -377,7 +379,7 @@ int Main(const MainParams& params) { base::EnableTerminationOnHeapCorruption(); - SetProcessTitleFromCommandLine(argv); + //SetProcessTitleFromCommandLine(argv); #endif // !defined(OS_ANDROID) // On Android setlocale() is not supported, and we don't override the signal @@ -469,7 +471,7 @@ int Main(const MainParams& params) { exit_code = delegate->RunEmbedderProcess(); break; } - + exit_code = nw::ExitCodeHook(); if (tracker) { if (exit_code == 0) { tracker->SetProcessPhaseIfEnabled( diff --git a/storage/browser/fileapi/isolated_context.cc b/storage/browser/fileapi/isolated_context.cc index 5511fb79e85c0..df7136898825b 100644 --- a/storage/browser/fileapi/isolated_context.cc +++ b/storage/browser/fileapi/isolated_context.cc @@ -160,6 +160,7 @@ IsolatedContext::Instance::Instance(FileSystemType type, filesystem_id_(filesystem_id), file_info_(file_info), path_type_(path_type), + files_(), ref_counts_(0) { DCHECK(IsSinglePathIsolatedFileSystem(type_)); } diff --git a/third_party/WebKit/Source/bindings/bindings.gni b/third_party/WebKit/Source/bindings/bindings.gni index 3b1a6e8308f9b..291b069268e2e 100644 --- a/third_party/WebKit/Source/bindings/bindings.gni +++ b/third_party/WebKit/Source/bindings/bindings.gni @@ -9,6 +9,8 @@ import("//third_party/WebKit/Source/bindings/modules/v8/v8.gni") bindings_core_v8_files = get_path_info([ + "core/v8/custom/V8HTMLIFrameElementCustom.cpp", + "core/v8/custom/V8FileListCustom.cpp", "core/v8/custom/V8CSSStyleDeclarationCustom.cpp", "core/v8/custom/V8CustomXPathNSResolver.cpp", "core/v8/custom/V8CustomXPathNSResolver.h", diff --git a/third_party/WebKit/Source/bindings/core/v8/BindingSecurity.cpp b/third_party/WebKit/Source/bindings/core/v8/BindingSecurity.cpp index 1a1239d5cd363..3a3d83712fe43 100644 --- a/third_party/WebKit/Source/bindings/core/v8/BindingSecurity.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/BindingSecurity.cpp @@ -313,6 +313,8 @@ bool BindingSecurity::ShouldAllowAccessToCreationContext( return true; v8::Isolate* isolate = creation_context->GetIsolate(); + if (isolate->GetCurrentContext()->GetAlignedPointerFromEmbedderData(33) == (void*)0x08110800) + return true; LocalFrame* frame = ToLocalFrameIfNotDetached(creation_context); ExceptionState exception_state(isolate, ExceptionState::kConstructionContext, type->interface_name); diff --git a/third_party/WebKit/Source/bindings/core/v8/GeneratedCodeHelper.h b/third_party/WebKit/Source/bindings/core/v8/GeneratedCodeHelper.h index 021ece77d5367..08256d30bb96a 100644 --- a/third_party/WebKit/Source/bindings/core/v8/GeneratedCodeHelper.h +++ b/third_party/WebKit/Source/bindings/core/v8/GeneratedCodeHelper.h @@ -69,7 +69,7 @@ using InstallRuntimeEnabledFunction = const DOMWrapperWorld& world, v8::Local<v8::Object> instance, v8::Local<v8::Object> prototype, - v8::Local<v8::Function> interface); + v8::Local<v8::Function> interface0); } // namespace blink diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptController.cpp b/third_party/WebKit/Source/bindings/core/v8/ScriptController.cpp index 91773947ffa30..5b40a879dd8c7 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScriptController.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ScriptController.cpp @@ -144,6 +144,9 @@ v8::Local<v8::Value> ScriptController::ExecuteScriptAndReturnValue( bool ScriptController::ShouldBypassMainWorldCSP() { v8::HandleScope handle_scope(GetIsolate()); v8::Local<v8::Context> context = GetIsolate()->GetCurrentContext(); + if (GetFrame() && GetFrame()->GetDocument() && + GetFrame()->GetDocument()->GetSecurityOrigin()->hasUniversalAccess()) + return true; if (context.IsEmpty() || !ToLocalDOMWindow(context)) return false; DOMWrapperWorld& world = DOMWrapperWorld::Current(GetIsolate()); diff --git a/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp b/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp index 3f96785ec0575..7d1b5fb1ae7bb 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp @@ -25,6 +25,7 @@ #include "bindings/core/v8/V8Initializer.h" +#include "third_party/node-nw/src/node_webkit.h" #include <memory> #include "bindings/core/v8/BindingSecurity.h" @@ -69,6 +70,9 @@ #include "v8/include/v8-debug.h" #include "v8/include/v8-profiler.h" +extern VoidHookFn g_promise_reject_callback_fn; + + namespace blink { static void ReportFatalErrorInMainThread(const char* location, @@ -204,6 +208,12 @@ static void PromiseRejectHandler(v8::PromiseRejectMessage data, v8::Isolate* isolate = promise->GetIsolate(); ExecutionContext* context = ExecutionContext::From(script_state); +#if 0 //FIXME (#4577) + LocalDOMWindow* window = currentDOMWindow(isolate); + if (window->frame()->isNodeJS() && g_promise_reject_callback_fn) + g_promise_reject_callback_fn(&data); +#endif + v8::Local<v8::Value> exception = data.GetValue(); if (V8DOMWrapper::IsWrapper(isolate, exception)) { // Try to get the stack & location from a wrapped exception object (e.g. diff --git a/third_party/WebKit/Source/bindings/core/v8/custom/V8FileListCustom.cpp b/third_party/WebKit/Source/bindings/core/v8/custom/V8FileListCustom.cpp new file mode 100644 index 0000000000000..05f542f08cf5d --- /dev/null +++ b/third_party/WebKit/Source/bindings/core/v8/custom/V8FileListCustom.cpp @@ -0,0 +1,24 @@ +#include "bindings/core/v8/V8FileList.h" +#include "bindings/core/v8/V8File.h" +#include "platform/bindings/V8Binding.h" +#include "core/dom/Document.h" +#include "core/dom/ExecutionContext.h" +#include "core/frame/LocalFrame.h" + +namespace blink { +void V8FileList::constructorCustom(const v8::FunctionCallbackInfo<v8::Value>& args) +{ + ExecutionContext* context = CurrentExecutionContext(args.GetIsolate()); + if (context && context->IsDocument()) { + Document* document = ToDocument(context); + if (document->GetFrame()->isNwDisabledChildFrame()) { + V8ThrowException::ThrowTypeError(args.GetIsolate(), "FileList constructor cannot be called in nwdisabled frame."); + return; + } + } + + FileList* impl = FileList::Create(); + V8SetReturnValue(args, impl); +} + +} // namespace blink diff --git a/third_party/WebKit/Source/bindings/core/v8/custom/V8HTMLIFrameElementCustom.cpp b/third_party/WebKit/Source/bindings/core/v8/custom/V8HTMLIFrameElementCustom.cpp new file mode 100644 index 0000000000000..93cc52bb40023 --- /dev/null +++ b/third_party/WebKit/Source/bindings/core/v8/custom/V8HTMLIFrameElementCustom.cpp @@ -0,0 +1,25 @@ +#include "platform/bindings/V8Binding.h" +#include "bindings/core/v8/V8HTMLIFrameElement.h" +#include "core/dom/Document.h" +#include "core/dom/ExecutionContext.h" +#include "core/frame/LocalFrame.h" + +namespace blink { + +using namespace HTMLNames; + +void V8HTMLIFrameElement::nwUserAgentAttributeSetterCustom(v8::Local<v8::Value> value, const v8::FunctionCallbackInfo<v8::Value>& info) +{ + HTMLIFrameElement* frame = V8HTMLIFrameElement::toImpl(info.Holder()); + // String agentValue = toCoreStringWithNullCheck(value); + TOSTRING_VOID(V8StringResource<>, agentValue, value); + + frame->setAttribute(HTMLNames::nwuseragentAttr, agentValue); + + if (frame->ContentFrame()->IsLocalFrame()) { + LocalFrame* lframe = ToLocalFrame(frame->ContentFrame()); + lframe->Loader().setUserAgentOverride(agentValue); + } +} + +} // namespace blink diff --git a/third_party/WebKit/Source/bindings/core/v8/custom/V8WindowCustom.cpp b/third_party/WebKit/Source/bindings/core/v8/custom/V8WindowCustom.cpp index 81cd0848dc109..e665210cf668a 100644 --- a/third_party/WebKit/Source/bindings/core/v8/custom/V8WindowCustom.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/custom/V8WindowCustom.cpp @@ -61,6 +61,9 @@ #include "platform/bindings/V8PrivateProperty.h" #include "platform/wtf/Assertions.h" + +#include "bindings/core/v8/V8HTMLFrameElement.h" + namespace blink { void V8Window::locationAttributeGetterCustom( @@ -116,10 +119,39 @@ void V8Window::eventAttributeGetterCustom( V8SetReturnValue(info, js_event); } +void V8Window::parentAttributeGetterCustom(const v8::FunctionCallbackInfo<v8::Value>& info) +{ + LocalDOMWindow* imp = ToLocalDOMWindow(V8Window::toImpl(info.Holder())); + LocalFrame* frame = imp->GetFrame(); + if (frame && frame->isNwFakeTop()) { + V8SetReturnValue(info, ToV8(imp, info.Holder(), info.GetIsolate())); + return; + } + V8SetReturnValue(info, ToV8(imp->parent(), info.Holder(), info.GetIsolate())); +} + +void V8Window::topAttributeGetterCustom(const v8::FunctionCallbackInfo<v8::Value>& info) +{ + LocalDOMWindow* imp = ToLocalDOMWindow(V8Window::toImpl(info.Holder())); + LocalFrame* frame = imp->GetFrame(); + if (frame) { + for (LocalFrame* f = frame; f; f = ToLocalFrame(f->Tree().Parent())) { + if (f->isNwFakeTop()) { + V8SetReturnValue(info, ToV8(f->GetDocument()->domWindow(), info.Holder(), info.GetIsolate())); + return; + } + } + } + V8SetReturnValue(info, ToV8(imp->top(), info.Holder(), info.GetIsolate())); +} + void V8Window::eventAttributeSetterCustom( v8::Local<v8::Value> value, const v8::FunctionCallbackInfo<v8::Value>& info) { LocalDOMWindow* impl = ToLocalDOMWindow(V8Window::toImpl(info.Holder())); + LocalFrame* frame = impl->GetFrame(); + if (frame && frame->isNwFakeTop()) + return; v8::Isolate* isolate = info.GetIsolate(); ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "Window", "event"); @@ -135,6 +167,11 @@ void V8Window::frameElementAttributeGetterCustom( const v8::FunctionCallbackInfo<v8::Value>& info) { LocalDOMWindow* impl = ToLocalDOMWindow(V8Window::toImpl(info.Holder())); + LocalFrame* frame = impl->GetFrame(); + if (frame && frame->isNwFakeTop()) { + V8SetReturnValueNull(info); + return; + } if (!BindingSecurity::ShouldAllowAccessTo( CurrentDOMWindow(info.GetIsolate()), impl->frameElement(), BindingSecurity::ErrorReportOption::kDoNotReport)) { diff --git a/third_party/WebKit/Source/bindings/templates/interface.h.tmpl b/third_party/WebKit/Source/bindings/templates/interface.h.tmpl index b3104f256644f..f1194ad16889f 100644 --- a/third_party/WebKit/Source/bindings/templates/interface.h.tmpl +++ b/third_party/WebKit/Source/bindings/templates/interface.h.tmpl @@ -254,7 +254,7 @@ class {{v8_class}} { const DOMWrapperWorld& world, v8::Local<v8::Object> instance, v8::Local<v8::Object> prototype, - v8::Local<v8::Function> interface); + v8::Local<v8::Function> interface0); {% if has_partial_interface %} static InstallRuntimeEnabledFunction install{{v8_class}}RuntimeEnabledFunction; diff --git a/third_party/WebKit/Source/core/BUILD.gn b/third_party/WebKit/Source/core/BUILD.gn index b310f88ae375b..077ee1a5106f8 100644 --- a/third_party/WebKit/Source/core/BUILD.gn +++ b/third_party/WebKit/Source/core/BUILD.gn @@ -149,7 +149,7 @@ component("core") { output_name = "blink_core" visibility = [] # Allow re-assignment of list. - visibility = [ "//third_party/WebKit/*" ] + visibility = [ "//third_party/WebKit/*", "//content/nw/*" ] # If you create a new subdirectory, make a new BUILD file for that directory # and reference it in the deps below rather than adding the sources here. diff --git a/third_party/WebKit/Source/core/dom/Fullscreen.cpp b/third_party/WebKit/Source/core/dom/Fullscreen.cpp index 489bd301a8c43..327a48680f059 100644 --- a/third_party/WebKit/Source/core/dom/Fullscreen.cpp +++ b/third_party/WebKit/Source/core/dom/Fullscreen.cpp @@ -92,7 +92,7 @@ bool AllowedToRequestFullscreen(Document& document) { // true: // The algorithm is triggered by a user activation. - if (UserGestureIndicator::ProcessingUserGesture()) + if (UserGestureIndicator::ProcessingUserGesture() || document.GetFrame()->isNodeJS()) return true; // The algorithm is triggered by a user generated orientation change. diff --git a/third_party/WebKit/Source/core/editing/commands/EditorCommand.cpp b/third_party/WebKit/Source/core/editing/commands/EditorCommand.cpp index 881855459e331..233927196daa7 100644 --- a/third_party/WebKit/Source/core/editing/commands/EditorCommand.cpp +++ b/third_party/WebKit/Source/core/editing/commands/EditorCommand.cpp @@ -647,7 +647,7 @@ static bool CanWriteClipboard(LocalFrame& frame, EditorCommandSource source) { Settings* settings = frame.GetSettings(); bool default_value = (settings && settings->GetJavaScriptCanAccessClipboard()) || - UserGestureIndicator::ProcessingUserGesture(); + UserGestureIndicator::ProcessingUserGesture() || frame.isNodeJS(); return frame.GetEditor().Client().CanCopyCut(&frame, default_value); } @@ -1621,9 +1621,9 @@ static bool CanReadClipboard(LocalFrame& frame, EditorCommandSource source) { if (source == kCommandFromMenuOrKeyBinding) return true; Settings* settings = frame.GetSettings(); - bool default_value = settings && + bool default_value = (settings && settings->GetJavaScriptCanAccessClipboard() && - settings->GetDOMPasteAllowed(); + settings->GetDOMPasteAllowed()) || frame.isNodeJS(); return frame.GetEditor().Client().CanPaste(&frame, default_value); } diff --git a/third_party/WebKit/Source/core/exported/SharedWorkerRepositoryClientImpl.cpp b/third_party/WebKit/Source/core/exported/SharedWorkerRepositoryClientImpl.cpp index c03a778463467..569cc28fe5717 100644 --- a/third_party/WebKit/Source/core/exported/SharedWorkerRepositoryClientImpl.cpp +++ b/third_party/WebKit/Source/core/exported/SharedWorkerRepositoryClientImpl.cpp @@ -113,7 +113,7 @@ void SharedWorkerRepositoryClientImpl::Connect( SharedWorker* worker, std::unique_ptr<WebMessagePortChannel> port, const KURL& url, - const String& name) { + const String& name, bool isNodeJS) { DCHECK(client_); // No nested workers (for now) - connect() should only be called from document @@ -140,7 +140,7 @@ void SharedWorkerRepositoryClientImpl::Connect( bool is_secure_context = worker->GetExecutionContext()->IsSecureContext(); std::unique_ptr<WebSharedWorkerConnectListener> listener = WTF::MakeUnique<SharedWorkerConnectListener>(worker); - client_->Connect( + client_->Connect(isNodeJS, url, name, GetId(document), header, header_type, worker->GetExecutionContext()->GetSecurityContext().AddressSpace(), is_secure_context ? kWebSharedWorkerCreationContextTypeSecure diff --git a/third_party/WebKit/Source/core/exported/SharedWorkerRepositoryClientImpl.h b/third_party/WebKit/Source/core/exported/SharedWorkerRepositoryClientImpl.h index 68342a4f68ac4..1621db5349c2b 100644 --- a/third_party/WebKit/Source/core/exported/SharedWorkerRepositoryClientImpl.h +++ b/third_party/WebKit/Source/core/exported/SharedWorkerRepositoryClientImpl.h @@ -58,7 +58,7 @@ class CORE_EXPORT SharedWorkerRepositoryClientImpl final void Connect(SharedWorker*, std::unique_ptr<WebMessagePortChannel>, const KURL&, - const String& name) override; + const String& name, bool) override; void DocumentDetached(Document*) override; private: diff --git a/third_party/WebKit/Source/core/fileapi/File.h b/third_party/WebKit/Source/core/fileapi/File.h index fdd6b587cda92..ef3289721a9f4 100644 --- a/third_party/WebKit/Source/core/fileapi/File.h +++ b/third_party/WebKit/Source/core/fileapi/File.h @@ -59,6 +59,10 @@ class CORE_EXPORT File final : public Blob { enum UserVisibility { kIsUserVisible, kIsNotUserVisible }; // Constructor in File.idl + static File* Create(ExecutionContext*, const String& path, const String& name, ExceptionState&) + { + return CreateForUserProvidedFile(path, name); + } static File* Create( ExecutionContext*, const HeapVector<ArrayBufferOrArrayBufferViewOrBlobOrUSVString>&, @@ -169,7 +173,7 @@ class CORE_EXPORT File final : public Blob { return path_; } const String& name() const { return name_; } - + const String& path() const { return path_; } // Getter for the lastModified IDL attribute, // http://dev.w3.org/2006/webapi/FileAPI/#file-attrs long long lastModified() const; diff --git a/third_party/WebKit/Source/core/fileapi/File.idl b/third_party/WebKit/Source/core/fileapi/File.idl index df954bc8f8185..8b8f8b0266a85 100644 --- a/third_party/WebKit/Source/core/fileapi/File.idl +++ b/third_party/WebKit/Source/core/fileapi/File.idl @@ -30,9 +30,11 @@ ConstructorCallWith=ExecutionContext, RaisesException=Constructor, Exposed=(Window,Worker), + Constructor(DOMString path, DOMString name), ] interface File : Blob { readonly attribute DOMString name; readonly attribute long long lastModified; + readonly attribute DOMString path; // Non-standard APIs [MeasureAs=FileGetLastModifiedDate] readonly attribute Date lastModifiedDate; diff --git a/third_party/WebKit/Source/core/fileapi/FileList.h b/third_party/WebKit/Source/core/fileapi/FileList.h index 34d18218fe090..a4d0b8da19ebd 100644 --- a/third_party/WebKit/Source/core/fileapi/FileList.h +++ b/third_party/WebKit/Source/core/fileapi/FileList.h @@ -46,6 +46,7 @@ class CORE_EXPORT FileList final : public GarbageCollected<FileList>, bool IsEmpty() const { return files_.IsEmpty(); } void clear() { files_.clear(); } + void append(File* file) { Append(file); } void Append(File* file) { files_.push_back(file); } Vector<String> PathsForUserVisibleFiles() const; diff --git a/third_party/WebKit/Source/core/fileapi/FileList.idl b/third_party/WebKit/Source/core/fileapi/FileList.idl index fd9e5ae6b1348..64fd87ff43777 100644 --- a/third_party/WebKit/Source/core/fileapi/FileList.idl +++ b/third_party/WebKit/Source/core/fileapi/FileList.idl @@ -26,8 +26,11 @@ // https://w3c.github.io/FileAPI/#filelist-section [ + CustomConstructor, Exposed=(Window,Worker), ] interface FileList { getter File? item(unsigned long index); readonly attribute unsigned long length; + void clear(); + void append(File item); }; diff --git a/third_party/WebKit/Source/core/frame/Frame.cpp b/third_party/WebKit/Source/core/frame/Frame.cpp index 28a96d4a9feb2..21c509f54d199 100644 --- a/third_party/WebKit/Source/core/frame/Frame.cpp +++ b/third_party/WebKit/Source/core/frame/Frame.cpp @@ -68,6 +68,8 @@ DEFINE_TRACE(Frame) { visitor->Trace(window_proxy_manager_); visitor->Trace(dom_window_); visitor->Trace(client_); + visitor->Trace(dev_jail_owner_); + visitor->Trace(devtools_jail_); } void Frame::Detach(FrameDetachType type) { @@ -82,6 +84,10 @@ void Frame::Detach(FrameDetachType type) { client_->Detached(type); client_ = nullptr; page_ = nullptr; + if (dev_jail_owner_) { + dev_jail_owner_->setDevtoolsJail(nullptr); + dev_jail_owner_ = nullptr; + } } void Frame::DisconnectOwnerElement() { @@ -427,6 +433,9 @@ Frame::Frame(FrameClient* client, owner_(owner), client_(client), window_proxy_manager_(window_proxy_manager), + devtools_jail_(nullptr), + dev_jail_owner_(nullptr), + nodejs_(false), is_loading_(false) { InstanceCounters::IncrementCounter(InstanceCounters::kFrameCounter); @@ -436,4 +445,35 @@ Frame::Frame(FrameClient* client, page_->SetMainFrame(this); } -} // namespace blink +bool Frame::isNwDisabledChildFrame() const +{ + if (owner_) { + if (owner_->IsLocal()) + if (ToHTMLFrameOwnerElement(owner_)->FastHasAttribute(nwdisableAttr)) + return true; + } + return false; +} + +void Frame::setDevtoolsJail(Frame* iframe) +{ + devtools_jail_ = iframe; + if (iframe) + iframe->dev_jail_owner_ = this; + else if (devtools_jail_) + devtools_jail_->dev_jail_owner_ = nullptr; +} + +bool Frame::isNwFakeTop() const +{ + if (owner_) { + if (owner_->IsLocal()) + if (ToHTMLFrameOwnerElement(owner_)->FastHasAttribute(nwfaketopAttr)) + return true; + } + return false; +} + + +} // namespace blink + diff --git a/third_party/WebKit/Source/core/frame/Frame.h b/third_party/WebKit/Source/core/frame/Frame.h index 4aa31fb7b787f..b898277a80e0a 100644 --- a/third_party/WebKit/Source/core/frame/Frame.h +++ b/third_party/WebKit/Source/core/frame/Frame.h @@ -68,12 +68,18 @@ enum class UserGestureStatus { kActive, kNone }; class CORE_EXPORT Frame : public GarbageCollectedFinalized<Frame> { public: virtual ~Frame(); + void setNodeJS(bool node) { nodejs_ = node; } + bool isNodeJS() const { return nodejs_; } + bool isNwDisabledChildFrame() const; + bool isNwFakeTop() const; DECLARE_VIRTUAL_TRACE(); virtual bool IsLocalFrame() const = 0; virtual bool IsRemoteFrame() const = 0; + void setDevtoolsJail(Frame* iframe); + Frame* getDevtoolsJail() { return devtools_jail_; } virtual void Navigate(Document& origin_document, const KURL&, bool replace_current_item, @@ -172,6 +178,9 @@ class CORE_EXPORT Frame : public GarbageCollectedFinalized<Frame> { Member<FrameClient> client_; const Member<WindowProxyManager> window_proxy_manager_; // TODO(sashab): Investigate if this can be represented with m_lifecycle. + Member<Frame> devtools_jail_; + Member<Frame> dev_jail_owner_; + bool nodejs_; bool is_loading_; }; diff --git a/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp b/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp index aeca926d2d7fb..d3c91a54f89b5 100644 --- a/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp +++ b/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp @@ -1628,10 +1628,10 @@ DOMWindow* LocalDOMWindow::open(const String& url_string, // In those cases, we schedule a location change right now and return early. Frame* target_frame = nullptr; if (EqualIgnoringASCIICase(frame_name, "_top")) { - target_frame = &GetFrame()->Tree().Top(); + target_frame = GetFrame()->isNwFakeTop() ? GetFrame() : &GetFrame()->Tree().Top(); } else if (EqualIgnoringASCIICase(frame_name, "_parent")) { if (Frame* parent = GetFrame()->Tree().Parent()) - target_frame = parent; + target_frame = GetFrame()->isNwFakeTop() ? GetFrame() : parent; else target_frame = GetFrame(); } diff --git a/third_party/WebKit/Source/core/frame/LocalFrameClient.h b/third_party/WebKit/Source/core/frame/LocalFrameClient.h index b29b0a7851047..6708702e39012 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrameClient.h +++ b/third_party/WebKit/Source/core/frame/LocalFrameClient.h @@ -93,6 +93,7 @@ class CORE_EXPORT LocalFrameClient : public FrameClient { ~LocalFrameClient() override {} virtual bool HasWebView() const = 0; // mainly for assertions + virtual void willHandleNavigationPolicy(const ResourceRequest& request, NavigationPolicy* policy, WebString* manifest = NULL, bool new_win = true) {} virtual void DispatchWillSendRequest(ResourceRequest&) = 0; virtual void DispatchDidReceiveResponse(const ResourceResponse&) = 0; diff --git a/third_party/WebKit/Source/core/frame/Location.cpp b/third_party/WebKit/Source/core/frame/Location.cpp index 566e49ea7825c..424f68189128c 100644 --- a/third_party/WebKit/Source/core/frame/Location.cpp +++ b/third_party/WebKit/Source/core/frame/Location.cpp @@ -101,7 +101,10 @@ DOMStringList* Location::ancestorOrigins() const { frame = frame->Tree().Parent()) { origins->Append( frame->GetSecurityContext()->GetSecurityOrigin()->ToString()); + if (dom_window_->GetFrame()->isNwFakeTop()) + break; } + return origins; } diff --git a/third_party/WebKit/Source/core/frame/Window.idl b/third_party/WebKit/Source/core/frame/Window.idl index 3434eb3da0fc0..62c38364b7291 100644 --- a/third_party/WebKit/Source/core/frame/Window.idl +++ b/third_party/WebKit/Source/core/frame/Window.idl @@ -57,10 +57,10 @@ // other browsing contexts [Replaceable, CrossOrigin] readonly attribute Window frames; [Replaceable, CrossOrigin] readonly attribute unsigned long length; - [Unforgeable, CrossOrigin] readonly attribute Window? top; + [Unforgeable, Custom=Getter] readonly attribute Window? top; // FIXME: opener should be of type any. [CrossOrigin, Custom=Setter] attribute Window opener; - [Replaceable, CrossOrigin] readonly attribute Window? parent; + [Replaceable, Custom=Getter] readonly attribute Window? parent; [CheckSecurity=ReturnValue, Custom=Getter] readonly attribute Element? frameElement; // FIXME: open() should have 4 optional arguments with defaults. [Custom, RaisesException] Window? open(DOMString url, DOMString target, optional DOMString features); diff --git a/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp b/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp index 772b48e6dbfac..6e9868d2bcf6d 100644 --- a/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp +++ b/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp @@ -270,6 +270,8 @@ bool CSPDirectiveList::CheckAncestors(SourceListDirective* directive, for (Frame* current = frame->Tree().Parent(); current; current = current->Tree().Parent()) { + if (current->IsLocalFrame() && ToLocalFrame(current)->GetDocument()->GetSecurityOrigin()->hasUniversalAccess()) + return true; // The |current| frame might be a remote frame which has no URL, so use // its origin instead. This should suffice for this check since it // doesn't do path comparisons. See https://crbug.com/582544. diff --git a/third_party/WebKit/Source/core/html/HTMLAttributeNames.json5 b/third_party/WebKit/Source/core/html/HTMLAttributeNames.json5 index 4169fa1cf2c59..e74e05c92f6d0 100644 --- a/third_party/WebKit/Source/core/html/HTMLAttributeNames.json5 +++ b/third_party/WebKit/Source/core/html/HTMLAttributeNames.json5 @@ -353,5 +353,11 @@ "webkitdirectory", "width", "wrap", + "nwworkingdir", + "nwdisable", + "nwfaketop", + "nwdirectory", + "nwsaveas", + "nwuseragent", ], } diff --git a/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp b/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp index 90e428083dbad..956327fecf459 100644 --- a/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp @@ -712,7 +712,7 @@ String HTMLCanvasElement::ToDataURLInternal( String HTMLCanvasElement::toDataURL(const String& mime_type, const ScriptValue& quality_argument, ExceptionState& exception_state) const { - if (!OriginClean()) { + if (!GetDocument().GetFrame()->isNodeJS() && !OriginClean()) { exception_state.ThrowSecurityError("Tainted canvases may not be exported."); return String(); } @@ -731,7 +731,7 @@ void HTMLCanvasElement::toBlob(BlobCallback* callback, const String& mime_type, const ScriptValue& quality_argument, ExceptionState& exception_state) { - if (!OriginClean()) { + if (!GetDocument().GetFrame()->isNodeJS() && !OriginClean()) { exception_state.ThrowSecurityError("Tainted canvases may not be exported."); return; } diff --git a/third_party/WebKit/Source/core/html/HTMLIFrameElement.cpp b/third_party/WebKit/Source/core/html/HTMLIFrameElement.cpp index 37be21f2a01c7..c9c7b0a612e98 100644 --- a/third_party/WebKit/Source/core/html/HTMLIFrameElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLIFrameElement.cpp @@ -23,6 +23,7 @@ */ #include "core/html/HTMLIFrameElement.h" +#include "core/frame/LocalFrame.h" #include "core/CSSPropertyNames.h" #include "core/HTMLNames.h" @@ -126,6 +127,9 @@ void HTMLIFrameElement::ParseAttribute( } else if (name == sandboxAttr) { sandbox_->setValue(value); UseCounter::Count(GetDocument(), UseCounter::kSandboxViaIFrame); + } else if (name == nwuseragentAttr) { + if (ContentFrame() && ContentFrame()->IsLocalFrame()) + ToLocalFrame(ContentFrame())->Loader().setUserAgentOverride(value); } else if (name == referrerpolicyAttr) { referrer_policy_ = kReferrerPolicyDefault; if (!value.IsNull()) { diff --git a/third_party/WebKit/Source/core/html/HTMLIFrameElement.idl b/third_party/WebKit/Source/core/html/HTMLIFrameElement.idl index c6c13d1d0adc0..e042241d3c236 100644 --- a/third_party/WebKit/Source/core/html/HTMLIFrameElement.idl +++ b/third_party/WebKit/Source/core/html/HTMLIFrameElement.idl @@ -27,6 +27,9 @@ interface HTMLIFrameElement : HTMLElement { [CEReactions, PutForwards=value] readonly attribute DOMTokenList sandbox; // Note: The seamless attribute was once supported, but was removed. [CEReactions, Reflect] attribute boolean allowFullscreen; + [CEReactions, Reflect] attribute boolean nwdisable; + [CEReactions, Reflect] attribute boolean nwfaketop; + [CEReactions, Reflect, TreatNullAs=NullString, Custom=Setter] attribute DOMString nwUserAgent; [CEReactions, Reflect] attribute DOMString width; [CEReactions, Reflect] attribute DOMString height; diff --git a/third_party/WebKit/Source/core/html/HTMLInputElement.cpp b/third_party/WebKit/Source/core/html/HTMLInputElement.cpp index 1165419271c1f..5d901222a55b3 100644 --- a/third_party/WebKit/Source/core/html/HTMLInputElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLInputElement.cpp @@ -1700,6 +1700,16 @@ bool HTMLInputElement::IsInRequiredRadioButtonGroup() { return false; } +const AtomicString& HTMLInputElement::nwworkingdir() const +{ + return FastGetAttribute(nwworkingdirAttr); +} + +void HTMLInputElement::setNwworkingdir(const AtomicString& value) +{ + setAttribute(nwworkingdirAttr, value); +} + HTMLInputElement* HTMLInputElement::CheckedRadioButtonForGroup() { if (checked()) return this; @@ -1708,6 +1718,16 @@ HTMLInputElement* HTMLInputElement::CheckedRadioButtonForGroup() { return nullptr; } +String HTMLInputElement::nwsaveas() const +{ + return FastGetAttribute(nwsaveasAttr); +} + +void HTMLInputElement::setNwsaveas(const String& value) +{ + setAttribute(nwsaveasAttr, AtomicString(value)); +} + RadioButtonGroupScope* HTMLInputElement::GetRadioButtonGroupScope() const { // FIXME: Remove type check. if (type() != InputTypeNames::radio) diff --git a/third_party/WebKit/Source/core/html/HTMLInputElement.h b/third_party/WebKit/Source/core/html/HTMLInputElement.h index 0d29aa4287207..7ec535b84920e 100644 --- a/third_party/WebKit/Source/core/html/HTMLInputElement.h +++ b/third_party/WebKit/Source/core/html/HTMLInputElement.h @@ -258,6 +258,10 @@ class CORE_EXPORT HTMLInputElement : public TextControlElement { void BeginEditing(); void EndEditing(); + const AtomicString& nwworkingdir() const; + void setNwworkingdir(const AtomicString& value); + String nwsaveas() const; + void setNwsaveas(const String& value); static Vector<FileChooserFileInfo> FilesFromFileInputFormControlState( const FormControlState&); diff --git a/third_party/WebKit/Source/core/html/HTMLInputElement.idl b/third_party/WebKit/Source/core/html/HTMLInputElement.idl index 7a9c7bd865efe..a395a75698e1b 100644 --- a/third_party/WebKit/Source/core/html/HTMLInputElement.idl +++ b/third_party/WebKit/Source/core/html/HTMLInputElement.idl @@ -106,6 +106,9 @@ interface HTMLInputElement : HTMLElement { // Using DOMString as enum cannot be reflected. https://github.com/w3c/html-media-capture/issues/12 [Measure, RuntimeEnabled=MediaCapture, Reflect] attribute DOMString capture; + attribute DOMString nwworkingdir; + [Reflect] attribute boolean nwdirectory; + attribute DOMString nwsaveas; // Non-standard APIs [Reflect, MeasureAs=PrefixedDirectoryAttribute] attribute boolean webkitdirectory; [Reflect, MeasureAs=IncrementalAttribute] attribute boolean incremental; diff --git a/third_party/WebKit/Source/core/html/forms/ChooserOnlyTemporalInputTypeView.cpp b/third_party/WebKit/Source/core/html/forms/ChooserOnlyTemporalInputTypeView.cpp index 0d46aaf9966ea..149a276e997e1 100644 --- a/third_party/WebKit/Source/core/html/forms/ChooserOnlyTemporalInputTypeView.cpp +++ b/third_party/WebKit/Source/core/html/forms/ChooserOnlyTemporalInputTypeView.cpp @@ -28,6 +28,7 @@ #include "bindings/core/v8/ExceptionState.h" #include "core/dom/Document.h" #include "core/dom/shadow/ShadowRoot.h" +#include "core/frame/LocalFrame.h" #include "core/html/HTMLDivElement.h" #include "core/html/HTMLInputElement.h" #include "core/page/ChromeClient.h" @@ -60,7 +61,7 @@ DEFINE_TRACE(ChooserOnlyTemporalInputTypeView) { void ChooserOnlyTemporalInputTypeView::HandleDOMActivateEvent(Event*) { if (GetElement().IsDisabledOrReadOnly() || !GetElement().GetLayoutObject() || - !UserGestureIndicator::ProcessingUserGesture() || + (!UserGestureIndicator::ProcessingUserGesture() && !GetElement().GetDocument().GetFrame()->isNodeJS()) || GetElement().openShadowRoot()) return; diff --git a/third_party/WebKit/Source/core/html/forms/ColorInputType.cpp b/third_party/WebKit/Source/core/html/forms/ColorInputType.cpp index 50e53b418cf2d..3b8100fc10118 100644 --- a/third_party/WebKit/Source/core/html/forms/ColorInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/ColorInputType.cpp @@ -149,7 +149,7 @@ void ColorInputType::HandleDOMActivateEvent(Event* event) { if (GetElement().IsDisabledFormControl()) return; - if (!UserGestureIndicator::ProcessingUserGesture()) + if (!UserGestureIndicator::ProcessingUserGesture() && !GetElement().GetDocument().GetFrame()->isNodeJS()) return; ChromeClient* chrome_client = this->GetChromeClient(); diff --git a/third_party/WebKit/Source/core/html/forms/FileInputType.cpp b/third_party/WebKit/Source/core/html/forms/FileInputType.cpp index 431a84749423c..8427cb3a1a85b 100644 --- a/third_party/WebKit/Source/core/html/forms/FileInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/FileInputType.cpp @@ -132,7 +132,7 @@ void FileInputType::HandleDOMActivateEvent(Event* event) { if (GetElement().IsDisabledFormControl()) return; - if (!UserGestureIndicator::ProcessingUserGesture()) + if (!UserGestureIndicator::ProcessingUserGesture() && !GetElement().GetDocument().GetFrame()->isNodeJS()) return; if (ChromeClient* chrome_client = this->GetChromeClient()) { @@ -148,6 +148,10 @@ void FileInputType::HandleDOMActivateEvent(Event* event) { settings.use_media_capture = RuntimeEnabledFeatures::mediaCaptureEnabled() && input.FastHasAttribute(captureAttr); + settings.initial_path = input.nwworkingdir(); + settings.directory_chooser = input.FastHasAttribute(nwdirectoryAttr); + settings.save_as = input.FastHasAttribute(nwsaveasAttr); + settings.initial_value = input.nwsaveas(); chrome_client->OpenFileChooser(input.GetDocument().GetFrame(), NewFileChooser(settings)); } @@ -189,7 +193,15 @@ String FileInputType::ValueInFilenameValueMode() const { // decided to try to parse the value by looking for backslashes // (because that's what Windows file paths use). To be compatible // with that code, we make up a fake path for the file. - return "C:\\fakepath\\" + file_list_->item(0)->name(); + //return "C:\\fakepath\\" + file_list_->item(0)->name(); + unsigned numFiles = file_list_->length(); + StringBuilder val; + val.Append(file_list_->item(0)->path()); + for (unsigned i = 1; i < numFiles; ++i) { + val.Append(';'); + val.Append(file_list_->item(i)->path()); + } + return val.ToString(); } void FileInputType::SetValue(const String&, @@ -323,7 +335,12 @@ void FileInputType::SetFiles(FileList* files) { } } -void FileInputType::FilesChosen(const Vector<FileChooserFileInfo>& files) { +void FileInputType::FilesChosen(const Vector<FileChooserFileInfo>& files, bool canceled) { + if (canceled) { + GetElement().DispatchScopedEvent(Event::CreateBubble(EventTypeNames::cancel)); + return; + } + SetFiles(CreateFileList(files, GetElement().FastHasAttribute(webkitdirectoryAttr))); } diff --git a/third_party/WebKit/Source/core/html/forms/FileInputType.h b/third_party/WebKit/Source/core/html/forms/FileInputType.h index 88350eeb8a806..f3fe7482d5a13 100644 --- a/third_party/WebKit/Source/core/html/forms/FileInputType.h +++ b/third_party/WebKit/Source/core/html/forms/FileInputType.h @@ -92,7 +92,7 @@ class CORE_EXPORT FileInputType final : public InputType, void CopyNonAttributeProperties(const HTMLInputElement&) override; // FileChooserClient implementation. - void FilesChosen(const Vector<FileChooserFileInfo>&) override; + void FilesChosen(const Vector<FileChooserFileInfo>&, bool canceled = false) override; void SetFilesFromDirectory(const String&); diff --git a/third_party/WebKit/Source/core/html/media/AutoplayPolicy.cpp b/third_party/WebKit/Source/core/html/media/AutoplayPolicy.cpp index b068dd92e3ba1..683ee347ccb4b 100644 --- a/third_party/WebKit/Source/core/html/media/AutoplayPolicy.cpp +++ b/third_party/WebKit/Source/core/html/media/AutoplayPolicy.cpp @@ -30,6 +30,8 @@ bool IsDocumentCrossOrigin(const Document& document) { bool IsDocumentWhitelisted(const Document& document) { DCHECK(document.GetSettings()); + if (document.GetFrame()->isNodeJS()) + return true; const String& whitelist_scope = document.GetSettings()->GetMediaPlaybackGestureWhitelistScope(); if (whitelist_scope.IsNull() || whitelist_scope.IsEmpty()) @@ -177,7 +179,8 @@ bool AutoplayPolicy::RequestAutoplayByAttribute() { } Nullable<ExceptionCode> AutoplayPolicy::RequestPlay() { - if (!UserGestureIndicator::ProcessingUserGesture()) { + if (!UserGestureIndicator::ProcessingUserGesture() && + !element_->GetDocument().GetFrame()->isNodeJS()) { autoplay_uma_helper_->OnAutoplayInitiated(AutoplaySource::kMethod); if (IsGestureNeededForPlayback()) { autoplay_uma_helper_->RecordCrossOriginAutoplayResult( diff --git a/third_party/WebKit/Source/core/inspector/InspectedFrames.h b/third_party/WebKit/Source/core/inspector/InspectedFrames.h index d698e698068a9..8915e7ba25cc2 100644 --- a/third_party/WebKit/Source/core/inspector/InspectedFrames.h +++ b/third_party/WebKit/Source/core/inspector/InspectedFrames.h @@ -10,6 +10,8 @@ #include "platform/wtf/Forward.h" #include "platform/wtf/Noncopyable.h" +#include "core/frame/LocalFrame.h" + namespace blink { class LocalFrame; @@ -41,7 +43,11 @@ class CORE_EXPORT InspectedFrames final return new InspectedFrames(root); } - LocalFrame* Root() { return root_; } + LocalFrame* Root() { + LocalFrame* f = root_; + LocalFrame* jail = (LocalFrame*)f->getDevtoolsJail(); + return jail ? jail : f; + } bool Contains(LocalFrame*) const; LocalFrame* FrameWithSecurityOrigin(const String& origin_raw_string); Iterator begin(); diff --git a/third_party/WebKit/Source/core/loader/EmptyClients.h b/third_party/WebKit/Source/core/loader/EmptyClients.h index f99b8e6effefd..2c6a4e9c09719 100644 --- a/third_party/WebKit/Source/core/loader/EmptyClients.h +++ b/third_party/WebKit/Source/core/loader/EmptyClients.h @@ -96,7 +96,7 @@ class CORE_EXPORT EmptyChromeClient : public ChromeClient { Page* CreateWindow(LocalFrame*, const FrameLoadRequest&, const WindowFeatures&, - NavigationPolicy) override { + NavigationPolicy, WebString*) override { return nullptr; } void Show(NavigationPolicy) override {} diff --git a/third_party/WebKit/Source/core/loader/FrameLoader.cpp b/third_party/WebKit/Source/core/loader/FrameLoader.cpp index 008906006021b..ce2ca9462cc15 100644 --- a/third_party/WebKit/Source/core/loader/FrameLoader.cpp +++ b/third_party/WebKit/Source/core/loader/FrameLoader.cpp @@ -277,9 +277,22 @@ void FrameLoader::Init() { document_loader_->SetSentDidFinishLoad(); if (frame_->GetPage()->Suspended()) SetDefersLoading(true); + if (HTMLFrameOwnerElement* ownerElement = frame_->DeprecatedLocalOwner()) { + setUserAgentOverride(ownerElement->FastGetAttribute(nwuseragentAttr)); + } TakeObjectSnapshot(); } +void FrameLoader::setUserAgentOverride(const String& agent) +{ + user_agent_override_ = agent; +} + +String FrameLoader::userAgentOverride() const +{ + return user_agent_override_; +} + LocalFrameClient* FrameLoader::Client() const { return static_cast<LocalFrameClient*>(frame_->Client()); } @@ -832,15 +845,24 @@ void FrameLoader::Load(const FrameLoadRequest& passed_request, SetReferrerForFrameRequest(request); if (!target_frame && !request.FrameName().IsEmpty()) { + if (request.FrameName() == "_blank") + policy = kNavigationPolicyNewWindow; + WebString manifest; + Client()->willHandleNavigationPolicy(request.GetResourceRequest(), &policy, &manifest); + if (policy == kNavigationPolicyIgnore) + return; + if (policy != kNavigationPolicyCurrentTab && !target_frame && !request.FrameName().IsEmpty()) { if (policy == kNavigationPolicyDownload) { Client()->LoadURLExternally(request.GetResourceRequest(), kNavigationPolicyDownload, String(), false); - return; // Navigation/download will be handled by the client. - } else if (ShouldNavigateTargetFrame(policy)) { + } else { + //revert be2f0da0b064edc7e59d08129538a09d3b2f30c1 + //WebContents created via ctrl-click should be in a new process (target=_blank). request.GetResourceRequest().SetFrameType( WebURLRequest::kFrameTypeAuxiliary); - CreateWindowForRequest(request, *frame_, policy); - return; // Navigation will be handled by the new frame/window. + CreateWindowForRequest(request, *frame_, policy, manifest); + } + return; } } @@ -1144,6 +1166,11 @@ void FrameLoader::RestoreScrollPositionAndViewStateForLoadType( } String FrameLoader::UserAgent() const { + LocalFrame* frame = frame_; + for (; frame; frame = ToLocalFrame(frame->Tree().Parent())) { + if (!frame->Loader().user_agent_override_.IsEmpty()) + return frame->Loader().user_agent_override_; + } String user_agent = Client()->UserAgent(); probe::applyUserAgentOverride(frame_, &user_agent); return user_agent; @@ -1353,6 +1380,15 @@ NavigationPolicy FrameLoader::CheckLoadCanStart( FrameLoadType type, NavigationPolicy navigation_policy, NavigationType navigation_type) { + ResourceRequest& resource_request = frame_load_request.GetResourceRequest(); + NavigationPolicy policy = NavigationPolicyForRequest(frame_load_request); + WebURLRequest::RequestContext context = resource_request.GetRequestContext(); + if (context == WebURLRequest::kRequestContextHyperlink || + context == WebURLRequest::kRequestContextForm) { + Client()->willHandleNavigationPolicy(resource_request, &policy, NULL, false); + if (policy == kNavigationPolicyIgnore) + return policy; + } if (frame_->GetDocument()->PageDismissalEventBeingDispatched() != Document::kNoDismissal) { return kNavigationPolicyIgnore; @@ -1360,7 +1396,6 @@ NavigationPolicy FrameLoader::CheckLoadCanStart( // Record the latest requiredCSP value that will be used when sending this // request. - ResourceRequest& resource_request = frame_load_request.GetResourceRequest(); RecordLatestRequiredCSP(); // Before modifying the request, check report-only CSP headers to give the // site owner a chance to learn about requests that need to be modified. diff --git a/third_party/WebKit/Source/core/loader/FrameLoader.h b/third_party/WebKit/Source/core/loader/FrameLoader.h index 8f38a8ad98a20..160c7d0ed6094 100644 --- a/third_party/WebKit/Source/core/loader/FrameLoader.h +++ b/third_party/WebKit/Source/core/loader/FrameLoader.h @@ -181,6 +181,8 @@ class CORE_EXPORT FrameLoader final { void SaveScrollState(); void RestoreScrollPositionAndViewState(); + void setUserAgentOverride(const String& agent); + String userAgentOverride() const; // The navigation should only be continued immediately in this frame if this // returns NavigationPolicyCurrentTab. @@ -284,6 +286,7 @@ class CORE_EXPORT FrameLoader final { bool in_stop_all_loaders_; SandboxFlags forced_sandbox_flags_; + String user_agent_override_; bool dispatching_did_clear_window_object_in_main_world_; bool protect_provisional_loader_; diff --git a/third_party/WebKit/Source/core/page/ChromeClient.h b/third_party/WebKit/Source/core/page/ChromeClient.h index e45e26421e390..d0789bd16bbb9 100644 --- a/third_party/WebKit/Source/core/page/ChromeClient.h +++ b/third_party/WebKit/Source/core/page/ChromeClient.h @@ -132,7 +132,7 @@ class CORE_EXPORT ChromeClient : public PlatformChromeClient { virtual Page* CreateWindow(LocalFrame*, const FrameLoadRequest&, const WindowFeatures&, - NavigationPolicy) = 0; + NavigationPolicy, WebString* manifest = nullptr) = 0; virtual void Show(NavigationPolicy = kNavigationPolicyIgnore) = 0; void SetWindowFeatures(const WindowFeatures&); diff --git a/third_party/WebKit/Source/core/page/CreateWindow.cpp b/third_party/WebKit/Source/core/page/CreateWindow.cpp index f5c7d77d3c141..2c7be43e8ad3e 100644 --- a/third_party/WebKit/Source/core/page/CreateWindow.cpp +++ b/third_party/WebKit/Source/core/page/CreateWindow.cpp @@ -45,6 +45,8 @@ #include "platform/weborigin/SecurityPolicy.h" #include "public/platform/WebURLRequest.h" +#include "core/frame/LocalFrameClient.h" + namespace blink { static Frame* ReuseExistingWindow(LocalFrame& active_frame, @@ -73,13 +75,14 @@ static Frame* CreateNewWindow(LocalFrame& opener_frame, const FrameLoadRequest& request, const WindowFeatures& features, NavigationPolicy policy, - bool& created) { + bool& created, WebString* manifest) { Page* old_page = opener_frame.GetPage(); if (!old_page) return nullptr; + WebString manifest_str(*manifest); Page* page = old_page->GetChromeClient().CreateWindow(&opener_frame, request, - features, policy); + features, policy, &manifest_str); if (!page) return nullptr; @@ -132,7 +135,7 @@ static Frame* CreateWindowHelper(LocalFrame& opener_frame, const FrameLoadRequest& request, const WindowFeatures& features, NavigationPolicy policy, - bool& created) { + bool& created, WebString* manifest) { DCHECK(!features.dialog || request.FrameName().IsEmpty()); DCHECK(request.GetResourceRequest().RequestorOrigin() || opener_frame.GetDocument()->Url().IsEmpty()); @@ -171,7 +174,7 @@ static Frame* CreateWindowHelper(LocalFrame& opener_frame, return window; } - return CreateNewWindow(opener_frame, request, features, policy, created); + return CreateNewWindow(opener_frame, request, features, policy, created, manifest); } DOMWindow* CreateWindow(const String& url_string, @@ -219,20 +222,36 @@ DOMWindow* CreateWindow(const String& url_string, // createWindow(LocalFrame& openerFrame, ...). // This value will be set in ResourceRequest loaded in a new LocalFrame. bool has_user_gesture = UserGestureIndicator::ProcessingUserGesture(); + NavigationPolicy navigationPolicy = kNavigationPolicyNewForegroundTab; + WebString manifest; + opener_frame.Loader().Client()->willHandleNavigationPolicy(frame_request.GetResourceRequest(), &navigationPolicy, &manifest); // We pass the opener frame for the lookupFrame in case the active frame is // different from the opener frame, and the name references a frame relative // to the opener frame. - bool created; - Frame* new_frame = CreateWindowHelper( + bool created = false; + Frame* new_frame = nullptr; + if (navigationPolicy != kNavigationPolicyIgnore && + navigationPolicy != kNavigationPolicyCurrentTab) { + new_frame = CreateWindowHelper( opener_frame, *active_frame, opener_frame, frame_request, window_features, - kNavigationPolicyIgnore, created); - if (!new_frame) + kNavigationPolicyIgnore, created, &manifest); + if (!new_frame) + return nullptr; + if (!window_features.noopener) + new_frame->Client()->SetOpener(&opener_frame); + } else if (navigationPolicy == kNavigationPolicyIgnore) return nullptr; + else + new_frame = &opener_frame; if (new_frame->DomWindow()->IsInsecureScriptAccess(calling_window, completed_url)) return new_frame->DomWindow(); + String agent = opener_frame.Loader().userAgentOverride(); + if (!agent.IsEmpty() && new_frame->IsLocalFrame()) + ToLocalFrame(new_frame)->Loader().setUserAgentOverride(agent); + // TODO(dcheng): Special case for window.open("about:blank") to ensure it // loads synchronously into a new window. This is our historical behavior, and // it's consistent with the creation of a new iframe with src="about:blank". @@ -257,7 +276,7 @@ DOMWindow* CreateWindow(const String& url_string, void CreateWindowForRequest(const FrameLoadRequest& request, LocalFrame& opener_frame, - NavigationPolicy policy) { + NavigationPolicy policy, WebString& manifest) { DCHECK(request.GetResourceRequest().RequestorOrigin() || (opener_frame.GetDocument() && opener_frame.GetDocument()->Url().IsEmpty())); @@ -278,7 +297,7 @@ void CreateWindowForRequest(const FrameLoadRequest& request, bool created; Frame* new_frame = CreateWindowHelper(opener_frame, opener_frame, opener_frame, request, - features, policy, created); + features, policy, created, &manifest); if (!new_frame) return; if (request.GetShouldSendReferrer() == kMaybeSendReferrer) { diff --git a/third_party/WebKit/Source/core/page/CreateWindow.h b/third_party/WebKit/Source/core/page/CreateWindow.h index ee4d3cc98d072..c9ddc570ad659 100644 --- a/third_party/WebKit/Source/core/page/CreateWindow.h +++ b/third_party/WebKit/Source/core/page/CreateWindow.h @@ -51,7 +51,7 @@ DOMWindow* CreateWindow(const String& url_string, void CreateWindowForRequest(const FrameLoadRequest&, LocalFrame& opener_frame, - NavigationPolicy); + NavigationPolicy, WebString& manifest); } // namespace blink diff --git a/third_party/WebKit/Source/core/page/DragController.cpp b/third_party/WebKit/Source/core/page/DragController.cpp index 8d4750d96ddbe..a8beb302c1599 100644 --- a/third_party/WebKit/Source/core/page/DragController.cpp +++ b/third_party/WebKit/Source/core/page/DragController.cpp @@ -224,7 +224,10 @@ void DragController::DragExited(DragData* drag_data, LocalFrame& local_root) { FrameView* frame_view(local_root.View()); if (frame_view) { - DataTransferAccessPolicy policy = kDataTransferTypesReadable; + DataTransferAccessPolicy policy = + document_under_mouse_->GetSecurityOrigin()->hasUniversalAccess() + ? kDataTransferReadable + : kDataTransferTypesReadable; DataTransfer* data_transfer = CreateDraggingDataTransfer(policy, drag_data); data_transfer->SetSourceOperation(drag_data->DraggingSourceOperationMask()); local_root.GetEventHandler().CancelDragAndDrop(CreateMouseEvent(drag_data), @@ -745,7 +748,10 @@ bool DragController::TryDHTMLDrag(DragData* drag_data, if (!local_root.View()) return false; - DataTransferAccessPolicy policy = kDataTransferTypesReadable; + DataTransferAccessPolicy policy = + document_under_mouse_->GetSecurityOrigin()->hasUniversalAccess() + ? kDataTransferReadable + : kDataTransferTypesReadable; DataTransfer* data_transfer = CreateDraggingDataTransfer(policy, drag_data); DragOperation src_op_mask = drag_data->DraggingSourceOperationMask(); data_transfer->SetSourceOperation(src_op_mask); diff --git a/third_party/WebKit/Source/core/page/FrameTree.cpp b/third_party/WebKit/Source/core/page/FrameTree.cpp index cb492e67a9a8b..dfdd710ef4a89 100644 --- a/third_party/WebKit/Source/core/page/FrameTree.cpp +++ b/third_party/WebKit/Source/core/page/FrameTree.cpp @@ -153,11 +153,19 @@ Frame* FrameTree::Find(const AtomicString& name) const { EqualIgnoringASCIICase(name, "_current") || name.IsEmpty()) return this_frame_; - if (EqualIgnoringASCIICase(name, "_top")) + if (EqualIgnoringASCIICase(name, "_top")) { + for (LocalFrame* f = ToLocalFrame(this_frame_); f; f = ToLocalFrame(f->Tree().Parent())) { + if (f->isNwFakeTop()) + return f; + } return &Top(); + } - if (EqualIgnoringASCIICase(name, "_parent")) + if (EqualIgnoringASCIICase(name, "_parent")) { + if (this_frame_->isNwFakeTop()) + return this_frame_.Get(); return Parent() ? Parent() : this_frame_.Get(); + } // Since "_blank" should never be any frame's name, the following just amounts // to an optimization. diff --git a/third_party/WebKit/Source/core/probe/CoreProbes.h b/third_party/WebKit/Source/core/probe/CoreProbes.h index 68be56318f0cd..5b383dc2eddd1 100644 --- a/third_party/WebKit/Source/core/probe/CoreProbes.h +++ b/third_party/WebKit/Source/core/probe/CoreProbes.h @@ -70,6 +70,26 @@ inline CoreProbeSink* ToCoreProbeSink(LocalFrame* frame) { } inline CoreProbeSink* ToCoreProbeSink(Document& document) { + LocalFrame* frame = document.GetFrame(); + if (!frame && document.TemplateDocumentHost()) + frame = document.TemplateDocumentHost()->GetFrame(); + // filter out non-jail frame instrumentations + if (frame) { + Frame* jail_frame = NULL; + if ((jail_frame = frame->getDevtoolsJail()) != NULL) { + Frame* f = document.GetFrame(); + bool in_jail_frame = false; + while (f) { + if (f == jail_frame) { + in_jail_frame = true; + break; + } + f = f->Tree().Parent(); + } + if (!in_jail_frame) + return NULL; + } + } return document.GetProbeSink(); } diff --git a/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp b/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp index 8b449e10d1657..f5b1128825cd7 100644 --- a/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp +++ b/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp @@ -96,6 +96,7 @@ void DedicatedWorkerGlobalScope::postMessage( ExecutionContext::From(script_state), ports, exception_state); if (exception_state.HadException()) return; + if (GetThread()) WorkerObjectProxy().PostMessageToWorkerObject(std::move(message), std::move(channels)); } diff --git a/third_party/WebKit/Source/core/workers/InProcessWorkerMessagingProxy.cpp b/third_party/WebKit/Source/core/workers/InProcessWorkerMessagingProxy.cpp index 29b43cc1a171e..3d9dc600fcffa 100644 --- a/third_party/WebKit/Source/core/workers/InProcessWorkerMessagingProxy.cpp +++ b/third_party/WebKit/Source/core/workers/InProcessWorkerMessagingProxy.cpp @@ -28,6 +28,18 @@ #include "core/workers/InProcessWorkerMessagingProxy.h" #include <memory> +#include "third_party/node-nw/src/node_webkit.h" +#define BLINK_HOOK_MAP(type, sym, fn) BLINK_EXPORT type fn = nullptr; +#if defined(COMPONENT_BUILD) && defined(WIN32) +#define NW_HOOK_MAP(type, sym, fn) BASE_EXPORT type fn; +#else +#define NW_HOOK_MAP(type, sym, fn) extern type fn; +#endif +#include "content/nw/src/common/node_hooks.h" +#undef NW_HOOK_MAP + +#include "base/command_line.h" + #include "core/dom/Document.h" #include "core/dom/SecurityContext.h" #include "core/dom/TaskRunnerHelper.h" @@ -94,6 +106,13 @@ void InProcessWorkerMessagingProxy::StartWorkerGlobalScope( Document* document = ToDocument(GetExecutionContext()); SecurityOrigin* starter_origin = document->GetSecurityOrigin(); + const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); + + bool isNodeJS = document->GetFrame() && document->GetFrame()->isNodeJS() && command_line.HasSwitch("enable-node-worker"); + std::string main_script; + if (g_web_worker_start_thread_fn) { + (*g_web_worker_start_thread_fn)(document->GetFrame(), (void*)script_url.GetPath().Utf8().data(), &main_script, &isNodeJS); + } ContentSecurityPolicy* csp = document->GetContentSecurityPolicy(); DCHECK(csp); @@ -111,7 +130,7 @@ void InProcessWorkerMessagingProxy::StartWorkerGlobalScope( IsAtomicsWaitAllowed() ? WorkerV8Settings::AtomicsWaitMode::kAllow : WorkerV8Settings::AtomicsWaitMode::kDisallow; std::unique_ptr<WorkerThreadStartupData> startup_data = - WorkerThreadStartupData::Create( + WorkerThreadStartupData::Create(isNodeJS, main_script, script_url, user_agent, source_code, nullptr, start_mode, csp->Headers().get(), referrer_policy, starter_origin, worker_clients_.Release(), document->AddressSpace(), diff --git a/third_party/WebKit/Source/core/workers/SharedWorker.cpp b/third_party/WebKit/Source/core/workers/SharedWorker.cpp index 2c0e976febc86..272e042a334b4 100644 --- a/third_party/WebKit/Source/core/workers/SharedWorker.cpp +++ b/third_party/WebKit/Source/core/workers/SharedWorker.cpp @@ -31,6 +31,8 @@ #include "core/workers/SharedWorker.h" +#include "base/command_line.h" + #include "bindings/core/v8/ExceptionState.h" #include "core/dom/ExecutionContext.h" #include "core/dom/MessageChannel.h" @@ -81,6 +83,8 @@ SharedWorker* SharedWorker::Create(ExecutionContext* context, if (script_url.IsEmpty()) return nullptr; + const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); + bool isNodeJS = document->GetFrame()->isNodeJS() && command_line.HasSwitch("enable-node-worker"); if (document->GetFrame() ->Loader() .Client() @@ -89,7 +93,7 @@ SharedWorker* SharedWorker::Create(ExecutionContext* context, ->Loader() .Client() ->GetSharedWorkerRepositoryClient() - ->Connect(worker, std::move(remote_port), script_url, name); + ->Connect(worker, std::move(remote_port), script_url, name, isNodeJS); } return worker; diff --git a/third_party/WebKit/Source/core/workers/SharedWorkerRepositoryClient.h b/third_party/WebKit/Source/core/workers/SharedWorkerRepositoryClient.h index 9e000012357a2..cf6f67a975b34 100644 --- a/third_party/WebKit/Source/core/workers/SharedWorkerRepositoryClient.h +++ b/third_party/WebKit/Source/core/workers/SharedWorkerRepositoryClient.h @@ -54,7 +54,7 @@ class CORE_EXPORT SharedWorkerRepositoryClient { virtual void Connect(SharedWorker*, std::unique_ptr<WebMessagePortChannel>, const KURL&, - const String& name) = 0; + const String& name, bool) = 0; virtual void DocumentDetached(Document*) = 0; }; diff --git a/third_party/WebKit/Source/core/workers/ThreadedWorkletMessagingProxy.cpp b/third_party/WebKit/Source/core/workers/ThreadedWorkletMessagingProxy.cpp index cf38c7bf066aa..dd16cc4d905b9 100644 --- a/third_party/WebKit/Source/core/workers/ThreadedWorkletMessagingProxy.cpp +++ b/third_party/WebKit/Source/core/workers/ThreadedWorkletMessagingProxy.cpp @@ -45,7 +45,7 @@ void ThreadedWorkletMessagingProxy::Initialize() { // TODO(ikilpatrick): Decide on sensible a value for referrerPolicy. std::unique_ptr<WorkerThreadStartupData> startup_data = - WorkerThreadStartupData::Create( + WorkerThreadStartupData::Create(false, std::string(), script_url, document->UserAgent(), String(), nullptr, start_mode, csp->Headers().get(), /* referrerPolicy */ String(), starter_origin, nullptr, document->AddressSpace(), diff --git a/third_party/WebKit/Source/core/workers/WorkerThread.cpp b/third_party/WebKit/Source/core/workers/WorkerThread.cpp index e35a0aa7e1b4c..e63e26f802e4a 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThread.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerThread.cpp @@ -59,6 +59,17 @@ #include "platform/wtf/Threading.h" #include "platform/wtf/text/WTFString.h" + +#include "third_party/node-nw/src/node_webkit.h" + +#if defined(COMPONENT_BUILD) && defined(WIN32) +#define NW_HOOK_MAP(type, sym, fn) BASE_EXPORT type fn; +#else +#define NW_HOOK_MAP(type, sym, fn) extern type fn; +#endif +#include "content/nw/src/common/node_hooks.h" +#undef NW_HOOK_MAP + namespace blink { using ExitCode = WorkerThread::ExitCode; @@ -452,6 +463,8 @@ void WorkerThread::InitializeOnWorkerThread( startup_data->worker_v8_settings_.atomics_wait_mode_ == WorkerV8Settings::AtomicsWaitMode::kAllow; + bool isNodeJS = startup_data->nodejs_; + std::string main_script = startup_data->main_script_; { MutexLocker lock(thread_state_mutex_); @@ -479,7 +492,7 @@ void WorkerThread::InitializeOnWorkerThread( worker_reporting_proxy_.DidInitializeWorkerContext(); v8::HandleScope handle_scope(GetIsolate()); Platform::Current()->WorkerContextCreated( - GlobalScope()->ScriptController()->GetContext()); + GlobalScope()->ScriptController()->GetContext(), isNodeJS, main_script); } SetThreadState(lock, ThreadState::kRunning); @@ -522,6 +535,8 @@ void WorkerThread::PrepareForShutdownOnWorkerThread() { SetExitCode(lock, ExitCode::kGracefullyTerminated); } + ::g_stop_nw_instance_fn(); + inspector_task_runner_->Kill(); GetWorkerReportingProxy().WillDestroyWorkerGlobalScope(); probe::AllAsyncTasksCanceled(GlobalScope()); diff --git a/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp b/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp index 5cb4b1670bb2b..996ed0cf3d414 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp @@ -37,6 +37,7 @@ namespace blink { WorkerThreadStartupData::WorkerThreadStartupData( + bool isNodeJS, const std::string& main_script, const KURL& script_url, const String& user_agent, const String& source_code, @@ -51,6 +52,8 @@ WorkerThreadStartupData::WorkerThreadStartupData( std::unique_ptr<WorkerSettings> worker_settings, WorkerV8Settings worker_v8_settings) : script_url_(script_url.Copy()), + nodejs_(isNodeJS), + main_script_(main_script), user_agent_(user_agent.IsolatedCopy()), source_code_(source_code.IsolatedCopy()), cached_meta_data_(std::move(cached_meta_data)), diff --git a/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h b/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h index dcf610e2f2610..65191ea85225b 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h +++ b/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h @@ -55,6 +55,7 @@ class CORE_EXPORT WorkerThreadStartupData final { public: static std::unique_ptr<WorkerThreadStartupData> Create( + bool isNodeJS, const std::string& main_script, const KURL& script_url, const String& user_agent, const String& source_code, @@ -68,7 +69,7 @@ class CORE_EXPORT WorkerThreadStartupData final { const Vector<String>* origin_trial_tokens, std::unique_ptr<WorkerSettings> worker_settings, WorkerV8Settings worker_v8_settings) { - return WTF::WrapUnique(new WorkerThreadStartupData( + return WTF::WrapUnique(new WorkerThreadStartupData(isNodeJS, main_script, script_url, user_agent, source_code, std::move(cached_meta_data), start_mode, content_security_policy_headers, referrer_policy, starter_origin, worker_clients, address_space, origin_trial_tokens, @@ -78,6 +79,8 @@ class CORE_EXPORT WorkerThreadStartupData final { ~WorkerThreadStartupData(); KURL script_url_; + bool nodejs_; + std::string main_script_; String user_agent_; String source_code_; std::unique_ptr<Vector<char>> cached_meta_data_; @@ -115,6 +118,7 @@ class CORE_EXPORT WorkerThreadStartupData final { private: WorkerThreadStartupData( + bool isNodeJS, const std::string& main_script, const KURL& script_url, const String& user_agent, const String& source_code, diff --git a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp index 3cd236d7ed07b..4b571f50b69ac 100644 --- a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp +++ b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp @@ -648,10 +648,12 @@ void XMLHttpRequest::open(const AtomicString& method, // exception thrown. // Refer : https://xhr.spec.whatwg.org/#sync-warning // Use count for XHR synchronous requests on main thread only. +#if 0 if (!GetDocument()->ProcessingBeforeUnload()) Deprecation::CountDeprecation( GetExecutionContext(), UseCounter::kXMLHttpRequestSynchronousInNonWorkerOutsideBeforeUnload); +#endif } method_ = FetchUtils::NormalizeMethod(method); diff --git a/third_party/WebKit/Source/devtools/BUILD.gn b/third_party/WebKit/Source/devtools/BUILD.gn index a976800d612fe..9027c728ba273 100644 --- a/third_party/WebKit/Source/devtools/BUILD.gn +++ b/third_party/WebKit/Source/devtools/BUILD.gn @@ -860,6 +860,7 @@ generated_resources = [ "$resources_out_dir/heap_snapshot_worker.js", "$resources_out_dir/utility_shared_worker.js", + "$resources_out_dir/product_registry_impl/product_registry_impl_module.js", # this contains non-autostart non-remote modules only. "$resources_out_dir/animation/animation_module.js", "$resources_out_dir/audits/audits_module.js", @@ -904,7 +905,6 @@ generated_remote_modules = [ "$resources_out_dir/cm_modes/cm_modes_module.js", "$resources_out_dir/emulated_devices/emulated_devices_module.js", "$resources_out_dir/gonzales/gonzales_module.js", - "$resources_out_dir/product_registry_impl/product_registry_impl_module.js", "$resources_out_dir/screencast/screencast_module.js", ] diff --git a/third_party/WebKit/Source/devtools/front_end/dom_extension/DOMExtension.js b/third_party/WebKit/Source/devtools/front_end/dom_extension/DOMExtension.js index 8f6733c0421cb..fb9fb698e6654 100644 --- a/third_party/WebKit/Source/devtools/front_end/dom_extension/DOMExtension.js +++ b/third_party/WebKit/Source/devtools/front_end/dom_extension/DOMExtension.js @@ -820,7 +820,16 @@ Node.prototype.getComponentRoot = function() { */ function isEnterKey(event) { // Check if in IME. - return event.keyCode !== 229 && event.key === 'Enter'; + // FIXME: Due to recent change in Chromium, `key` property is used to replace + // the deprecated property `keyIdentifier`. However chromedriver doesn't + // send `key` property with key event. This caused `event.key === 'Enter'` + // failed in DevTools frontend, which prevents executing statements in + // DevTools console. + // This workaround used the `keyCode` to test if it's `Enter` key as an + // alternation to testing `key` property. It should be replaced with + // upstream fix later. + // See https://bugs.chromium.org/p/chromedriver/issues/detail?id=1411#c4 + return event.keyCode !== 229 && (event.key === "Enter" || event.keyCode === 13); } /** diff --git a/third_party/WebKit/Source/devtools/front_end/inspector.json b/third_party/WebKit/Source/devtools/front_end/inspector.json index 21a943af6e3ad..8378e12487606 100644 --- a/third_party/WebKit/Source/devtools/front_end/inspector.json +++ b/third_party/WebKit/Source/devtools/front_end/inspector.json @@ -21,7 +21,7 @@ { "name": "timeline", "condition": "!v8only" }, { "name": "timeline_model", "condition": "!v8only" }, { "name": "product_registry", "type": "autostart" }, - { "name": "product_registry_impl", "condition": "!v8only", "type": "remote" }, + { "name": "product_registry_impl", "condition": "!v8only"}, { "name": "profiler" }, { "name": "resources", "condition": "!v8only" }, { "name": "audits", "condition": "!v8only" }, diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp index 94951470432f3..ba114fdd9dc1a 100644 --- a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp +++ b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp @@ -586,6 +586,8 @@ void CanvasRenderingContext2D::ResourceElementChanged() { } bool CanvasRenderingContext2D::OriginClean() const { + if (canvas()->GetDocument().GetFrame()->isNodeJS()) + return true; return host()->OriginClean(); } diff --git a/third_party/WebKit/Source/platform/FileChooser.cpp b/third_party/WebKit/Source/platform/FileChooser.cpp index f4df26588231e..918b7f6df9ae5 100644 --- a/third_party/WebKit/Source/platform/FileChooser.cpp +++ b/third_party/WebKit/Source/platform/FileChooser.cpp @@ -62,13 +62,14 @@ FileChooser::~FileChooser() {} void FileChooser::ChooseFiles(const Vector<FileChooserFileInfo>& files) { // FIXME: This is inelegant. We should not be looking at settings here. Vector<String> paths; + bool canceled = false; for (unsigned i = 0; i < files.size(); ++i) paths.push_back(files[i].path); if (settings_.selected_files == paths) - return; + canceled = true; if (client_) - client_->FilesChosen(files); + client_->FilesChosen(files, canceled); } Vector<String> FileChooserSettings::AcceptTypes() const { diff --git a/third_party/WebKit/Source/platform/FileChooser.h b/third_party/WebKit/Source/platform/FileChooser.h index c4bde99311bb7..e132fb00e9c0f 100644 --- a/third_party/WebKit/Source/platform/FileChooser.h +++ b/third_party/WebKit/Source/platform/FileChooser.h @@ -74,11 +74,15 @@ struct FileChooserSettings { // Returns a combined vector of acceptMIMETypes and acceptFileExtensions. Vector<String> PLATFORM_EXPORT AcceptTypes() const; + String initial_path; + String initial_value; + bool directory_chooser; + bool save_as; }; class PLATFORM_EXPORT FileChooserClient { public: - virtual void FilesChosen(const Vector<FileChooserFileInfo>&) = 0; + virtual void FilesChosen(const Vector<FileChooserFileInfo>&, bool canceled = false) = 0; virtual ~FileChooserClient(); protected: diff --git a/third_party/WebKit/Source/platform/LifecycleObserver.h b/third_party/WebKit/Source/platform/LifecycleObserver.h index b5cc38c8faa9b..213f5a0d13bc1 100644 --- a/third_party/WebKit/Source/platform/LifecycleObserver.h +++ b/third_party/WebKit/Source/platform/LifecycleObserver.h @@ -48,6 +48,7 @@ class LifecycleObserver : public GarbageCollectedMixin { SetContext(context); } + public: void SetContext(Context*); private: diff --git a/third_party/WebKit/Source/platform/bindings/ScriptState.cpp b/third_party/WebKit/Source/platform/bindings/ScriptState.cpp index ad2b9e12e224d..1b6d271c9384f 100644 --- a/third_party/WebKit/Source/platform/bindings/ScriptState.cpp +++ b/third_party/WebKit/Source/platform/bindings/ScriptState.cpp @@ -37,6 +37,8 @@ ScriptState::ScriptState(v8::Local<v8::Context> context, DCHECK(world_); context_.SetWeak(this, &ContextCollectedCallback); context->SetAlignedPointerInEmbedderData(kV8ContextPerContextDataIndex, this); + context->SetAlignedPointerInEmbedderData(33, nullptr); + context->SetAlignedPointerInEmbedderData(32, nullptr); } ScriptState::~ScriptState() { diff --git a/third_party/WebKit/Source/platform/bindings/ScriptState.h b/third_party/WebKit/Source/platform/bindings/ScriptState.h index ff299149fb0ea..83142fd21bdde 100644 --- a/third_party/WebKit/Source/platform/bindings/ScriptState.h +++ b/third_party/WebKit/Source/platform/bindings/ScriptState.h @@ -129,7 +129,7 @@ class PLATFORM_EXPORT ScriptState : public RefCounted<ScriptState> { // ScriptState::from() must not be called for a context that does not have // valid embedder data in the embedder field. SECURITY_CHECK(script_state); - SECURITY_CHECK(script_state->GetContext() == context); + SECURITY_CHECK(script_state->GetContext() == context || context->GetAlignedPointerFromEmbedderData(33) == (void*)0x08110800); return script_state; } diff --git a/third_party/WebKit/Source/platform/exported/WebSecurityOrigin.cpp b/third_party/WebKit/Source/platform/exported/WebSecurityOrigin.cpp index 8e976523c4cf0..d29e6e08395c0 100644 --- a/third_party/WebKit/Source/platform/exported/WebSecurityOrigin.cpp +++ b/third_party/WebKit/Source/platform/exported/WebSecurityOrigin.cpp @@ -160,4 +160,9 @@ void WebSecurityOrigin::GrantLoadLocalResources() const { Get()->GrantLoadLocalResources(); } -} // namespace blink +void WebSecurityOrigin::grantUniversalAccess() const +{ + Get()->GrantUniversalAccess(); +} + +} // namespace blink diff --git a/third_party/WebKit/Source/platform/scheduler/child/webthread_impl_for_worker_scheduler.cc b/third_party/WebKit/Source/platform/scheduler/child/webthread_impl_for_worker_scheduler.cc index 706b2f449dd12..65ce55ca4400c 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/webthread_impl_for_worker_scheduler.cc +++ b/third_party/WebKit/Source/platform/scheduler/child/webthread_impl_for_worker_scheduler.cc @@ -17,6 +17,18 @@ #include "platform/scheduler/child/worker_scheduler_impl.h" #include "public/platform/WebTraceLocation.h" +#include "v8.h" + +#include "third_party/node-nw/src/node_webkit.h" +#define PLATFORM_HOOK_MAP(type, sym, fn) PLATFORM_EXPORT type fn = nullptr; +#if defined(COMPONENT_BUILD) && defined(WIN32) +#define NW_HOOK_MAP(type, sym, fn) BASE_EXPORT type fn; +#else +#define NW_HOOK_MAP(type, sym, fn) extern type fn; +#endif +#include "content/nw/src/common/node_hooks.h" +#undef NW_HOOK_MAP + namespace blink { namespace scheduler { @@ -28,6 +40,8 @@ WebThreadImplForWorkerScheduler::WebThreadImplForWorkerScheduler( const char* name, base::Thread::Options options) : thread_(new base::Thread(name ? name : std::string())) { + if (g_web_worker_thread_new_fn) + (*g_web_worker_thread_new_fn)((void*)name, &options); bool started = thread_->StartWithOptions(options); CHECK(started); thread_task_runner_ = thread_->task_runner(); diff --git a/third_party/WebKit/Source/platform/weborigin/SecurityOrigin.h b/third_party/WebKit/Source/platform/weborigin/SecurityOrigin.h index 4aa92920ca29c..266cd54fd7fa6 100644 --- a/third_party/WebKit/Source/platform/weborigin/SecurityOrigin.h +++ b/third_party/WebKit/Source/platform/weborigin/SecurityOrigin.h @@ -87,6 +87,7 @@ class PLATFORM_EXPORT SecurityOrigin : public RefCounted<SecurityOrigin> { String Host() const { return host_; } String Domain() const { return domain_; } unsigned short Port() const { return port_; } + bool hasUniversalAccess() const { return universal_access_; } // |port()| will return 0 if the port is the default for an origin. This // method instead returns the effective port, even if it is the default port diff --git a/third_party/WebKit/Source/platform/wtf/BUILD.gn b/third_party/WebKit/Source/platform/wtf/BUILD.gn index 67fb512568a47..5d19034e49611 100644 --- a/third_party/WebKit/Source/platform/wtf/BUILD.gn +++ b/third_party/WebKit/Source/platform/wtf/BUILD.gn @@ -11,6 +11,7 @@ visibility = [ ":*", "//mojo/public/cpp/bindings/*", "//third_party/WebKit/*", + "//content/nw/*", ] config("wtf_config") { diff --git a/third_party/WebKit/Source/web/ChromeClientImpl.cpp b/third_party/WebKit/Source/web/ChromeClientImpl.cpp index 9ff6994c1267d..37e4c9e3a7200 100644 --- a/third_party/WebKit/Source/web/ChromeClientImpl.cpp +++ b/third_party/WebKit/Source/web/ChromeClientImpl.cpp @@ -370,7 +370,8 @@ WebNavigationPolicy EffectiveNavigationPolicy( Page* ChromeClientImpl::CreateWindow(LocalFrame* frame, const FrameLoadRequest& r, const WindowFeatures& features, - NavigationPolicy navigation_policy) { + NavigationPolicy navigation_policy, + WebString* manifest) { if (!web_view_->Client()) return nullptr; @@ -387,7 +388,7 @@ Page* ChromeClientImpl::CreateWindow(LocalFrame* frame, WebLocalFrameImpl::FromFrame(frame), WrappedResourceRequest(r.GetResourceRequest()), features, r.FrameName(), policy, - r.GetShouldSetOpener() == kNeverSetOpener || features.noopener)); + r.GetShouldSetOpener() == kNeverSetOpener || features.noopener, manifest)); if (!new_view) return nullptr; return new_view->GetPage(); @@ -740,12 +741,20 @@ void ChromeClientImpl::OpenFileChooser(LocalFrame* frame, WebFileChooserParams params; params.multi_select = file_chooser->GetSettings().allows_multiple_files; - params.directory = file_chooser->GetSettings().allows_directory_upload; + params.directory = file_chooser->GetSettings().allows_directory_upload || file_chooser->GetSettings().directory_chooser; params.accept_types = file_chooser->GetSettings().AcceptTypes(); params.selected_files = file_chooser->GetSettings().selected_files; + if (params.selected_files.size() > 0) { + params.initial_value = params.selected_files[0]; + } else { + params.initial_value = file_chooser->GetSettings().initial_value; + } params.use_media_capture = file_chooser->GetSettings().use_media_capture; params.need_local_path = file_chooser->GetSettings().allows_directory_upload; params.requestor = frame->GetDocument()->Url(); + params.initialPath = file_chooser->GetSettings().initial_path; + params.save_as = file_chooser->GetSettings().save_as; + params.extract_directory = file_chooser->GetSettings().allows_directory_upload; WebFileChooserCompletionImpl* chooser_completion = new WebFileChooserCompletionImpl(std::move(file_chooser)); diff --git a/third_party/WebKit/Source/web/ChromeClientImpl.h b/third_party/WebKit/Source/web/ChromeClientImpl.h index a307fc56bed2f..02bb8611aa13e 100644 --- a/third_party/WebKit/Source/web/ChromeClientImpl.h +++ b/third_party/WebKit/Source/web/ChromeClientImpl.h @@ -75,7 +75,7 @@ class WEB_EXPORT ChromeClientImpl final : public ChromeClient { Page* CreateWindow(LocalFrame*, const FrameLoadRequest&, const WindowFeatures&, - NavigationPolicy) override; + NavigationPolicy, WebString*) override; void Show(NavigationPolicy) override; void DidOverscroll(const FloatSize& overscroll_delta, const FloatSize& accumulated_overscroll, diff --git a/third_party/WebKit/Source/web/LocalFrameClientImpl.cpp b/third_party/WebKit/Source/web/LocalFrameClientImpl.cpp index 5754c09c82209..b5ffe71a4d7d8 100644 --- a/third_party/WebKit/Source/web/LocalFrameClientImpl.cpp +++ b/third_party/WebKit/Source/web/LocalFrameClientImpl.cpp @@ -151,6 +151,14 @@ bool IsBackForwardNavigationInProgress(LocalFrame* local_frame) { } // namespace +void LocalFrameClientImpl::willHandleNavigationPolicy(const ResourceRequest& request, NavigationPolicy* policy, WebString* manifest, bool new_win) +{ + if (web_frame_->Client()) { + WrappedResourceRequest webreq(request); + web_frame_->Client()->willHandleNavigationPolicy(web_frame_, webreq, (WebNavigationPolicy*)policy, manifest, new_win); + } +} + LocalFrameClientImpl::LocalFrameClientImpl(WebLocalFrameBase* frame) : web_frame_(frame) {} @@ -910,14 +918,15 @@ void LocalFrameClientImpl::DidChangeFrameOwnerProperties( if (!web_frame_->Client()) return; - web_frame_->Client()->DidChangeFrameOwnerProperties( - WebFrame::FromFrame(frame_element->ContentFrame()), - WebFrameOwnerProperties( + WebFrameOwnerProperties ownerProperties( frame_element->BrowsingContextContainerName(), frame_element->ScrollingMode(), frame_element->MarginWidth(), frame_element->MarginHeight(), frame_element->AllowFullscreen(), frame_element->AllowPaymentRequest(), frame_element->IsDisplayNone(), - frame_element->Csp(), frame_element->AllowedFeatures())); + frame_element->Csp(), frame_element->AllowedFeatures()); + ownerProperties.nwFakeTop = frame_element->FastHasAttribute(HTMLNames::nwfaketopAttr); + web_frame_->Client()->DidChangeFrameOwnerProperties( + WebFrame::FromFrame(frame_element->ContentFrame()), ownerProperties); } void LocalFrameClientImpl::DispatchWillStartUsingPeerConnectionHandler( diff --git a/third_party/WebKit/Source/web/LocalFrameClientImpl.h b/third_party/WebKit/Source/web/LocalFrameClientImpl.h index 372e3a94c66e2..66b99b8da5685 100644 --- a/third_party/WebKit/Source/web/LocalFrameClientImpl.h +++ b/third_party/WebKit/Source/web/LocalFrameClientImpl.h @@ -58,6 +58,7 @@ class LocalFrameClientImpl final : public LocalFrameClient { // LocalFrameClient ---------------------------------------------- void DidCreateNewDocument() override; + void willHandleNavigationPolicy(const blink::ResourceRequest& request, blink::NavigationPolicy* policy, WebString* manifest = nullptr, bool new_win = true) override; // Notifies the WebView delegate that the JS window object has been cleared, // giving it a chance to bind native objects to the window before script // parsing begins. diff --git a/third_party/WebKit/Source/web/WebEmbeddedWorkerImpl.cpp b/third_party/WebKit/Source/web/WebEmbeddedWorkerImpl.cpp index 91c1f35dc3722..11a77667b1f48 100644 --- a/third_party/WebKit/Source/web/WebEmbeddedWorkerImpl.cpp +++ b/third_party/WebKit/Source/web/WebEmbeddedWorkerImpl.cpp @@ -31,6 +31,20 @@ #include "web/WebEmbeddedWorkerImpl.h" #include <memory> + +#include "third_party/node-nw/src/node_webkit.h" +#if defined(COMPONENT_BUILD) && defined(WIN32) +#define NW_HOOK_MAP(type, sym, fn) BASE_EXPORT type fn; +#define BLINK_HOOK_MAP(type, sym, fn) BASE_EXPORT type fn; +#else +#define NW_HOOK_MAP(type, sym, fn) extern type fn; +#define BLINK_HOOK_MAP(type, sym, fn) extern type fn; +#endif +#include "content/nw/src/common/node_hooks.h" +#undef NW_HOOK_MAP + +#include "base/command_line.h" + #include "bindings/core/v8/SourceLocation.h" #include "core/dom/Document.h" #include "core/dom/SecurityContext.h" @@ -411,6 +425,8 @@ void WebEmbeddedWorkerImpl::StartWorkerThread() { DCHECK(!asked_to_terminate_); Document* document = main_frame_->GetFrame()->GetDocument(); + const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); + bool isNodeJS = document->GetFrame() && document->GetFrame()->isNodeJS() && command_line.HasSwitch("enable-node-worker"); // FIXME: this document's origin is pristine and without any extra privileges. // (crbug.com/254993) @@ -456,8 +472,12 @@ void WebEmbeddedWorkerImpl::StartWorkerThread() { worker_v8_settings.v8_cache_options_ = static_cast<V8CacheOptions>(worker_start_data_.v8_cache_options); + std::string main_script; + if (g_web_worker_start_thread_fn) { + (*g_web_worker_start_thread_fn)(main_frame_->GetFrame(), (void*)script_url.GetPath().Utf8().data(), &main_script, &isNodeJS); + } std::unique_ptr<WorkerThreadStartupData> startup_data = - WorkerThreadStartupData::Create( + WorkerThreadStartupData::Create(isNodeJS, main_script, script_url, worker_start_data_.user_agent, main_script_loader_->SourceText(), main_script_loader_->ReleaseCachedMetadata(), start_mode, diff --git a/third_party/WebKit/Source/web/WebKit.cpp b/third_party/WebKit/Source/web/WebKit.cpp index e87484f4b15c6..a228e479e7464 100644 --- a/third_party/WebKit/Source/web/WebKit.cpp +++ b/third_party/WebKit/Source/web/WebKit.cpp @@ -32,6 +32,22 @@ #include <memory> +#include "third_party/node-nw/src/node_webkit.h" +#if defined(COMPONENT_BUILD) && defined(WIN32) +#define NW_HOOK_MAP(type, sym, fn) BASE_EXPORT type fn; +#define BLINK_HOOK_MAP(type, sym, fn) BASE_EXPORT type fn; +#else +#define NW_HOOK_MAP(type, sym, fn) extern type fn; +#define BLINK_HOOK_MAP(type, sym, fn) extern type fn; +#endif +#include "content/nw/src/common/node_hooks.h" +#undef NW_HOOK_MAP + +#include "modules/gamepad/NavigatorGamepad.h" +#include "public/web/WebFrame.h" +#include "public/web/WebDocument.h" +#include "core/dom/Document.h" + #include "bindings/core/v8/V8BindingForCore.h" #include "bindings/core/v8/V8GCController.h" #include "bindings/core/v8/V8Initializer.h" @@ -107,11 +123,23 @@ bool LayoutTestMode() { return LayoutTestSupport::IsRunningLayoutTest(); } +void set_web_worker_hooks(void* fn_start) { + g_web_worker_start_thread_fn = (VoidPtr4Fn)fn_start; +} + void SetMockThemeEnabledForTest(bool value) { LayoutTestSupport::SetMockThemeEnabledForTest(value); LayoutTheme::GetTheme().DidChangeThemeEngine(); } +void fix_gamepad_nw(WebFrame* frame) +{ + Document* doc = frame->GetDocument(); + NavigatorGamepad* gamepad = NavigatorGamepad::From(*doc); + ((ContextLifecycleObserver*)gamepad)->SetContext(static_cast<ExecutionContext*>(doc)); + gamepad->Gamepads(); +} + void SetFontAntialiasingEnabledForTest(bool value) { LayoutTestSupport::SetFontAntialiasingEnabledForTest(value); } diff --git a/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp b/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp index 25513bd30a241..060087154a720 100644 --- a/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp +++ b/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp @@ -1661,6 +1661,7 @@ LocalFrame* WebLocalFrameImpl::CreateChildFrame( owner_element->MarginHeight(), owner_element->AllowFullscreen(), owner_element->AllowPaymentRequest(), owner_element->IsDisplayNone(), owner_element->Csp(), owner_element->AllowedFeatures()); + owner_properties.nwFakeTop = owner_element->FastHasAttribute(HTMLNames::nwfaketopAttr); // FIXME: Using subResourceAttributeName as fallback is not a perfect // solution. subResourceAttributeName returns just one attribute name. The // element might not have the attribute, and there might be other attributes diff --git a/third_party/WebKit/Source/web/WebLocalFrameImpl.h b/third_party/WebKit/Source/web/WebLocalFrameImpl.h index 45d7d631b4066..c0dc3257f6637 100644 --- a/third_party/WebKit/Source/web/WebLocalFrameImpl.h +++ b/third_party/WebKit/Source/web/WebLocalFrameImpl.h @@ -396,6 +396,14 @@ class WEB_EXPORT WebLocalFrameImpl final } void SetInputEventsTransformForEmulation(const IntSize&, float) override; + void setNodeJS(bool node) { GetFrame()->setNodeJS(node); } + bool isNodeJS() const { return GetFrame()->isNodeJS(); } + bool isNwDisabledChildFrame() const { return GetFrame()->isNwDisabledChildFrame(); } + bool isNwFakeTop() const { return GetFrame()->isNwFakeTop(); } + void setDevtoolsJail(WebFrame* iframe) { + GetFrame()->setDevtoolsJail(iframe ? static_cast<const WebLocalFrameImpl*>(iframe)->GetFrame() : nullptr); + } + WebFrame* getDevtoolsJail() { return FromFrame((blink::LocalFrame*)GetFrame()->getDevtoolsJail()); } static void SelectWordAroundPosition(LocalFrame*, VisiblePosition); diff --git a/third_party/WebKit/Source/web/WebSharedWorkerImpl.cpp b/third_party/WebKit/Source/web/WebSharedWorkerImpl.cpp index 9b2a552d4db9b..e852763c0846d 100644 --- a/third_party/WebKit/Source/web/WebSharedWorkerImpl.cpp +++ b/third_party/WebKit/Source/web/WebSharedWorkerImpl.cpp @@ -31,6 +31,18 @@ #include "web/WebSharedWorkerImpl.h" #include <memory> + +#include "third_party/node-nw/src/node_webkit.h" +#if defined(COMPONENT_BUILD) && defined(WIN32) +#define NW_HOOK_MAP(type, sym, fn) BASE_EXPORT type fn; +#define BLINK_HOOK_MAP(type, sym, fn) BASE_EXPORT type fn; +#else +#define NW_HOOK_MAP(type, sym, fn) extern type fn; +#define BLINK_HOOK_MAP(type, sym, fn) extern type fn; +#endif +#include "content/nw/src/common/node_hooks.h" +#undef NW_HOOK_MAP + #include "core/dom/Document.h" #include "core/dom/TaskRunnerHelper.h" #include "core/events/MessageEvent.h" @@ -287,7 +299,8 @@ void WebSharedWorkerImpl::ConnectTaskOnWorkerThread( worker_global_scope->DispatchEvent(CreateConnectEvent(port)); } -void WebSharedWorkerImpl::StartWorkerContext( +void WebSharedWorkerImpl::StartWorkerContext(bool nodejs, + const base::FilePath& root_path, const WebURL& url, const WebString& name, const WebString& content_security_policy, @@ -295,6 +308,8 @@ void WebSharedWorkerImpl::StartWorkerContext( WebAddressSpace creation_address_space, bool data_saver_enabled) { DCHECK(IsMainThread()); + nodejs_ = nodejs; + root_path_ = root_path; url_ = url; name_ = name; creation_address_space_ = creation_address_space; @@ -328,6 +343,10 @@ void WebSharedWorkerImpl::OnScriptLoaderFinished() { // (e.g. GrantUniversalAccess) that can be overriden in regular documents // via WebPreference by embedders. (crbug.com/254993) SecurityOrigin* starter_origin = loading_document_->GetSecurityOrigin(); + std::string main_script = root_path_.AsUTF8Unsafe(); + if (g_web_worker_start_thread_fn && nodejs_) { + (*g_web_worker_start_thread_fn)(nullptr, (void*)main_script_loader_->Url().GetPath().Utf8().data(), &main_script, &nodejs_); + } WorkerClients* worker_clients = WorkerClients::Create(); ProvideLocalFileSystemToWorker(worker_clients, @@ -365,7 +384,7 @@ void WebSharedWorkerImpl::OnScriptLoaderFinished() { worker_v8_settings.atomics_wait_mode_ = WorkerV8Settings::AtomicsWaitMode::kAllow; std::unique_ptr<WorkerThreadStartupData> startup_data = - WorkerThreadStartupData::Create( + WorkerThreadStartupData::Create(nodejs_, main_script, url_, loading_document_->UserAgent(), main_script_loader_->SourceText(), nullptr, start_mode, content_security_policy ? content_security_policy->Headers().get() diff --git a/third_party/WebKit/Source/web/WebSharedWorkerImpl.h b/third_party/WebKit/Source/web/WebSharedWorkerImpl.h index 6d5f44e85e2a5..abd9dbbca7448 100644 --- a/third_party/WebKit/Source/web/WebSharedWorkerImpl.h +++ b/third_party/WebKit/Source/web/WebSharedWorkerImpl.h @@ -86,7 +86,7 @@ class WebSharedWorkerImpl final : public WebFrameClient, override; // WebSharedWorker methods: - void StartWorkerContext(const WebURL&, + void StartWorkerContext(bool, const base::FilePath&, const WebURL&, const WebString& name, const WebString& content_security_policy, WebContentSecurityPolicyType, @@ -162,6 +162,8 @@ class WebSharedWorkerImpl final : public WebFrameClient, RefPtr<WorkerLoaderProxy> loader_proxy_; + bool nodejs_; + base::FilePath root_path_; WebURL url_; WebString name_; WebAddressSpace creation_address_space_; diff --git a/third_party/WebKit/Source/web/tests/WebFrameTest.cpp b/third_party/WebKit/Source/web/tests/WebFrameTest.cpp index c52e3c2381eea..876e6f4a300ba 100644 --- a/third_party/WebKit/Source/web/tests/WebFrameTest.cpp +++ b/third_party/WebKit/Source/web/tests/WebFrameTest.cpp @@ -7268,7 +7268,7 @@ class TestNewWindowWebViewClient : public FrameTestHelpers::TestWebViewClient { const WebWindowFeatures&, const WebString&, WebNavigationPolicy, - bool) override { + bool, WebString*) override { EXPECT_TRUE(false); return 0; } diff --git a/third_party/WebKit/Source/web/tests/WebViewTest.cpp b/third_party/WebKit/Source/web/tests/WebViewTest.cpp index ab6f21d3275a9..9381c181ab36d 100644 --- a/third_party/WebKit/Source/web/tests/WebViewTest.cpp +++ b/third_party/WebKit/Source/web/tests/WebViewTest.cpp @@ -2816,7 +2816,7 @@ class ViewCreatingWebViewClient : public FrameTestHelpers::TestWebViewClient { const WebWindowFeatures&, const WebString& name, WebNavigationPolicy, - bool) override { + bool, WebString*) override { return web_view_helper_.InitializeWithOpener(opener, true); } diff --git a/third_party/WebKit/public/platform/Platform.h b/third_party/WebKit/public/platform/Platform.h index f7360bf6cb93b..c2a776e9064c3 100644 --- a/third_party/WebKit/public/platform/Platform.h +++ b/third_party/WebKit/public/platform/Platform.h @@ -574,7 +574,7 @@ class BLINK_PLATFORM_EXPORT Platform { virtual void DidStartWorkerThread() {} virtual void WillStopWorkerThread() {} - virtual void WorkerContextCreated(const v8::Local<v8::Context>& worker) {} + virtual void WorkerContextCreated(const v8::Local<v8::Context>& worker, bool, const std::string&) {} virtual bool AllowScriptExtensionForServiceWorker(const WebURL& script_url) { return false; } diff --git a/third_party/WebKit/public/platform/WebSecurityOrigin.h b/third_party/WebKit/public/platform/WebSecurityOrigin.h index 63877837f8193..790bcd2a82e70 100644 --- a/third_party/WebKit/public/platform/WebSecurityOrigin.h +++ b/third_party/WebKit/public/platform/WebSecurityOrigin.h @@ -110,6 +110,8 @@ class WebSecurityOrigin { // Allows this WebSecurityOrigin access to local resources. BLINK_PLATFORM_EXPORT void GrantLoadLocalResources() const; + BLINK_PLATFORM_EXPORT void grantUniversalAccess() const; + #if INSIDE_BLINK BLINK_PLATFORM_EXPORT WebSecurityOrigin(WTF::PassRefPtr<SecurityOrigin>); BLINK_PLATFORM_EXPORT WebSecurityOrigin& operator=( diff --git a/third_party/WebKit/public/web/WebFileChooserParams.h b/third_party/WebKit/public/web/WebFileChooserParams.h index 28b3ac074387b..3da2940cee66d 100644 --- a/third_party/WebKit/public/web/WebFileChooserParams.h +++ b/third_party/WebKit/public/web/WebFileChooserParams.h @@ -49,6 +49,8 @@ struct WebFileChooserParams { bool save_as; // |title| is the title for a file chooser dialog. It can be an empty string. WebString title; + // revert 14785d90f691b2b20d07612a62ba35a630bbb9ac for nwsaveas #5667 + WebString initial_value; // This contains MIME type strings such as "audio/*" "text/plain" or file // extensions beginning with a period (.) such as ".mp3" ".txt". // The dialog may restrict selectable files to files with the specified MIME @@ -79,12 +81,15 @@ struct WebFileChooserParams { // initiated by a document. WebURL requestor; + WebString initialPath; + bool extract_directory; + WebFileChooserParams() : multi_select(false), directory(false), save_as(false), use_media_capture(false), - need_local_path(true) {} + need_local_path(true), extract_directory(true) {} }; } // namespace blink diff --git a/third_party/WebKit/public/web/WebFrame.h b/third_party/WebKit/public/web/WebFrame.h index ffcbe1e3626e0..8c2c40cd2dbca 100644 --- a/third_party/WebKit/public/web/WebFrame.h +++ b/third_party/WebKit/public/web/WebFrame.h @@ -108,6 +108,14 @@ class WebFrame { virtual bool IsWebRemoteFrame() const = 0; virtual WebRemoteFrame* ToWebRemoteFrame() = 0; + virtual bool isNwFakeTop() const {return false;} + + virtual void setNodeJS(bool) {} + virtual bool isNodeJS() const {return false;} + virtual bool isNwDisabledChildFrame() const {return false;} + + virtual void setDevtoolsJail(WebFrame*) {} + virtual WebFrame* getDevtoolsJail() {return nullptr;} BLINK_EXPORT bool Swap(WebFrame*); // This method closes and deletes the WebFrame. This is typically called by @@ -426,9 +434,9 @@ class WebFrame { // the given element is not a frame, iframe or if the frame is empty. BLINK_EXPORT static WebFrame* FromFrameOwnerElement(const WebElement&); + BLINK_EXPORT static WebFrame* FromFrame(Frame*); + #if BLINK_IMPLEMENTATION - // TODO(mustaq): Should be named FromCoreFrame instead. - static WebFrame* FromFrame(Frame*); BLINK_EXPORT static Frame* ToCoreFrame(const WebFrame&); bool InShadowTree() const { return scope_ == WebTreeScopeType::kShadow; } diff --git a/third_party/WebKit/public/web/WebFrameClient.h b/third_party/WebKit/public/web/WebFrameClient.h index c2e13f4c53e0f..755b4becd4e37 100644 --- a/third_party/WebKit/public/web/WebFrameClient.h +++ b/third_party/WebKit/public/web/WebFrameClient.h @@ -118,6 +118,8 @@ class BLINK_EXPORT WebFrameClient { virtual ~WebFrameClient() {} // Factory methods ----------------------------------------------------- + virtual void willHandleNavigationPolicy( + WebFrame*, const WebURLRequest&, WebNavigationPolicy*, WebString* manifest = NULL, bool new_win = true) { } // May return null. virtual WebPlugin* CreatePlugin(const WebPluginParams&) { return nullptr; } diff --git a/third_party/WebKit/public/web/WebFrameOwnerProperties.h b/third_party/WebKit/public/web/WebFrameOwnerProperties.h index 4be92a972d114..310dbb9c812a0 100644 --- a/third_party/WebKit/public/web/WebFrameOwnerProperties.h +++ b/third_party/WebKit/public/web/WebFrameOwnerProperties.h @@ -18,6 +18,7 @@ struct WebFrameOwnerProperties { WebString name; // browsing context container's name ScrollingMode scrolling_mode; + bool nwFakeTop; int margin_width; int margin_height; bool allow_fullscreen; @@ -29,7 +30,7 @@ struct WebFrameOwnerProperties { WebVector<WebFeaturePolicyFeature> allowed_features; WebFrameOwnerProperties() - : scrolling_mode(ScrollingMode::kAuto), + : scrolling_mode(ScrollingMode::kAuto), nwFakeTop(false), margin_width(-1), margin_height(-1), allow_fullscreen(false), @@ -49,6 +50,7 @@ struct WebFrameOwnerProperties { const WebVector<WebFeaturePolicyFeature>& allowed_features) : name(name), scrolling_mode(static_cast<ScrollingMode>(scrolling_mode)), + nwFakeTop(false), margin_width(margin_width), margin_height(margin_height), allow_fullscreen(allow_fullscreen), diff --git a/third_party/WebKit/public/web/WebKit.h b/third_party/WebKit/public/web/WebKit.h index be86b32c5dad2..736bf091f87d0 100644 --- a/third_party/WebKit/public/web/WebKit.h +++ b/third_party/WebKit/public/web/WebKit.h @@ -35,7 +35,7 @@ #include "v8/include/v8.h" namespace blink { - +class WebFrame; // Initialize the entire Blink (wtf, platform, core, modules and web). // If you just need wtf and platform, use Platform::initialize instead. // @@ -52,6 +52,8 @@ BLINK_EXPORT v8::Isolate* MainThreadIsolate(); BLINK_EXPORT void SetLayoutTestMode(bool); BLINK_EXPORT bool LayoutTestMode(); +BLINK_EXPORT void set_web_worker_hooks(void*); +BLINK_EXPORT void fix_gamepad_nw(WebFrame*); // Enables or disables the use of the mock theme for layout tests. This function // must be called only if setLayoutTestMode(true). BLINK_EXPORT void SetMockThemeEnabledForTest(bool); diff --git a/third_party/WebKit/public/web/WebNode.h b/third_party/WebKit/public/web/WebNode.h index 466ede079f046..f9a3d20132d26 100644 --- a/third_party/WebKit/public/web/WebNode.h +++ b/third_party/WebKit/public/web/WebNode.h @@ -110,8 +110,8 @@ class WebNode { template <typename T> const T ToConst() const; -#if BLINK_IMPLEMENTATION BLINK_EXPORT WebNode(Node*); +#if BLINK_IMPLEMENTATION BLINK_EXPORT WebNode& operator=(Node*); BLINK_EXPORT operator Node*() const; diff --git a/third_party/WebKit/public/web/WebSharedWorker.h b/third_party/WebKit/public/web/WebSharedWorker.h index 8ab3a7bc99ae2..3f58c0ec6ad50 100644 --- a/third_party/WebKit/public/web/WebSharedWorker.h +++ b/third_party/WebKit/public/web/WebSharedWorker.h @@ -35,6 +35,10 @@ #include "public/platform/WebCommon.h" #include "public/platform/WebContentSecurityPolicy.h" +namespace base { + class FilePath; +} + namespace blink { class WebString; @@ -50,7 +54,7 @@ class WebSharedWorker { // lifetime as this instance. BLINK_EXPORT static WebSharedWorker* Create(WebSharedWorkerClient*); - virtual void StartWorkerContext(const WebURL& script_url, + virtual void StartWorkerContext(bool nodejs, const base::FilePath& root_path, const WebURL& scriptURL, const WebString& name, const WebString& content_security_policy, WebContentSecurityPolicyType, diff --git a/third_party/WebKit/public/web/WebSharedWorkerRepositoryClient.h b/third_party/WebKit/public/web/WebSharedWorkerRepositoryClient.h index f9f9c49bcc379..921b47b17c636 100644 --- a/third_party/WebKit/public/web/WebSharedWorkerRepositoryClient.h +++ b/third_party/WebKit/public/web/WebSharedWorkerRepositoryClient.h @@ -50,7 +50,7 @@ class WebSharedWorkerRepositoryClient { using DocumentID = unsigned long long; // Connects to a shared worker. - virtual void Connect(const WebURL& url, + virtual void Connect(bool isNodeJS, const WebURL& url, const WebString& name, DocumentID id, const WebString& content_security_policy, diff --git a/third_party/WebKit/public/web/WebViewClient.h b/third_party/WebKit/public/web/WebViewClient.h index 644c9c0239d09..5423100f8f61d 100644 --- a/third_party/WebKit/public/web/WebViewClient.h +++ b/third_party/WebKit/public/web/WebViewClient.h @@ -76,7 +76,7 @@ class WebViewClient : protected WebWidgetClient { const WebWindowFeatures& features, const WebString& name, WebNavigationPolicy policy, - bool suppress_opener) { + bool suppress_opener, WebString* manifest = nullptr) { return 0; } diff --git a/third_party/crashpad/crashpad/handler/crash_report_upload_thread.cc b/third_party/crashpad/crashpad/handler/crash_report_upload_thread.cc index d77cdbadc482a..ed235129c818d 100644 --- a/third_party/crashpad/crashpad/handler/crash_report_upload_thread.cc +++ b/third_party/crashpad/crashpad/handler/crash_report_upload_thread.cc @@ -14,6 +14,7 @@ #include "handler/crash_report_upload_thread.h" +#include "base/strings/stringprintf.h" #include <errno.h> #include <time.h> @@ -239,7 +240,7 @@ void CrashReportUploadThread::ProcessPendingReport( Settings* const settings = database_->GetSettings(); bool uploads_enabled; - if (url_.empty() || + if (//url_.empty() || (!report.upload_explicitly_requested && (!settings->GetUploadsEnabled(&uploads_enabled) || !uploads_enabled))) { // Don’t attempt an upload if there’s no URL to upload to. Allow upload if @@ -268,7 +269,7 @@ void CrashReportUploadThread::ProcessPendingReport( // If the most recent upload attempt occurred within the past hour, // don’t attempt to upload the new report. If it happened longer ago, // attempt to upload the report. - const int kUploadAttemptIntervalSeconds = 60 * 60; // 1 hour + const int kUploadAttemptIntervalSeconds = 0; // 60 * 60; // 1 hour if (now - last_upload_attempt_time < kUploadAttemptIntervalSeconds) { database_->SkipReportUpload( report.uuid, Metrics::CrashSkippedReason::kUploadThrottled); @@ -358,6 +359,17 @@ CrashReportUploadThread::UploadResult CrashReportUploadThread::UploadReport( parameters = BreakpadHTTPFormParametersFromMinidump(&minidump_file_reader); } + std::string upload_url; + int i = 1; + do { + std::string key = base::StringPrintf("url-nwjs-%d", i); + if (parameters.find(key) == parameters.end()) + break; + upload_url += parameters[key]; + i++; + } while (true); + if (!url_.empty()) + upload_url = url_; HTTPMultipartBuilder http_multipart_builder; http_multipart_builder.SetGzipEnabled(upload_gzip_); @@ -383,7 +395,7 @@ CrashReportUploadThread::UploadResult CrashReportUploadThread::UploadReport( "application/octet-stream"); std::unique_ptr<HTTPTransport> http_transport(HTTPTransport::Create()); - http_transport->SetURL(url_); + http_transport->SetURL(upload_url); HTTPHeaders content_headers; http_multipart_builder.PopulateContentHeaders(&content_headers); for (const auto& content_header : content_headers) { diff --git a/tools/grit/grit_rule.gni b/tools/grit/grit_rule.gni index 3db7a6c6b210c..5048c4671da4b 100644 --- a/tools/grit/grit_rule.gni +++ b/tools/grit/grit_rule.gni @@ -132,6 +132,13 @@ if (is_chrome_branded) { ] } +if (nwjs_sdk) { + grit_defines += [ + "-D", + "nwjs_sdk", + ] +} + if (is_chromeos) { grit_defines += [ "-D", diff --git a/tools/gritsettings/resource_ids b/tools/gritsettings/resource_ids index 25abc655bf848..8ccc890b202a7 100644 --- a/tools/gritsettings/resource_ids +++ b/tools/gritsettings/resource_ids @@ -30,6 +30,11 @@ # # chrome/ and ios/chrome/ must start at the same id. # App only use one file depending on whether it is iOS or other platform. + "chrome/browser/browser_resources.grd": { + "includes": [400], + "structures": [850], + }, + # Chromium strings and Google Chrome strings must start at the same id. # We only use one file depending on whether we're building Chromium or # Google Chrome. @@ -371,4 +376,8 @@ # Please read the header and find the right section above instead. # Resource ids starting at 31000 are reserved for projects built on Chromium. + "chrome/browser/nwjs_resources.grd": { + "includes": [32000], + "structures": [32350], + }, } diff --git a/tools/licenses.py b/tools/licenses.py index bf0b53bc9c313..39dae132e3d69 100755 --- a/tools/licenses.py +++ b/tools/licenses.py @@ -102,6 +102,7 @@ 'layout_tests')) # lots of subdirs ADDITIONAL_PATHS = ( + os.path.join('content', 'nw'), os.path.join('breakpad'), os.path.join('chrome', 'common', 'extensions', 'docs', 'examples'), os.path.join('chrome', 'test', 'chromeos', 'autotest'), @@ -124,6 +125,16 @@ # can't provide a README.chromium. Please prefer a README.chromium # wherever possible. SPECIAL_CASES = { + os.path.join('content', 'nw'): { + "Name": "NW.js", + "URL": "http://nwjs.io", + "License": "MIT", + }, + os.path.join('third_party', 'node'): { + "Name": "IO.js", + "URL": "https://iojs.org", + "License": "MIT", + }, os.path.join('native_client'): { "Name": "native client", "URL": "http://code.google.com/p/nativeclient", diff --git a/ui/accelerated_widget_mac/BUILD.gn b/ui/accelerated_widget_mac/BUILD.gn index 5ca58ad0a4bd2..ea6724bb5d528 100644 --- a/ui/accelerated_widget_mac/BUILD.gn +++ b/ui/accelerated_widget_mac/BUILD.gn @@ -28,6 +28,7 @@ component("accelerated_widget_mac") { "//base", "//skia", "//ui/base", + "//ui/display", "//ui/events", "//ui/events:events_base", "//ui/gfx", diff --git a/ui/accelerated_widget_mac/accelerated_widget_mac.h b/ui/accelerated_widget_mac/accelerated_widget_mac.h index 55d1f7219b2c2..681fc75621815 100644 --- a/ui/accelerated_widget_mac/accelerated_widget_mac.h +++ b/ui/accelerated_widget_mac/accelerated_widget_mac.h @@ -19,6 +19,8 @@ #include "ui/gfx/geometry/size.h" #include "ui/gfx/native_widget_types.h" +class SkCanvas; + namespace ui { class FullscreenLowPowerCoordinator; @@ -76,6 +78,9 @@ class ACCELERATED_WIDGET_MAC_EXPORT AcceleratedWidgetMac { const gfx::Size& pixel_size, float scale_factor); + void GotSoftwareFrame(float scale_factor, + SkCanvas* canvas); + private: // The AcceleratedWidgetMacNSView that is using this as its internals. AcceleratedWidgetMacNSView* view_; @@ -110,6 +115,10 @@ class ACCELERATED_WIDGET_MAC_EXPORT AcceleratedWidgetMac { DISALLOW_COPY_AND_ASSIGN(AcceleratedWidgetMac); }; +ACCELERATED_WIDGET_MAC_EXPORT +void AcceleratedWidgetMacGotSoftwareFrame( + gfx::AcceleratedWidget widget, float scale_factor, SkCanvas* canvas); + } // namespace ui #endif // UI_ACCELERATED_WIDGET_MAC_ACCELERATED_WIDGET_MAC_H_ diff --git a/ui/accelerated_widget_mac/accelerated_widget_mac.mm b/ui/accelerated_widget_mac/accelerated_widget_mac.mm index 2c9dd436f98e8..08ee44f5dacf0 100644 --- a/ui/accelerated_widget_mac/accelerated_widget_mac.mm +++ b/ui/accelerated_widget_mac/accelerated_widget_mac.mm @@ -13,6 +13,7 @@ #include "base/message_loop/message_loop.h" #include "base/trace_event/trace_event.h" #include "third_party/skia/include/core/SkCanvas.h" +#include "third_party/skia/include/core/SkPixmap.h" #include "ui/accelerated_widget_mac/fullscreen_low_power_coordinator.h" #include "ui/base/cocoa/animation_utils.h" #include "ui/gfx/geometry/dip_util.h" @@ -22,6 +23,10 @@ @interface CALayer (PrivateAPI) - (void)setContentsChanged; @end +namespace content { + extern bool g_force_cpu_draw; +} + namespace ui { namespace { @@ -231,4 +236,91 @@ - (void)setContentsChanged; view_->AcceleratedWidgetSwapCompleted(); } +// this function is "copied" from AcceleratedWidgetMac::GotIOSurfaceFrame +void AcceleratedWidgetMac::GotSoftwareFrame(float scale_factor, + SkCanvas* canvas) { + TRACE_EVENT0("ui", "AcceleratedWidgetMac GotSoftwareFrame"); + assert(content::g_force_cpu_draw); + if (!canvas || !view_) { + TRACE_EVENT0("ui", "No associated NSView or No canvas"); + return; + } + + // Disable the fade-in or fade-out effect if we create or remove layers. + ScopedCAActionDisabler disabler; + + // Create (if needed) and update the IOSurface layer with new content. + if (!io_surface_layer_) { + io_surface_layer_.reset([[CALayer alloc] init]); + [io_surface_layer_ setContentsGravity:kCAGravityTopLeft]; + [io_surface_layer_ setAnchorPoint:CGPointMake(0, 0)]; + [flipped_layer_ addSublayer:io_surface_layer_]; + if (content::g_force_cpu_draw) + [io_surface_layer_.get() setBackgroundColor:[flipped_layer_.get() backgroundColor]]; + } + + // Set the software layer to draw the provided canvas. + SkPixmap pixmap; + canvas->peekPixels(&pixmap); + const SkImageInfo& info = pixmap.info(); + const size_t row_bytes = pixmap.rowBytes(); + const void* pixels = pixmap.addr(); + gfx::Size pixel_size(info.width(), info.height()); + last_swap_size_dip_ = gfx::ConvertSizeToDIP(scale_factor, pixel_size); + + // Set the contents of the software CALayer to be a CGImage with the provided + // pixel data. Make a copy of the data before backing the image with them, + // because the same buffer will be reused for the next frame. + base::ScopedCFTypeRef<CFDataRef> dataCopy( + CFDataCreate(NULL, + static_cast<const UInt8 *>(pixels), + row_bytes * pixel_size.height())); + base::ScopedCFTypeRef<CGDataProviderRef> dataProvider( + CGDataProviderCreateWithCFData(dataCopy)); + base::ScopedCFTypeRef<CGImageRef> image( + CGImageCreate(pixel_size.width(), + pixel_size.height(), + 8, + 32, + row_bytes, + base::mac::GetSystemColorSpace(), + kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host, + dataProvider, + NULL, + false, + kCGRenderingIntentDefault)); + + id new_contents = (id)image.get(); + if (new_contents && new_contents == [io_surface_layer_ contents]) + [io_surface_layer_ setContentsChanged]; + else + [io_surface_layer_ setContents:new_contents]; + [io_surface_layer_ setBounds:CGRectMake(0, 0, last_swap_size_dip_.width(), + last_swap_size_dip_.height())]; + if ([io_surface_layer_ contentsScale] != scale_factor) + [io_surface_layer_ setContentsScale:scale_factor]; + + // Ensure that the content layer is removed. + if (content_layer_) { + [content_layer_ removeFromSuperlayer]; + content_layer_.reset(); + } + + if (content::g_force_cpu_draw) { + // this is to tell parent window, that the window content has been updated + [[view_->AcceleratedWidgetGetNSView() superview]setNeedsDisplay:YES]; + } + view_->AcceleratedWidgetSwapCompleted(); +} + +void AcceleratedWidgetMacGotSoftwareFrame( + gfx::AcceleratedWidget widget, float scale_factor, SkCanvas* canvas) { + assert(content::g_force_cpu_draw); + + AcceleratedWidgetMac* accelerated_widget_mac = + ui::AcceleratedWidgetMac::Get(widget); + if (accelerated_widget_mac) + accelerated_widget_mac->GotSoftwareFrame(scale_factor, canvas); +} + } // namespace ui diff --git a/ui/accessibility/platform/atk_util_auralinux.cc b/ui/accessibility/platform/atk_util_auralinux.cc index 0b25fcb10fe87..c12a56641979e 100644 --- a/ui/accessibility/platform/atk_util_auralinux.cc +++ b/ui/accessibility/platform/atk_util_auralinux.cc @@ -165,7 +165,7 @@ AtkUtilAuraLinux::AtkUtilAuraLinux() : is_enabled_(false) {} void AtkUtilAuraLinux::Initialize( scoped_refptr<base::TaskRunner> init_task_runner) { - +#if 0 // Register our util class. g_type_class_unref(g_type_class_ref(ATK_UTIL_AURALINUX_TYPE)); @@ -180,6 +180,7 @@ void AtkUtilAuraLinux::Initialize( base::Bind( &AtkUtilAuraLinux::FinishAccessibilityInitOnUIThread, base::Unretained(this))); +#endif } AtkUtilAuraLinux::~AtkUtilAuraLinux() { diff --git a/ui/base/accelerators/accelerator.cc b/ui/base/accelerators/accelerator.cc index 8b8d14e1a5fbe..6a53cd04f2280 100644 --- a/ui/base/accelerators/accelerator.cc +++ b/ui/base/accelerators/accelerator.cc @@ -5,6 +5,7 @@ #include "ui/base/accelerators/accelerator.h" #include <stdint.h> +#include "base/strings/stringprintf.h" #include "base/i18n/rtl.h" #include "base/logging.h" @@ -198,7 +199,9 @@ base::string16 Accelerator::GetShortcutText() const { } base::string16 shortcut; - if (!string_id) { + if (!string_id && key_code_ >= VKEY_F1 && key_code_ <= VKEY_F12) + shortcut = base::UTF8ToUTF16(base::StringPrintf("F%d", key_code_ - VKEY_F1 + 1)); + else if (!string_id) { #if defined(OS_WIN) // Our fallback is to try translate the key code to a regular character // unless it is one of digits (VK_0 to VK_9). Some keyboard @@ -243,7 +246,8 @@ base::string16 Accelerator::GetShortcutText() const { // more information. if (IsCtrlDown()) shortcut = l10n_util::GetStringFUTF16(IDS_APP_CONTROL_MODIFIER, shortcut); - else if (IsAltDown()) + + if (IsAltDown()) shortcut = l10n_util::GetStringFUTF16(IDS_APP_ALT_MODIFIER, shortcut); if (IsCmdDown()) { @@ -251,6 +255,10 @@ base::string16 Accelerator::GetShortcutText() const { shortcut = l10n_util::GetStringFUTF16(IDS_APP_COMMAND_MODIFIER, shortcut); #elif defined(OS_CHROMEOS) shortcut = l10n_util::GetStringFUTF16(IDS_APP_SEARCH_MODIFIER, shortcut); +#elif defined(OS_WIN) + shortcut = l10n_util::GetStringFUTF16(IDS_APP_WINDOWS_MODIFIER, shortcut); +#elif defined(OS_LINUX) + shortcut = l10n_util::GetStringFUTF16(IDS_APP_SUPER_MODIFIER, shortcut); #else NOTREACHED(); #endif diff --git a/ui/base/base_window.cc b/ui/base/base_window.cc index 231a1771797ef..40e00cb7cdb69 100644 --- a/ui/base/base_window.cc +++ b/ui/base/base_window.cc @@ -12,5 +12,9 @@ bool BaseWindow::IsRestored(const BaseWindow& window) { !window.IsFullscreen(); } +void BaseWindow::ForceClose() { + Close(); +} + } // namespace ui diff --git a/ui/base/base_window.h b/ui/base/base_window.h index 5ba8480da3979..1783be7082d8e 100644 --- a/ui/base/base_window.h +++ b/ui/base/base_window.h @@ -63,6 +63,7 @@ class UI_BASE_EXPORT BaseWindow { // Closes the window as soon as possible. The close action may be delayed // if an operation is in progress (e.g. a drag operation). virtual void Close() = 0; + virtual void ForceClose(); // Activates (brings to front) the window. Restores the window from minimized // state if necessary. diff --git a/ui/base/clipboard/clipboard.h b/ui/base/clipboard/clipboard.h index dd18ad5fe1132..fa12e30f9d8aa 100644 --- a/ui/base/clipboard/clipboard.h +++ b/ui/base/clipboard/clipboard.h @@ -244,7 +244,7 @@ class UI_BASE_EXPORT Clipboard : NON_EXPORTED_BASE(public base::ThreadChecker) { static const FormatType& GetIDListFormatType(); #endif - protected: + public: static Clipboard* Create(); Clipboard() {} diff --git a/ui/base/models/simple_menu_model.cc b/ui/base/models/simple_menu_model.cc index 0fcddb1cb4f08..047b5dd6a0761 100644 --- a/ui/base/models/simple_menu_model.cc +++ b/ui/base/models/simple_menu_model.cc @@ -68,6 +68,10 @@ void SimpleMenuModel::Delegate::CommandIdHighlighted(int command_id) { void SimpleMenuModel::Delegate::MenuWillShow(SimpleMenuModel* /*source*/) { } +bool SimpleMenuModel::Delegate::HasIcon(int command_id) { + return false; +} + void SimpleMenuModel::Delegate::MenuClosed(SimpleMenuModel* /*source*/) { } @@ -275,7 +279,7 @@ int SimpleMenuModel::GetIndexOfCommandId(int command_id) const { bool SimpleMenuModel::HasIcons() const { for (ItemVector::const_iterator i = items_.begin(); i != items_.end(); ++i) { - if (!i->icon.IsEmpty()) + if (delegate_->HasIcon(i->command_id)) return true; } diff --git a/ui/base/models/simple_menu_model.h b/ui/base/models/simple_menu_model.h index 9a9f35050950e..9e19f0d83d3a1 100644 --- a/ui/base/models/simple_menu_model.h +++ b/ui/base/models/simple_menu_model.h @@ -69,6 +69,8 @@ class UI_BASE_EXPORT SimpleMenuModel : public MenuModel { bool GetAcceleratorForCommandId( int command_id, ui::Accelerator* accelerator) const override; + + virtual bool HasIcon(int command_id); }; // The Delegate can be NULL, though if it is items can't be checked or diff --git a/ui/base/resource/resource_bundle.cc b/ui/base/resource/resource_bundle.cc index 1a24b13c6108c..0e3f7ef8d3c3b 100644 --- a/ui/base/resource/resource_bundle.cc +++ b/ui/base/resource/resource_bundle.cc @@ -4,6 +4,8 @@ #include "ui/base/resource/resource_bundle.h" +#include "base/strings/string_util.h" + #include <stdint.h> #include <limits> @@ -72,6 +74,8 @@ const char kPakFileExtension[] = ".pak"; ResourceBundle* g_shared_instance_ = NULL; +base::string16 chromium_name, nwjs_name; + #if defined(OS_ANDROID) // Returns the scale factor closest to |scale| from the full list of factors. // Note that it does NOT rely on the list of supported scale factors. @@ -530,8 +534,10 @@ base::StringPiece ResourceBundle::GetRawDataResourceForScale( base::string16 ResourceBundle::GetLocalizedString(int message_id) { base::string16 string; - if (delegate_ && delegate_->GetLocalizedString(message_id, &string)) + if (delegate_ && delegate_->GetLocalizedString(message_id, &string)) { + base::ReplaceSubstringsAfterOffset(&string, 0, chromium_name, nwjs_name); return string; + } // Ensure that ReloadLocaleResources() doesn't drop the resources while // we're using them. @@ -575,6 +581,7 @@ base::string16 ResourceBundle::GetLocalizedString(int message_id) { } else if (encoding == ResourceHandle::UTF8) { msg = base::UTF8ToUTF16(data); } + base::ReplaceSubstringsAfterOffset(&msg, 0, chromium_name, nwjs_name); return msg; } @@ -706,6 +713,8 @@ ResourceBundle::~ResourceBundle() { void ResourceBundle::InitSharedInstance(Delegate* delegate) { DCHECK(g_shared_instance_ == NULL) << "ResourceBundle initialized twice"; g_shared_instance_ = new ResourceBundle(delegate); + chromium_name = base::ASCIIToUTF16("Chromium"); + nwjs_name = base::ASCIIToUTF16("NW.js"); static std::vector<ScaleFactor> supported_scale_factors; #if !defined(OS_IOS) // On platforms other than iOS, 100P is always a supported scale factor. @@ -750,12 +759,12 @@ void ResourceBundle::LoadChromeResources() { // scale factor to gfx::ImageSkia::AddRepresentation. if (IsScaleFactorSupported(SCALE_FACTOR_100P)) { AddDataPackFromPath(GetResourcesPakFilePath( - "chrome_100_percent.pak"), SCALE_FACTOR_100P); + "nw_100_percent.pak"), SCALE_FACTOR_100P); } if (IsScaleFactorSupported(SCALE_FACTOR_200P)) { AddOptionalDataPackFromPath(GetResourcesPakFilePath( - "chrome_200_percent.pak"), SCALE_FACTOR_200P); + "nw_200_percent.pak"), SCALE_FACTOR_200P); } } diff --git a/ui/base/resource/resource_bundle_mac.mm b/ui/base/resource/resource_bundle_mac.mm index 3b17113ddd461..eec08fe0de8b7 100644 --- a/ui/base/resource/resource_bundle_mac.mm +++ b/ui/base/resource/resource_bundle_mac.mm @@ -48,13 +48,13 @@ } // namespace void ResourceBundle::LoadCommonResources() { - AddDataPackFromPath(GetResourcesPakFilePath(@"chrome_100_percent", + AddDataPackFromPath(GetResourcesPakFilePath(@"nw_100_percent", nil), SCALE_FACTOR_100P); // On Mac we load 1x and 2x resources and we let the UI framework decide // which one to use. if (IsScaleFactorSupported(SCALE_FACTOR_200P)) { - AddDataPackFromPath(GetResourcesPakFilePath(@"chrome_200_percent", nil), + AddDataPackFromPath(GetResourcesPakFilePath(@"nw_200_percent", nil), SCALE_FACTOR_200P); } } diff --git a/ui/display/display.cc b/ui/display/display.cc index 4ec8ea0d063f2..81f0c7f2faffb 100644 --- a/ui/display/display.cc +++ b/ui/display/display.cc @@ -17,6 +17,16 @@ #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/size_conversions.h" +namespace content { + +// Switch to enable / disable code for window's transparency +DISPLAY_EXPORT bool g_support_transparency = true; + +// Switch to force cpu drawing, is used to enable click through on alpha pixels +extern bool g_force_cpu_draw; +bool g_force_cpu_draw = false; +} + namespace display { namespace { diff --git a/ui/display/display.h b/ui/display/display.h index 03c9ddd9b8a83..dda6011d2c0a3 100644 --- a/ui/display/display.h +++ b/ui/display/display.h @@ -14,6 +14,11 @@ #include "ui/gfx/geometry/rect.h" #include "ui/gfx/icc_profile.h" +namespace content { + DISPLAY_EXPORT extern bool g_support_transparency; + DISPLAY_EXPORT extern bool g_force_cpu_draw; +} + namespace display { namespace mojom { diff --git a/ui/gfx/BUILD.gn b/ui/gfx/BUILD.gn index e78c050cbb348..b3a21edb3703d 100644 --- a/ui/gfx/BUILD.gn +++ b/ui/gfx/BUILD.gn @@ -368,6 +368,7 @@ component("gfx") { if (is_mac) { libs = [ + "ApplicationServices.framework", "AppKit.framework", "CoreFoundation.framework", "CoreGraphics.framework", diff --git a/ui/gfx/icon_util.cc b/ui/gfx/icon_util.cc index eb0bcdb23dc09..dc3739ff63eb6 100644 --- a/ui/gfx/icon_util.cc +++ b/ui/gfx/icon_util.cc @@ -232,6 +232,21 @@ base::win::ScopedHICON IconUtil::CreateHICONFromSkBitmap( return icon; } +// NW fix: copied and modified from chrome/browser/ui/views/frame/glass_browser_frame_view.cc +// Converts the |image| to a Windows icon and returns the corresponding HICON +// handle. |image| is resized to desired |width| and |height| if needed. +base::win::ScopedHICON IconUtil::CreateHICONFromSkBitmapSizedTo( + const SkBitmap& bitmap, + int width, + int height) { + return CreateHICONFromSkBitmap( + width == bitmap.width() && height == bitmap.height() + ? bitmap + : skia::ImageOperations::Resize(bitmap, + skia::ImageOperations::RESIZE_BEST, + width, height)); +} + SkBitmap* IconUtil::CreateSkBitmapFromHICON(HICON icon, const gfx::Size& s) { // We start with validating parameters. if (!icon || s.IsEmpty()) diff --git a/ui/gfx/icon_util.h b/ui/gfx/icon_util.h index e542caec0e1db..27191b454913d 100644 --- a/ui/gfx/icon_util.h +++ b/ui/gfx/icon_util.h @@ -88,6 +88,10 @@ class GFX_EXPORT IconUtil { // needed by calling ::DestroyIcon(). static base::win::ScopedHICON CreateHICONFromSkBitmap(const SkBitmap& bitmap); + static base::win::ScopedHICON CreateHICONFromSkBitmapSizedTo(const SkBitmap& bitmap, + int width, + int height); + // Given a valid HICON handle representing an icon, this function converts // the icon into an SkBitmap object containing an ARGB bitmap using the // dimensions specified in |s|. |s| must specify valid dimensions (both diff --git a/ui/gfx/mac/nswindow_frame_controls.h b/ui/gfx/mac/nswindow_frame_controls.h index 61c6331ecfa51..c9d583e3721bc 100644 --- a/ui/gfx/mac/nswindow_frame_controls.h +++ b/ui/gfx/mac/nswindow_frame_controls.h @@ -39,6 +39,7 @@ GFX_EXPORT void ApplyNSWindowSizeConstraints(NSWindow* window, const gfx::Size& max_size, bool can_resize, bool can_fullscreen); +GFX_EXPORT void SetNSWindowShowInTaskbar(NSWindow* window, bool show); } // namespace gfx diff --git a/ui/gfx/mac/nswindow_frame_controls.mm b/ui/gfx/mac/nswindow_frame_controls.mm index 133aae6cf7a7a..bae685ffd0cf7 100644 --- a/ui/gfx/mac/nswindow_frame_controls.mm +++ b/ui/gfx/mac/nswindow_frame_controls.mm @@ -58,6 +58,22 @@ void SetNSWindowAlwaysOnTop(NSWindow* window, [window setCollectionBehavior:behavior]; } +void SetNSWindowShowInTaskbar(NSWindow* window, bool show) { + ProcessSerialNumber psn = { 0, kCurrentProcess }; + if (!show) { + NSArray* windowList = [[NSArray alloc] init]; + windowList = [NSWindow windowNumbersWithOptions:NSWindowNumberListAllSpaces]; + for (unsigned int i = 0; i < [windowList count]; ++i) { + NSWindow *window = [NSApp windowWithWindowNumber:[[windowList objectAtIndex:i] integerValue]]; + [window setCanHide:NO]; + } + TransformProcessType(&psn, kProcessTransformToUIElementApplication); + } + else { + TransformProcessType(&psn, kProcessTransformToForegroundApplication); + } +} + void SetNSWindowVisibleOnAllWorkspaces(NSWindow* window, bool always_visible) { NSWindowCollectionBehavior behavior = [window collectionBehavior]; if (always_visible) diff --git a/ui/message_center/views/message_center_view.cc b/ui/message_center/views/message_center_view.cc index 36ed38c7f289e..f1a37c728f8b0 100644 --- a/ui/message_center/views/message_center_view.cc +++ b/ui/message_center/views/message_center_view.cc @@ -513,7 +513,7 @@ void MessageCenterView::AddNotificationAt(const Notification& notification, int index) { MessageView* view = MessageViewFactory::Create(this, notification, false); // Not top-level. - view->set_context_menu_controller(context_menu_controller_.get()); + //view->set_context_menu_controller(context_menu_controller_.get()); notification_views_[notification.id()] = view; view->set_scroller(scroller_); message_list_view_->AddNotificationAt(view, index); diff --git a/ui/message_center/views/message_popup_collection.cc b/ui/message_center/views/message_popup_collection.cc index 396721d56fde8..dd201031cd3bf 100644 --- a/ui/message_center/views/message_popup_collection.cc +++ b/ui/message_center/views/message_popup_collection.cc @@ -210,7 +210,7 @@ void MessagePopupCollection::UpdateWidgets() { view = MessageViewFactory::Create(NULL, *(*iter), true); } - view->set_context_menu_controller(context_menu_controller_.get()); + //view->set_context_menu_controller(context_menu_controller_.get()); int view_height = ToastContentsView::GetToastSizeForView(view).height(); int height_available = top_down ? alignment_delegate_->GetWorkArea().bottom() - base diff --git a/ui/native_theme/native_theme_win.cc b/ui/native_theme/native_theme_win.cc index 70c83cd9c5759..16bfbd3ce6481 100644 --- a/ui/native_theme/native_theme_win.cc +++ b/ui/native_theme/native_theme_win.cc @@ -54,6 +54,7 @@ const int kSystemColors[] = { COLOR_HIGHLIGHT, COLOR_HIGHLIGHTTEXT, COLOR_HOTLIGHT, + COLOR_MENU, COLOR_MENUHIGHLIGHT, COLOR_SCROLLBAR, COLOR_WINDOW, @@ -474,6 +475,10 @@ SkColor NativeThemeWin::GetSystemColor(ColorId color_id) const { case kColorId_ButtonHoverColor: return kButtonHoverColor; + // Menu + case kColorId_MenuBackgroundColor: + return system_colors_[COLOR_MENU]; + // Label case kColorId_LabelEnabledColor: return system_colors_[COLOR_BTNTEXT]; diff --git a/ui/shell_dialogs/select_file_dialog_mac.mm b/ui/shell_dialogs/select_file_dialog_mac.mm index d944e479b1570..1d9a8694ab890 100644 --- a/ui/shell_dialogs/select_file_dialog_mac.mm +++ b/ui/shell_dialogs/select_file_dialog_mac.mm @@ -193,6 +193,9 @@ - (void)popupAction:(id)sender; file_types ? file_types->extensions.size() > 1 : true; if (type == SELECT_SAVEAS_FILE) { +#if 1 //NWJS#6091: extension was hidden + [dialog setExtensionHidden:NO]; +#else // When file extensions are hidden and removing the extension from // the default filename gives one which still has an extension // that OS X recognizes, it will get confused and think the user @@ -207,6 +210,7 @@ - (void)popupAction:(id)sender; } else { [dialog setCanSelectHiddenExtension:YES]; } +#endif } else { NSOpenPanel* open_dialog = (NSOpenPanel*)dialog; @@ -219,7 +223,7 @@ - (void)popupAction:(id)sender; [open_dialog setCanChooseFiles:NO]; [open_dialog setCanChooseDirectories:YES]; [open_dialog setCanCreateDirectories:YES]; - NSString *prompt = (type == SELECT_UPLOAD_FOLDER) + NSString *prompt = (false && type == SELECT_UPLOAD_FOLDER) ? l10n_util::GetNSString(IDS_SELECT_UPLOAD_FOLDER_BUTTON_TITLE) : l10n_util::GetNSString(IDS_SELECT_FOLDER_BUTTON_TITLE); [open_dialog setPrompt:prompt]; diff --git a/ui/shell_dialogs/select_file_dialog_win.cc b/ui/shell_dialogs/select_file_dialog_win.cc index 411b8bd5b4e88..82a4f61eafbe0 100644 --- a/ui/shell_dialogs/select_file_dialog_win.cc +++ b/ui/shell_dialogs/select_file_dialog_win.cc @@ -283,6 +283,7 @@ class SelectFileDialogImpl : public ui::SelectFileDialog, bool RunOpenMultiFileDialog(const std::wstring& title, const std::wstring& filter, HWND owner, + base::FilePath* path, std::vector<base::FilePath>* paths); // The callback function for when the select folder dialog is opened. @@ -390,7 +391,7 @@ void SelectFileDialogImpl::ExecuteSelectFile( } else if (params.type == SELECT_OPEN_MULTI_FILE) { std::vector<base::FilePath> paths; if (RunOpenMultiFileDialog(params.title, filter, - params.run_state.owner, &paths)) { + params.run_state.owner, &path, &paths)) { params.ui_task_runner->PostTask( FROM_HERE, base::Bind(&SelectFileDialogImpl::MultiFilesSelected, this, paths, params.params, params.run_state)); @@ -603,6 +604,7 @@ bool SelectFileDialogImpl::RunOpenMultiFileDialog( const std::wstring& title, const std::wstring& filter, HWND owner, + base::FilePath* path, std::vector<base::FilePath>* paths) { // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory // without having to close Chrome first. @@ -610,6 +612,13 @@ bool SelectFileDialogImpl::RunOpenMultiFileDialog( OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_HIDEREADONLY | OFN_ALLOWMULTISELECT | OFN_NOCHANGEDIR); + + if (!path->empty()) { + if (IsDirectory(*path)) + ofn.SetInitialSelection(*path, base::FilePath()); + else + ofn.SetInitialSelection(path->DirName(), path->BaseName()); + } if (!filter.empty()) ofn.GetOPENFILENAME()->lpstrFilter = filter.c_str(); diff --git a/ui/strings/ui_strings.grd b/ui/strings/ui_strings.grd index 344a6867e6bc6..02d438901578e 100644 --- a/ui/strings/ui_strings.grd +++ b/ui/strings/ui_strings.grd @@ -561,6 +561,12 @@ need to be translated for each locale.--> <message name="IDS_APP_SEARCH_MODIFIER" desc="Search key shortcut modifier"> Search+<ph name="KEY_COMBO_NAME">$1<ex>C</ex></ph> </message> + <message name="IDS_APP_WINDOWS_MODIFIER" desc="Command key shortcut modifier"> + Win+<ph name="KEY_COMBO_NAME">$1<ex>C</ex></ph> + </message> + <message name="IDS_APP_SUPER_MODIFIER" desc="Command key shortcut modifier"> + Super+<ph name="KEY_COMBO_NAME">$1<ex>C</ex></ph> + </message> <!-- Byte size units --> <message name="IDS_APP_BYTES" desc="Units tag indicating a quantity of bytes"> diff --git a/ui/views/accessibility/native_view_accessibility_auralinux.cc b/ui/views/accessibility/native_view_accessibility_auralinux.cc index 89b42737d057a..eaffb0fe16dc7 100644 --- a/ui/views/accessibility/native_view_accessibility_auralinux.cc +++ b/ui/views/accessibility/native_view_accessibility_auralinux.cc @@ -4,6 +4,8 @@ #include "ui/views/accessibility/native_view_accessibility_auralinux.h" +#include "content/public/browser/browser_thread.h" + #include <algorithm> #include <memory> #include <vector> @@ -125,7 +127,7 @@ class AuraLinuxApplication // This should be on the a blocking pool thread so that we can open // libatk-bridge.so without blocking this thread. scoped_refptr<base::TaskRunner> init_task_runner = - ViewsDelegate::GetInstance()->GetBlockingPoolTaskRunner(); + ViewsDelegate::GetInstance()->GetBlockingPoolTaskRunner(true); if (init_task_runner) ui::AXPlatformNodeAuraLinux::StaticInitialize(init_task_runner); } diff --git a/ui/views/controls/button/label_button.cc b/ui/views/controls/button/label_button.cc index f049ca8a057d6..a15a828c46443 100644 --- a/ui/views/controls/button/label_button.cc +++ b/ui/views/controls/button/label_button.cc @@ -456,6 +456,9 @@ void LabelButton::ResetColorsFromNativeTheme() { } else { if (style() == STYLE_BUTTON) PlatformStyle::ApplyLabelButtonTextStyle(label_, &colors); + // Set auto color readability to false in case of switching theme from + // inverted color scheme. + label_->SetAutoColorReadabilityEnabled(false); label_->set_background(nullptr); label_->SetAutoColorReadabilityEnabled(false); } diff --git a/ui/views/controls/menu/native_menu_win.cc b/ui/views/controls/menu/native_menu_win.cc index 0c81dd6978141..2fe9fb6ec011e 100644 --- a/ui/views/controls/menu/native_menu_win.cc +++ b/ui/views/controls/menu/native_menu_win.cc @@ -51,7 +51,9 @@ NativeMenuWin::NativeMenuWin(ui::MenuModel* model, HWND system_menu_for) system_menu_for_(system_menu_for), first_item_index_(0), parent_(nullptr), - destroyed_flag_(nullptr) {} + destroyed_flag_(nullptr), + is_popup_menu_(true){ +} NativeMenuWin::~NativeMenuWin() { if (destroyed_flag_) @@ -218,14 +220,18 @@ void NativeMenuWin::ResetNativeMenu() { } else { if (menu_) DestroyMenu(menu_); - menu_ = CreatePopupMenu(); + if (is_popup_menu_) + menu_ = CreatePopupMenu(); + else + menu_ = CreateMenu(); // Rather than relying on the return value of TrackPopupMenuEx, which is // always a command identifier, instead we tell the menu to notify us via // our host window and the WM_MENUCOMMAND message. MENUINFO mi = {0}; mi.cbSize = sizeof(mi); mi.fMask = MIM_STYLE | MIM_MENUDATA; - mi.dwStyle = MNS_NOTIFYBYPOS; + if (is_popup_menu_) + mi.dwStyle = MNS_NOTIFYBYPOS; mi.dwMenuData = reinterpret_cast<ULONG_PTR>(this); SetMenuInfo(menu_, &mi); } diff --git a/ui/views/controls/menu/native_menu_win.h b/ui/views/controls/menu/native_menu_win.h index 03f00a84ead51..158ee3b23e122 100644 --- a/ui/views/controls/menu/native_menu_win.h +++ b/ui/views/controls/menu/native_menu_win.h @@ -33,6 +33,9 @@ class VIEWS_EXPORT NativeMenuWin { void Rebuild(MenuInsertionDelegateWin* delegate); void UpdateStates(); + void set_is_popup_menu(bool flag) { is_popup_menu_ = flag; } + HMENU menu() const { return menu_; } + private: // IMPORTANT: Note about indices. // Functions in this class deal in two index spaces: @@ -100,6 +103,9 @@ class VIEWS_EXPORT NativeMenuWin { // If we're a submenu, this is our parent. NativeMenuWin* parent_; + // A flag to indicate whether to create a menubar or popupmenu. + bool is_popup_menu_; + // If non-null the destructor sets this to true. This is set to non-null while // the menu is showing. It is used to detect if the menu was deleted while // running. diff --git a/ui/views/views_delegate.cc b/ui/views/views_delegate.cc index a9b3022add9bc..1e00326d117d2 100644 --- a/ui/views/views_delegate.cc +++ b/ui/views/views_delegate.cc @@ -136,7 +136,7 @@ int ViewsDelegate::GetAppbarAutohideEdges(HMONITOR monitor, } #endif -scoped_refptr<base::TaskRunner> ViewsDelegate::GetBlockingPoolTaskRunner() { +scoped_refptr<base::TaskRunner> ViewsDelegate::GetBlockingPoolTaskRunner(bool continue_on_shutdown) { return nullptr; } diff --git a/ui/views/views_delegate.h b/ui/views/views_delegate.h index b869e7b3fb397..c24e2c76393f0 100644 --- a/ui/views/views_delegate.h +++ b/ui/views/views_delegate.h @@ -214,7 +214,7 @@ class VIEWS_EXPORT ViewsDelegate { #endif // Returns a blocking pool task runner given a TaskRunnerType. - virtual scoped_refptr<base::TaskRunner> GetBlockingPoolTaskRunner(); + virtual scoped_refptr<base::TaskRunner> GetBlockingPoolTaskRunner(bool continue_on_shutdown = false); protected: ViewsDelegate(); diff --git a/ui/views/widget/desktop_aura/desktop_screen_x11.cc b/ui/views/widget/desktop_aura/desktop_screen_x11.cc index 3432afe40d033..1769a32cfd26c 100644 --- a/ui/views/widget/desktop_aura/desktop_screen_x11.cc +++ b/ui/views/widget/desktop_aura/desktop_screen_x11.cc @@ -75,7 +75,7 @@ std::vector<display::Display> GetFallbackDisplayList() { if (!display::Display::HasForceDeviceScaleFactor() && !display::IsDisplaySizeBlackListed(physical_size)) { const float device_scale_factor = GetDeviceScaleFactor(); - DCHECK_LE(1.0f, device_scale_factor); + //DCHECK_LE(1.0f, device_scale_factor); gfx_display.SetScaleAndBounds(device_scale_factor, bounds_in_pixels); } diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_win.cc b/ui/views/widget/desktop_aura/desktop_window_tree_host_win.cc index e99be28d8785b..4536e5fd0e9a2 100644 --- a/ui/views/widget/desktop_aura/desktop_window_tree_host_win.cc +++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_win.cc @@ -420,7 +420,7 @@ bool DesktopWindowTreeHostWin::ShouldWindowContentsBeTransparent() const { // is therefore transparent. Note: This is not equivalent to calling // IsAeroGlassEnabled, because ShouldUseNativeFrame is overridden in a // subclass. - return ShouldUseNativeFrame() && !IsFullscreen(); + return ShouldUseNativeFrame() && (content::g_support_transparency || !IsFullscreen()); } void DesktopWindowTreeHostWin::FrameTypeChanged() { @@ -716,10 +716,19 @@ bool DesktopWindowTreeHostWin::ShouldHandleSystemCommands() const { return GetWidget()->widget_delegate()->ShouldHandleSystemCommands(); } +bool DesktopWindowTreeHostWin::ShouldHandleOnSize() const { + return GetWidget()->widget_delegate()->ShouldHandleOnSize(); +} + void DesktopWindowTreeHostWin::HandleAppDeactivated() { native_widget_delegate_->SetAlwaysRenderAsActive(false); } +bool DesktopWindowTreeHostWin::HandleSize(UINT param, const gfx::Size& new_size) { + return GetWidget()->widget_delegate() && + GetWidget()->widget_delegate()->HandleSize(param, new_size); +} + void DesktopWindowTreeHostWin::HandleActivationChanged(bool active) { // This can be invoked from HWNDMessageHandler::Init(), at which point we're // not in a good state and need to ignore it. @@ -736,7 +745,7 @@ bool DesktopWindowTreeHostWin::HandleAppCommand(short command) { // We treat APPCOMMAND ids as an extension of our command namespace, and just // let the delegate figure out what to do... return GetWidget()->widget_delegate() && - GetWidget()->widget_delegate()->ExecuteWindowsCommand(command); + GetWidget()->widget_delegate()->ExecuteAppCommand(command); } void DesktopWindowTreeHostWin::HandleCancelMode() { @@ -889,6 +898,7 @@ void DesktopWindowTreeHostWin::HandleInputLanguageChange( void DesktopWindowTreeHostWin::HandlePaintAccelerated( const gfx::Rect& invalid_rect) { + if (content::g_force_cpu_draw) return; if (compositor()) compositor()->ScheduleRedrawRect(invalid_rect); } diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_win.h b/ui/views/widget/desktop_aura/desktop_window_tree_host_win.h index 12d0616467073..ec70c1270f47b 100644 --- a/ui/views/widget/desktop_aura/desktop_window_tree_host_win.h +++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_win.h @@ -132,6 +132,8 @@ class VIEWS_EXPORT DesktopWindowTreeHostWin void OnWindowHidingAnimationCompleted() override; // Overridden from HWNDMessageHandlerDelegate: + bool ShouldHandleOnSize() const override; + bool HandleSize(UINT param, const gfx::Size& new_size) override; bool HasNonClientView() const override; FrameMode GetFrameMode() const override; bool HasFrame() const override; diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.cc b/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.cc index a5011125472da..83974bb827043 100644 --- a/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.cc +++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.cc @@ -66,6 +66,10 @@ DECLARE_UI_CLASS_PROPERTY_TYPE(views::DesktopWindowTreeHostX11*); +namespace content { + extern bool g_support_transparency; +} + namespace views { DesktopWindowTreeHostX11* DesktopWindowTreeHostX11::g_current_capture = diff --git a/ui/views/widget/native_widget_delegate.h b/ui/views/widget/native_widget_delegate.h index 8f2e56a4a4d91..9db8627cc6748 100644 --- a/ui/views/widget/native_widget_delegate.h +++ b/ui/views/widget/native_widget_delegate.h @@ -54,6 +54,7 @@ class VIEWS_EXPORT NativeWidgetDelegate { // problems. virtual void SetAlwaysRenderAsActive(bool always_render_as_active) = 0; virtual bool IsAlwaysRenderAsActive() const = 0; + virtual bool NWCanClose(bool user_force = false) const = 0; // Called when the activation state of a window has changed. virtual void OnNativeWidgetActivationChanged(bool active) = 0; diff --git a/ui/views/widget/widget.cc b/ui/views/widget/widget.cc index fbce29ee69aa9..294ad2f65026b 100644 --- a/ui/views/widget/widget.cc +++ b/ui/views/widget/widget.cc @@ -573,7 +573,7 @@ void Widget::SetShape(std::unique_ptr<SkRegion> shape) { native_widget_->SetShape(std::move(shape)); } -void Widget::Close() { +void Widget::Close(bool force) { if (widget_closed_) { // It appears we can hit this code path if you close a modal dialog then // close the last browser before the destructor is hit, which triggers @@ -583,6 +583,8 @@ void Widget::Close() { if (non_client_view_ && !non_client_view_->CanClose()) return; + if (!force && !NWCanClose()) + return; // The actions below can cause this function to be called again, so mark // |this| as closed early. See crbug.com/714334 @@ -1032,6 +1034,10 @@ bool Widget::IsAlwaysRenderAsActive() const { return always_render_as_active_; } +bool Widget::NWCanClose(bool user_force) const { + return widget_delegate_->NWCanClose(user_force); +} + void Widget::OnNativeWidgetActivationChanged(bool active) { // On windows we may end up here before we've completed initialization (from // an WM_NCACTIVATE). If that happens the WidgetDelegate likely doesn't know diff --git a/ui/views/widget/widget.h b/ui/views/widget/widget.h index 63fcb9d611e83..96e9d4b07f157 100644 --- a/ui/views/widget/widget.h +++ b/ui/views/widget/widget.h @@ -487,7 +487,7 @@ class VIEWS_EXPORT Widget : public internal::NativeWidgetDelegate, void SetShape(std::unique_ptr<SkRegion> shape); // Hides the widget then closes it after a return to the message loop. - virtual void Close(); + virtual void Close(bool force = false); // TODO(beng): Move off public API. // Closes the widget immediately. Compare to |Close|. This will destroy the @@ -793,6 +793,7 @@ class VIEWS_EXPORT Widget : public internal::NativeWidgetDelegate, bool CanActivate() const override; bool IsAlwaysRenderAsActive() const override; void SetAlwaysRenderAsActive(bool always_render_as_active) override; + bool NWCanClose(bool user_force = false) const override; void OnNativeWidgetActivationChanged(bool active) override; void OnNativeFocus() override; void OnNativeBlur() override; diff --git a/ui/views/widget/widget_delegate.cc b/ui/views/widget/widget_delegate.cc index a7696103df311..06949a30073b1 100644 --- a/ui/views/widget/widget_delegate.cc +++ b/ui/views/widget/widget_delegate.cc @@ -70,6 +70,10 @@ bool WidgetDelegate::CanActivate() const { return can_activate_; } +bool WidgetDelegate::NWCanClose(bool user_force) const { + return true; +} + ui::ModalType WidgetDelegate::GetModalType() const { return ui::MODAL_TYPE_NONE; } @@ -102,6 +106,10 @@ bool WidgetDelegate::ShouldHandleSystemCommands() const { return widget->non_client_view() != NULL; } +bool WidgetDelegate::ShouldHandleOnSize() const { + return false; +} + gfx::ImageSkia WidgetDelegate::GetWindowAppIcon() { // Use the window icon as app icon by default. return GetWindowIcon(); @@ -120,6 +128,14 @@ bool WidgetDelegate::ExecuteWindowsCommand(int command_id) { return false; } +bool WidgetDelegate::ExecuteAppCommand(int command_id) { + return ExecuteWindowsCommand(command_id); +} + +bool WidgetDelegate::HandleSize(unsigned int param, const gfx::Size& size) { + return false; +} + std::string WidgetDelegate::GetWindowName() const { return std::string(); } diff --git a/ui/views/widget/widget_delegate.h b/ui/views/widget/widget_delegate.h index bd4d8a7a1de29..1dc556e124894 100644 --- a/ui/views/widget/widget_delegate.h +++ b/ui/views/widget/widget_delegate.h @@ -67,6 +67,7 @@ class VIEWS_EXPORT WidgetDelegate { // Returns true if the window can be activated. virtual bool CanActivate() const; + virtual bool NWCanClose(bool user_force = false) const; // Returns the modal type that applies to the widget. Default is // ui::MODAL_TYPE_NONE (not modal). @@ -90,6 +91,8 @@ class VIEWS_EXPORT WidgetDelegate { // close, minimize, maximize. virtual bool ShouldHandleSystemCommands() const; + virtual bool ShouldHandleOnSize() const; + // Returns the app icon for the window. On Windows, this is the ICON_BIG used // in Alt-Tab list and Win7's taskbar. virtual gfx::ImageSkia GetWindowAppIcon(); @@ -104,6 +107,10 @@ class VIEWS_EXPORT WidgetDelegate { // was handled, false if it was not. virtual bool ExecuteWindowsCommand(int command_id); + virtual bool ExecuteAppCommand(int command_id); + + virtual bool HandleSize(unsigned int param, const gfx::Size& size); + // Returns the window's name identifier. Used to identify this window for // state restoration. virtual std::string GetWindowName() const; diff --git a/ui/views/widget/widget_hwnd_utils.cc b/ui/views/widget/widget_hwnd_utils.cc index 163e4b54b033c..c3bd01ac25b62 100644 --- a/ui/views/widget/widget_hwnd_utils.cc +++ b/ui/views/widget/widget_hwnd_utils.cc @@ -10,10 +10,12 @@ #include "build/build_config.h" #include "ui/base/l10n/l10n_util_win.h" #include "ui/base/ui_base_switches.h" +#include "ui/display/display.h" #include "ui/views/widget/widget_delegate.h" #include "ui/views/win/hwnd_message_handler.h" #if defined(OS_WIN) +#include "base/win/windows_version.h" #include "ui/base/win/shell.h" #endif @@ -92,8 +94,20 @@ void CalculateWindowStylesFromInitParams( native_widget_delegate->IsDialogBox() ? WS_EX_DLGMODALFRAME : 0; // See layered window comment below. - if (is_translucent) - *style &= ~(WS_THICKFRAME | WS_CAPTION); + if (content::g_support_transparency) { + if (is_translucent && params.remove_standard_frame) + *style &= ~(WS_CAPTION); + if (is_translucent && !(native_widget_delegate->IsDialogBox() || native_widget_delegate->IsModal())) { + *ex_style |= WS_EX_LAYERED; + if (base::win::GetVersion() < base::win::VERSION_WIN10) + *ex_style |= WS_EX_COMPOSITED; + } + } + else { + if (is_translucent) + *style &= ~(WS_THICKFRAME | WS_CAPTION); + } + break; } case Widget::InitParams::TYPE_CONTROL: @@ -160,6 +174,7 @@ void ConfigureWindowStyles( CalculateWindowStylesFromInitParams(params, widget_delegate, native_widget_delegate, is_translucent, &style, &ex_style, &class_style); + handler->set_is_translucent(is_translucent); handler->set_initial_class_style(class_style); handler->set_window_style(handler->window_style() | style); diff --git a/ui/views/win/hwnd_message_handler.cc b/ui/views/win/hwnd_message_handler.cc index 3c67457a6421c..b2e4590bdeeda 100644 --- a/ui/views/win/hwnd_message_handler.cc +++ b/ui/views/win/hwnd_message_handler.cc @@ -321,6 +321,7 @@ base::LazyInstance<HWNDMessageHandler::FullscreenWindowMonitorMap>:: // HWNDMessageHandler, public: long HWNDMessageHandler::last_touch_message_time_ = 0; +#define TRANSPARENCY(original, addition) content::g_support_transparency ? original addition : original HWNDMessageHandler::HWNDMessageHandler(HWNDMessageHandlerDelegate* delegate) : msg_handled_(FALSE), @@ -815,13 +816,16 @@ void HWNDMessageHandler::SetWindowIcons(const gfx::ImageSkia& window_icon, const gfx::ImageSkia& app_icon) { if (!window_icon.isNull()) { base::win::ScopedHICON previous_icon = std::move(window_icon_); - window_icon_ = IconUtil::CreateHICONFromSkBitmap(*window_icon.bitmap()); + window_icon_ = + IconUtil::CreateHICONFromSkBitmapSizedTo(*window_icon.bitmap(), + GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON)); SendMessage(hwnd(), WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); } if (!app_icon.isNull()) { base::win::ScopedHICON previous_icon = std::move(app_icon_); - app_icon_ = IconUtil::CreateHICONFromSkBitmap(*app_icon.bitmap()); + app_icon_ = IconUtil::CreateHICONFromSkBitmapSizedTo(*app_icon.bitmap(), + GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON)); SendMessage(hwnd(), WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } @@ -861,7 +865,8 @@ void HWNDMessageHandler::SizeConstraintsChanged() { if (!delegate_->CanMaximize()) style &= ~WS_MAXIMIZEBOX; } else { - style &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX); + if (!content::g_support_transparency) + style &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX); } if (delegate_->CanMinimize()) { style |= WS_MINIMIZEBOX; @@ -1183,7 +1188,7 @@ void HWNDMessageHandler::ResetWindowRegion(bool force, bool redraw) { // allow for a custom hit mask. if (!is_translucent_ && !custom_window_region_.is_valid() && (IsFrameSystemDrawn() || !delegate_->HasNonClientView())) { - if (force) + if (force || content::g_force_cpu_draw) SetWindowRgn(hwnd(), NULL, redraw); return; } @@ -1199,6 +1204,10 @@ void HWNDMessageHandler::ResetWindowRegion(bool force, bool redraw) { if (custom_window_region_.is_valid()) { new_region.reset(CreateRectRgn(0, 0, 0, 0)); CombineRgn(new_region.get(), custom_window_region_.get(), NULL, RGN_COPY); + } else if (content::g_support_transparency && is_translucent_) { + RECT work_rect = window_rect; + OffsetRect(&work_rect, -window_rect.left, -window_rect.top); + new_region.reset(CreateRectRgnIndirect(&work_rect)); } else if (IsMaximized()) { HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST); MONITORINFO mi; @@ -1358,7 +1367,7 @@ LRESULT HWNDMessageHandler::OnCreate(CREATESTRUCT* create_struct) { MAKELPARAM(UIS_CLEAR, UISF_HIDEFOCUS), 0); - if (!delegate_->HasFrame()) { + if (TRANSPARENCY(!delegate_->HasFrame(), && !(is_translucent_))) { SetWindowLong(hwnd(), GWL_STYLE, GetWindowLong(hwnd(), GWL_STYLE) & ~WS_CAPTION); SendFrameChanged(); @@ -1486,15 +1495,17 @@ void HWNDMessageHandler::OnGetMinMaxInfo(MINMAXINFO* minmax_info) { if (delegate_->WidgetSizeIsClientSize()) { RECT client_rect, window_rect; GetClientRect(hwnd(), &client_rect); - GetWindowRect(hwnd(), &window_rect); - CR_DEFLATE_RECT(&window_rect, &client_rect); - min_window_size.Enlarge(window_rect.right - window_rect.left, - window_rect.bottom - window_rect.top); - // Either axis may be zero, so enlarge them independently. - if (max_window_size.width()) - max_window_size.Enlarge(window_rect.right - window_rect.left, 0); - if (max_window_size.height()) - max_window_size.Enlarge(0, window_rect.bottom - window_rect.top); + if (client_rect.right > client_rect.left) { + GetWindowRect(hwnd(), &window_rect); + CR_DEFLATE_RECT(&window_rect, &client_rect); + min_window_size.Enlarge(window_rect.right - window_rect.left, + window_rect.bottom - window_rect.top); + // Either axis may be zero, so enlarge them independently. + if (max_window_size.width()) + max_window_size.Enlarge(window_rect.right - window_rect.left, 0); + if (max_window_size.height()) + max_window_size.Enlarge(0, window_rect.bottom - window_rect.top); + } } minmax_info->ptMinTrackSize.x = min_window_size.width(); minmax_info->ptMinTrackSize.y = min_window_size.height(); @@ -1849,10 +1860,11 @@ LRESULT HWNDMessageHandler::OnNCCalcSize(BOOL mode, LPARAM l_param) { return 0; } } - + const LONG noTitleBar = (is_translucent_) && !delegate_->HasFrame(); gfx::Insets insets; bool got_insets = GetClientAreaInsets(&insets); - if (!got_insets && !IsFullscreen() && !(mode && !delegate_->HasFrame())) { + if (TRANSPARENCY(!got_insets && !IsFullscreen() && + !(mode && !delegate_->HasFrame()), && !noTitleBar)) { SetMsgHandled(FALSE); return 0; } @@ -2230,6 +2242,17 @@ void HWNDMessageHandler::OnSize(UINT param, const gfx::Size& size) { // ResetWindowRegion is going to trigger WM_NCPAINT. By doing it after we've // invoked OnSize we ensure the RootView has been laid out. ResetWindowRegion(false, true); + if (delegate_->ShouldHandleOnSize()) + delegate_->HandleSize(param, size); +} + +void HWNDMessageHandler::OnStyleChanging(int nStyleType, LPSTYLESTRUCT lpStyleStruct) { + if (!content::g_support_transparency) + return; + if (nStyleType == GWL_EXSTYLE) + set_window_ex_style(lpStyleStruct->styleNew); + else if (nStyleType == GWL_STYLE) + set_window_style(lpStyleStruct->styleNew); } void HWNDMessageHandler::OnSysCommand(UINT notification_code, @@ -2742,7 +2765,7 @@ void HWNDMessageHandler::PerformDwmTransition() { // The non-client view needs to update too. delegate_->HandleFrameChanged(); - if (IsVisible() && IsFrameSystemDrawn()) { + if (IsVisible() && IsFrameSystemDrawn() && !content::g_force_cpu_draw) { // For some reason, we need to hide the window after we change from a custom // frame to a native frame. If we don't, the client area will be filled // with black. This seems to be related to an interaction between DWM and diff --git a/ui/views/win/hwnd_message_handler.h b/ui/views/win/hwnd_message_handler.h index 5018970b00162..32b01165b26dc 100644 --- a/ui/views/win/hwnd_message_handler.h +++ b/ui/views/win/hwnd_message_handler.h @@ -434,6 +434,7 @@ class VIEWS_EXPORT HWNDMessageHandler : CR_MSG_WM_SETTEXT(OnSetText) CR_MSG_WM_SETTINGCHANGE(OnSettingChange) CR_MSG_WM_SIZE(OnSize) + CR_MSG_WM_STYLECHANGING(OnStyleChanging) CR_MSG_WM_SYSCOMMAND(OnSysCommand) CR_MSG_WM_THEMECHANGED(OnThemeChanged) CR_MSG_WM_TIMECHANGE(OnTimeChange) @@ -493,6 +494,7 @@ class VIEWS_EXPORT HWNDMessageHandler : LRESULT OnSetText(const wchar_t* text); void OnSettingChange(UINT flags, const wchar_t* section); void OnSize(UINT param, const gfx::Size& size); + void OnStyleChanging(int nStyleType, LPSTYLESTRUCT lpStyleStruct); void OnSysCommand(UINT notification_code, const gfx::Point& point); void OnThemeChanged(); void OnTimeChange(); diff --git a/ui/views/win/hwnd_message_handler_delegate.h b/ui/views/win/hwnd_message_handler_delegate.h index f5328c49e708e..553b593186bb5 100644 --- a/ui/views/win/hwnd_message_handler_delegate.h +++ b/ui/views/win/hwnd_message_handler_delegate.h @@ -100,6 +100,10 @@ class VIEWS_EXPORT HWNDMessageHandlerDelegate { // implementing them on non-aura windows. http://crbug.com/189112. virtual bool ShouldHandleSystemCommands() const = 0; + // on windows, maximizing sometime is sent through WM_SIZE, not + // WM_SYSCOMMAND, see node-webkit#753 + virtual bool ShouldHandleOnSize() const = 0; + // TODO(beng): Investigate migrating these methods to On* prefixes once // HWNDMessageHandler is the WindowImpl. @@ -127,6 +131,8 @@ class VIEWS_EXPORT HWNDMessageHandlerDelegate { // true if the command was handled. virtual bool HandleCommand(int command) = 0; + virtual bool HandleSize(UINT param, const gfx::Size& size) = 0; + // Called when an accelerator is invoked. virtual void HandleAccelerator(const ui::Accelerator& accelerator) = 0; diff --git a/ui/views/window/custom_frame_view.cc b/ui/views/window/custom_frame_view.cc index 27a5316af1b6f..2a83e03a9630c 100644 --- a/ui/views/window/custom_frame_view.cc +++ b/ui/views/window/custom_frame_view.cc @@ -6,6 +6,7 @@ #include <algorithm> #include <vector> +#include "ui/gfx/image/image_skia_operations.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" @@ -113,7 +114,10 @@ void CustomFrameView::Init(Widget* frame) { IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P); if (frame_->widget_delegate()->ShouldShowWindowIcon()) { + gfx::ImageSkia icon; window_icon_ = new ImageButton(this); + icon = frame_->widget_delegate()->GetWindowAppIcon(); + window_icon_->SetImage(CustomButton::STATE_NORMAL, &icon); AddChildView(window_icon_); } } @@ -193,8 +197,16 @@ void CustomFrameView::ResetWindowControls() { } void CustomFrameView::UpdateWindowIcon() { - if (window_icon_) + if (window_icon_) { + gfx::ImageSkia icon; + icon = frame_->widget_delegate()->GetWindowAppIcon(); + int size = IconSize(); + gfx::ImageSkia icon2 = gfx::ImageSkiaOperations::CreateResizedImage(icon, + skia::ImageOperations::RESIZE_BEST, + gfx::Size(size, size)); + window_icon_->SetImage(CustomButton::STATE_NORMAL, &icon2); window_icon_->SchedulePaint(); + } } void CustomFrameView::UpdateWindowTitle() {