<commit_before>//@author A0094446X
#include "stdafx.h"
#include <QApplication>
#include <QList>
#include <QPair>
#include "task_panel_manager.h"
namespace You {
namespace GUI {

using Date = boost::gregorian::date;
const QString MainWindow::TaskPanelManager::TASK_COLUMN_1 = "Hidden ID Column";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_2 = "Index";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_3 = "Description";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_4 = "Deadline";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_5 = "Priority";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_6 = "Dependencies";

MainWindow::TaskPanelManager::TaskPanelManager(MainWindow* const parentGUI)
: BaseManager(parentGUI), deleteAction(QString("Delete"), this),
editAction(QString("Edit"), this), addAction(QString("Add"), this),
deleteSignalMapper(this), editSignalMapper(this) {
}

MainWindow::TaskPanelManager::~TaskPanelManager() {
}

void MainWindow::TaskPanelManager::setup() {
	QStringList columnHeaders({
		TASK_COLUMN_1,
		TASK_COLUMN_2,
		TASK_COLUMN_3,
		TASK_COLUMN_4,
		TASK_COLUMN_5,
		TASK_COLUMN_6
	});
	QTreeWidget* taskTreePanel = parentGUI->ui.taskTreePanel;
	connect(taskTreePanel, SIGNAL(itemSelectionChanged()),
		parentGUI, SLOT(taskSelected()));

	connect(taskTreePanel, SIGNAL(customContextMenuRequested(const QPoint &)),
		this, SLOT(contextMenu(const QPoint &)));
	taskTreePanel->setColumnCount(columnHeaders.size());
	taskTreePanel->setHeaderItem(createItem(columnHeaders).release());
	// TODO(angathorion): remove magic constants.
	QHeaderView* header = taskTreePanel->header();
	header->setStretchLastSection(true);

	for (int i = 1; i < columnHeaders.size(); ++i) {
		if (i == 2) {
			continue;
		}
		header->resizeSection(i, header->defaultSectionSize());
	}

	taskTreePanel->header()->setMinimumSectionSize(75);
	taskTreePanel->setColumnHidden(0, true);
	taskTreePanel->setColumnHidden(5, true);
}

void MainWindow::TaskPanelManager::addTask(const Task& task) {
	std::unique_ptr<QTreeWidgetItem> item(createItem(task));
	parentGUI->ui.taskTreePanel->addTopLevelItem(item.release());
	updateRowNumbers();
}

void MainWindow::TaskPanelManager::addSubtask(QTreeWidgetItem* parent,
	const QStringList& rowStrings) {
	std::unique_ptr<QTreeWidgetItem> item(createItem(rowStrings));
	parent->addChild(item.release());
	updateRowNumbers();
}

void MainWindow::TaskPanelManager::editTask(const Task& task) {
	QList<QTreeWidgetItem*> items = findItems(task.getID());
	assert(items.length() == 1);
	QTreeWidgetItem item = *items.at(0);
	QStringList wstr = taskToStrVec(task);
	*items.at(0) = *createItem(wstr);
	updateRowNumbers();
}

void MainWindow::TaskPanelManager::deleteTask(Task::ID taskID) {
	QList<QTreeWidgetItem*> items = findItems(taskID);
	assert(items.length() == 1);
	deleteTask(items.at(0));
	updateRowNumbers();
}

void MainWindow::TaskPanelManager::deleteTask(QTreeWidgetItem* task) {
	delete task;
}

std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem(
	const Task& task) {
	return createItem(taskToStrVec(task));
}

std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem(
	const QStringList& rowStrings) {
	return std::make_unique<QTreeWidgetItem>(rowStrings);
}

QList<QTreeWidgetItem*> MainWindow::TaskPanelManager::findItems(
	You::Controller::Task::ID taskID) const {
	return parentGUI->ui.taskTreePanel->findItems(
		boost::lexical_cast<QString>(taskID), 0);
}

QStringList MainWindow::TaskPanelManager::taskToStrVec(
	const You::Controller::Task& task) {
	QStringList result;

	// Insert id
	result.push_back(boost::lexical_cast<QString>(task.getID()));

	// Insert dummy count
	result.push_back("0");

	// Insert description
	result.push_back(QString::fromStdWString(task.getDescription()));

	// Insert deadline
	std::wstringstream wss;
	if (task.getDeadline() == Task::NEVER) {
		wss << L"Never";
	} else if (isPastDue(task.getDeadline())) {
		wss << L"Overdue (" << task.getDeadline() << L")";
	} else if (isDueAfter(task.getDeadline(), 0)) {
		wss << L"Today (" << task.getDeadline() << L")";
	} else if (isDueAfter(task.getDeadline(), 1)) {
		wss << L"Tomorrow (" << task.getDeadline() << L")";
	} else if (isDueAfter(task.getDeadline(), 2)) {
		wss << L"In two days (" << task.getDeadline() << L")";
	} else if (isDueWithin(task.getDeadline(), 7)) {
		wss << L"Within one week (" << task.getDeadline() << L")";
	} else if (isDueWithin(task.getDeadline(), 14)) {
		wss << L"Within two weeks (" << task.getDeadline() << L")";
	} else if (isDueWithin(task.getDeadline(), 21)) {
		wss << L"Within three weeks (" << task.getDeadline() << L")";
	} else if (isDueWithin(task.getDeadline(), 28)) {
		wss << L"Within one month (" << task.getDeadline() << L")";
	} else {
		wss << L"More than a month away (" << task.getDeadline() << L")";
	}
	result.push_back(boost::lexical_cast<QString>(wss.str()));

	// Insert priority
	QString priority[] { "High", "Normal" };

	switch (task.getPriority()) {
	case Task::Priority::HIGH:
		result.push_back(priority[0]);
	case Task::Priority::NORMAL:
		result.push_back(priority[1]);
	}

	// Insert dependencies
	std::wstringstream ss;
	if (task.getDependencies().size() != 0) {
		ss << task.getDependencies().at(0);
		for (int i = 1; i < task.getDependencies().size(); i++) {
			ss << ", " << task.getDependencies().at(i);
		}
		result.push_back(QString::fromStdWString(ss.str()));
	} else {
		result.push_back("None");
	}

	return result;
}

void MainWindow::TaskPanelManager::updateRowNumbers() {
	int rowNum = 0;
	for (QTreeWidgetItemIterator it(parentGUI->ui.taskTreePanel); *it; ++it) {
		(*it)->setData(1, Qt::DisplayRole, rowNum++);
	}
}

bool MainWindow::TaskPanelManager::isPastDue(Task::Time deadline) {
	Task::Time now = boost::posix_time::second_clock::local_time();

	if (deadline < now) {
		return true;
	} else {
		return false;
	}
}

bool MainWindow::TaskPanelManager::isDueAfter(
		Task::Time deadline, int daysLeft) {
	Date by = Date(deadline.date());
	Date today = boost::gregorian::day_clock::local_day();
	if (by.modjulian_day() - today.modjulian_day() == daysLeft) {
		return true;
	} else {
		return false;
	}
}

bool MainWindow::TaskPanelManager::isDueWithin(
	Task::Time deadline, int daysLeft) {
	Date by = Date(deadline.date());
	Date today = boost::gregorian::day_clock::local_day();
	if (by.julian_day() - today.julian_day() < daysLeft) {
		return true;
	} else {
		return false;
	}
}

void MainWindow::TaskPanelManager::contextMenu(const QPoint &pos) {
	/// Try to get the item at the position of the context menu
	QTreeWidgetItem *item = parentGUI->ui.taskTreePanel->itemAt(pos);
	itemContextMenu.reset(new QMenu(parentGUI->ui.taskTreePanel));

	/// Adds the Add Task action. This is always present in the menu.
	itemContextMenu->addAction(&addAction);
	connect(&addAction, SIGNAL(triggered()), parentGUI, SLOT(contextAddTask()));

	/// Adds the Edit Task and Delete Task actions if an item is selected.
	/// QSignalMapper is necessary because arguments need to be passed
	/// as part of the signal.
	if (item) {
		deleteSignalMapper.setMapping(&deleteAction, item->text(1).toInt());
		connect(&deleteAction, SIGNAL(triggered()),
			&deleteSignalMapper, SLOT(map()));
		itemContextMenu->addAction(&deleteAction);
		connect(&deleteSignalMapper, SIGNAL(mapped(int)),
			parentGUI, SLOT(contextDeleteTask(int)));

		editSignalMapper.setMapping(&editAction, item->text(1).toInt());
		connect(&editAction, SIGNAL(triggered()),
			&editSignalMapper, SLOT(map()));
		itemContextMenu->addAction(&editAction);
		connect(&editSignalMapper, SIGNAL(mapped(int)),
			parentGUI, SLOT(contextEditTask(int)));
	}

	itemContextMenu->popup(
		parentGUI->ui.taskTreePanel->viewport()->mapToGlobal(pos));
}

}  // namespace GUI
}  // namespace You
<commit_msg>Dependency fix<commit_after>//@author A0094446X
#include "stdafx.h"
#include <QApplication>
#include <QList>
#include <QPair>
#include "task_panel_manager.h"
namespace You {
namespace GUI {

using Date = boost::gregorian::date;
const QString MainWindow::TaskPanelManager::TASK_COLUMN_1 = "Hidden ID Column";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_2 = "Index";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_3 = "Description";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_4 = "Deadline";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_5 = "Priority";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_6 = "Dependencies";

MainWindow::TaskPanelManager::TaskPanelManager(MainWindow* const parentGUI)
: BaseManager(parentGUI), deleteAction(QString("Delete"), this),
editAction(QString("Edit"), this), addAction(QString("Add"), this),
deleteSignalMapper(this), editSignalMapper(this) {
}

MainWindow::TaskPanelManager::~TaskPanelManager() {
}

void MainWindow::TaskPanelManager::setup() {
	QStringList columnHeaders({
		TASK_COLUMN_1,
		TASK_COLUMN_2,
		TASK_COLUMN_3,
		TASK_COLUMN_4,
		TASK_COLUMN_5,
		TASK_COLUMN_6
	});
	QTreeWidget* taskTreePanel = parentGUI->ui.taskTreePanel;
	connect(taskTreePanel, SIGNAL(itemSelectionChanged()),
		parentGUI, SLOT(taskSelected()));

	connect(taskTreePanel, SIGNAL(customContextMenuRequested(const QPoint &)),
		this, SLOT(contextMenu(const QPoint &)));
	taskTreePanel->setColumnCount(columnHeaders.size());
	taskTreePanel->setHeaderItem(createItem(columnHeaders).release());
	// TODO(angathorion): remove magic constants.
	QHeaderView* header = taskTreePanel->header();
	header->setStretchLastSection(true);

	for (int i = 1; i < columnHeaders.size(); ++i) {
		if (i == 2) {
			continue;
		}
		header->resizeSection(i, header->defaultSectionSize());
	}

	taskTreePanel->header()->setMinimumSectionSize(75);
	taskTreePanel->setColumnHidden(0, true);
	taskTreePanel->setColumnHidden(5, true);
}

void MainWindow::TaskPanelManager::addTask(const Task& task) {
	std::unique_ptr<QTreeWidgetItem> item(createItem(task));
	parentGUI->ui.taskTreePanel->addTopLevelItem(item.release());
	updateRowNumbers();
}

void MainWindow::TaskPanelManager::addSubtask(QTreeWidgetItem* parent,
	const QStringList& rowStrings) {
	std::unique_ptr<QTreeWidgetItem> item(createItem(rowStrings));
	parent->addChild(item.release());
	updateRowNumbers();
}

void MainWindow::TaskPanelManager::editTask(const Task& task) {
	QList<QTreeWidgetItem*> items = findItems(task.getID());
	assert(items.length() == 1);
	QTreeWidgetItem item = *items.at(0);
	QStringList wstr = taskToStrVec(task);
	*items.at(0) = *createItem(wstr);
	updateRowNumbers();
}

void MainWindow::TaskPanelManager::deleteTask(Task::ID taskID) {
	QList<QTreeWidgetItem*> items = findItems(taskID);
	assert(items.length() == 1);
	deleteTask(items.at(0));
	updateRowNumbers();
}

void MainWindow::TaskPanelManager::deleteTask(QTreeWidgetItem* task) {
	delete task;
}

std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem(
	const Task& task) {
	return createItem(taskToStrVec(task));
}

std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem(
	const QStringList& rowStrings) {
	return std::make_unique<QTreeWidgetItem>(rowStrings);
}

QList<QTreeWidgetItem*> MainWindow::TaskPanelManager::findItems(
	You::Controller::Task::ID taskID) const {
	return parentGUI->ui.taskTreePanel->findItems(
		boost::lexical_cast<QString>(taskID), 0);
}

QStringList MainWindow::TaskPanelManager::taskToStrVec(
	const You::Controller::Task& task) {
	QStringList result;

	// Insert id
	result.push_back(boost::lexical_cast<QString>(task.getID()));

	// Insert dummy count
	result.push_back("0");

	// Insert description
	result.push_back(QString::fromStdWString(task.getDescription()));

	// Insert deadline
	std::wstringstream wss;
	if (task.getDeadline() == Task::NEVER) {
		wss << L"Never";
	} else if (isPastDue(task.getDeadline())) {
		wss << L"Overdue (" << task.getDeadline() << L")";
	} else if (isDueAfter(task.getDeadline(), 0)) {
		wss << L"Today (" << task.getDeadline() << L")";
	} else if (isDueAfter(task.getDeadline(), 1)) {
		wss << L"Tomorrow (" << task.getDeadline() << L")";
	} else if (isDueAfter(task.getDeadline(), 2)) {
		wss << L"In two days (" << task.getDeadline() << L")";
	} else if (isDueWithin(task.getDeadline(), 7)) {
		wss << L"Within one week (" << task.getDeadline() << L")";
	} else if (isDueWithin(task.getDeadline(), 14)) {
		wss << L"Within two weeks (" << task.getDeadline() << L")";
	} else if (isDueWithin(task.getDeadline(), 21)) {
		wss << L"Within three weeks (" << task.getDeadline() << L")";
	} else if (isDueWithin(task.getDeadline(), 28)) {
		wss << L"Within one month (" << task.getDeadline() << L")";
	} else {
		wss << L"More than a month away (" << task.getDeadline() << L")";
	}
	result.push_back(boost::lexical_cast<QString>(wss.str()));

	// Insert priority
	QString priority[] { "High", "Normal" };

	switch (task.getPriority()) {
	case Task::Priority::HIGH:
		result.push_back(priority[0]);
	case Task::Priority::NORMAL:
		result.push_back(priority[1]);
	}

	// Insert dependencies
	std::ostringstream ss;
	if (task.getDependencies().size() != 0) {
		Task::Dependencies dependencies = task.getDependencies();
		std::copy(dependencies.begin(), dependencies.end() - 1,
			std::ostream_iterator<int64_t>(ss, ", "));
		ss << dependencies.back();
		result.push_back(QString::fromStdString(ss.str()));
	} else {
		result.push_back("None");
	}

	return result;
}

void MainWindow::TaskPanelManager::updateRowNumbers() {
	int rowNum = 0;
	for (QTreeWidgetItemIterator it(parentGUI->ui.taskTreePanel); *it; ++it) {
		(*it)->setData(1, Qt::DisplayRole, rowNum++);
	}
}

bool MainWindow::TaskPanelManager::isPastDue(Task::Time deadline) {
	Task::Time now = boost::posix_time::second_clock::local_time();

	if (deadline < now) {
		return true;
	} else {
		return false;
	}
}

bool MainWindow::TaskPanelManager::isDueAfter(
		Task::Time deadline, int daysLeft) {
	Date by = Date(deadline.date());
	Date today = boost::gregorian::day_clock::local_day();
	if (by.modjulian_day() - today.modjulian_day() == daysLeft) {
		return true;
	} else {
		return false;
	}
}

bool MainWindow::TaskPanelManager::isDueWithin(
	Task::Time deadline, int daysLeft) {
	Date by = Date(deadline.date());
	Date today = boost::gregorian::day_clock::local_day();
	if (by.julian_day() - today.julian_day() < daysLeft) {
		return true;
	} else {
		return false;
	}
}

void MainWindow::TaskPanelManager::contextMenu(const QPoint &pos) {
	/// Try to get the item at the position of the context menu
	QTreeWidgetItem *item = parentGUI->ui.taskTreePanel->itemAt(pos);
	itemContextMenu.reset(new QMenu(parentGUI->ui.taskTreePanel));

	/// Adds the Add Task action. This is always present in the menu.
	itemContextMenu->addAction(&addAction);
	connect(&addAction, SIGNAL(triggered()), parentGUI, SLOT(contextAddTask()));

	/// Adds the Edit Task and Delete Task actions if an item is selected.
	/// QSignalMapper is necessary because arguments need to be passed
	/// as part of the signal.
	if (item) {
		deleteSignalMapper.setMapping(&deleteAction, item->text(1).toInt());
		connect(&deleteAction, SIGNAL(triggered()),
			&deleteSignalMapper, SLOT(map()));
		itemContextMenu->addAction(&deleteAction);
		connect(&deleteSignalMapper, SIGNAL(mapped(int)),
			parentGUI, SLOT(contextDeleteTask(int)));

		editSignalMapper.setMapping(&editAction, item->text(1).toInt());
		connect(&editAction, SIGNAL(triggered()),
			&editSignalMapper, SLOT(map()));
		itemContextMenu->addAction(&editAction);
		connect(&editSignalMapper, SIGNAL(mapped(int)),
			parentGUI, SLOT(contextEditTask(int)));
	}

	itemContextMenu->popup(
		parentGUI->ui.taskTreePanel->viewport()->mapToGlobal(pos));
}

}  // namespace GUI
}  // namespace You
<|endoftext|>


