Merge remote-tracking branch 'origin/master' into renaesop_master

This commit is contained in:
Kevin Sawicki 2017-05-18 10:08:40 -07:00
commit 84a9b6a42d
336 changed files with 16704 additions and 2418 deletions

View file

@ -92,12 +92,12 @@ CertificateManagerModel::CertificateManagerModel(
CertificateManagerModel::~CertificateManagerModel() {
}
int CertificateManagerModel::ImportFromPKCS12(net::CryptoModule* module,
int CertificateManagerModel::ImportFromPKCS12(PK11SlotInfo* slot_info,
const std::string& data,
const base::string16& password,
bool is_extractable,
net::CertificateList* imported_certs) {
return cert_db_->ImportFromPKCS12(module, data, password,
return cert_db_->ImportFromPKCS12(slot_info, data, password,
is_extractable, imported_certs);
}

View file

@ -44,7 +44,7 @@ class CertificateManagerModel {
// |data|, using the given |password|. If |is_extractable| is false,
// mark the private key as unextractable from the module.
// Returns a net error code on failure.
int ImportFromPKCS12(net::CryptoModule* module,
int ImportFromPKCS12(PK11SlotInfo* slot_info,
const std::string& data,
const base::string16& password,
bool is_extractable,

View file

@ -8,6 +8,8 @@
#include <set>
#include <sstream>
using base::PlatformThreadRef;
#include "base/hash.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"

View file

@ -18,10 +18,9 @@
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/common/chrome_utility_messages.h"
#include "chrome/common/print_messages.h"
#include "chrome/common/chrome_utility_printing_messages.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_data.h"
#include "content/public/browser/utility_process_host.h"
@ -30,13 +29,13 @@
#include "printing/pdf_render_settings.h"
#include "ui/base/l10n/l10n_util.h"
using content::BrowserThread;
namespace printing {
namespace {
using content::BrowserThread;
class PdfToEmfConverterImpl;
class PdfConverterImpl;
// Allows to delete temporary directory after all temporary files created inside
// are closed. Windows cannot delete directory with opened files. Directory is
@ -59,8 +58,8 @@ class RefCountedTempDir
DISALLOW_COPY_AND_ASSIGN(RefCountedTempDir);
};
typedef std::unique_ptr<base::File, BrowserThread::DeleteOnFileThread>
ScopedTempFile;
using ScopedTempFile =
std::unique_ptr<base::File, BrowserThread::DeleteOnFileThread>;
// Wrapper for Emf to keep only file handle in memory, and load actual data only
// on playback. Emf::InitFromFile() can play metafile directly from disk, but it
@ -74,21 +73,39 @@ class LazyEmf : public MetafilePlayer {
}
~LazyEmf() override { Close(); }
protected:
// MetafilePlayer:
bool SafePlayback(HDC hdc) const override;
bool GetDataAsVector(std::vector<char>* buffer) const override;
bool SaveTo(base::File* file) const override;
private:
void Close() const;
bool LoadEmf(Emf* emf) const;
private:
mutable scoped_refptr<RefCountedTempDir> temp_dir_;
mutable ScopedTempFile file_; // Mutable because of consts in base class.
bool GetDataAsVector(std::vector<char>* buffer) const override;
bool SaveTo(base::File* file) const override;
DISALLOW_COPY_AND_ASSIGN(LazyEmf);
};
// Converts PDF into EMF.
// Postscript metafile subclass to override SafePlayback.
class PostScriptMetaFile : public LazyEmf {
public:
PostScriptMetaFile(const scoped_refptr<RefCountedTempDir>& temp_dir,
ScopedTempFile file)
: LazyEmf(temp_dir, std::move(file)) {}
~PostScriptMetaFile() override;
protected:
// MetafilePlayer:
bool SafePlayback(HDC hdc) const override;
DISALLOW_COPY_AND_ASSIGN(PostScriptMetaFile);
};
// Class for converting PDF to another format for printing (Emf, Postscript).
// Class uses 3 threads: UI, IO and FILE.
// Internal workflow is following:
// 1. Create instance on the UI thread. (files_, settings_,)
@ -101,36 +118,33 @@ class LazyEmf : public MetafilePlayer {
//
// All these steps work sequentially, so no data should be accessed
// simultaneously by several threads.
class PdfToEmfUtilityProcessHostClient
class PdfConverterUtilityProcessHostClient
: public content::UtilityProcessHostClient {
public:
PdfToEmfUtilityProcessHostClient(
base::WeakPtr<PdfToEmfConverterImpl> converter,
PdfConverterUtilityProcessHostClient(
base::WeakPtr<PdfConverterImpl> converter,
const PdfRenderSettings& settings);
void Start(const scoped_refptr<base::RefCountedMemory>& data,
bool print_text_with_gdi,
const PdfToEmfConverter::StartCallback& start_callback);
const PdfConverter::StartCallback& start_callback);
void GetPage(int page_number,
const PdfToEmfConverter::GetPageCallback& get_page_callback);
const PdfConverter::GetPageCallback& get_page_callback);
void Stop();
// UtilityProcessHostClient implementation.
void OnProcessCrashed(int exit_code) override;
void OnProcessLaunchFailed(int exit_code) override;
// Needs to be public to handle ChromeUtilityHostMsg_PreCacheFontCharacters
// sync message replies.
bool Send(IPC::Message* msg);
// UtilityProcessHostClient implementation.
void OnProcessCrashed(int exit_code) override;
void OnProcessLaunchFailed(int exit_code) override;
bool OnMessageReceived(const IPC::Message& message) override;
private:
protected:
class GetPageCallbackData {
public:
GetPageCallbackData(int page_number,
PdfToEmfConverter::GetPageCallback callback)
GetPageCallbackData(int page_number, PdfConverter::GetPageCallback callback)
: page_number_(page_number), callback_(callback) {}
GetPageCallbackData(GetPageCallbackData&& other) {
@ -140,45 +154,62 @@ class PdfToEmfUtilityProcessHostClient
GetPageCallbackData& operator=(GetPageCallbackData&& rhs) {
page_number_ = rhs.page_number_;
callback_ = rhs.callback_;
emf_ = std::move(rhs.emf_);
file_ = std::move(rhs.file_);
return *this;
}
int page_number() const { return page_number_; }
const PdfToEmfConverter::GetPageCallback& callback() const {
return callback_;
}
ScopedTempFile TakeEmf() { return std::move(emf_); }
void set_emf(ScopedTempFile emf) { emf_ = std::move(emf); }
const PdfConverter::GetPageCallback& callback() const { return callback_; }
ScopedTempFile TakeFile() { return std::move(file_); }
void set_file(ScopedTempFile file) { file_ = std::move(file); }
private:
int page_number_;
PdfToEmfConverter::GetPageCallback callback_;
ScopedTempFile emf_;
PdfConverter::GetPageCallback callback_;
ScopedTempFile file_;
DISALLOW_COPY_AND_ASSIGN(GetPageCallbackData);
};
~PdfToEmfUtilityProcessHostClient() override;
~PdfConverterUtilityProcessHostClient() override;
// Message handlers.
bool OnMessageReceived(const IPC::Message& message) override;
// Helper functions: must be overridden by subclasses
// Set the process name
virtual base::string16 GetName() const;
// Create a metafileplayer subclass file from a temporary file.
virtual std::unique_ptr<MetafilePlayer> GetFileFromTemp(
std::unique_ptr<base::File, content::BrowserThread::DeleteOnFileThread>
temp_file);
// Send the messages to Start, GetPage, and Stop.
virtual void SendStartMessage(IPC::PlatformFileForTransit transit);
virtual void SendGetPageMessage(int page_number,
IPC::PlatformFileForTransit transit);
virtual void SendStopMessage();
// Message handlers:
void OnPageCount(int page_count);
void OnPageDone(bool success, float scale_factor);
void OnFailed();
void OnTempPdfReady(ScopedTempFile pdf);
void OnTempFileReady(GetPageCallbackData* callback_data,
ScopedTempFile temp_file);
// Additional message handler needed for Pdf to Emf
void OnPreCacheFontCharacters(const LOGFONT& log_font,
const base::string16& characters);
void OnFailed();
void OnTempPdfReady(bool print_text_with_gdi, ScopedTempFile pdf);
void OnTempEmfReady(GetPageCallbackData* callback_data, ScopedTempFile emf);
scoped_refptr<RefCountedTempDir> temp_dir_;
// Used to suppress callbacks after PdfToEmfConverterImpl is deleted.
base::WeakPtr<PdfToEmfConverterImpl> converter_;
// Used to suppress callbacks after PdfConverter is deleted.
base::WeakPtr<PdfConverterImpl> converter_;
PdfRenderSettings settings_;
// Document loaded callback.
PdfToEmfConverter::StartCallback start_callback_;
PdfConverter::StartCallback start_callback_;
// Process host for IPC.
base::WeakPtr<content::UtilityProcessHost> utility_process_host_;
@ -186,22 +217,37 @@ class PdfToEmfUtilityProcessHostClient
// Queue of callbacks for GetPage() requests. Utility process should reply
// with PageDone in the same order as requests were received.
// Use containers that keeps element pointers valid after push() and pop().
typedef std::queue<GetPageCallbackData> GetPageCallbacks;
using GetPageCallbacks = std::queue<GetPageCallbackData>;
GetPageCallbacks get_page_callbacks_;
DISALLOW_COPY_AND_ASSIGN(PdfToEmfUtilityProcessHostClient);
DISALLOW_COPY_AND_ASSIGN(PdfConverterUtilityProcessHostClient);
};
class PdfToEmfConverterImpl : public PdfToEmfConverter {
public:
PdfToEmfConverterImpl();
std::unique_ptr<MetafilePlayer>
PdfConverterUtilityProcessHostClient::GetFileFromTemp(
std::unique_ptr<base::File, content::BrowserThread::DeleteOnFileThread>
temp_file) {
if (settings_.mode == PdfRenderSettings::Mode::POSTSCRIPT_LEVEL2 ||
settings_.mode == PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3) {
return base::MakeUnique<PostScriptMetaFile>(temp_dir_,
std::move(temp_file));
}
return base::MakeUnique<LazyEmf>(temp_dir_, std::move(temp_file));
}
~PdfToEmfConverterImpl() override;
class PdfConverterImpl : public PdfConverter {
public:
PdfConverterImpl();
~PdfConverterImpl() override;
base::WeakPtr<PdfConverterImpl> GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
void Start(const scoped_refptr<base::RefCountedMemory>& data,
const PdfRenderSettings& conversion_settings,
bool print_text_with_gdi,
const StartCallback& start_callback) override;
const StartCallback& start_callback);
void GetPage(int page_number,
const GetPageCallback& get_page_callback) override;
@ -209,11 +255,17 @@ class PdfToEmfConverterImpl : public PdfToEmfConverter {
// Helps to cancel callbacks if this object is destroyed.
void RunCallback(const base::Closure& callback);
private:
scoped_refptr<PdfToEmfUtilityProcessHostClient> utility_client_;
base::WeakPtrFactory<PdfToEmfConverterImpl> weak_ptr_factory_;
void Start(
const scoped_refptr<PdfConverterUtilityProcessHostClient>& utility_client,
const scoped_refptr<base::RefCountedMemory>& data,
const StartCallback& start_callback);
DISALLOW_COPY_AND_ASSIGN(PdfToEmfConverterImpl);
private:
scoped_refptr<PdfConverterUtilityProcessHostClient> utility_client_;
base::WeakPtrFactory<PdfConverterImpl> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(PdfConverterImpl);
};
ScopedTempFile CreateTempFile(scoped_refptr<RefCountedTempDir>* temp_dir) {
@ -260,10 +312,10 @@ ScopedTempFile CreateTempPdfFile(
bool LazyEmf::SafePlayback(HDC hdc) const {
Emf emf;
bool result = LoadEmf(&emf) && emf.SafePlayback(hdc);
// TODO(vitalybuka): Fix destruction of metafiles. For some reasons
// instances of Emf are not deleted. crbug.com/411683
// TODO(thestig): Fix destruction of metafiles. For some reasons
// instances of Emf are not deleted. https://crbug.com/260806
// It's known that the Emf going to be played just once to a printer. So just
// release file here.
// release |file_| here.
Close();
return result;
}
@ -280,7 +332,7 @@ bool LazyEmf::SaveTo(base::File* file) const {
void LazyEmf::Close() const {
file_.reset();
temp_dir_ = NULL;
temp_dir_ = nullptr;
}
bool LazyEmf::LoadEmf(Emf* emf) const {
@ -294,24 +346,55 @@ bool LazyEmf::LoadEmf(Emf* emf) const {
return emf->InitFromData(data.data(), data.size());
}
PdfToEmfUtilityProcessHostClient::PdfToEmfUtilityProcessHostClient(
base::WeakPtr<PdfToEmfConverterImpl> converter,
PostScriptMetaFile::~PostScriptMetaFile() {
}
bool PostScriptMetaFile::SafePlayback(HDC hdc) const {
// TODO(thestig): Fix destruction of metafiles. For some reasons
// instances of Emf are not deleted. https://crbug.com/260806
// It's known that the Emf going to be played just once to a printer. So just
// release |file_| before returning.
Emf emf;
if (!LoadEmf(&emf)) {
Close();
return false;
}
{
// Ensure enumerator destruction before calling Close() below.
Emf::Enumerator emf_enum(emf, nullptr, nullptr);
for (const Emf::Record& record : emf_enum) {
auto* emf_record = record.record();
if (emf_record->iType != EMR_GDICOMMENT)
continue;
const EMRGDICOMMENT* comment =
reinterpret_cast<const EMRGDICOMMENT*>(emf_record);
const char* data = reinterpret_cast<const char*>(comment->Data);
const uint16_t* ptr = reinterpret_cast<const uint16_t*>(data);
int ret = ExtEscape(hdc, PASSTHROUGH, 2 + *ptr, data, 0, nullptr);
DCHECK_EQ(*ptr, ret);
}
}
Close();
return true;
}
PdfConverterUtilityProcessHostClient::PdfConverterUtilityProcessHostClient(
base::WeakPtr<PdfConverterImpl> converter,
const PdfRenderSettings& settings)
: converter_(converter), settings_(settings) {
}
: converter_(converter), settings_(settings) {}
PdfToEmfUtilityProcessHostClient::~PdfToEmfUtilityProcessHostClient() {
}
PdfConverterUtilityProcessHostClient::~PdfConverterUtilityProcessHostClient() {}
void PdfToEmfUtilityProcessHostClient::Start(
void PdfConverterUtilityProcessHostClient::Start(
const scoped_refptr<base::RefCountedMemory>& data,
bool print_text_with_gdi,
const PdfToEmfConverter::StartCallback& start_callback) {
const PdfConverter::StartCallback& start_callback) {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&PdfToEmfUtilityProcessHostClient::Start, this, data,
print_text_with_gdi, start_callback));
base::Bind(&PdfConverterUtilityProcessHostClient::Start, this, data,
start_callback));
return;
}
@ -324,50 +407,41 @@ void PdfToEmfUtilityProcessHostClient::Start(
utility_process_host_ = content::UtilityProcessHost::Create(
this, base::ThreadTaskRunnerHandle::Get())
->AsWeakPtr();
utility_process_host_->SetName(base::ASCIIToUTF16(
"IDS_UTILITY_PROCESS_EMF_CONVERTOR_NAME"));
utility_process_host_->SetName(GetName());
BrowserThread::PostTaskAndReplyWithResult(
BrowserThread::FILE, FROM_HERE,
base::Bind(&CreateTempPdfFile, data, &temp_dir_),
base::Bind(&PdfToEmfUtilityProcessHostClient::OnTempPdfReady, this,
print_text_with_gdi));
base::Bind(&PdfConverterUtilityProcessHostClient::OnTempPdfReady, this));
}
void PdfToEmfUtilityProcessHostClient::OnTempPdfReady(bool print_text_with_gdi,
ScopedTempFile pdf) {
void PdfConverterUtilityProcessHostClient::OnTempPdfReady(ScopedTempFile pdf) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!utility_process_host_ || !pdf)
return OnFailed();
// Should reply with OnPageCount().
Send(new ChromeUtilityMsg_RenderPDFPagesToMetafiles(
IPC::GetPlatformFileForTransit(pdf->GetPlatformFile(), false), settings_,
print_text_with_gdi));
SendStartMessage(
IPC::GetPlatformFileForTransit(pdf->GetPlatformFile(), false));
}
void PdfToEmfUtilityProcessHostClient::OnPageCount(int page_count) {
void PdfConverterUtilityProcessHostClient::OnPageCount(int page_count) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (start_callback_.is_null())
return OnFailed();
BrowserThread::PostTask(BrowserThread::UI,
FROM_HERE,
base::Bind(&PdfToEmfConverterImpl::RunCallback,
converter_,
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(&PdfConverterImpl::RunCallback, converter_,
base::Bind(start_callback_, page_count)));
start_callback_.Reset();
}
void PdfToEmfUtilityProcessHostClient::GetPage(
void PdfConverterUtilityProcessHostClient::GetPage(
int page_number,
const PdfToEmfConverter::GetPageCallback& get_page_callback) {
const PdfConverter::GetPageCallback& get_page_callback) {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(&PdfToEmfUtilityProcessHostClient::GetPage,
this,
page_number,
get_page_callback));
BrowserThread::IO, FROM_HERE,
base::Bind(&PdfConverterUtilityProcessHostClient::GetPage, this,
page_number, get_page_callback));
return;
}
@ -378,55 +452,84 @@ void PdfToEmfUtilityProcessHostClient::GetPage(
return OnFailed();
BrowserThread::PostTaskAndReplyWithResult(
BrowserThread::FILE,
FROM_HERE,
base::Bind(&CreateTempFile, &temp_dir_),
base::Bind(&PdfToEmfUtilityProcessHostClient::OnTempEmfReady,
this,
BrowserThread::FILE, FROM_HERE, base::Bind(&CreateTempFile, &temp_dir_),
base::Bind(&PdfConverterUtilityProcessHostClient::OnTempFileReady, this,
&get_page_callbacks_.back()));
}
void PdfToEmfUtilityProcessHostClient::OnTempEmfReady(
void PdfConverterUtilityProcessHostClient::OnTempFileReady(
GetPageCallbackData* callback_data,
ScopedTempFile emf) {
ScopedTempFile temp_file) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!utility_process_host_ || !emf)
if (!utility_process_host_ || !temp_file)
return OnFailed();
IPC::PlatformFileForTransit transit =
IPC::GetPlatformFileForTransit(emf->GetPlatformFile(), false);
callback_data->set_emf(std::move(emf));
IPC::GetPlatformFileForTransit(temp_file->GetPlatformFile(), false);
callback_data->set_file(std::move(temp_file));
// Should reply with OnPageDone().
Send(new ChromeUtilityMsg_RenderPDFPagesToMetafiles_GetPage(
callback_data->page_number(), transit));
SendGetPageMessage(callback_data->page_number(), transit);
}
void PdfToEmfUtilityProcessHostClient::OnPageDone(bool success,
float scale_factor) {
void PdfConverterUtilityProcessHostClient::OnPageDone(bool success,
float scale_factor) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (get_page_callbacks_.empty())
return OnFailed();
GetPageCallbackData& data = get_page_callbacks_.front();
std::unique_ptr<MetafilePlayer> emf;
std::unique_ptr<MetafilePlayer> file;
if (success) {
ScopedTempFile temp_emf = data.TakeEmf();
if (!temp_emf) // Unexpected message from utility process.
ScopedTempFile temp_file = data.TakeFile();
if (!temp_file) // Unexpected message from utility process.
return OnFailed();
emf = base::MakeUnique<LazyEmf>(temp_dir_, std::move(temp_emf));
file = GetFileFromTemp(std::move(temp_file));
}
BrowserThread::PostTask(BrowserThread::UI,
FROM_HERE,
base::Bind(&PdfToEmfConverterImpl::RunCallback,
converter_,
base::Bind(data.callback(),
data.page_number(),
scale_factor,
base::Passed(&emf))));
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&PdfConverterImpl::RunCallback, converter_,
base::Bind(data.callback(), data.page_number(), scale_factor,
base::Passed(&file))));
get_page_callbacks_.pop();
}
void PdfToEmfUtilityProcessHostClient::OnPreCacheFontCharacters(
void PdfConverterUtilityProcessHostClient::Stop() {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&PdfConverterUtilityProcessHostClient::Stop, this));
return;
}
SendStopMessage();
}
void PdfConverterUtilityProcessHostClient::OnProcessCrashed(int exit_code) {
OnFailed();
}
void PdfConverterUtilityProcessHostClient::OnProcessLaunchFailed(
int exit_code) {
OnFailed();
}
bool PdfConverterUtilityProcessHostClient::Send(IPC::Message* msg) {
if (utility_process_host_)
return utility_process_host_->Send(msg);
delete msg;
return false;
}
void PdfConverterUtilityProcessHostClient::OnFailed() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!start_callback_.is_null())
OnPageCount(0);
while (!get_page_callbacks_.empty())
OnPageDone(false, 0.0f);
utility_process_host_.reset();
}
void PdfConverterUtilityProcessHostClient::OnPreCacheFontCharacters(
const LOGFONT& font,
const base::string16& str) {
// TODO(scottmg): pdf/ppapi still require the renderer to be able to precache
@ -458,29 +561,10 @@ void PdfToEmfUtilityProcessHostClient::OnPreCacheFontCharacters(
DeleteEnhMetaFile(metafile);
}
void PdfToEmfUtilityProcessHostClient::Stop() {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(&PdfToEmfUtilityProcessHostClient::Stop, this));
return;
}
Send(new ChromeUtilityMsg_RenderPDFPagesToMetafiles_Stop());
}
void PdfToEmfUtilityProcessHostClient::OnProcessCrashed(int exit_code) {
OnFailed();
}
void PdfToEmfUtilityProcessHostClient::OnProcessLaunchFailed(int exit_code) {
OnFailed();
}
bool PdfToEmfUtilityProcessHostClient::OnMessageReceived(
bool PdfConverterUtilityProcessHostClient::OnMessageReceived(
const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(PdfToEmfUtilityProcessHostClient, message)
IPC_BEGIN_MESSAGE_MAP(PdfConverterUtilityProcessHostClient, message)
IPC_MESSAGE_HANDLER(
ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageCount, OnPageCount)
IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageDone,
@ -492,59 +576,69 @@ bool PdfToEmfUtilityProcessHostClient::OnMessageReceived(
return handled;
}
bool PdfToEmfUtilityProcessHostClient::Send(IPC::Message* msg) {
if (utility_process_host_)
return utility_process_host_->Send(msg);
delete msg;
return false;
base::string16 PdfConverterUtilityProcessHostClient::GetName() const {
return L"ChromeUtilityProcessPDFConvertor";
}
void PdfToEmfUtilityProcessHostClient::OnFailed() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!start_callback_.is_null())
OnPageCount(0);
while (!get_page_callbacks_.empty())
OnPageDone(false, 0.0f);
utility_process_host_.reset();
void PdfConverterUtilityProcessHostClient::SendGetPageMessage(
int page_number,
IPC::PlatformFileForTransit transit) {
Send(new ChromeUtilityMsg_RenderPDFPagesToMetafiles_GetPage(page_number,
transit));
}
PdfToEmfConverterImpl::PdfToEmfConverterImpl() : weak_ptr_factory_(this) {
void PdfConverterUtilityProcessHostClient::SendStartMessage(
IPC::PlatformFileForTransit transit) {
Send(new ChromeUtilityMsg_RenderPDFPagesToMetafiles(transit, settings_));
}
PdfToEmfConverterImpl::~PdfToEmfConverterImpl() {
void PdfConverterUtilityProcessHostClient::SendStopMessage() {
Send(new ChromeUtilityMsg_RenderPDFPagesToMetafiles_Stop());
}
// Pdf Converter Impl and subclasses
PdfConverterImpl::PdfConverterImpl() : weak_ptr_factory_(this) {}
PdfConverterImpl::~PdfConverterImpl() {
if (utility_client_.get())
utility_client_->Stop();
}
void PdfToEmfConverterImpl::Start(
const scoped_refptr<base::RefCountedMemory>& data,
const PdfRenderSettings& conversion_settings,
bool print_text_with_gdi,
const StartCallback& start_callback) {
DCHECK(!utility_client_.get());
utility_client_ = new PdfToEmfUtilityProcessHostClient(
weak_ptr_factory_.GetWeakPtr(), conversion_settings);
utility_client_->Start(data, print_text_with_gdi, start_callback);
void PdfConverterImpl::Start(
const scoped_refptr<PdfConverterUtilityProcessHostClient>& utility_client,
const scoped_refptr<base::RefCountedMemory>& data,
const StartCallback& start_callback) {
DCHECK(!utility_client_);
utility_client_ = utility_client;
utility_client_->Start(data, start_callback);
}
void PdfToEmfConverterImpl::GetPage(int page_number,
const GetPageCallback& get_page_callback) {
void PdfConverterImpl::GetPage(int page_number,
const GetPageCallback& get_page_callback) {
utility_client_->GetPage(page_number, get_page_callback);
}
void PdfToEmfConverterImpl::RunCallback(const base::Closure& callback) {
void PdfConverterImpl::RunCallback(const base::Closure& callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
callback.Run();
}
} // namespace
PdfToEmfConverter::~PdfToEmfConverter() {
}
PdfConverter::~PdfConverter() {}
// static
std::unique_ptr<PdfToEmfConverter> PdfToEmfConverter::CreateDefault() {
return std::unique_ptr<PdfToEmfConverter>(new PdfToEmfConverterImpl());
std::unique_ptr<PdfConverter> PdfConverter::StartPdfConverter(
const scoped_refptr<base::RefCountedMemory>& data,
const PdfRenderSettings& conversion_settings,
const StartCallback& start_callback) {
std::unique_ptr<PdfConverterImpl> converter =
base::MakeUnique<PdfConverterImpl>();
converter->Start(
new PdfConverterUtilityProcessHostClient(converter->GetWeakPtr(),
conversion_settings),
data, start_callback);
return std::move(converter);
}
} // namespace printing

View file

@ -15,24 +15,21 @@ namespace printing {
class MetafilePlayer;
struct PdfRenderSettings;
class PdfToEmfConverter {
class PdfConverter {
public:
typedef base::Callback<void(int page_count)> StartCallback;
typedef base::Callback<void(int page_number,
float scale_factor,
std::unique_ptr<MetafilePlayer> emf)>
GetPageCallback;
virtual ~PdfToEmfConverter();
static std::unique_ptr<PdfToEmfConverter> CreateDefault();
using StartCallback = base::Callback<void(int page_count)>;
using GetPageCallback =
base::Callback<void(int page_number,
float scale_factor,
std::unique_ptr<MetafilePlayer> file)>;
virtual ~PdfConverter();
// Starts conversion of PDF provided as |data|. Calls |start_callback|
// with positive |page_count|. |page_count| is 0 if initialization failed.
virtual void Start(const scoped_refptr<base::RefCountedMemory>& data,
const PdfRenderSettings& conversion_settings,
bool print_text_with_gdi,
const StartCallback& start_callback) = 0;
static std::unique_ptr<PdfConverter> StartPdfConverter(
const scoped_refptr<base::RefCountedMemory>& data,
const PdfRenderSettings& conversion_settings,
const StartCallback& start_callback);
// Requests conversion of the page. |page_number| is 0-base page number in
// PDF provided in Start() call.
@ -41,7 +38,6 @@ class PdfToEmfConverter {
virtual void GetPage(int page_number,
const GetPageCallback& get_page_callback) = 0;
};
} // namespace printing
#endif // CHROME_BROWSER_PRINTING_PDF_TO_EMF_CONVERTER_H_

View file

@ -14,6 +14,7 @@
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/threading/worker_pool.h"
@ -222,27 +223,23 @@ PrintedDocument* PrintJob::document() const {
}
#if defined(OS_WIN)
class PrintJob::PdfToEmfState {
class PrintJob::PdfConversionState {
public:
PdfToEmfState(const gfx::Size& page_size, const gfx::Rect& content_area)
PdfConversionState(gfx::Size page_size, gfx::Rect content_area)
: page_count_(0),
current_page_(0),
pages_in_progress_(0),
page_size_(page_size),
content_area_(content_area),
converter_(PdfToEmfConverter::CreateDefault()) {}
content_area_(content_area) {}
void Start(const scoped_refptr<base::RefCountedMemory>& data,
const PdfRenderSettings& conversion_settings,
bool print_text_with_gdi,
const PdfToEmfConverter::StartCallback& start_callback) {
converter_->Start(data, conversion_settings, print_text_with_gdi,
start_callback);
const PdfConverter::StartCallback& start_callback) {
converter_ = PdfConverter::StartPdfConverter(
data, conversion_settings, start_callback);
}
void GetMorePages(
const PdfToEmfConverter::GetPageCallback& get_page_callback) {
void GetMorePages(const PdfConverter::GetPageCallback& get_page_callback) {
const int kMaxNumberOfTempFilesPerDocument = 3;
while (pages_in_progress_ < kMaxNumberOfTempFilesPerDocument &&
current_page_ < page_count_) {
@ -251,8 +248,7 @@ class PrintJob::PdfToEmfState {
}
}
void OnPageProcessed(
const PdfToEmfConverter::GetPageCallback& get_page_callback) {
void OnPageProcessed(const PdfConverter::GetPageCallback& get_page_callback) {
--pages_in_progress_;
GetMorePages(get_page_callback);
// Release converter if we don't need this any more.
@ -270,7 +266,7 @@ class PrintJob::PdfToEmfState {
int pages_in_progress_;
gfx::Size page_size_;
gfx::Rect content_area_;
std::unique_ptr<PdfToEmfConverter> converter_;
std::unique_ptr<PdfConverter> converter_;
};
void PrintJob::AppendPrintedPage(int page_number) {
@ -282,46 +278,67 @@ void PrintJob::StartPdfToEmfConversion(
const gfx::Size& page_size,
const gfx::Rect& content_area,
bool print_text_with_gdi) {
DCHECK(!pdf_to_emf_state_);
pdf_to_emf_state_ = base::MakeUnique<PdfToEmfState>(page_size, content_area);
DCHECK(!pdf_conversion_state_);
pdf_conversion_state_ =
base::MakeUnique<PdfConversionState>(page_size, content_area);
const int kPrinterDpi = settings().dpi();
pdf_to_emf_state_->Start(
bytes, PdfRenderSettings(content_area, kPrinterDpi, true),
print_text_with_gdi, base::Bind(&PrintJob::OnPdfToEmfStarted, this));
PdfRenderSettings settings(
content_area, gfx::Point(0, 0), kPrinterDpi, /*autorotate=*/true,
print_text_with_gdi ? PdfRenderSettings::Mode::GDI_TEXT
: PdfRenderSettings::Mode::NORMAL);
pdf_conversion_state_->Start(
bytes, settings, base::Bind(&PrintJob::OnPdfConversionStarted, this));
}
void PrintJob::OnPdfToEmfStarted(int page_count) {
void PrintJob::OnPdfConversionStarted(int page_count) {
if (page_count <= 0) {
pdf_to_emf_state_.reset();
pdf_conversion_state_.reset();
Cancel();
return;
}
pdf_to_emf_state_->set_page_count(page_count);
pdf_to_emf_state_->GetMorePages(
base::Bind(&PrintJob::OnPdfToEmfPageConverted, this));
pdf_conversion_state_->set_page_count(page_count);
pdf_conversion_state_->GetMorePages(
base::Bind(&PrintJob::OnPdfPageConverted, this));
}
void PrintJob::OnPdfToEmfPageConverted(int page_number,
float scale_factor,
std::unique_ptr<MetafilePlayer> emf) {
DCHECK(pdf_to_emf_state_);
if (!document_.get() || !emf || page_number < 0 ||
void PrintJob::OnPdfPageConverted(int page_number,
float scale_factor,
std::unique_ptr<MetafilePlayer> metafile) {
DCHECK(pdf_conversion_state_);
if (!document_.get() || !metafile || page_number < 0 ||
static_cast<size_t>(page_number) >= pdf_page_mapping_.size()) {
pdf_to_emf_state_.reset();
pdf_conversion_state_.reset();
Cancel();
return;
}
// Update the rendered document. It will send notifications to the listener.
document_->SetPage(pdf_page_mapping_[page_number], std::move(emf),
scale_factor, pdf_to_emf_state_->page_size(),
pdf_to_emf_state_->content_area());
document_->SetPage(pdf_page_mapping_[page_number], std::move(metafile),
scale_factor, pdf_conversion_state_->page_size(),
pdf_conversion_state_->content_area());
pdf_to_emf_state_->GetMorePages(
base::Bind(&PrintJob::OnPdfToEmfPageConverted, this));
pdf_conversion_state_->GetMorePages(
base::Bind(&PrintJob::OnPdfPageConverted, this));
}
#endif // OS_WIN
void PrintJob::StartPdfToPostScriptConversion(
const scoped_refptr<base::RefCountedMemory>& bytes,
const gfx::Rect& content_area,
const gfx::Point& physical_offsets,
bool ps_level2) {
DCHECK(!pdf_conversion_state_);
pdf_conversion_state_ = base::MakeUnique<PdfConversionState>(
gfx::Size(), gfx::Rect());
const int kPrinterDpi = settings().dpi();
PdfRenderSettings settings(
content_area, physical_offsets, kPrinterDpi, true /* autorotate? */,
ps_level2 ? PdfRenderSettings::Mode::POSTSCRIPT_LEVEL2
: PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3);
pdf_conversion_state_->Start(
bytes, settings, base::Bind(&PrintJob::OnPdfConversionStarted, this));
}
#endif // defined(OS_WIN)
void PrintJob::UpdatePrintedDocument(PrintedDocument* new_document) {
if (document_.get() == new_document)
@ -372,8 +389,10 @@ void PrintJob::OnNotifyPrintJobEvent(const JobEventDetails& event_details) {
}
case JobEventDetails::PAGE_DONE:
#if defined(OS_WIN)
pdf_to_emf_state_->OnPageProcessed(
base::Bind(&PrintJob::OnPdfToEmfPageConverted, this));
if (pdf_conversion_state_) {
pdf_conversion_state_->OnPageProcessed(
base::Bind(&PrintJob::OnPdfPageConverted, this));
}
#endif // defined(OS_WIN)
break;
default: {

View file

@ -100,6 +100,12 @@ class PrintJob : public PrintJobWorkerOwner,
const gfx::Size& page_size,
const gfx::Rect& content_area,
bool print_text_with_gdi);
void StartPdfToPostScriptConversion(
const scoped_refptr<base::RefCountedMemory>& bytes,
const gfx::Rect& content_area,
const gfx::Point& physical_offset,
bool ps_level2);
#endif // defined(OS_WIN)
protected:
@ -126,10 +132,10 @@ class PrintJob : public PrintJobWorkerOwner,
void HoldUntilStopIsCalled();
#if defined(OS_WIN)
void OnPdfToEmfStarted(int page_count);
void OnPdfToEmfPageConverted(int page_number,
float scale_factor,
std::unique_ptr<MetafilePlayer> emf);
void OnPdfConversionStarted(int page_count);
void OnPdfPageConverted(int page_number,
float scale_factor,
std::unique_ptr<MetafilePlayer> emf);
#endif // defined(OS_WIN)
content::NotificationRegistrar registrar_;
@ -157,8 +163,8 @@ class PrintJob : public PrintJobWorkerOwner,
bool is_canceling_;
#if defined(OS_WIN)
class PdfToEmfState;
std::unique_ptr<PdfToEmfState> pdf_to_emf_state_;
class PdfConversionState;
std::unique_ptr<PdfConversionState> pdf_conversion_state_;
std::vector<int> pdf_page_mapping_;
#endif // defined(OS_WIN)

View file

@ -49,25 +49,34 @@
#include <unistd.h>
#include <cstring>
#include <memory>
#include <set>
#include <string>
#include <stddef.h>
#include "atom/common/atom_command_line.h"
#include "base/base_paths.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_descriptor_watcher_posix.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram_macros.h"
#include "base/path_service.h"
#include "base/posix/eintr_wrapper.h"
#include "base/posix/safe_strerror.h"
#include "base/rand_util.h"
#include "base/sequenced_task_runner_helpers.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
@ -78,6 +87,7 @@
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "build/build_config.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/network_interfaces.h"
#include "ui/base/l10n/l10n_util.h"
@ -222,9 +232,8 @@ int SetupSocketOnly() {
int sock = socket(PF_UNIX, SOCK_STREAM, 0);
PCHECK(sock >= 0) << "socket() failed";
int rv = base::SetNonBlocking(sock);
DCHECK_EQ(0, rv) << "Failed to make non-blocking socket.";
rv = SetCloseOnExec(sock);
DCHECK(base::SetNonBlocking(sock)) << "Failed to make non-blocking socket.";
int rv = SetCloseOnExec(sock);
DCHECK_EQ(0, rv) << "Failed to set CLOEXEC on socket.";
return sock;
@ -305,7 +314,6 @@ bool ParseLockPath(const base::FilePath& path,
bool DisplayProfileInUseError(const base::FilePath& lock_path,
const std::string& hostname,
int pid) {
// TODO: yolo
return true;
}
@ -455,44 +463,38 @@ bool ReplaceOldSingletonLock(const base::FilePath& symlink_content,
// This class sets up a listener on the singleton socket and handles parsing
// messages that come in on the singleton socket.
class ProcessSingleton::LinuxWatcher
: public base::MessageLoopForIO::Watcher,
public base::MessageLoop::DestructionObserver,
public base::RefCountedThreadSafe<ProcessSingleton::LinuxWatcher,
: public base::RefCountedThreadSafe<ProcessSingleton::LinuxWatcher,
BrowserThread::DeleteOnIOThread> {
public:
// A helper class to read message from an established socket.
class SocketReader : public base::MessageLoopForIO::Watcher {
class SocketReader {
public:
SocketReader(ProcessSingleton::LinuxWatcher* parent,
base::MessageLoop* ui_message_loop,
scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
int fd)
: parent_(parent),
ui_message_loop_(ui_message_loop),
ui_task_runner_(ui_task_runner),
fd_(fd),
bytes_read_(0) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
// Wait for reads.
base::MessageLoopForIO::current()->WatchFileDescriptor(
fd, true, base::MessageLoopForIO::WATCH_READ, &fd_reader_, this);
fd_watch_controller_ = base::FileDescriptorWatcher::WatchReadable(
fd, base::Bind(&SocketReader::OnSocketCanReadWithoutBlocking,
base::Unretained(this)));
// If we haven't completed in a reasonable amount of time, give up.
timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kTimeoutInSeconds),
this, &SocketReader::CleanupAndDeleteSelf);
}
~SocketReader() override { CloseSocket(fd_); }
// MessageLoopForIO::Watcher impl.
void OnFileCanReadWithoutBlocking(int fd) override;
void OnFileCanWriteWithoutBlocking(int fd) override {
// SocketReader only watches for accept (read) events.
NOTREACHED();
}
~SocketReader() { CloseSocket(fd_); }
// Finish handling the incoming message by optionally sending back an ACK
// message and removing this SocketReader.
void FinishWithACK(const char *message, size_t length);
private:
void OnSocketCanReadWithoutBlocking();
void CleanupAndDeleteSelf() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
@ -500,13 +502,15 @@ class ProcessSingleton::LinuxWatcher
// We're deleted beyond this point.
}
base::MessageLoopForIO::FileDescriptorWatcher fd_reader_;
// Controls watching |fd_|.
std::unique_ptr<base::FileDescriptorWatcher::Controller>
fd_watch_controller_;
// The ProcessSingleton::LinuxWatcher that owns us.
ProcessSingleton::LinuxWatcher* const parent_;
// A reference to the UI message loop.
base::MessageLoop* const ui_message_loop_;
// A reference to the UI task runner.
scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_;
// The file descriptor we're reading.
const int fd_;
@ -525,9 +529,7 @@ class ProcessSingleton::LinuxWatcher
// We expect to only be constructed on the UI thread.
explicit LinuxWatcher(ProcessSingleton* parent)
: ui_message_loop_(base::MessageLoop::current()),
parent_(parent) {
}
: ui_task_runner_(base::ThreadTaskRunnerHandle::Get()), parent_(parent) {}
// Start listening for connections on the socket. This method should be
// called from the IO thread.
@ -540,79 +542,63 @@ class ProcessSingleton::LinuxWatcher
const std::vector<std::string>& argv,
SocketReader* reader);
// MessageLoopForIO::Watcher impl. These run on the IO thread.
void OnFileCanReadWithoutBlocking(int fd) override;
void OnFileCanWriteWithoutBlocking(int fd) override {
// ProcessSingleton only watches for accept (read) events.
NOTREACHED();
}
// MessageLoop::DestructionObserver
void WillDestroyCurrentMessageLoop() override {
fd_watcher_.StopWatchingFileDescriptor();
}
private:
friend struct BrowserThread::DeleteOnThread<BrowserThread::IO>;
friend class base::DeleteHelper<ProcessSingleton::LinuxWatcher>;
~LinuxWatcher() override {
~LinuxWatcher() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
STLDeleteElements(&readers_);
base::MessageLoopForIO* ml = base::MessageLoopForIO::current();
ml->RemoveDestructionObserver(this);
}
void OnSocketCanReadWithoutBlocking(int socket);
// Removes and deletes the SocketReader.
void RemoveSocketReader(SocketReader* reader);
base::MessageLoopForIO::FileDescriptorWatcher fd_watcher_;
std::unique_ptr<base::FileDescriptorWatcher::Controller> socket_watcher_;
// A reference to the UI message loop (i.e., the message loop we were
// constructed on).
base::MessageLoop* ui_message_loop_;
scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_;
// The ProcessSingleton that owns us.
ProcessSingleton* const parent_;
std::set<SocketReader*> readers_;
std::set<std::unique_ptr<SocketReader>> readers_;
DISALLOW_COPY_AND_ASSIGN(LinuxWatcher);
};
void ProcessSingleton::LinuxWatcher::OnFileCanReadWithoutBlocking(int fd) {
void ProcessSingleton::LinuxWatcher::OnSocketCanReadWithoutBlocking(
int socket) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
// Accepting incoming client.
sockaddr_un from;
socklen_t from_len = sizeof(from);
int connection_socket = HANDLE_EINTR(accept(
fd, reinterpret_cast<sockaddr*>(&from), &from_len));
int connection_socket = HANDLE_EINTR(
accept(socket, reinterpret_cast<sockaddr*>(&from), &from_len));
if (-1 == connection_socket) {
PLOG(ERROR) << "accept() failed";
return;
}
int rv = base::SetNonBlocking(connection_socket);
DCHECK_EQ(0, rv) << "Failed to make non-blocking socket.";
SocketReader* reader = new SocketReader(this,
ui_message_loop_,
connection_socket);
readers_.insert(reader);
DCHECK(base::SetNonBlocking(connection_socket))
<< "Failed to make non-blocking socket.";
readers_.insert(
base::MakeUnique<SocketReader>(this, ui_task_runner_, connection_socket));
}
void ProcessSingleton::LinuxWatcher::StartListening(int socket) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
// Watch for client connections on this socket.
base::MessageLoopForIO* ml = base::MessageLoopForIO::current();
ml->AddDestructionObserver(this);
ml->WatchFileDescriptor(socket, true, base::MessageLoopForIO::WATCH_READ,
&fd_watcher_, this);
socket_watcher_ = base::FileDescriptorWatcher::WatchReadable(
socket, base::Bind(&LinuxWatcher::OnSocketCanReadWithoutBlocking,
base::Unretained(this), socket));
}
void ProcessSingleton::LinuxWatcher::HandleMessage(
const std::string& current_dir, const std::vector<std::string>& argv,
SocketReader* reader) {
DCHECK(ui_message_loop_ == base::MessageLoop::current());
DCHECK(ui_task_runner_->BelongsToCurrentThread());
DCHECK(reader);
if (parent_->notification_callback_.Run(argv,
@ -632,25 +618,27 @@ void ProcessSingleton::LinuxWatcher::HandleMessage(
void ProcessSingleton::LinuxWatcher::RemoveSocketReader(SocketReader* reader) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(reader);
readers_.erase(reader);
delete reader;
auto it = std::find_if(readers_.begin(), readers_.end(),
[reader](const std::unique_ptr<SocketReader>& ptr) {
return ptr.get() == reader;
});
readers_.erase(it);
}
///////////////////////////////////////////////////////////////////////////////
// ProcessSingleton::LinuxWatcher::SocketReader
//
void ProcessSingleton::LinuxWatcher::SocketReader::OnFileCanReadWithoutBlocking(
int fd) {
void ProcessSingleton::LinuxWatcher::SocketReader::
OnSocketCanReadWithoutBlocking() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK_EQ(fd, fd_);
while (bytes_read_ < sizeof(buf_)) {
ssize_t rv = HANDLE_EINTR(
read(fd, buf_ + bytes_read_, sizeof(buf_) - bytes_read_));
ssize_t rv =
HANDLE_EINTR(read(fd_, buf_ + bytes_read_, sizeof(buf_) - bytes_read_));
if (rv < 0) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
PLOG(ERROR) << "read() failed";
CloseSocket(fd);
CloseSocket(fd_);
return;
} else {
// It would block, so we just return and continue to watch for the next
@ -696,10 +684,10 @@ void ProcessSingleton::LinuxWatcher::SocketReader::OnFileCanReadWithoutBlocking(
tokens.erase(tokens.begin());
// Return to the UI thread to handle opening a new browser tab.
ui_message_loop_->task_runner()->PostTask(
ui_task_runner_->PostTask(
FROM_HERE, base::Bind(&ProcessSingleton::LinuxWatcher::HandleMessage,
parent_, current_dir, tokens, this));
fd_reader_.StopWatchingFileDescriptor();
fd_watch_controller_.reset();
// LinuxWatcher::HandleMessage() is in charge of destroying this SocketReader
// object by invoking SocketReader::FinishWithACK().
@ -731,7 +719,8 @@ ProcessSingleton::ProcessSingleton(
const base::FilePath& user_data_dir,
const NotificationCallback& notification_callback)
: notification_callback_(notification_callback),
current_pid_(base::GetCurrentProcId()) {
current_pid_(base::GetCurrentProcId()),
watcher_(new LinuxWatcher(this)) {
// The user_data_dir may have not been created yet.
base::CreateDirectoryAndGetError(user_data_dir, nullptr);
@ -897,12 +886,26 @@ ProcessSingleton::NotifyOtherProcessWithTimeoutOrCreate(
const base::CommandLine& command_line,
int retry_attempts,
const base::TimeDelta& timeout) {
const base::TimeTicks begin_ticks = base::TimeTicks::Now();
NotifyResult result = NotifyOtherProcessWithTimeout(
command_line, retry_attempts, timeout, true);
if (result != PROCESS_NONE)
if (result != PROCESS_NONE) {
if (result == PROCESS_NOTIFIED) {
UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToNotify",
base::TimeTicks::Now() - begin_ticks);
} else {
UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToFailure",
base::TimeTicks::Now() - begin_ticks);
}
return result;
if (Create())
}
if (Create()) {
UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToCreate",
base::TimeTicks::Now() - begin_ticks);
return PROCESS_NONE;
}
// If the Create() failed, try again to notify. (It could be that another
// instance was starting at the same time and managed to grab the lock before
// we did.)
@ -910,6 +913,15 @@ ProcessSingleton::NotifyOtherProcessWithTimeoutOrCreate(
// aren't going to try to take over the lock ourselves.
result = NotifyOtherProcessWithTimeout(
command_line, retry_attempts, timeout, false);
if (result == PROCESS_NOTIFIED) {
UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToNotify",
base::TimeTicks::Now() - begin_ticks);
} else {
UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToFailure",
base::TimeTicks::Now() - begin_ticks);
}
if (result != PROCESS_NONE)
return result;
@ -1019,15 +1031,13 @@ bool ProcessSingleton::Create() {
if (listen(sock, 5) < 0)
NOTREACHED() << "listen failed: " << base::safe_strerror(errno);
// In Electron the ProcessSingleton is created earlier than the IO
// thread gets created, so we have to postpone the call until message
// loop is up an running.
scoped_refptr<base::SingleThreadTaskRunner> task_runner =
base::ThreadTaskRunnerHandle::Get();
task_runner->PostTask(
DCHECK(BrowserThread::IsMessageLoopValid(BrowserThread::IO));
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(&ProcessSingleton::StartListening,
base::Unretained(this), sock));
base::Bind(&ProcessSingleton::LinuxWatcher::StartListening,
watcher_,
sock));
return true;
}
@ -1038,17 +1048,6 @@ void ProcessSingleton::Cleanup() {
UnlinkPath(lock_path_);
}
void ProcessSingleton::StartListening(int sock) {
watcher_ = new LinuxWatcher(this);
DCHECK(BrowserThread::IsMessageLoopValid(BrowserThread::IO));
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(&ProcessSingleton::LinuxWatcher::StartListening,
watcher_.get(),
sock));
}
bool ProcessSingleton::IsSameChromeInstance(pid_t pid) {
pid_t cur_pid = current_pid_;
while (pid != cur_pid) {