refactor: rename the atom directory to shell

This commit is contained in:
Samuel Attard 2019-06-19 13:43:10 -07:00 committed by Samuel Attard
parent 4575a4aae3
commit d7f07e8a80
631 changed files with 0 additions and 0 deletions

5
shell/app/BRANDING.json Normal file
View file

@ -0,0 +1,5 @@
{
"project_name": "electron",
"product_name": "Electron",
"mac_bundle_id": "com.github.Electron"
}

View file

@ -0,0 +1,275 @@
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/app/atom_content_client.h"
#include <string>
#include <vector>
#include "atom/common/options_switches.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/pepper_plugin_info.h"
#include "electron/buildflags/buildflags.h"
#include "ppapi/shared_impl/ppapi_permissions.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "url/url_constants.h"
// In SHARED_INTERMEDIATE_DIR.
#include "widevine_cdm_version.h" // NOLINT(build/include)
#if defined(WIDEVINE_CDM_AVAILABLE)
#include "base/native_library.h"
#include "content/public/common/cdm_info.h"
#include "media/base/video_codecs.h"
#endif // defined(WIDEVINE_CDM_AVAILABLE)
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "atom/common/atom_constants.h"
#include "pdf/pdf.h"
#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
namespace atom {
namespace {
#if defined(WIDEVINE_CDM_AVAILABLE)
bool IsWidevineAvailable(
base::FilePath* cdm_path,
std::vector<media::VideoCodec>* codecs_supported,
base::flat_set<media::CdmSessionType>* session_types_supported,
base::flat_set<media::EncryptionMode>* modes_supported) {
static enum {
NOT_CHECKED,
FOUND,
NOT_FOUND,
} widevine_cdm_file_check = NOT_CHECKED;
if (widevine_cdm_file_check == NOT_CHECKED) {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
*cdm_path = command_line->GetSwitchValuePath(switches::kWidevineCdmPath);
if (!cdm_path->empty()) {
*cdm_path = cdm_path->AppendASCII(
base::GetNativeLibraryName(kWidevineCdmLibraryName));
widevine_cdm_file_check = base::PathExists(*cdm_path) ? FOUND : NOT_FOUND;
}
}
if (widevine_cdm_file_check == FOUND) {
// Add the supported codecs as if they came from the component manifest.
// This list must match the CDM that is being bundled with Chrome.
codecs_supported->push_back(media::VideoCodec::kCodecVP8);
codecs_supported->push_back(media::VideoCodec::kCodecVP9);
#if BUILDFLAG(USE_PROPRIETARY_CODECS)
codecs_supported->push_back(media::VideoCodec::kCodecH264);
#endif // BUILDFLAG(USE_PROPRIETARY_CODECS)
// TODO(crbug.com/767941): Push persistent-license support info here once
// we check in a new CDM that supports it on Linux.
session_types_supported->insert(media::CdmSessionType::kTemporary);
#if defined(OS_CHROMEOS)
session_types_supported->insert(media::CdmSessionType::kPersistentLicense);
#endif // defined(OS_CHROMEOS)
modes_supported->insert(media::EncryptionMode::kCenc);
return true;
}
return false;
}
#endif // defined(WIDEVINE_CDM_AVAILABLE)
#if BUILDFLAG(ENABLE_PEPPER_FLASH)
content::PepperPluginInfo CreatePepperFlashInfo(const base::FilePath& path,
const std::string& version) {
content::PepperPluginInfo plugin;
plugin.is_out_of_process = true;
plugin.name = content::kFlashPluginName;
plugin.path = path;
plugin.permissions = ppapi::PERMISSION_ALL_BITS;
std::vector<std::string> flash_version_numbers = base::SplitString(
version, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
if (flash_version_numbers.empty())
flash_version_numbers.push_back("11");
// |SplitString()| puts in an empty string given an empty string. :(
else if (flash_version_numbers[0].empty())
flash_version_numbers[0] = "11";
if (flash_version_numbers.size() < 2)
flash_version_numbers.push_back("2");
if (flash_version_numbers.size() < 3)
flash_version_numbers.push_back("999");
if (flash_version_numbers.size() < 4)
flash_version_numbers.push_back("999");
// E.g., "Shockwave Flash 10.2 r154":
plugin.description = plugin.name + " " + flash_version_numbers[0] + "." +
flash_version_numbers[1] + " r" +
flash_version_numbers[2];
plugin.version = base::JoinString(flash_version_numbers, ".");
content::WebPluginMimeType swf_mime_type(content::kFlashPluginSwfMimeType,
content::kFlashPluginSwfExtension,
content::kFlashPluginSwfDescription);
plugin.mime_types.push_back(swf_mime_type);
content::WebPluginMimeType spl_mime_type(content::kFlashPluginSplMimeType,
content::kFlashPluginSplExtension,
content::kFlashPluginSplDescription);
plugin.mime_types.push_back(spl_mime_type);
return plugin;
}
void AddPepperFlashFromCommandLine(
base::CommandLine* command_line,
std::vector<content::PepperPluginInfo>* plugins) {
base::FilePath flash_path =
command_line->GetSwitchValuePath(switches::kPpapiFlashPath);
if (flash_path.empty())
return;
auto flash_version =
command_line->GetSwitchValueASCII(switches::kPpapiFlashVersion);
plugins->push_back(CreatePepperFlashInfo(flash_path, flash_version));
}
#endif // BUILDFLAG(ENABLE_PEPPER_FLASH)
void ComputeBuiltInPlugins(std::vector<content::PepperPluginInfo>* plugins) {
#if BUILDFLAG(ENABLE_PDF_VIEWER)
content::PepperPluginInfo pdf_info;
pdf_info.is_internal = true;
pdf_info.is_out_of_process = true;
pdf_info.name = "Chromium PDF Viewer";
pdf_info.description = "Portable Document Format";
pdf_info.path = base::FilePath::FromUTF8Unsafe(kPdfPluginPath);
content::WebPluginMimeType pdf_mime_type(kPdfPluginMimeType, "pdf",
"Portable Document Format");
pdf_info.mime_types.push_back(pdf_mime_type);
pdf_info.internal_entry_points.get_interface = chrome_pdf::PPP_GetInterface;
pdf_info.internal_entry_points.initialize_module =
chrome_pdf::PPP_InitializeModule;
pdf_info.internal_entry_points.shutdown_module =
chrome_pdf::PPP_ShutdownModule;
pdf_info.permissions = ppapi::PERMISSION_PRIVATE | ppapi::PERMISSION_DEV;
plugins->push_back(pdf_info);
#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
}
void ConvertStringWithSeparatorToVector(std::vector<std::string>* vec,
const char* separator,
const char* cmd_switch) {
auto* command_line = base::CommandLine::ForCurrentProcess();
auto string_with_separator = command_line->GetSwitchValueASCII(cmd_switch);
if (!string_with_separator.empty())
*vec = base::SplitString(string_with_separator, separator,
base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
}
} // namespace
AtomContentClient::AtomContentClient() {}
AtomContentClient::~AtomContentClient() {}
base::string16 AtomContentClient::GetLocalizedString(int message_id) const {
return l10n_util::GetStringUTF16(message_id);
}
base::StringPiece AtomContentClient::GetDataResource(
int resource_id,
ui::ScaleFactor scale_factor) const {
return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(
resource_id, scale_factor);
}
gfx::Image& AtomContentClient::GetNativeImageNamed(int resource_id) const {
return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed(
resource_id);
}
base::RefCountedMemory* AtomContentClient::GetDataResourceBytes(
int resource_id) const {
return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytes(
resource_id);
}
void AtomContentClient::AddAdditionalSchemes(Schemes* schemes) {
std::vector<std::string> splited;
ConvertStringWithSeparatorToVector(&splited, ",",
switches::kServiceWorkerSchemes);
for (const std::string& scheme : splited)
schemes->service_worker_schemes.push_back(scheme);
schemes->service_worker_schemes.push_back(url::kFileScheme);
ConvertStringWithSeparatorToVector(&splited, ",", switches::kStandardSchemes);
for (const std::string& scheme : splited)
schemes->standard_schemes.push_back(scheme);
schemes->standard_schemes.push_back("chrome-extension");
ConvertStringWithSeparatorToVector(&splited, ",", switches::kSecureSchemes);
for (const std::string& scheme : splited)
schemes->secure_schemes.push_back(scheme);
ConvertStringWithSeparatorToVector(&splited, ",",
switches::kBypassCSPSchemes);
for (const std::string& scheme : splited)
schemes->csp_bypassing_schemes.push_back(scheme);
ConvertStringWithSeparatorToVector(&splited, ",", switches::kCORSSchemes);
for (const std::string& scheme : splited)
schemes->cors_enabled_schemes.push_back(scheme);
}
void AtomContentClient::AddPepperPlugins(
std::vector<content::PepperPluginInfo>* plugins) {
#if BUILDFLAG(ENABLE_PEPPER_FLASH)
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
AddPepperFlashFromCommandLine(command_line, plugins);
#endif // BUILDFLAG(ENABLE_PEPPER_FLASH)
ComputeBuiltInPlugins(plugins);
}
void AtomContentClient::AddContentDecryptionModules(
std::vector<content::CdmInfo>* cdms,
std::vector<media::CdmHostFilePath>* cdm_host_file_paths) {
if (cdms) {
#if defined(WIDEVINE_CDM_AVAILABLE)
base::FilePath cdm_path;
std::vector<media::VideoCodec> video_codecs_supported;
base::flat_set<media::CdmSessionType> session_types_supported;
base::flat_set<media::EncryptionMode> encryption_modes_supported;
if (IsWidevineAvailable(&cdm_path, &video_codecs_supported,
&session_types_supported,
&encryption_modes_supported)) {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
auto cdm_version_string =
command_line->GetSwitchValueASCII(switches::kWidevineCdmVersion);
// CdmInfo needs |path| to be the actual Widevine library,
// not the adapter, so adjust as necessary. It will be in the
// same directory as the installed adapter.
const base::Version version(cdm_version_string);
DCHECK(version.IsValid());
content::CdmCapability capability(
video_codecs_supported, encryption_modes_supported,
session_types_supported, base::flat_set<media::CdmProxy::Protocol>());
cdms->push_back(content::CdmInfo(
kWidevineCdmDisplayName, kWidevineCdmGuid, version, cdm_path,
kWidevineCdmFileSystemId, capability, kWidevineKeySystem, false));
}
#endif // defined(WIDEVINE_CDM_AVAILABLE)
}
}
bool AtomContentClient::IsDataResourceGzipped(int resource_id) const {
return ui::ResourceBundle::GetSharedInstance().IsGzipped(resource_id);
}
} // namespace atom

View file

@ -0,0 +1,42 @@
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_APP_ATOM_CONTENT_CLIENT_H_
#define ATOM_APP_ATOM_CONTENT_CLIENT_H_
#include <set>
#include <string>
#include <vector>
#include "content/public/common/content_client.h"
namespace atom {
class AtomContentClient : public content::ContentClient {
public:
AtomContentClient();
~AtomContentClient() override;
protected:
// content::ContentClient:
base::string16 GetLocalizedString(int message_id) const override;
base::StringPiece GetDataResource(int resource_id,
ui::ScaleFactor) const override;
gfx::Image& GetNativeImageNamed(int resource_id) const override;
base::RefCountedMemory* GetDataResourceBytes(int resource_id) const override;
void AddAdditionalSchemes(Schemes* schemes) override;
void AddPepperPlugins(
std::vector<content::PepperPluginInfo>* plugins) override;
void AddContentDecryptionModules(
std::vector<content::CdmInfo>* cdms,
std::vector<media::CdmHostFilePath>* cdm_host_file_paths) override;
bool IsDataResourceGzipped(int resource_id) const override;
private:
DISALLOW_COPY_AND_ASSIGN(AtomContentClient);
};
} // namespace atom
#endif // ATOM_APP_ATOM_CONTENT_CLIENT_H_

View file

@ -0,0 +1,23 @@
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_APP_ATOM_LIBRARY_MAIN_H_
#define ATOM_APP_ATOM_LIBRARY_MAIN_H_
#include "build/build_config.h"
#include "electron/buildflags/buildflags.h"
#if defined(OS_MACOSX)
extern "C" {
__attribute__((visibility("default"))) int AtomMain(int argc, char* argv[]);
#if BUILDFLAG(ENABLE_RUN_AS_NODE)
__attribute__((visibility("default"))) int AtomInitializeICUandStartNode(
int argc,
char* argv[]);
#endif
}
#endif // OS_MACOSX
#endif // ATOM_APP_ATOM_LIBRARY_MAIN_H_

View file

@ -0,0 +1,38 @@
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/app/atom_library_main.h"
#include "atom/app/atom_main_delegate.h"
#include "atom/app/node_main.h"
#include "atom/common/atom_command_line.h"
#include "atom/common/mac/main_application_bundle.h"
#include "base/at_exit.h"
#include "base/i18n/icu_util.h"
#include "base/mac/bundle_locations.h"
#include "base/mac/scoped_nsautorelease_pool.h"
#include "content/public/app/content_main.h"
int AtomMain(int argc, char* argv[]) {
atom::AtomMainDelegate delegate;
content::ContentMainParams params(&delegate);
params.argc = argc;
params.argv = const_cast<const char**>(argv);
atom::AtomCommandLine::Init(argc, argv);
return content::ContentMain(params);
}
#if BUILDFLAG(ENABLE_RUN_AS_NODE)
int AtomInitializeICUandStartNode(int argc, char* argv[]) {
base::AtExitManager atexit_manager;
base::mac::ScopedNSAutoreleasePool pool;
base::mac::SetOverrideFrameworkBundlePath(
atom::MainApplicationBundlePath()
.Append("Contents")
.Append("Frameworks")
.Append(ELECTRON_PRODUCT_NAME " Framework.framework"));
base::i18n::InitializeICU();
return atom::NodeMain(argc, argv);
}
#endif

View file

@ -0,0 +1,16 @@
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#import <Cocoa/Cocoa.h>
int main(int argc, char* argv[]) {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSArray* pathComponents = [[[NSBundle mainBundle] bundlePath] pathComponents];
pathComponents = [pathComponents
subarrayWithRange:NSMakeRange(0, [pathComponents count] - 4)];
NSString* path = [NSString pathWithComponents:pathComponents];
[[NSWorkspace sharedWorkspace] launchApplication:path];
[pool drain];
return 0;
}

252
shell/app/atom_main.cc Normal file
View file

@ -0,0 +1,252 @@
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/app/atom_main.h"
#include <algorithm>
#include <cstdlib>
#include <memory>
#include <vector>
#if defined(OS_WIN)
#include <windows.h> // windows.h must be included first
#include <atlbase.h> // ensures that ATL statics like `_AtlWinModule` are initialized (it's an issue in static debug build)
#include <shellapi.h>
#include <shellscalingapi.h>
#include <tchar.h>
#include "atom/app/atom_main_delegate.h"
#include "atom/app/command_line_args.h"
#include "atom/common/crash_reporter/win/crash_service_main.h"
#include "base/environment.h"
#include "base/process/launch.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/windows_version.h"
#include "content/public/app/sandbox_helper_win.h"
#include "sandbox/win/src/sandbox_types.h"
#elif defined(OS_LINUX) // defined(OS_WIN)
#include <unistd.h>
#include <cstdio>
#include "atom/app/atom_main_delegate.h" // NOLINT
#include "content/public/app/content_main.h"
#else // defined(OS_LINUX)
#include <mach-o/dyld.h>
#include <unistd.h>
#include <cstdio>
#include "atom/app/atom_library_main.h"
#endif // defined(OS_MACOSX)
#include "atom/app/node_main.h"
#include "atom/common/atom_command_line.h"
#include "atom/common/atom_constants.h"
#include "base/at_exit.h"
#include "base/i18n/icu_util.h"
#include "electron/buildflags/buildflags.h"
#if defined(HELPER_EXECUTABLE) && !defined(MAS_BUILD)
#include "sandbox/mac/seatbelt_exec.h" // nogncheck
#endif
namespace {
ALLOW_UNUSED_TYPE bool IsEnvSet(const char* name) {
#if defined(OS_WIN)
size_t required_size;
getenv_s(&required_size, nullptr, 0, name);
return required_size != 0;
#else
char* indicator = getenv(name);
return indicator && indicator[0] != '\0';
#endif
}
#if defined(OS_POSIX)
void FixStdioStreams() {
// libuv may mark stdin/stdout/stderr as close-on-exec, which interferes
// with chromium's subprocess spawning. As a workaround, we detect if these
// streams are closed on startup, and reopen them as /dev/null if necessary.
// Otherwise, an unrelated file descriptor will be assigned as stdout/stderr
// which may cause various errors when attempting to write to them.
//
// For details see https://github.com/libuv/libuv/issues/2062
struct stat st;
if (fstat(STDIN_FILENO, &st) < 0 && errno == EBADF)
ignore_result(freopen("/dev/null", "r", stdin));
if (fstat(STDOUT_FILENO, &st) < 0 && errno == EBADF)
ignore_result(freopen("/dev/null", "w", stdout));
if (fstat(STDERR_FILENO, &st) < 0 && errno == EBADF)
ignore_result(freopen("/dev/null", "w", stderr));
}
#endif
} // namespace
#if defined(OS_WIN)
namespace crash_reporter {
extern const char kCrashpadProcess[];
}
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
struct Arguments {
int argc = 0;
wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
~Arguments() { LocalFree(argv); }
} arguments;
if (!arguments.argv)
return -1;
#ifdef _DEBUG
// Don't display assert dialog boxes in CI test runs
static const char* kCI = "ELECTRON_CI";
bool is_ci = IsEnvSet(kCI);
if (!is_ci) {
for (int i = 0; i < arguments.argc; ++i) {
if (!_wcsicmp(arguments.argv[i], L"--ci")) {
is_ci = true;
_putenv_s(kCI, "1"); // set flag for child processes
break;
}
}
}
if (is_ci) {
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
_set_error_mode(_OUT_TO_STDERR);
}
#endif
#if BUILDFLAG(ENABLE_RUN_AS_NODE)
bool run_as_node = IsEnvSet(atom::kRunAsNode);
#else
bool run_as_node = false;
#endif
// Make sure the output is printed to console.
if (run_as_node || !IsEnvSet("ELECTRON_NO_ATTACH_CONSOLE"))
base::RouteStdioToConsole(false);
#ifndef DEBUG
// Chromium has its own TLS subsystem which supports automatic destruction
// of thread-local data, and also depends on memory allocation routines
// provided by the CRT. The problem is that the auto-destruction mechanism
// uses a hidden feature of the OS loader which calls a callback on thread
// exit, but only after all loaded DLLs have been detached. Since the CRT is
// also a DLL, it happens that by the time Chromium's `OnThreadExit` function
// is called, the heap functions, though still in memory, no longer perform
// their duties, and when Chromium calls `free` on its buffer, it triggers
// an access violation error.
// We work around this problem by invoking Chromium's `OnThreadExit` in time
// from within the CRT's atexit facility, ensuring the heap functions are
// still active. The second invocation from the OS loader will be a no-op.
extern void NTAPI OnThreadExit(PVOID module, DWORD reason, PVOID reserved);
atexit([]() { OnThreadExit(nullptr, DLL_THREAD_DETACH, nullptr); });
#endif
std::vector<char*> argv(arguments.argc);
std::transform(arguments.argv, arguments.argv + arguments.argc, argv.begin(),
[](auto& a) { return _strdup(base::WideToUTF8(a).c_str()); });
#if BUILDFLAG(ENABLE_RUN_AS_NODE)
if (run_as_node) {
base::AtExitManager atexit_manager;
base::i18n::InitializeICU();
auto ret = atom::NodeMain(argv.size(), argv.data());
std::for_each(argv.begin(), argv.end(), free);
return ret;
}
#endif
base::CommandLine::Init(argv.size(), argv.data());
const base::CommandLine& cmd_line = *base::CommandLine::ForCurrentProcess();
if (cmd_line.GetSwitchValueASCII("type") ==
crash_reporter::kCrashpadProcess) {
return crash_service::Main(&argv);
}
if (!atom::CheckCommandLineArguments(arguments.argc, arguments.argv))
return -1;
sandbox::SandboxInterfaceInfo sandbox_info = {0};
content::InitializeSandboxInfo(&sandbox_info);
atom::AtomMainDelegate delegate;
content::ContentMainParams params(&delegate);
params.instance = instance;
params.sandbox_info = &sandbox_info;
atom::AtomCommandLine::Init(arguments.argc, arguments.argv);
return content::ContentMain(params);
}
#elif defined(OS_LINUX) // defined(OS_WIN)
int main(int argc, char* argv[]) {
FixStdioStreams();
#if BUILDFLAG(ENABLE_RUN_AS_NODE)
if (IsEnvSet(atom::kRunAsNode)) {
base::i18n::InitializeICU();
base::AtExitManager atexit_manager;
return atom::NodeMain(argc, argv);
}
#endif
atom::AtomMainDelegate delegate;
content::ContentMainParams params(&delegate);
params.argc = argc;
params.argv = const_cast<const char**>(argv);
atom::AtomCommandLine::Init(argc, argv);
return content::ContentMain(params);
}
#else // defined(OS_LINUX)
int main(int argc, char* argv[]) {
FixStdioStreams();
#if BUILDFLAG(ENABLE_RUN_AS_NODE)
if (IsEnvSet(atom::kRunAsNode)) {
return AtomInitializeICUandStartNode(argc, argv);
}
#endif
#if defined(HELPER_EXECUTABLE) && !defined(MAS_BUILD)
uint32_t exec_path_size = 0;
int rv = _NSGetExecutablePath(NULL, &exec_path_size);
if (rv != -1) {
fprintf(stderr, "_NSGetExecutablePath: get length failed\n");
abort();
}
std::unique_ptr<char[]> exec_path(new char[exec_path_size]);
rv = _NSGetExecutablePath(exec_path.get(), &exec_path_size);
if (rv != 0) {
fprintf(stderr, "_NSGetExecutablePath: get path failed\n");
abort();
}
sandbox::SeatbeltExecServer::CreateFromArgumentsResult seatbelt =
sandbox::SeatbeltExecServer::CreateFromArguments(exec_path.get(), argc,
argv);
if (seatbelt.sandbox_required) {
if (!seatbelt.server) {
fprintf(stderr, "Failed to create seatbelt sandbox server.\n");
abort();
}
if (!seatbelt.server->InitializeSandbox()) {
fprintf(stderr, "Failed to initialize sandbox.\n");
abort();
}
}
#endif // defined(HELPER_EXECUTABLE) && !defined(MAS_BUILD)
return AtomMain(argc, argv);
}
#endif // defined(OS_MACOSX)

10
shell/app/atom_main.h Normal file
View file

@ -0,0 +1,10 @@
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_APP_ATOM_MAIN_H_
#define ATOM_APP_ATOM_MAIN_H_
#include "content/public/app/content_main.h"
#endif // ATOM_APP_ATOM_MAIN_H_

View file

@ -0,0 +1,329 @@
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/app/atom_main_delegate.h"
#include <iostream>
#include <memory>
#include <string>
#if defined(OS_LINUX)
#include <glib.h> // for g_setenv()
#endif
#include "atom/app/atom_content_client.h"
#include "atom/browser/atom_browser_client.h"
#include "atom/browser/atom_gpu_client.h"
#include "atom/browser/feature_list.h"
#include "atom/browser/relauncher.h"
#include "atom/common/options_switches.h"
#include "atom/renderer/atom_renderer_client.h"
#include "atom/renderer/atom_sandboxed_renderer_client.h"
#include "atom/utility/atom_content_utility_client.h"
#include "base/command_line.h"
#include "base/debug/stack_trace.h"
#include "base/environment.h"
#include "base/logging.h"
#include "base/mac/bundle_locations.h"
#include "base/path_service.h"
#include "chrome/common/chrome_paths.h"
#include "content/public/common/content_switches.h"
#include "electron/buildflags/buildflags.h"
#include "ipc/ipc_buildflags.h"
#include "services/service_manager/embedder/switches.h"
#include "services/service_manager/sandbox/switches.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_switches.h"
#if defined(OS_MACOSX)
#include "atom/app/atom_main_delegate_mac.h"
#endif
#if defined(OS_WIN)
#include "base/win/win_util.h"
#if defined(_WIN64)
#include "atom/common/crash_reporter/crash_reporter_win.h"
#endif
#endif
namespace atom {
namespace {
const char* kRelauncherProcess = "relauncher";
bool IsBrowserProcess(base::CommandLine* cmd) {
std::string process_type = cmd->GetSwitchValueASCII(::switches::kProcessType);
return process_type.empty();
}
// Returns true if this subprocess type needs the ResourceBundle initialized
// and resources loaded.
bool SubprocessNeedsResourceBundle(const std::string& process_type) {
return
#if defined(OS_POSIX) && !defined(OS_MACOSX)
// The zygote process opens the resources for the renderers.
process_type == service_manager::switches::kZygoteProcess ||
#endif
#if defined(OS_MACOSX)
// Mac needs them too for scrollbar related images and for sandbox
// profiles.
process_type == ::switches::kPpapiPluginProcess ||
process_type == ::switches::kPpapiBrokerProcess ||
process_type == ::switches::kGpuProcess ||
#endif
process_type == ::switches::kRendererProcess ||
process_type == ::switches::kUtilityProcess;
}
#if defined(OS_WIN)
void InvalidParameterHandler(const wchar_t*,
const wchar_t*,
const wchar_t*,
unsigned int,
uintptr_t) {
// noop.
}
#endif
} // namespace
void LoadResourceBundle(const std::string& locale) {
const bool initialized = ui::ResourceBundle::HasSharedInstance();
if (initialized)
ui::ResourceBundle::CleanupSharedInstance();
// Load other resource files.
base::FilePath pak_dir;
#if defined(OS_MACOSX)
pak_dir =
base::mac::FrameworkBundlePath().Append(FILE_PATH_LITERAL("Resources"));
#else
base::PathService::Get(base::DIR_MODULE, &pak_dir);
#endif
ui::ResourceBundle::InitSharedInstanceWithLocale(
locale, nullptr, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
bundle.ReloadLocaleResources(locale);
bundle.AddDataPackFromPath(pak_dir.Append(FILE_PATH_LITERAL("resources.pak")),
ui::SCALE_FACTOR_NONE);
#if BUILDFLAG(ENABLE_PDF_VIEWER)
NOTIMPLEMENTED()
<< "Hi, whoever's fixing PDF support! Thanks! The pdf "
"viewer resources haven't been ported over to the GN build yet, so "
"you'll probably need to change this bit of code.";
bundle.AddDataPackFromPath(
pak_dir.Append(FILE_PATH_LITERAL("pdf_viewer_resources.pak")),
ui::GetSupportedScaleFactors()[0]);
#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
}
AtomMainDelegate::AtomMainDelegate() {}
AtomMainDelegate::~AtomMainDelegate() {}
bool AtomMainDelegate::BasicStartupComplete(int* exit_code) {
auto* command_line = base::CommandLine::ForCurrentProcess();
logging::LoggingSettings settings;
#if defined(OS_WIN)
#if defined(_WIN64)
crash_reporter::CrashReporterWin::SetUnhandledExceptionFilter();
#endif
// On Windows the terminal returns immediately, so we add a new line to
// prevent output in the same line as the prompt.
if (IsBrowserProcess(command_line))
std::wcout << std::endl;
#if defined(DEBUG)
// Print logging to debug.log on Windows
settings.logging_dest = logging::LOG_TO_ALL;
base::FilePath log_filename;
base::PathService::Get(base::DIR_EXE, &log_filename);
log_filename = log_filename.AppendASCII("debug.log");
settings.log_file = log_filename.value().c_str();
settings.lock_log = logging::LOCK_LOG_FILE;
settings.delete_old = logging::DELETE_OLD_LOG_FILE;
#else
settings.logging_dest =
logging::LOG_TO_SYSTEM_DEBUG_LOG | logging::LOG_TO_STDERR;
#endif // defined(DEBUG)
#else // defined(OS_WIN)
settings.logging_dest =
logging::LOG_TO_SYSTEM_DEBUG_LOG | logging::LOG_TO_STDERR;
#endif // !defined(OS_WIN)
// Only enable logging when --enable-logging is specified.
auto env = base::Environment::Create();
if (!command_line->HasSwitch(::switches::kEnableLogging) &&
!env->HasVar("ELECTRON_ENABLE_LOGGING")) {
settings.logging_dest = logging::LOG_NONE;
logging::SetMinLogLevel(logging::LOG_NUM_SEVERITIES);
}
logging::InitLogging(settings);
// Logging with pid and timestamp.
logging::SetLogItems(true, false, true, false);
// Enable convient stack printing. This is enabled by default in non-official
// builds.
if (env->HasVar("ELECTRON_ENABLE_STACK_DUMPING"))
base::debug::EnableInProcessStackDumping();
if (env->HasVar("ELECTRON_DISABLE_SANDBOX"))
command_line->AppendSwitch(service_manager::switches::kNoSandbox);
chrome::RegisterPathProvider();
#if defined(OS_MACOSX)
OverrideChildProcessPath();
OverrideFrameworkBundlePath();
SetUpBundleOverrides();
#endif
#if defined(OS_WIN)
// Ignore invalid parameter errors.
_set_invalid_parameter_handler(InvalidParameterHandler);
// Disable the ActiveVerifier, which is used by Chrome to track possible
// bugs, but no use in Electron.
base::win::DisableHandleVerifier();
if (IsBrowserProcess(command_line))
base::win::PinUser32();
#endif
content_client_ = std::make_unique<AtomContentClient>();
SetContentClient(content_client_.get());
return false;
}
void AtomMainDelegate::PostEarlyInitialization(bool is_running_tests) {
std::string custom_locale;
ui::ResourceBundle::InitSharedInstanceWithLocale(
custom_locale, nullptr, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
auto* cmd_line = base::CommandLine::ForCurrentProcess();
if (cmd_line->HasSwitch(::switches::kLang)) {
const std::string locale = cmd_line->GetSwitchValueASCII(::switches::kLang);
const base::FilePath locale_file_path =
ui::ResourceBundle::GetSharedInstance().GetLocaleFilePath(locale, true);
if (!locale_file_path.empty()) {
custom_locale = locale;
#if defined(OS_LINUX)
/* When built with USE_GLIB, libcc's GetApplicationLocaleInternal() uses
* glib's g_get_language_names(), which keys off of getenv("LC_ALL") */
g_setenv("LC_ALL", custom_locale.c_str(), TRUE);
#endif
}
}
#if defined(OS_MACOSX)
if (custom_locale.empty())
l10n_util::OverrideLocaleWithCocoaLocale();
#endif
LoadResourceBundle(custom_locale);
AtomBrowserClient::SetApplicationLocale(
l10n_util::GetApplicationLocale(custom_locale));
}
void AtomMainDelegate::PreSandboxStartup() {
auto* command_line = base::CommandLine::ForCurrentProcess();
std::string process_type =
command_line->GetSwitchValueASCII(::switches::kProcessType);
// Initialize ResourceBundle which handles files loaded from external
// sources. The language should have been passed in to us from the
// browser process as a command line flag.
if (SubprocessNeedsResourceBundle(process_type)) {
std::string locale = command_line->GetSwitchValueASCII(::switches::kLang);
LoadResourceBundle(locale);
}
// Only append arguments for browser process.
if (!IsBrowserProcess(command_line))
return;
// Allow file:// URIs to read other file:// URIs by default.
command_line->AppendSwitch(::switches::kAllowFileAccessFromFiles);
#if defined(OS_MACOSX)
// Enable AVFoundation.
command_line->AppendSwitch("enable-avfoundation");
#endif
}
void AtomMainDelegate::PreCreateMainMessageLoop() {
// This is initialized early because the service manager reads some feature
// flags and we need to make sure the feature list is initialized before the
// service manager reads the features.
InitializeFeatureList();
#if defined(OS_MACOSX)
RegisterAtomCrApp();
#endif
}
content::ContentBrowserClient* AtomMainDelegate::CreateContentBrowserClient() {
browser_client_.reset(new AtomBrowserClient);
return browser_client_.get();
}
content::ContentGpuClient* AtomMainDelegate::CreateContentGpuClient() {
gpu_client_.reset(new AtomGpuClient);
return gpu_client_.get();
}
content::ContentRendererClient*
AtomMainDelegate::CreateContentRendererClient() {
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableSandbox) ||
!base::CommandLine::ForCurrentProcess()->HasSwitch(
service_manager::switches::kNoSandbox)) {
renderer_client_.reset(new AtomSandboxedRendererClient);
} else {
renderer_client_.reset(new AtomRendererClient);
}
return renderer_client_.get();
}
content::ContentUtilityClient* AtomMainDelegate::CreateContentUtilityClient() {
utility_client_.reset(new AtomContentUtilityClient);
return utility_client_.get();
}
int AtomMainDelegate::RunProcess(
const std::string& process_type,
const content::MainFunctionParams& main_function_params) {
if (process_type == kRelauncherProcess)
return relauncher::RelauncherMain(main_function_params);
else
return -1;
}
#if defined(OS_MACOSX)
bool AtomMainDelegate::ShouldSendMachPort(const std::string& process_type) {
return process_type != kRelauncherProcess;
}
bool AtomMainDelegate::DelaySandboxInitialization(
const std::string& process_type) {
return process_type == kRelauncherProcess;
}
#endif
bool AtomMainDelegate::ShouldLockSchemeRegistry() {
return false;
}
bool AtomMainDelegate::ShouldCreateFeatureList() {
return false;
}
} // namespace atom

View file

@ -0,0 +1,61 @@
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_APP_ATOM_MAIN_DELEGATE_H_
#define ATOM_APP_ATOM_MAIN_DELEGATE_H_
#include <memory>
#include <string>
#include "content/public/app/content_main_delegate.h"
#include "content/public/common/content_client.h"
namespace atom {
void LoadResourceBundle(const std::string& locale);
class AtomMainDelegate : public content::ContentMainDelegate {
public:
AtomMainDelegate();
~AtomMainDelegate() override;
protected:
// content::ContentMainDelegate:
bool BasicStartupComplete(int* exit_code) override;
void PreSandboxStartup() override;
void PreCreateMainMessageLoop() override;
void PostEarlyInitialization(bool is_running_tests) override;
content::ContentBrowserClient* CreateContentBrowserClient() override;
content::ContentGpuClient* CreateContentGpuClient() override;
content::ContentRendererClient* CreateContentRendererClient() override;
content::ContentUtilityClient* CreateContentUtilityClient() override;
int RunProcess(
const std::string& process_type,
const content::MainFunctionParams& main_function_params) override;
#if defined(OS_MACOSX)
bool ShouldSendMachPort(const std::string& process_type) override;
bool DelaySandboxInitialization(const std::string& process_type) override;
#endif
bool ShouldLockSchemeRegistry() override;
bool ShouldCreateFeatureList() override;
private:
#if defined(OS_MACOSX)
void OverrideChildProcessPath();
void OverrideFrameworkBundlePath();
void SetUpBundleOverrides();
#endif
std::unique_ptr<content::ContentBrowserClient> browser_client_;
std::unique_ptr<content::ContentClient> content_client_;
std::unique_ptr<content::ContentGpuClient> gpu_client_;
std::unique_ptr<content::ContentRendererClient> renderer_client_;
std::unique_ptr<content::ContentUtilityClient> utility_client_;
DISALLOW_COPY_AND_ASSIGN(AtomMainDelegate);
};
} // namespace atom
#endif // ATOM_APP_ATOM_MAIN_DELEGATE_H_

View file

@ -0,0 +1,15 @@
// Copyright 2013 Slack Technologies, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ATOM_APP_ATOM_MAIN_DELEGATE_MAC_H_
#define ATOM_APP_ATOM_MAIN_DELEGATE_MAC_H_
namespace atom {
// Initializes NSApplication.
void RegisterAtomCrApp();
} // namespace atom
#endif // ATOM_APP_ATOM_MAIN_DELEGATE_MAC_H_

View file

@ -0,0 +1,71 @@
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/app/atom_main_delegate.h"
#include <string>
#include "atom/browser/mac/atom_application.h"
#include "atom/common/application_info.h"
#include "atom/common/mac/main_application_bundle.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/mac/bundle_locations.h"
#include "base/mac/foundation_util.h"
#include "base/mac/scoped_nsautorelease_pool.h"
#include "base/path_service.h"
#include "base/strings/sys_string_conversions.h"
#include "content/public/common/content_paths.h"
namespace atom {
namespace {
base::FilePath GetFrameworksPath() {
return MainApplicationBundlePath().Append("Contents").Append("Frameworks");
}
base::FilePath GetHelperAppPath(const base::FilePath& frameworks_path,
const std::string& name) {
return frameworks_path.Append(name + " Helper.app")
.Append("Contents")
.Append("MacOS")
.Append(name + " Helper");
}
} // namespace
void AtomMainDelegate::OverrideFrameworkBundlePath() {
base::mac::SetOverrideFrameworkBundlePath(
GetFrameworksPath().Append(ELECTRON_PRODUCT_NAME " Framework.framework"));
}
void AtomMainDelegate::OverrideChildProcessPath() {
base::FilePath frameworks_path = GetFrameworksPath();
base::FilePath helper_path =
GetHelperAppPath(frameworks_path, ELECTRON_PRODUCT_NAME);
if (!base::PathExists(helper_path))
helper_path = GetHelperAppPath(frameworks_path, GetApplicationName());
if (!base::PathExists(helper_path))
LOG(FATAL) << "Unable to find helper app";
base::PathService::Override(content::CHILD_PROCESS_EXE, helper_path);
}
void AtomMainDelegate::SetUpBundleOverrides() {
base::mac::ScopedNSAutoreleasePool pool;
NSBundle* bundle = MainApplicationBundle();
std::string base_bundle_id =
base::SysNSStringToUTF8([bundle bundleIdentifier]);
NSString* team_id = [bundle objectForInfoDictionaryKey:@"ElectronTeamID"];
if (team_id)
base_bundle_id = base::SysNSStringToUTF8(team_id) + "." + base_bundle_id;
base::mac::SetBaseBundleID(base_bundle_id.c_str());
}
void RegisterAtomCrApp() {
// Force the NSApplication subclass to be used.
[AtomApplication sharedApplication];
}
} // namespace atom

View file

@ -0,0 +1,53 @@
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/app/command_line_args.h"
namespace {
bool IsUrlArg(const base::CommandLine::CharType* arg) {
// the first character must be a letter for this to be a URL
auto c = *arg;
if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')) {
for (auto* p = arg + 1; *p; ++p) {
c = *p;
// colon indicates that the argument starts with a URI scheme
if (c == ':') {
// it could also be a Windows filesystem path
if (p == arg + 1)
break;
return true;
}
// white-space before a colon means it's not a URL
if (c == ' ' || (0x9 <= c && c <= 0xD))
break;
}
}
return false;
}
} // namespace
namespace atom {
bool CheckCommandLineArguments(int argc, base::CommandLine::CharType** argv) {
const base::CommandLine::StringType dashdash(2, '-');
bool block_args = false;
for (int i = 0; i < argc; ++i) {
if (argv[i] == dashdash)
break;
if (block_args) {
return false;
} else if (IsUrlArg(argv[i])) {
block_args = true;
}
}
return true;
}
} // namespace atom