<commit_before>#include "ZeroCopyNetworkReaderStream.h"
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>

ZeroCopyNetworkReaderStream::ZeroCopyNetworkReaderStream(
  int fd,
  protobuf::uint32 totalMessageSize,
  protobuf::uint8* pDataBuffer,
  protobuf::uint32 bufferSize) :
  m_fd(fd),
  m_remainingMessageSizeBytes(totalMessageSize),
  m_pDataBuffer(pDataBuffer),
  m_bufferSize(bufferSize),
  m_numBytesLastRead(0),
  m_backupPos(m_numBytesLastRead),
  m_byteCount(0)
{
}

//--------------------------------------------------------------------------------------------------

ZeroCopyNetworkReaderStream::~ZeroCopyNetworkReaderStream()
{
}

//--------------------------------------------------------------------------------------------------

bool ZeroCopyNetworkReaderStream::Next(const void** data, int* size) {
  if (data == 0 || size == 0) {
    return false;
  }

  *size = 0;

  if (m_remainingMessageSizeBytes == 0) {
    return false;
  }

  if (m_backupPos < m_numBytesLastRead) {
    // A BackUp() call has been issued
    *size = m_numBytesLastRead - m_backupPos;
    *data = &m_pDataBuffer[m_backupPos];
    // We've returned everything from the backup position to the end of the last read
    m_backupPos = m_numBytesLastRead;
    return true;
  }

  const protobuf::uint32 numBytesToRead =
    std::min(m_remainingMessageSizeBytes, m_bufferSize);

  ssize_t bytesRead = -1;
  do {
    bytesRead = recv(m_fd, m_pDataBuffer, numBytesToRead, MSG_WAITALL);
  } while (bytesRead == -1 && errno == EINTR);
  if (bytesRead == 0) {
    //pan::log(pan::notice, "Peer has performed an orderly shutdown on fd: ", pan::i(m_fd),
    //  " during normal receive");
    return false;
  }
  if (bytesRead == -1) {
    //pan::log(pan::error, "Failed to read message, numBytesToRead: ", pan::i(numBytesToRead),
    //  ", m_remainingMessageSizeBytes: ", pan::i(m_remainingMessageSizeBytes), ", m_fd: ",
      pan::i(m_fd), ". ", ErrnoInserter());
    return false;
  }
  // TODO: for non-blocking I/O sockets the following test isn't correct
  if (bytesRead != numBytesToRead) {
    //pan::log(pan::error, "Partially read message, bytesRead: ", pan::i(bytesRead),
    //  ", numBytesToRead: ", pan::i(numBytesToRead), ", m_remainingMessageSizeBytes: ",
      pan::i(m_remainingMessageSizeBytes), ". ", ErrnoInserter());
    return false;
  }

  *data = m_pDataBuffer;
  *size = bytesRead;
  m_numBytesLastRead = m_backupPos = bytesRead;
  m_remainingMessageSizeBytes -= bytesRead;
  m_byteCount += bytesRead;

  return true;
}

//--------------------------------------------------------------------------------------------------

void ZeroCopyNetworkReaderStream::BackUp(int count) {
  m_backupPos -= count;
}

//--------------------------------------------------------------------------------------------------

bool ZeroCopyNetworkReaderStream::Skip(int count) {
  if (m_backupPos < m_numBytesLastRead) {
    const protobuf::uint32 numBytesToSkipInBackup =
      std::min(m_numBytesLastRead - m_backupPos, (protobuf::uint32) count);
    m_backupPos += numBytesToSkipInBackup;
    count -= numBytesToSkipInBackup;
  }

  if (count == 0) {
    return (m_remainingMessageSizeBytes > 0);
  }

  // Read the remaining <count> bytes from the stream and dump them
  // TODO: can we simply seek() instead of actually reading the data?
  char dumpBuf[128];
  protobuf::uint32 bytesToDump = std::min(m_remainingMessageSizeBytes, (protobuf::uint32) count);
  while (bytesToDump > 0) {
    protobuf::uint32 bytesToDumpThisIteration =
      std::min(bytesToDump, (protobuf::uint32) sizeof(dumpBuf));
    ssize_t bytesRead = -1;
    do {
      bytesRead = recv(m_fd, dumpBuf, bytesToDumpThisIteration, MSG_WAITALL);
    } while (bytesRead == -1 && errno == EINTR);
    if (bytesRead == 0) {
      //pan::log(pan::notice, "Peer has performed an orderly shutdown on m_fd ", pan::i(m_fd),
      //  " during data dump");
      return false;
    }
    if (bytesRead == -1) {
      //pan::log(pan::error, "Failed to read data to dump, bytesToDumpThisIteration: ",
      //  pan::i(bytesToDumpThisIteration), ". ", ErrnoInserter());
      return false;
    }

    // TODO: proper error handling of read()
    m_remainingMessageSizeBytes -= bytesToDumpThisIteration;
    m_byteCount += bytesToDumpThisIteration;
  }

  return (m_remainingMessageSizeBytes > 0);
}

//--------------------------------------------------------------------------------------------------

protobuf::int64 ZeroCopyNetworkReaderStream::ByteCount() const {
  return m_byteCount;
}
<commit_msg>Comment out more logging code (oops)<commit_after>#include "ZeroCopyNetworkReaderStream.h"
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>

ZeroCopyNetworkReaderStream::ZeroCopyNetworkReaderStream(
  int fd,
  protobuf::uint32 totalMessageSize,
  protobuf::uint8* pDataBuffer,
  protobuf::uint32 bufferSize) :
  m_fd(fd),
  m_remainingMessageSizeBytes(totalMessageSize),
  m_pDataBuffer(pDataBuffer),
  m_bufferSize(bufferSize),
  m_numBytesLastRead(0),
  m_backupPos(m_numBytesLastRead),
  m_byteCount(0)
{
}

//--------------------------------------------------------------------------------------------------

ZeroCopyNetworkReaderStream::~ZeroCopyNetworkReaderStream()
{
}

//--------------------------------------------------------------------------------------------------

bool ZeroCopyNetworkReaderStream::Next(const void** data, int* size) {
  if (data == 0 || size == 0) {
    return false;
  }

  *size = 0;

  if (m_remainingMessageSizeBytes == 0) {
    return false;
  }

  if (m_backupPos < m_numBytesLastRead) {
    // A BackUp() call has been issued
    *size = m_numBytesLastRead - m_backupPos;
    *data = &m_pDataBuffer[m_backupPos];
    // We've returned everything from the backup position to the end of the last read
    m_backupPos = m_numBytesLastRead;
    return true;
  }

  const protobuf::uint32 numBytesToRead =
    std::min(m_remainingMessageSizeBytes, m_bufferSize);

  ssize_t bytesRead = -1;
  do {
    bytesRead = recv(m_fd, m_pDataBuffer, numBytesToRead, MSG_WAITALL);
  } while (bytesRead == -1 && errno == EINTR);
  if (bytesRead == 0) {
    //pan::log(pan::notice, "Peer has performed an orderly shutdown on fd: ", pan::i(m_fd),
    //  " during normal receive");
    return false;
  }
  if (bytesRead == -1) {
    //pan::log(pan::error, "Failed to read message, numBytesToRead: ", pan::i(numBytesToRead),
    //  ", m_remainingMessageSizeBytes: ", pan::i(m_remainingMessageSizeBytes), ", m_fd: ",
    //  pan::i(m_fd), ". ", ErrnoInserter());
    return false;
  }
  // TODO: for non-blocking I/O sockets the following test isn't correct
  if (bytesRead != numBytesToRead) {
    //pan::log(pan::error, "Partially read message, bytesRead: ", pan::i(bytesRead),
    //  ", numBytesToRead: ", pan::i(numBytesToRead), ", m_remainingMessageSizeBytes: ",
    //  pan::i(m_remainingMessageSizeBytes), ". ", ErrnoInserter());
    return false;
  }

  *data = m_pDataBuffer;
  *size = bytesRead;
  m_numBytesLastRead = m_backupPos = bytesRead;
  m_remainingMessageSizeBytes -= bytesRead;
  m_byteCount += bytesRead;

  return true;
}

//--------------------------------------------------------------------------------------------------

void ZeroCopyNetworkReaderStream::BackUp(int count) {
  m_backupPos -= count;
}

//--------------------------------------------------------------------------------------------------

bool ZeroCopyNetworkReaderStream::Skip(int count) {
  if (m_backupPos < m_numBytesLastRead) {
    const protobuf::uint32 numBytesToSkipInBackup =
      std::min(m_numBytesLastRead - m_backupPos, (protobuf::uint32) count);
    m_backupPos += numBytesToSkipInBackup;
    count -= numBytesToSkipInBackup;
  }

  if (count == 0) {
    return (m_remainingMessageSizeBytes > 0);
  }

  // Read the remaining <count> bytes from the stream and dump them
  // TODO: can we simply seek() instead of actually reading the data?
  char dumpBuf[128];
  protobuf::uint32 bytesToDump = std::min(m_remainingMessageSizeBytes, (protobuf::uint32) count);
  while (bytesToDump > 0) {
    protobuf::uint32 bytesToDumpThisIteration =
      std::min(bytesToDump, (protobuf::uint32) sizeof(dumpBuf));
    ssize_t bytesRead = -1;
    do {
      bytesRead = recv(m_fd, dumpBuf, bytesToDumpThisIteration, MSG_WAITALL);
    } while (bytesRead == -1 && errno == EINTR);
    if (bytesRead == 0) {
      //pan::log(pan::notice, "Peer has performed an orderly shutdown on m_fd ", pan::i(m_fd),
      //  " during data dump");
      return false;
    }
    if (bytesRead == -1) {
      //pan::log(pan::error, "Failed to read data to dump, bytesToDumpThisIteration: ",
      //  pan::i(bytesToDumpThisIteration), ". ", ErrnoInserter());
      return false;
    }

    // TODO: proper error handling of read()
    m_remainingMessageSizeBytes -= bytesToDumpThisIteration;
    m_byteCount += bytesToDumpThisIteration;
  }

  return (m_remainingMessageSizeBytes > 0);
}

//--------------------------------------------------------------------------------------------------

protobuf::int64 ZeroCopyNetworkReaderStream::ByteCount() const {
  return m_byteCount;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 *
 * XPLC - Cross-Platform Lightweight Components
 * Copyright (C) 2000, Pierre Phaneuf
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public License
 * as published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 */

#include <stdlib.h>
#include <xplc/xplc.h>
#include "servmgr.h"

IServiceManager* XPLC::getServiceManager() {
  return new ServiceManager;
}

<commit_msg>Service manager was not a singleton: fixed.<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 *
 * XPLC - Cross-Platform Lightweight Components
 * Copyright (C) 2000, Pierre Phaneuf
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public License
 * as published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 */

#include <stdlib.h>
#include <xplc/xplc.h>
#include "servmgr.h"

static ServiceManager* servmgr;

IServiceManager* XPLC::getServiceManager() {
  if(!servmgr)
    servmgr = new ServiceManager;

  if(servmgr)
    servmgr->addRef();

  return servmgr;
}

<|endoftext|>


<commit_before><commit_msg>Enumerating Kelly references.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/icon_loader.h"

#include "base/message_loop.h"
#include "base/mime_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "third_party/skia/include/core/SkBitmap.h"

IconLoader::IconLoader(const IconGroupID& group, IconSize size,
                       Delegate* delegate)
    : group_(group),
      icon_size_(size),
      bitmap_(NULL),
      delegate_(delegate) {
}

IconLoader::~IconLoader() {
  delete bitmap_;
}

void IconLoader::Start() {
  target_message_loop_ = MessageLoop::current();

#if defined(OS_LINUX)
  // This call must happen on the UI thread before we can start loading icons.
  mime_util::DetectGtkTheme();
#endif

  g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE,
      NewRunnableMethod(this, &IconLoader::ReadIcon));
}

void IconLoader::NotifyDelegate() {
  if (delegate_->OnBitmapLoaded(this, bitmap_))
    bitmap_ = NULL;
}
<commit_msg>Coverity: Initialize target_message_loop_ in the constructor.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/icon_loader.h"

#include "base/message_loop.h"
#include "base/mime_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "third_party/skia/include/core/SkBitmap.h"

IconLoader::IconLoader(const IconGroupID& group, IconSize size,
                       Delegate* delegate)
    : target_message_loop_(NULL),
      group_(group),
      icon_size_(size),
      bitmap_(NULL),
      delegate_(delegate) {
}

IconLoader::~IconLoader() {
  delete bitmap_;
}

void IconLoader::Start() {
  target_message_loop_ = MessageLoop::current();

#if defined(OS_LINUX)
  // This call must happen on the UI thread before we can start loading icons.
  mime_util::DetectGtkTheme();
#endif

  g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE,
      NewRunnableMethod(this, &IconLoader::ReadIcon));
}