View file

@ -0,0 +1,16 @@
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_APP_COMMAND_LINE_ARGS_H_
#define ATOM_APP_COMMAND_LINE_ARGS_H_
#include "base/command_line.h"
namespace atom {
bool CheckCommandLineArguments(int argc, base::CommandLine::CharType** argv);
} // namespace atom
#endif // ATOM_APP_COMMAND_LINE_ARGS_H_

65
shell/app/manifests.cc Normal file
View file

@ -0,0 +1,65 @@
// Copyright (c) 2019 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/app/manifests.h"
#include "base/no_destructor.h"
#include "electron/atom/common/api/api.mojom.h"
#include "printing/buildflags/buildflags.h"
#include "services/proxy_resolver/public/cpp/manifest.h"
#include "services/service_manager/public/cpp/manifest_builder.h"
#if BUILDFLAG(ENABLE_PRINTING)
#include "components/services/pdf_compositor/public/cpp/manifest.h"
#endif
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
#include "chrome/services/printing/public/cpp/manifest.h"
#endif
namespace {
// TODO(https://crbug.com/781334): Remove these helpers and just update the
// manifest definitions to be marked out-of-process. This is here only to avoid
// extra churn when transitioning away from content_packaged_services.
service_manager::Manifest MakeOutOfProcess(
const service_manager::Manifest& manifest) {
// cpplint.py emits a false positive [build/include_what_you_use]
service_manager::Manifest copy(manifest); // NOLINT
copy.options.execution_mode =
service_manager::Manifest::ExecutionMode::kOutOfProcessBuiltin;
return copy;
}
} // namespace
const service_manager::Manifest& GetElectronContentBrowserOverlayManifest() {
static base::NoDestructor<service_manager::Manifest> manifest{
service_manager::ManifestBuilder()
.WithDisplayName("Electron (browser process)")
.RequireCapability("device", "device:geolocation_control")
.RequireCapability("proxy_resolver", "factory")
.RequireCapability("chrome_printing", "converter")
.RequireCapability("pdf_compositor", "compositor")
.ExposeInterfaceFilterCapability_Deprecated(
"navigation:frame", "renderer",
service_manager::Manifest::InterfaceList<
atom::mojom::ElectronBrowser>())
.Build()};
return *manifest;
}
const std::vector<service_manager::Manifest>&
GetElectronBuiltinServiceManifests() {
static base::NoDestructor<std::vector<service_manager::Manifest>> manifests{{
MakeOutOfProcess(proxy_resolver::GetManifest()),
#if BUILDFLAG(ENABLE_PRINTING)
MakeOutOfProcess(printing::GetPdfCompositorManifest()),
#endif
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
MakeOutOfProcess(GetChromePrintingManifest()),
#endif
}};
return *manifests;
}