void IconLoader::NotifyDelegate() {
  if (delegate_->OnBitmapLoaded(this, bitmap_))
    bitmap_ = NULL;
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/chrome_paths.h"

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"

#if defined(OS_MACOSX)
#include "base/mac_util.h"
#endif

namespace {

// File name of the internal Flash plugin on different platforms.
const FilePath::CharType kInternalFlashPluginFileName[] =
#if defined(OS_MACOSX)
    FILE_PATH_LITERAL("Flash Player Plugin for Chrome.plugin");
#elif defined(OS_WIN)
    FILE_PATH_LITERAL("gcswf32.dll");
#else  // OS_LINUX, etc.
    FILE_PATH_LITERAL("libgcflashplayer.so");
#endif

}  // namespace

namespace chrome {

// Gets the path for internal (or bundled) plugins.
bool GetInternalPluginsDirectory(FilePath* result) {
#if defined(OS_MACOSX)
  // If called from Chrome, get internal plugins from the versioned directory.
  if (mac_util::AmIBundled()) {
    *result = chrome::GetVersionedDirectory();
    DCHECK(!result->empty());
    return true;
  }
  // In tests, just look in the module directory (below).
#endif

  // The rest of the world expects plugins in the module directory.
  return PathService::Get(base::DIR_MODULE, result);
}

bool GetGearsPluginPathFromCommandLine(FilePath* path) {
#ifndef NDEBUG
  // for debugging, support a cmd line based override
  FilePath plugin_path =
      CommandLine::ForCurrentProcess()->GetSwitchValuePath(
          switches::kGearsPluginPathOverride);
  *path = plugin_path;
  return !plugin_path.empty();
#else
  return false;
#endif
}

bool PathProvider(int key, FilePath* result) {
  // Some keys are just aliases...
  switch (key) {
    case chrome::DIR_APP:
      return PathService::Get(base::DIR_MODULE, result);
    case chrome::DIR_LOGS:
#ifdef NDEBUG
      // Release builds write to the data dir
      return PathService::Get(chrome::DIR_USER_DATA, result);
#else
      // Debug builds write next to the binary (in the build tree)
#if defined(OS_MACOSX)
      if (!PathService::Get(base::DIR_EXE, result))
        return false;
      if (mac_util::AmIBundled()) {
        // If we're called from chrome, dump it beside the app (outside the
        // app bundle), if we're called from a unittest, we'll already
        // outside the bundle so use the exe dir.
        // exe_dir gave us .../Chromium.app/Contents/MacOS/Chromium.
        *result = result->DirName();
        *result = result->DirName();
        *result = result->DirName();
      }
      return true;
#else
      return PathService::Get(base::DIR_EXE, result);
#endif  // defined(OS_MACOSX)
#endif  // NDEBUG
    case chrome::FILE_RESOURCE_MODULE:
      return PathService::Get(base::FILE_MODULE, result);
  }

  // Assume that we will not need to create the directory if it does not exist.
  // This flag can be set to true for the cases where we want to create it.
  bool create_dir = false;

  FilePath cur;
  switch (key) {
    case chrome::DIR_USER_DATA:
      if (!GetDefaultUserDataDirectory(&cur)) {
        NOTREACHED();
        return false;
      }
      create_dir = true;
      break;
    case chrome::DIR_USER_DOCUMENTS:
      if (!GetUserDocumentsDirectory(&cur))
        return false;
      create_dir = true;
      break;
    case chrome::DIR_DEFAULT_DOWNLOADS_SAFE:
#if defined(OS_WIN)
      if (!GetUserDownloadsDirectorySafe(&cur))
        return false;
      break;
#else
      // Fall through for all other platforms.
#endif
    case chrome::DIR_DEFAULT_DOWNLOADS:
      if (!GetUserDownloadsDirectory(&cur))
        return false;
      // Do not create the download directory here, we have done it twice now
      // and annoyed a lot of users.
      break;
    case chrome::DIR_CRASH_DUMPS:
      // The crash reports are always stored relative to the default user data
      // directory.  This avoids the problem of having to re-initialize the
      // exception handler after parsing command line options, which may
      // override the location of the app's profile directory.
      if (!GetDefaultUserDataDirectory(&cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("Crash Reports"));
      create_dir = true;
      break;
    case chrome::DIR_USER_DESKTOP:
      if (!GetUserDesktop(&cur))
        return false;
      break;
    case chrome::DIR_RESOURCES:
#if defined(OS_MACOSX)
      cur = mac_util::MainAppBundlePath();
      cur = cur.Append(FILE_PATH_LITERAL("Resources"));
#else
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("resources"));
#endif
      break;
    case chrome::DIR_SHARED_RESOURCES:
      if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("shared"));
      break;
    case chrome::DIR_BOOKMARK_MANAGER:
      if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("bookmark_manager"));
      break;
    case chrome::DIR_INSPECTOR:
      if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("inspector"));
      break;
    case chrome::DIR_NET_INTERNALS:
      if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("net_internals"));
      break;
    case chrome::DIR_APP_DICTIONARIES:
#if defined(OS_LINUX) || defined(OS_MACOSX)
      // We can't write into the EXE dir on Linux, so keep dictionaries
      // alongside the safe browsing database in the user data dir.
      // And we don't want to write into the bundle on the Mac, so push
      // it to the user data dir there also.
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
#else
      if (!PathService::Get(base::DIR_EXE, &cur))
        return false;
#endif
      cur = cur.Append(FILE_PATH_LITERAL("Dictionaries"));
      create_dir = true;
      break;
    case chrome::DIR_USER_DATA_TEMP:
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("Temp"));
      create_dir = true;
      break;
    case chrome::DIR_INTERNAL_PLUGINS:
      if (!GetInternalPluginsDirectory(&cur))
        return false;
      break;
    case chrome::FILE_LOCAL_STATE:
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
      cur = cur.Append(chrome::kLocalStateFilename);
      break;
    case chrome::FILE_RECORDED_SCRIPT:
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("script.log"));
      break;
    case chrome::FILE_GEARS_PLUGIN:
      if (!GetGearsPluginPathFromCommandLine(&cur)) {
#if defined(OS_WIN)
        // Search for gears.dll alongside chrome.dll first.  This new model
        // allows us to package gears.dll with the Chrome installer and update
        // it while Chrome is running.
        if (!GetInternalPluginsDirectory(&cur))
          return false;
        cur = cur.Append(FILE_PATH_LITERAL("gears.dll"));

        if (!file_util::PathExists(cur)) {
          if (!PathService::Get(base::DIR_EXE, &cur))
            return false;
          cur = cur.Append(FILE_PATH_LITERAL("plugins"));
          cur = cur.Append(FILE_PATH_LITERAL("gears"));
          cur = cur.Append(FILE_PATH_LITERAL("gears.dll"));
        }
#else
        // No gears.dll on non-Windows systems.
        return false;
#endif
      }
      break;
    case chrome::FILE_FLASH_PLUGIN:
      if (!GetInternalPluginsDirectory(&cur))
        return false;
      cur = cur.Append(kInternalFlashPluginFileName);
      if (!file_util::PathExists(cur))
        return false;
      break;
    case chrome::FILE_PDF_PLUGIN:
      if (!PathService::Get(base::DIR_MODULE, &cur))
        return false;
#if defined(OS_WIN)
      cur = cur.Append(FILE_PATH_LITERAL("pdf.dll"));
#elif defined(OS_MACOSX)
      NOTIMPLEMENTED();
      return false;
#else  // Linux and Chrome OS
      cur = cur.Append(FILE_PATH_LITERAL("libpdf.so"));
#endif
      if (!file_util::PathExists(cur))
        return false;
      break;
#if defined(OS_CHROMEOS)
    case chrome::FILE_CHROMEOS_API:
      if (!PathService::Get(base::DIR_MODULE, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("chromeos"));
      cur = cur.Append(FILE_PATH_LITERAL("libcros.so"));
      break;
#endif
    // The following are only valid in the development environment, and
    // will fail if executed from an installed executable (because the
    // generated path won't exist).
    case chrome::DIR_TEST_DATA:
      if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("chrome"));
      cur = cur.Append(FILE_PATH_LITERAL("test"));
      cur = cur.Append(FILE_PATH_LITERAL("data"));
      if (!file_util::PathExists(cur))  // we don't want to create this
        return false;
      break;
    case chrome::DIR_TEST_TOOLS:
      if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("chrome"));
      cur = cur.Append(FILE_PATH_LITERAL("tools"));
      cur = cur.Append(FILE_PATH_LITERAL("test"));
      if (!file_util::PathExists(cur))  // we don't want to create this
        return false;
      break;
    default:
      return false;
  }

  if (create_dir && !file_util::PathExists(cur) &&
      !file_util::CreateDirectory(cur))
    return false;

  *result = cur;
  return true;
}

// This cannot be done as a static initializer sadly since Visual Studio will
// eliminate this object file if there is no direct entry point into it.
void RegisterPathProvider() {
  PathService::RegisterProvider(PathProvider, PATH_START, PATH_END);
}

}  // namespace chrome
<commit_msg>[Mac] stop the output that is slowing down all the tests that seem to walk this code path.<commit_after>// Copyright (c) 2006-2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/chrome_paths.h"

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"

#if defined(OS_MACOSX)
#include "base/mac_util.h"
#endif

namespace {

// File name of the internal Flash plugin on different platforms.
const FilePath::CharType kInternalFlashPluginFileName[] =
#if defined(OS_MACOSX)
    FILE_PATH_LITERAL("Flash Player Plugin for Chrome.plugin");
#elif defined(OS_WIN)
    FILE_PATH_LITERAL("gcswf32.dll");
#else  // OS_LINUX, etc.
    FILE_PATH_LITERAL("libgcflashplayer.so");
#endif

}  // namespace

namespace chrome {

// Gets the path for internal (or bundled) plugins.
bool GetInternalPluginsDirectory(FilePath* result) {
#if defined(OS_MACOSX)
  // If called from Chrome, get internal plugins from the versioned directory.
  if (mac_util::AmIBundled()) {
    *result = chrome::GetVersionedDirectory();
    DCHECK(!result->empty());
    return true;
  }
  // In tests, just look in the module directory (below).
#endif

  // The rest of the world expects plugins in the module directory.
  return PathService::Get(base::DIR_MODULE, result);
}

bool GetGearsPluginPathFromCommandLine(FilePath* path) {
#ifndef NDEBUG
  // for debugging, support a cmd line based override
  FilePath plugin_path =
      CommandLine::ForCurrentProcess()->GetSwitchValuePath(
          switches::kGearsPluginPathOverride);
  *path = plugin_path;
  return !plugin_path.empty();
#else
  return false;
#endif
}

bool PathProvider(int key, FilePath* result) {
  // Some keys are just aliases...
  switch (key) {
    case chrome::DIR_APP:
      return PathService::Get(base::DIR_MODULE, result);
    case chrome::DIR_LOGS:
#ifdef NDEBUG
      // Release builds write to the data dir
      return PathService::Get(chrome::DIR_USER_DATA, result);
#else
      // Debug builds write next to the binary (in the build tree)
#if defined(OS_MACOSX)
      if (!PathService::Get(base::DIR_EXE, result))
        return false;
      if (mac_util::AmIBundled()) {
        // If we're called from chrome, dump it beside the app (outside the
        // app bundle), if we're called from a unittest, we'll already
        // outside the bundle so use the exe dir.
        // exe_dir gave us .../Chromium.app/Contents/MacOS/Chromium.
        *result = result->DirName();
        *result = result->DirName();
        *result = result->DirName();
      }
      return true;
#else
      return PathService::Get(base::DIR_EXE, result);
#endif  // defined(OS_MACOSX)
#endif  // NDEBUG
    case chrome::FILE_RESOURCE_MODULE:
      return PathService::Get(base::FILE_MODULE, result);
  }

  // Assume that we will not need to create the directory if it does not exist.
  // This flag can be set to true for the cases where we want to create it.
  bool create_dir = false;

  FilePath cur;
  switch (key) {
    case chrome::DIR_USER_DATA:
      if (!GetDefaultUserDataDirectory(&cur)) {
        NOTREACHED();
        return false;
      }
      create_dir = true;
      break;
    case chrome::DIR_USER_DOCUMENTS:
      if (!GetUserDocumentsDirectory(&cur))
        return false;
      create_dir = true;
      break;
    case chrome::DIR_DEFAULT_DOWNLOADS_SAFE:
#if defined(OS_WIN)
      if (!GetUserDownloadsDirectorySafe(&cur))
        return false;
      break;
#else
      // Fall through for all other platforms.
#endif
    case chrome::DIR_DEFAULT_DOWNLOADS:
      if (!GetUserDownloadsDirectory(&cur))
        return false;
      // Do not create the download directory here, we have done it twice now
      // and annoyed a lot of users.
      break;
    case chrome::DIR_CRASH_DUMPS:
      // The crash reports are always stored relative to the default user data
      // directory.  This avoids the problem of having to re-initialize the
      // exception handler after parsing command line options, which may
      // override the location of the app's profile directory.
      if (!GetDefaultUserDataDirectory(&cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("Crash Reports"));
      create_dir = true;
      break;
    case chrome::DIR_USER_DESKTOP:
      if (!GetUserDesktop(&cur))
        return false;
      break;
    case chrome::DIR_RESOURCES:
#if defined(OS_MACOSX)
      cur = mac_util::MainAppBundlePath();
      cur = cur.Append(FILE_PATH_LITERAL("Resources"));
#else
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("resources"));
#endif
      break;
    case chrome::DIR_SHARED_RESOURCES:
      if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("shared"));
      break;
    case chrome::DIR_BOOKMARK_MANAGER:
      if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("bookmark_manager"));
      break;
    case chrome::DIR_INSPECTOR:
      if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("inspector"));
      break;
    case chrome::DIR_NET_INTERNALS:
      if (!PathService::Get(chrome::DIR_RESOURCES, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("net_internals"));
      break;
    case chrome::DIR_APP_DICTIONARIES:
#if defined(OS_LINUX) || defined(OS_MACOSX)
      // We can't write into the EXE dir on Linux, so keep dictionaries
      // alongside the safe browsing database in the user data dir.
      // And we don't want to write into the bundle on the Mac, so push
      // it to the user data dir there also.
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
#else
      if (!PathService::Get(base::DIR_EXE, &cur))
        return false;
#endif
      cur = cur.Append(FILE_PATH_LITERAL("Dictionaries"));
      create_dir = true;
      break;
    case chrome::DIR_USER_DATA_TEMP:
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("Temp"));
      create_dir = true;
      break;
    case chrome::DIR_INTERNAL_PLUGINS:
      if (!GetInternalPluginsDirectory(&cur))
        return false;
      break;
    case chrome::FILE_LOCAL_STATE:
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
      cur = cur.Append(chrome::kLocalStateFilename);
      break;
    case chrome::FILE_RECORDED_SCRIPT:
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("script.log"));
      break;
    case chrome::FILE_GEARS_PLUGIN:
      if (!GetGearsPluginPathFromCommandLine(&cur)) {
#if defined(OS_WIN)
        // Search for gears.dll alongside chrome.dll first.  This new model
        // allows us to package gears.dll with the Chrome installer and update
        // it while Chrome is running.
        if (!GetInternalPluginsDirectory(&cur))
          return false;
        cur = cur.Append(FILE_PATH_LITERAL("gears.dll"));

        if (!file_util::PathExists(cur)) {
          if (!PathService::Get(base::DIR_EXE, &cur))
            return false;
          cur = cur.Append(FILE_PATH_LITERAL("plugins"));
          cur = cur.Append(FILE_PATH_LITERAL("gears"));
          cur = cur.Append(FILE_PATH_LITERAL("gears.dll"));
        }
#else
        // No gears.dll on non-Windows systems.
        return false;
#endif
      }
      break;
    case chrome::FILE_FLASH_PLUGIN:
      if (!GetInternalPluginsDirectory(&cur))
        return false;
      cur = cur.Append(kInternalFlashPluginFileName);
      if (!file_util::PathExists(cur))
        return false;
      break;
    case chrome::FILE_PDF_PLUGIN:
      if (!PathService::Get(base::DIR_MODULE, &cur))
        return false;
#if defined(OS_WIN)
      cur = cur.Append(FILE_PATH_LITERAL("pdf.dll"));
#elif defined(OS_MACOSX)
      // http://crbug.com/44900
      return false;
#else  // Linux and Chrome OS
      cur = cur.Append(FILE_PATH_LITERAL("libpdf.so"));
#endif
      if (!file_util::PathExists(cur))
        return false;
      break;
#if defined(OS_CHROMEOS)
    case chrome::FILE_CHROMEOS_API:
      if (!PathService::Get(base::DIR_MODULE, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("chromeos"));
      cur = cur.Append(FILE_PATH_LITERAL("libcros.so"));
      break;
#endif
    // The following are only valid in the development environment, and
    // will fail if executed from an installed executable (because the
    // generated path won't exist).
    case chrome::DIR_TEST_DATA:
      if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("chrome"));
      cur = cur.Append(FILE_PATH_LITERAL("test"));
      cur = cur.Append(FILE_PATH_LITERAL("data"));
      if (!file_util::PathExists(cur))  // we don't want to create this
        return false;
      break;
    case chrome::DIR_TEST_TOOLS:
      if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))
        return false;
      cur = cur.Append(FILE_PATH_LITERAL("chrome"));
      cur = cur.Append(FILE_PATH_LITERAL("tools"));
      cur = cur.Append(FILE_PATH_LITERAL("test"));
      if (!file_util::PathExists(cur))  // we don't want to create this
        return false;
      break;
    default:
      return false;
  }

  if (create_dir && !file_util::PathExists(cur) &&
      !file_util::CreateDirectory(cur))
    return false;

  *result = cur;
  return true;
}

// This cannot be done as a static initializer sadly since Visual Studio will
// eliminate this object file if there is no direct entry point into it.
void RegisterPathProvider() {
  PathService::RegisterProvider(PathProvider, PATH_START, PATH_END);
}

}  // namespace chrome
<|endoftext|>


<commit_before>// UjoImro, 2013
// Experimental code for the CARP Project
// Copyright (c) RealEyes, 2013
// This version tests the responseMap calculation with input dumps

#include <chrono>
#include <string>
#include <stdlib.h>
#include <opencv2/core/core.hpp>
#include <boost/preprocessor.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/archive/binary_iarchive.hpp>

#include "cast.h"
#include "mlp.hpp"
#include "mlp_impl.h"

extern int EF_ALIGNMENT = 0;
extern int EF_PROTECT_BELOW = 0;
extern int EF_PROTECT_FREE = 0;
extern int EF_ALLOW_MALLOC_0 = 1;
extern int EF_FILL = 1922;

namespace { struct hack_t; }
MatChar  convertCVToMatChar ( const cv::Mat_<uint8_t> & input );
mlp *    convertHackToMlp ( const hack_t & hack );
void     freeClassifiers( mlp * classifiers[], int size );
MatChar  convertCVToMatChar ( const cv::Mat_<uint8_t> & input );
MatFloat convertCVToMatFloat (  const cv::Mat_<double> & input );
cv::Mat_<double> convertMatFloatToCV( MatFloat input );
void     allocateResponseMaps( int mapSize, int size, MatFloat * responseMaps[] );
void     freeResponseMaps( MatFloat * responseMaps[], int size );

namespace {

    struct hack_t {
        int m_visibleLandmarks_size;
        int m_mapSize;

        cv::Mat_<double> shape;
        cv::Mat_<uint8_t> alignedImage;
        std::vector<gel::MLP<double> > m_classifiers;
        std::vector<cv::Mat_<double> > responseMaps;

        template <class MT0>
        void serialize( MT0 & archiver, unsigned int ) {
            GEL_EXPORT_VAR( archiver, m_visibleLandmarks_size );
            GEL_EXPORT_VAR( archiver, m_mapSize );
            GEL_EXPORT_VAR( archiver, shape );
            GEL_EXPORT_VAR( archiver, alignedImage );
            GEL_EXPORT_VAR( archiver, m_classifiers );
            GEL_EXPORT_VAR( archiver, responseMaps );
        } // serialize

    }; // struct hack_t

    class conductor_t {
    public:
        int id;
        hack_t hack;
        std::ifstream dumpStream;
        boost::archive::binary_iarchive importer;

    public:

        conductor_t() : id(0), dumpStream("response_dumps.bin", std::ios::in | std::ios::binary ), importer(dumpStream) {

        }; // conductor_t

    }; // conductor_t

} // unnamed namespace

mlp *
convertHackToMlp ( const hack_t & hack )
{
    assert(hack.m_visibleLandmarks_size==hack.m_classifiers.size());
    assert(hack.m_visibleLandmarks_size==hack.responseMaps.size());

    mlp * result;
    result = reinterpret_cast<mlp*>( malloc( sizeof(mlp) * hack.m_visibleLandmarks_size ) );

    // we export each classifier
    for (int q=0; q<hack.m_visibleLandmarks_size; q++)
    {
        result[q].m_patchSize = hack.m_classifiers[q].m_patchSize;
        result[q].m_wIn       = convertCVToMatFloat(hack.m_classifiers[q].m_wIn);
        result[q].m_wOut      = convertCVToMatFloat(hack.m_classifiers[q].m_wOut);
        result[q].m_U         = convertCVToMatFloat(hack.m_classifiers[q].m_U);
        result[q].hidden_num  = hack.m_classifiers[q].hidden_num;
        result[q].rho2        = hack.m_classifiers[q].rho2;
    } // for q in m_visibleLandmarks_size

    return result;
} // convertHackToMlp