16
shell/app/manifests.h Normal file
View file

@ -0,0 +1,16 @@
// Copyright (c) 2019 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_APP_MANIFESTS_H_
#define ATOM_APP_MANIFESTS_H_
#include <vector>
#include "services/service_manager/public/cpp/manifest.h"
const service_manager::Manifest& GetElectronContentBrowserOverlayManifest();
const std::vector<service_manager::Manifest>&
GetElectronBuiltinServiceManifests();
#endif // ATOM_APP_MANIFESTS_H_

133
shell/app/node_main.cc Normal file
View file

@ -0,0 +1,133 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/app/node_main.h"
#include <memory>
#include <utility>
#include "atom/app/uv_task_runner.h"
#include "atom/browser/javascript_environment.h"
#include "atom/browser/node_debugger.h"
#include "atom/common/api/electron_bindings.h"
#include "atom/common/crash_reporter/crash_reporter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/node_bindings.h"
#include "atom/common/node_includes.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/task/thread_pool/thread_pool.h"
#include "base/threading/thread_task_runner_handle.h"
#include "electron/electron_version.h"
#include "gin/array_buffer.h"
#include "gin/public/isolate_holder.h"
#include "gin/v8_initializer.h"
#include "native_mate/dictionary.h"
#if defined(_WIN64)
#include "atom/common/crash_reporter/crash_reporter_win.h"
#endif
namespace atom {
int NodeMain(int argc, char* argv[]) {
base::CommandLine::Init(argc, argv);
int exit_code = 1;
{
// Feed gin::PerIsolateData with a task runner.
argv = uv_setup_args(argc, argv);
uv_loop_t* loop = uv_default_loop();
scoped_refptr<UvTaskRunner> uv_task_runner(new UvTaskRunner(loop));
base::ThreadTaskRunnerHandle handle(uv_task_runner);
// Initialize feature list.
auto feature_list = std::make_unique<base::FeatureList>();
feature_list->InitializeFromCommandLine("", "");
base::FeatureList::SetInstance(std::move(feature_list));
gin::V8Initializer::LoadV8Snapshot(
gin::V8Initializer::V8SnapshotFileType::kWithAdditionalContext);
gin::V8Initializer::LoadV8Natives();
// V8 requires a task scheduler apparently
base::ThreadPoolInstance::CreateAndStartWithDefaultParams("Electron");
// Initialize gin::IsolateHolder.
JavascriptEnvironment gin_env(loop);
#if defined(_WIN64)
crash_reporter::CrashReporterWin::SetUnhandledExceptionFilter();
#endif
// Explicitly register electron's builtin modules.
NodeBindings::RegisterBuiltinModules();
int exec_argc;
const char** exec_argv;
node::Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
node::Environment* env = node::CreateEnvironment(
node::CreateIsolateData(gin_env.isolate(), loop, gin_env.platform()),
gin_env.context(), argc, argv, exec_argc, exec_argv);
// Enable support for v8 inspector.
NodeDebugger node_debugger(env);
node_debugger.Start();
mate::Dictionary process(gin_env.isolate(), env->process_object());
#if defined(OS_WIN)
process.SetMethod("log", &ElectronBindings::Log);
#endif
process.SetMethod("crash", &ElectronBindings::Crash);
// Setup process.crashReporter.start in child node processes
auto reporter = mate::Dictionary::CreateEmpty(gin_env.isolate());
reporter.SetMethod("start", &crash_reporter::CrashReporter::StartInstance);
process.Set("crashReporter", reporter);
mate::Dictionary versions;
if (process.Get("versions", &versions)) {
versions.SetReadOnly(ELECTRON_PROJECT_NAME, ELECTRON_VERSION_STRING);
}
node::LoadEnvironment(env);
bool more;
do {
more = uv_run(env->event_loop(), UV_RUN_ONCE);
gin_env.platform()->DrainTasks(env->isolate());
if (more == false) {
node::EmitBeforeExit(env);
// Emit `beforeExit` if the loop became alive either after emitting
// event, or after running some callbacks.
more = uv_loop_alive(env->event_loop());
if (uv_run(env->event_loop(), UV_RUN_NOWAIT) != 0)
more = true;
}
} while (more == true);
node_debugger.Stop();
exit_code = node::EmitExit(env);
node::RunAtExit(env);
gin_env.platform()->DrainTasks(env->isolate());
gin_env.platform()->CancelPendingDelayedTasks(env->isolate());
gin_env.platform()->UnregisterIsolate(env->isolate());
node::FreeEnvironment(env);
}
// According to "src/gin/shell/gin_main.cc":
//
// gin::IsolateHolder waits for tasks running in ThreadPool in its
// destructor and thus must be destroyed before ThreadPool starts skipping
// CONTINUE_ON_SHUTDOWN tasks.
base::ThreadPoolInstance::Get()->Shutdown();
v8::V8::Dispose();
return exit_code;
}
} // namespace atom