void
freeClassifiers( mlp * classifiers[], int size )
{
    mlp * result = *classifiers;
    for (int q=0; q<size; q++ )
        freeMLP( &(result[q]) );

    free(*classifiers);
    *classifiers=NULL;

    return;
} // freeClassifiers

MatChar convertCVToMatChar ( const cv::Mat_<uint8_t> & input )
{
    MatChar result = CreateMatChar( input.rows, input.cols );

    for ( int q=0; q<input.rows; q++)
        for ( int w=0; w<input.cols; w++ )
            result.data[ q * result.step + w + result.start ] = input(q,w);

    return result;
} // convertCVToMatChar

MatFloat convertCVToMatFloat (  const cv::Mat_<double> & input )
{
    MatFloat result = CreateMatFloat( input.rows, input.cols );

    for ( int q=0; q<input.rows; q++)
        for ( int w=0; w<input.cols; w++ )
            result.data[ q * result.step + w + result.start ] = input(q,w);

    return result;
} // convertCVToMatFloat

cv::Mat_<double> convertMatFloatToCV( MatFloat input )
{
    cv::Mat_<double> result( input.rows, input.cols );

    for ( int q=0; q<input.rows; q++)
        for ( int w=0; w<input.cols; w++ )
            result(q,w) = input.data[ q * input.step + w + input.start ];

    return result;
} // convertMatFloatToCV

void allocateResponseMaps( int mapSize, int size, MatFloat * responseMaps[] )
{
    *responseMaps = (MatFloat*)malloc( sizeof(MatFloat) * size );
    assert(*responseMaps);
    MatFloat * result = *responseMaps;

    for ( int q=0; q<size; q++ )
        result[q] = CreateMatFloat( 2 * mapSize + 1, 2 * mapSize + 1 );

    return;
}

void freeResponseMaps( MatFloat * responseMaps[], int size )
{
    MatFloat * result = *responseMaps;
    assert(result);
    for ( int q=0; q<size; q++ )
        freeMatFloat(&(result[q]));

    free(result);
    *responseMaps=NULL;
    return;
}

template <class T0>
auto
microseconds( T0 t0 ) -> decltype(std::chrono::duration_cast<std::chrono::microseconds>(t0).count())
{
    return std::chrono::duration_cast<std::chrono::microseconds>(t0).count();
}

int main()
{
    conductor_t conductor;
    int fail = 0;
    long int elapsed_time = 0;

    for ( conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id);
          ((conductor.id != -1) and (conductor.id != 25));
          // conductor.id != -1;
          conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id)
        )
    {
        PRINT(conductor.id);
        conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);

        // here comes the function call
        {
            // preparing the inputs
            MatChar alignedImage = convertCVToMatChar(conductor.hack.alignedImage);
            MatFloat shape = convertCVToMatFloat(conductor.hack.shape);
            mlp * m_classifiers = convertHackToMlp(conductor.hack);
            MatFloat * responseMaps;
            allocateResponseMaps( conductor.hack.m_mapSize, conductor.hack.m_visibleLandmarks_size, &responseMaps );

            auto start = std::chrono::high_resolution_clock::now();
            calculateMaps(
                conductor.hack.m_visibleLandmarks_size,
                conductor.hack.m_mapSize,
                alignedImage,
                shape,
                m_classifiers,
                &responseMaps
                );
            auto end = std::chrono::high_resolution_clock::now();
            elapsed_time = microseconds(end - start);

            // releasing the inputs
            freeMatChar(&alignedImage);
            freeMatFloat(&shape);
            freeClassifiers(&m_classifiers, conductor.hack.m_classifiers.size());

            // converting the outputs
            std::vector< cv::Mat_<double> > calculatedResults;
            for (int q=0; q<conductor.hack.m_visibleLandmarks_size; q++)
            {
                cv::Mat_<double> nextResult;
                nextResult = convertMatFloatToCV( responseMaps[q] );
                calculatedResults.push_back(nextResult);
            }

            // testing the output
            for (int q=0; q<conductor.hack.m_visibleLandmarks_size; q++)
            {
                // std::cout << "cv::norm( conductor.hack.responseMaps[" << q << "] - calculatedResults[" << q << "] ) = "
                //           << cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) << std::endl;
                assert(cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) < 1.5);
                if (cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) > 0.5 ) fail++;
                // PRINT(fail);
                int tolerance = 49 * conductor.id * 0.005 + 3;
                // PRINT(tolerance);
                assert(fail < tolerance);
            }

            // releasing the outputs
            freeResponseMaps( &responseMaps, conductor.hack.m_visibleLandmarks_size );

        }
        // here comes the test
        // PRINT(cv::norm( ));
    }

    std::cout << "total elapsed time = " << elapsed_time / 1000000. << " s." << std::endl;
    //conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);

    return EXIT_SUCCESS;
}

// LuM end of file
<commit_msg>comment the memory debugger parameters<commit_after>// UjoImro, 2013
// Experimental code for the CARP Project
// Copyright (c) RealEyes, 2013
// This version tests the responseMap calculation with input dumps

#include <chrono>
#include <string>
#include <stdlib.h>
#include <opencv2/core/core.hpp>
#include <boost/preprocessor.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/archive/binary_iarchive.hpp>

#include "cast.h"
#include "mlp.hpp"
#include "mlp_impl.h"

/*
extern int EF_ALIGNMENT = 0;
extern int EF_PROTECT_BELOW = 0;
extern int EF_PROTECT_FREE = 0;
extern int EF_ALLOW_MALLOC_0 = 1;
extern int EF_FILL = 1922;
*/

namespace { struct hack_t; }
MatChar  convertCVToMatChar ( const cv::Mat_<uint8_t> & input );
mlp *    convertHackToMlp ( const hack_t & hack );
void     freeClassifiers( mlp * classifiers[], int size );
MatChar  convertCVToMatChar ( const cv::Mat_<uint8_t> & input );
MatFloat convertCVToMatFloat (  const cv::Mat_<double> & input );
cv::Mat_<double> convertMatFloatToCV( MatFloat input );
void     allocateResponseMaps( int mapSize, int size, MatFloat * responseMaps[] );
void     freeResponseMaps( MatFloat * responseMaps[], int size );

namespace {

    struct hack_t {
        int m_visibleLandmarks_size;
        int m_mapSize;

        cv::Mat_<double> shape;
        cv::Mat_<uint8_t> alignedImage;
        std::vector<gel::MLP<double> > m_classifiers;
        std::vector<cv::Mat_<double> > responseMaps;

        template <class MT0>
        void serialize( MT0 & archiver, unsigned int ) {
            GEL_EXPORT_VAR( archiver, m_visibleLandmarks_size );
            GEL_EXPORT_VAR( archiver, m_mapSize );
            GEL_EXPORT_VAR( archiver, shape );
            GEL_EXPORT_VAR( archiver, alignedImage );
            GEL_EXPORT_VAR( archiver, m_classifiers );
            GEL_EXPORT_VAR( archiver, responseMaps );
        } // serialize

    }; // struct hack_t

    class conductor_t {
    public:
        int id;
        hack_t hack;
        std::ifstream dumpStream;
        boost::archive::binary_iarchive importer;

    public:

        conductor_t() : id(0), dumpStream("response_dumps.bin", std::ios::in | std::ios::binary ), importer(dumpStream) {

        }; // conductor_t

    }; // conductor_t

} // unnamed namespace

mlp *
convertHackToMlp ( const hack_t & hack )
{
    assert(hack.m_visibleLandmarks_size==hack.m_classifiers.size());
    assert(hack.m_visibleLandmarks_size==hack.responseMaps.size());

    mlp * result;
    result = reinterpret_cast<mlp*>( malloc( sizeof(mlp) * hack.m_visibleLandmarks_size ) );

    // we export each classifier
    for (int q=0; q<hack.m_visibleLandmarks_size; q++)
    {
        result[q].m_patchSize = hack.m_classifiers[q].m_patchSize;
        result[q].m_wIn       = convertCVToMatFloat(hack.m_classifiers[q].m_wIn);
        result[q].m_wOut      = convertCVToMatFloat(hack.m_classifiers[q].m_wOut);
        result[q].m_U         = convertCVToMatFloat(hack.m_classifiers[q].m_U);
        result[q].hidden_num  = hack.m_classifiers[q].hidden_num;
        result[q].rho2        = hack.m_classifiers[q].rho2;
    } // for q in m_visibleLandmarks_size

    return result;
} // convertHackToMlp

void
freeClassifiers( mlp * classifiers[], int size )
{
    mlp * result = *classifiers;
    for (int q=0; q<size; q++ )
        freeMLP( &(result[q]) );

    free(*classifiers);
    *classifiers=NULL;

    return;
} // freeClassifiers

MatChar convertCVToMatChar ( const cv::Mat_<uint8_t> & input )
{
    MatChar result = CreateMatChar( input.rows, input.cols );

    for ( int q=0; q<input.rows; q++)
        for ( int w=0; w<input.cols; w++ )
            result.data[ q * result.step + w + result.start ] = input(q,w);

    return result;
} // convertCVToMatChar

MatFloat convertCVToMatFloat (  const cv::Mat_<double> & input )
{
    MatFloat result = CreateMatFloat( input.rows, input.cols );

    for ( int q=0; q<input.rows; q++)
        for ( int w=0; w<input.cols; w++ )
            result.data[ q * result.step + w + result.start ] = input(q,w);

    return result;
} // convertCVToMatFloat

cv::Mat_<double> convertMatFloatToCV( MatFloat input )
{
    cv::Mat_<double> result( input.rows, input.cols );

    for ( int q=0; q<input.rows; q++)
        for ( int w=0; w<input.cols; w++ )
            result(q,w) = input.data[ q * input.step + w + input.start ];

    return result;
} // convertMatFloatToCV

void allocateResponseMaps( int mapSize, int size, MatFloat * responseMaps[] )
{
    *responseMaps = (MatFloat*)malloc( sizeof(MatFloat) * size );
    assert(*responseMaps);
    MatFloat * result = *responseMaps;

    for ( int q=0; q<size; q++ )
        result[q] = CreateMatFloat( 2 * mapSize + 1, 2 * mapSize + 1 );

    return;
}

void freeResponseMaps( MatFloat * responseMaps[], int size )
{
    MatFloat * result = *responseMaps;
    assert(result);
    for ( int q=0; q<size; q++ )
        freeMatFloat(&(result[q]));

    free(result);
    *responseMaps=NULL;
    return;
}

template <class T0>
auto
microseconds( T0 t0 ) -> decltype(std::chrono::duration_cast<std::chrono::microseconds>(t0).count())
{
    return std::chrono::duration_cast<std::chrono::microseconds>(t0).count();
}

int main()
{
    conductor_t conductor;
    int fail = 0;
    long int elapsed_time = 0;

    for ( conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id);
          ((conductor.id != -1) and (conductor.id != 25));
          // conductor.id != -1;
          conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id)
        )
    {
        PRINT(conductor.id);
        conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);

        // here comes the function call
        {
            // preparing the inputs
            MatChar alignedImage = convertCVToMatChar(conductor.hack.alignedImage);
            MatFloat shape = convertCVToMatFloat(conductor.hack.shape);
            mlp * m_classifiers = convertHackToMlp(conductor.hack);
            MatFloat * responseMaps;
            allocateResponseMaps( conductor.hack.m_mapSize, conductor.hack.m_visibleLandmarks_size, &responseMaps );

            auto start = std::chrono::high_resolution_clock::now();
            calculateMaps(
                conductor.hack.m_visibleLandmarks_size,
                conductor.hack.m_mapSize,
                alignedImage,
                shape,
                m_classifiers,
                &responseMaps
                );
            auto end = std::chrono::high_resolution_clock::now();
            elapsed_time = microseconds(end - start);

            // releasing the inputs
            freeMatChar(&alignedImage);
            freeMatFloat(&shape);
            freeClassifiers(&m_classifiers, conductor.hack.m_classifiers.size());

            // converting the outputs
            std::vector< cv::Mat_<double> > calculatedResults;
            for (int q=0; q<conductor.hack.m_visibleLandmarks_size; q++)
            {
                cv::Mat_<double> nextResult;
                nextResult = convertMatFloatToCV( responseMaps[q] );
                calculatedResults.push_back(nextResult);
            }

            // testing the output
            for (int q=0; q<conductor.hack.m_visibleLandmarks_size; q++)
            {
                // std::cout << "cv::norm( conductor.hack.responseMaps[" << q << "] - calculatedResults[" << q << "] ) = "
                //           << cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) << std::endl;
                assert(cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) < 1.5);
                if (cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) > 0.5 ) fail++;
                // PRINT(fail);
                int tolerance = 49 * conductor.id * 0.005 + 3;
                // PRINT(tolerance);
                assert(fail < tolerance);
            }

            // releasing the outputs
            freeResponseMaps( &responseMaps, conductor.hack.m_visibleLandmarks_size );

        }
        // here comes the test
        // PRINT(cv::norm( ));
    }

    std::cout << "total elapsed time = " << elapsed_time / 1000000. << " s." << std::endl;
    //conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);

    return EXIT_SUCCESS;
}

// LuM end of file
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#endif

#include "chrome/common/chrome_paths.h"

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/sys_info.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_switches.h"

namespace chrome {

// Gets the default user data directory, regardless of whether
// DIR_USER_DATA has been overridden by a command-line option.
bool GetDefaultUserDataDirectory(std::wstring* result) {
#if defined(OS_WIN)
  if (!PathService::Get(base::DIR_LOCAL_APP_DATA, result))
    return false;
#if defined(GOOGLE_CHROME_BUILD)
  file_util::AppendToPath(result, L"Google");
#endif
  file_util::AppendToPath(result, chrome::kBrowserAppName);
  file_util::AppendToPath(result, chrome::kUserDataDirname);
  return true;
#else  // defined(OS_WIN)
  // TODO(port): Decide what to do on other platforms.
  NOTIMPLEMENTED();
  return false;
#endif  // defined(OS_WIN)
}

bool GetGearsPluginPathFromCommandLine(std::wstring *path) {
#ifndef NDEBUG
  // for debugging, support a cmd line based override
  CommandLine command_line;
  *path = command_line.GetSwitchValue(switches::kGearsPluginPathOverride);
  return !path->empty();
#else
  return false;
#endif
}

bool PathProvider(int key, FilePath* result) {
  // Some keys are just aliases...
  switch (key) {
    case chrome::DIR_APP:
      return PathService::Get(base::DIR_MODULE, result);
    case chrome::DIR_LOGS:
#ifndef NDEBUG
      return PathService::Get(chrome::DIR_USER_DATA, result);
#else
      return PathService::Get(base::DIR_EXE, result);
#endif
    case chrome::FILE_RESOURCE_MODULE:
      return PathService::Get(base::FILE_MODULE, result);
  }

  // Assume that we will need to create the directory if it does not already
  // exist.  This flag can be set to true to prevent checking.
  bool exists = false;

  std::wstring cur;
  switch (key) {
    case chrome::DIR_USER_DATA:
      if (!GetDefaultUserDataDirectory(&cur))
        return false;
      break;
    case chrome::DIR_USER_DOCUMENTS:
#if defined(OS_WIN)
      {
        wchar_t path_buf[MAX_PATH];
        if (FAILED(SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS, NULL,
                                   SHGFP_TYPE_CURRENT, path_buf)))
          return false;
        cur.assign(path_buf);
      }
#else
      // TODO(port): Get the path (possibly using xdg-user-dirs)
      // or decide we don't need it on other platforms.
      NOTIMPLEMENTED();
      return false;
#endif
      break;
    case chrome::DIR_DEFAULT_DOWNLOADS:
      // On Vista, we can get the download path using a Win API
      // (http://msdn.microsoft.com/en-us/library/bb762584(VS.85).aspx),
      // but it can be set to Desktop, which is dangerous. Instead,
      // we just use 'Downloads' under DIR_USER_DOCUMENTS. Localizing
      // 'downloads' is not a good idea because Chrome's UI language
      // can be changed.
      if (!PathService::Get(chrome::DIR_USER_DOCUMENTS, &cur))
        return false;
      file_util::AppendToPath(&cur, L"Downloads");
      // TODO(port): This will fail on other platforms unless we
      // implement DIR_USER_DOCUMENTS or use xdg-user-dirs to
      // get the download directory independently of DIR_USER_DOCUMENTS.
      break;
    case chrome::DIR_CRASH_DUMPS:
      // The crash reports are always stored relative to the default user data
      // directory.  This avoids the problem of having to re-initialize the
      // exception handler after parsing command line options, which may
      // override the location of the app's profile directory.
      if (!GetDefaultUserDataDirectory(&cur))
        return false;
      file_util::AppendToPath(&cur, L"Crash Reports");
      break;
    case chrome::DIR_USER_DESKTOP:
#if defined(OS_WIN)
      {
        // We need to go compute the value. It would be nice to support paths
        // with names longer than MAX_PATH, but the system functions don't seem
        // to be designed for it either, with the exception of GetTempPath
        // (but other things will surely break if the temp path is too long,
        // so we don't bother handling it.
        wchar_t system_buffer[MAX_PATH];
        system_buffer[0] = 0;
        if (FAILED(SHGetFolderPath(NULL, CSIDL_DESKTOPDIRECTORY, NULL,
                                   SHGFP_TYPE_CURRENT, system_buffer)))
          return false;
        cur.assign(system_buffer);
      }
#else
      // TODO(port): Get the path (possibly using xdg-user-dirs)
      // or decide we don't need it on other platforms.
      NOTIMPLEMENTED();
      return false;
#endif
      exists = true;
      break;
    case chrome::DIR_RESOURCES:
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      file_util::AppendToPath(&cur, L"resources");
      break;
    case chrome::DIR_INSPECTOR:
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      file_util::AppendToPath(&cur, L"Resources");
      file_util::AppendToPath(&cur, L"Inspector");
      exists = true;
      break;
    case chrome::DIR_THEMES:
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      file_util::AppendToPath(&cur, L"themes");
      break;
    case chrome::DIR_LOCALES:
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      file_util::AppendToPath(&cur, L"locales");
      break;
    case chrome::DIR_APP_DICTIONARIES:
      if (!PathService::Get(base::DIR_EXE, &cur))
        return false;
      file_util::AppendToPath(&cur, L"Dictionaries");
      break;
    case chrome::DIR_USER_SCRIPTS:
      // TODO(aa): Figure out where the script directory should live.
#if defined(OS_WIN)
      cur = L"C:\\SCRIPTS\\";
#else
      NOTIMPLEMENTED();
      return false;
#endif
      exists = true;  // don't trigger directory creation code
      break;
    case chrome::FILE_LOCAL_STATE:
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
      file_util::AppendToPath(&cur, chrome::kLocalStateFilename);
      exists = true;  // don't trigger directory creation code
      break;
    case chrome::FILE_RECORDED_SCRIPT:
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
      file_util::AppendToPath(&cur, L"script.log");
      exists = true;
      break;
    case chrome::FILE_GEARS_PLUGIN:
      if (!GetGearsPluginPathFromCommandLine(&cur)) {
        // Search for gears.dll alongside chrome.dll first.  This new model
        // allows us to package gears.dll with the Chrome installer and update
        // it while Chrome is running.
        if (!PathService::Get(base::DIR_MODULE, &cur))
          return false;
        file_util::AppendToPath(&cur, L"gears.dll");

        if (!file_util::PathExists(cur)) {
          if (!PathService::Get(base::DIR_EXE, &cur))
            return false;
          file_util::AppendToPath(&cur, L"plugins");
          file_util::AppendToPath(&cur, L"gears");
          file_util::AppendToPath(&cur, L"gears.dll");
        }
      }
      exists = true;
      break;
    // The following are only valid in the development environment, and
    // will fail if executed from an installed executable (because the
    // generated path won't exist).
    case chrome::DIR_TEST_DATA:
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      file_util::UpOneDirectory(&cur);
      file_util::AppendToPath(&cur, L"test");
      file_util::AppendToPath(&cur, L"data");
      if (!file_util::PathExists(cur))  // we don't want to create this
        return false;
      exists = true;
      break;
    case chrome::DIR_TEST_TOOLS:
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      file_util::UpOneDirectory(&cur);
      file_util::AppendToPath(&cur, L"tools");
      file_util::AppendToPath(&cur, L"test");
      if (!file_util::PathExists(cur))  // we don't want to create this
        return false;
      exists = true;
      break;
    case chrome::FILE_PYTHON_RUNTIME:
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      file_util::UpOneDirectory(&cur);  // chrome
      file_util::UpOneDirectory(&cur);
      file_util::AppendToPath(&cur, L"third_party");
      file_util::AppendToPath(&cur, L"python_24");
      file_util::AppendToPath(&cur, L"python.exe");
      if (!file_util::PathExists(cur))  // we don't want to create this
        return false;
      exists = true;
      break;
    case chrome::FILE_TEST_SERVER:
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      file_util::UpOneDirectory(&cur);
      file_util::AppendToPath(&cur, L"tools");
      file_util::AppendToPath(&cur, L"test");
      file_util::AppendToPath(&cur, L"testserver");
      file_util::AppendToPath(&cur, L"testserver.py");
      if (!file_util::PathExists(cur))  // we don't want to create this
        return false;
      exists = true;
      break;
    default:
      return false;
  }