14
shell/app/node_main.h Normal file
View file

@ -0,0 +1,14 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_APP_NODE_MAIN_H_
#define ATOM_APP_NODE_MAIN_H_
namespace atom {
int NodeMain(int argc, char* argv[]);
} // namespace atom
#endif // ATOM_APP_NODE_MAIN_H_

View file

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>${ELECTRON_BUNDLE_ID}</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundleExecutable</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>LSBackgroundOnly</key>
<true/>
</dict>
</plist>

View file

@ -0,0 +1,60 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <utility>
#include "atom/app/uv_task_runner.h"
#include "base/stl_util.h"
namespace atom {
UvTaskRunner::UvTaskRunner(uv_loop_t* loop) : loop_(loop) {}
UvTaskRunner::~UvTaskRunner() {
for (auto& iter : tasks_) {
uv_unref(reinterpret_cast<uv_handle_t*>(iter.first));
delete iter.first;
}
}
bool UvTaskRunner::PostDelayedTask(const base::Location& from_here,
base::OnceClosure task,
base::TimeDelta delay) {
auto* timer = new uv_timer_t;
timer->data = this;
uv_timer_init(loop_, timer);
uv_timer_start(timer, UvTaskRunner::OnTimeout, delay.InMilliseconds(), 0);
tasks_[timer] = std::move(task);
return true;
}
bool UvTaskRunner::RunsTasksInCurrentSequence() const {
return true;
}
bool UvTaskRunner::PostNonNestableDelayedTask(const base::Location& from_here,
base::OnceClosure task,
base::TimeDelta delay) {
return PostDelayedTask(from_here, std::move(task), delay);
}
// static
void UvTaskRunner::OnTimeout(uv_timer_t* timer) {
UvTaskRunner* self = static_cast<UvTaskRunner*>(timer->data);
if (!ContainsKey(self->tasks_, timer))
return;
std::move(self->tasks_[timer]).Run();
self->tasks_.erase(timer);
uv_timer_stop(timer);
uv_close(reinterpret_cast<uv_handle_t*>(timer), UvTaskRunner::OnClose);
}
// static
void UvTaskRunner::OnClose(uv_handle_t* handle) {
delete reinterpret_cast<uv_timer_t*>(handle);
}
} // namespace atom

View file

@ -0,0 +1,45 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_APP_UV_TASK_RUNNER_H_
#define ATOM_APP_UV_TASK_RUNNER_H_
#include <map>
#include "base/callback.h"
#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "uv.h" // NOLINT(build/include)
namespace atom {
// TaskRunner implementation that posts tasks into libuv's default loop.
class UvTaskRunner : public base::SingleThreadTaskRunner {
public:
explicit UvTaskRunner(uv_loop_t* loop);
// base::SingleThreadTaskRunner:
bool PostDelayedTask(const base::Location& from_here,
base::OnceClosure task,
base::TimeDelta delay) override;
bool RunsTasksInCurrentSequence() const override;
bool PostNonNestableDelayedTask(const base::Location& from_here,
base::OnceClosure task,
base::TimeDelta delay) override;
private:
~UvTaskRunner() override;
static void OnTimeout(uv_timer_t* timer);
static void OnClose(uv_handle_t* handle);
uv_loop_t* loop_;
std::map<uv_timer_t*, base::OnceClosure> tasks_;
DISALLOW_COPY_AND_ASSIGN(UvTaskRunner);
};
} // namespace atom
#endif // ATOM_APP_UV_TASK_RUNNER_H_