  if (!exists && !file_util::PathExists(cur) && !file_util::CreateDirectory(cur))
    return false;

  *result = FilePath::FromWStringHack(cur);
  return true;
}

// This cannot be done as a static initializer sadly since Visual Studio will
// eliminate this object file if there is no direct entry point into it.
void RegisterPathProvider() {
  PathService::RegisterProvider(PathProvider, PATH_START, PATH_END);
}

}  // namespace chrome

<commit_msg>Don't create the default download directory just because we ask for its location.  This is a first step toward not creating _any_ directories when we merely ask for their locations.  Patch by Marc-André Decoste, r=cpu.  See http://codereview.chromium.org/11586 .<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#endif

#include "chrome/common/chrome_paths.h"

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/sys_info.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_switches.h"

namespace chrome {

// Gets the default user data directory, regardless of whether
// DIR_USER_DATA has been overridden by a command-line option.
bool GetDefaultUserDataDirectory(std::wstring* result) {
#if defined(OS_WIN)
  if (!PathService::Get(base::DIR_LOCAL_APP_DATA, result))
    return false;
#if defined(GOOGLE_CHROME_BUILD)
  file_util::AppendToPath(result, L"Google");
#endif
  file_util::AppendToPath(result, chrome::kBrowserAppName);
  file_util::AppendToPath(result, chrome::kUserDataDirname);
  return true;
#else  // defined(OS_WIN)
  // TODO(port): Decide what to do on other platforms.
  NOTIMPLEMENTED();
  return false;
#endif  // defined(OS_WIN)
}

bool GetGearsPluginPathFromCommandLine(std::wstring *path) {
#ifndef NDEBUG
  // for debugging, support a cmd line based override
  CommandLine command_line;
  *path = command_line.GetSwitchValue(switches::kGearsPluginPathOverride);
  return !path->empty();
#else
  return false;
#endif
}

bool PathProvider(int key, FilePath* result) {
  // Some keys are just aliases...
  switch (key) {
    case chrome::DIR_APP:
      return PathService::Get(base::DIR_MODULE, result);
    case chrome::DIR_LOGS:
#ifndef NDEBUG
      return PathService::Get(chrome::DIR_USER_DATA, result);
#else
      return PathService::Get(base::DIR_EXE, result);
#endif
    case chrome::FILE_RESOURCE_MODULE:
      return PathService::Get(base::FILE_MODULE, result);
  }

  // Assume that we will not need to create the directory if it does not exist.
  // This flag can be set to true for the cases where we want to create it.
  bool create_dir = false;

  std::wstring cur;
  switch (key) {
    case chrome::DIR_USER_DATA:
      if (!GetDefaultUserDataDirectory(&cur))
        return false;
      create_dir = true;
      break;
    case chrome::DIR_USER_DOCUMENTS:
#if defined(OS_WIN)
      {
        wchar_t path_buf[MAX_PATH];
        if (FAILED(SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS, NULL,
                                   SHGFP_TYPE_CURRENT, path_buf)))
          return false;
        cur.assign(path_buf);
      }
#else
      // TODO(port): Get the path (possibly using xdg-user-dirs)
      // or decide we don't need it on other platforms.
      NOTIMPLEMENTED();
      return false;
#endif
      create_dir = true;
      break;
    case chrome::DIR_DEFAULT_DOWNLOADS:
      // On Vista, we can get the download path using a Win API
      // (http://msdn.microsoft.com/en-us/library/bb762584(VS.85).aspx),
      // but it can be set to Desktop, which is dangerous. Instead,
      // we just use 'Downloads' under DIR_USER_DOCUMENTS. Localizing
      // 'downloads' is not a good idea because Chrome's UI language
      // can be changed.
      if (!PathService::Get(chrome::DIR_USER_DOCUMENTS, &cur))
        return false;
      file_util::AppendToPath(&cur, L"Downloads");
      // TODO(port): This will fail on other platforms unless we
      // implement DIR_USER_DOCUMENTS or use xdg-user-dirs to
      // get the download directory independently of DIR_USER_DOCUMENTS.
      break;
    case chrome::DIR_CRASH_DUMPS:
      // The crash reports are always stored relative to the default user data
      // directory.  This avoids the problem of having to re-initialize the
      // exception handler after parsing command line options, which may
      // override the location of the app's profile directory.
      if (!GetDefaultUserDataDirectory(&cur))
        return false;
      file_util::AppendToPath(&cur, L"Crash Reports");
      create_dir = true;
      break;
    case chrome::DIR_USER_DESKTOP:
#if defined(OS_WIN)
      {
        // We need to go compute the value. It would be nice to support paths
        // with names longer than MAX_PATH, but the system functions don't seem
        // to be designed for it either, with the exception of GetTempPath
        // (but other things will surely break if the temp path is too long,
        // so we don't bother handling it.
        wchar_t system_buffer[MAX_PATH];
        system_buffer[0] = 0;
        if (FAILED(SHGetFolderPath(NULL, CSIDL_DESKTOPDIRECTORY, NULL,
                                   SHGFP_TYPE_CURRENT, system_buffer)))
          return false;
        cur.assign(system_buffer);
      }
#else
      // TODO(port): Get the path (possibly using xdg-user-dirs)
      // or decide we don't need it on other platforms.
      NOTIMPLEMENTED();
      return false;
#endif
      break;
    case chrome::DIR_RESOURCES:
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      file_util::AppendToPath(&cur, L"resources");
      create_dir = true;
      break;
    case chrome::DIR_INSPECTOR:
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      file_util::AppendToPath(&cur, L"Resources");
      file_util::AppendToPath(&cur, L"Inspector");
      break;
    case chrome::DIR_THEMES:
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      file_util::AppendToPath(&cur, L"themes");
      create_dir = true;
      break;
    case chrome::DIR_LOCALES:
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      file_util::AppendToPath(&cur, L"locales");
      create_dir = true;
      break;
    case chrome::DIR_APP_DICTIONARIES:
      if (!PathService::Get(base::DIR_EXE, &cur))
        return false;
      file_util::AppendToPath(&cur, L"Dictionaries");
      create_dir = true;
      break;
    case chrome::DIR_USER_SCRIPTS:
      // TODO(aa): Figure out where the script directory should live.
#if defined(OS_WIN)
      cur = L"C:\\SCRIPTS\\";
#else
      NOTIMPLEMENTED();
      return false;
#endif
      break;
    case chrome::FILE_LOCAL_STATE:
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
      file_util::AppendToPath(&cur, chrome::kLocalStateFilename);
      break;
    case chrome::FILE_RECORDED_SCRIPT:
      if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
        return false;
      file_util::AppendToPath(&cur, L"script.log");
      break;
    case chrome::FILE_GEARS_PLUGIN:
      if (!GetGearsPluginPathFromCommandLine(&cur)) {
        // Search for gears.dll alongside chrome.dll first.  This new model
        // allows us to package gears.dll with the Chrome installer and update
        // it while Chrome is running.
        if (!PathService::Get(base::DIR_MODULE, &cur))
          return false;
        file_util::AppendToPath(&cur, L"gears.dll");

        if (!file_util::PathExists(cur)) {
          if (!PathService::Get(base::DIR_EXE, &cur))
            return false;
          file_util::AppendToPath(&cur, L"plugins");
          file_util::AppendToPath(&cur, L"gears");
          file_util::AppendToPath(&cur, L"gears.dll");
        }
      }
      break;
    // The following are only valid in the development environment, and
    // will fail if executed from an installed executable (because the
    // generated path won't exist).
    case chrome::DIR_TEST_DATA:
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      file_util::UpOneDirectory(&cur);
      file_util::AppendToPath(&cur, L"test");
      file_util::AppendToPath(&cur, L"data");
      if (!file_util::PathExists(cur))  // we don't want to create this
        return false;
      break;
    case chrome::DIR_TEST_TOOLS:
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      file_util::UpOneDirectory(&cur);
      file_util::AppendToPath(&cur, L"tools");
      file_util::AppendToPath(&cur, L"test");
      if (!file_util::PathExists(cur))  // we don't want to create this
        return false;
      break;
    case chrome::FILE_PYTHON_RUNTIME:
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      file_util::UpOneDirectory(&cur);  // chrome
      file_util::UpOneDirectory(&cur);
      file_util::AppendToPath(&cur, L"third_party");
      file_util::AppendToPath(&cur, L"python_24");
      file_util::AppendToPath(&cur, L"python.exe");
      if (!file_util::PathExists(cur))  // we don't want to create this
        return false;
      break;
    case chrome::FILE_TEST_SERVER:
      if (!PathService::Get(chrome::DIR_APP, &cur))
        return false;
      file_util::UpOneDirectory(&cur);
      file_util::AppendToPath(&cur, L"tools");
      file_util::AppendToPath(&cur, L"test");
      file_util::AppendToPath(&cur, L"testserver");
      file_util::AppendToPath(&cur, L"testserver.py");
      if (!file_util::PathExists(cur))  // we don't want to create this
        return false;
      break;
    default:
      return false;
  }

  if (create_dir && !file_util::PathExists(cur) && !file_util::CreateDirectory(cur))
    return false;

  *result = FilePath::FromWStringHack(cur);
  return true;
}

// This cannot be done as a static initializer sadly since Visual Studio will
// eliminate this object file if there is no direct entry point into it.
void RegisterPathProvider() {
  PathService::RegisterProvider(PathProvider, PATH_START, PATH_END);
}

}  // namespace chrome

<|endoftext|>