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

#include "browser/devtools_delegate.h"

#include "base/values.h"
#include "browser/native_window.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/devtools_client_host.h"
#include "content/public/browser/devtools_http_handler.h"
#include "content/public/browser/devtools_manager.h"
#include "content/public/browser/web_contents.h"
#include "ui/gfx/point.h"

namespace atom {

DevToolsDelegate::DevToolsDelegate(NativeWindow* window,
                                   content::WebContents* target_web_contents)
    : content::WebContentsObserver(window->GetWebContents()),
      owner_window_(window),
      embedder_message_dispatcher_(
          new DevToolsEmbedderMessageDispatcher(this)) {
  content::WebContents* web_contents = window->GetWebContents();

  // Setup devtools.
  devtools_agent_host_ = content::DevToolsAgentHost::GetOrCreateFor(
      target_web_contents->GetRenderViewHost());
  devtools_client_host_.reset(
      content::DevToolsClientHost::CreateDevToolsFrontendHost(web_contents,
                                                              this));
  content::DevToolsManager::GetInstance()->RegisterDevToolsClientHostFor(
      devtools_agent_host_.get(), devtools_client_host_.get());

  // Go!
  base::DictionaryValue options;
  options.SetString("title", "DevTools Debugger");
  window->InitFromOptions(&options);
  web_contents->GetController().LoadURL(
      GURL("chrome-devtools://devtools/devtools.html?dockSide=undocked"),
      content::Referrer(),
      content::PAGE_TRANSITION_AUTO_TOPLEVEL,
      std::string());
}

DevToolsDelegate::~DevToolsDelegate() {
}

void DevToolsDelegate::DispatchOnEmbedder(const std::string& message) {
  embedder_message_dispatcher_->Dispatch(message);
}

void DevToolsDelegate::InspectedContentsClosing() {
  delete owner_window_;
}

void DevToolsDelegate::AboutToNavigateRenderView(
      content::RenderViewHost* render_view_host) {
  content::DevToolsClientHost::SetupDevToolsFrontendClient(
      owner_window_->GetWebContents()->GetRenderViewHost());
}

void DevToolsDelegate::OnWindowClosed() {
  delete owner_window_;
}

void DevToolsDelegate::ActivateWindow() {
}

void DevToolsDelegate::CloseWindow() {
  owner_window_->Close();
}

void DevToolsDelegate::MoveWindow(int x, int y) {
  owner_window_->SetPosition(gfx::Point(x, y));
}

void DevToolsDelegate::SetDockSide(const std::string& dock_side) {
  if (dock_side != "undocked")
    owner_window_->Close();
}

void DevToolsDelegate::OpenInNewTab(const std::string& url) {
}

void DevToolsDelegate::SaveToFile(
    const std::string& url, const std::string& content, bool save_as) {
}

void DevToolsDelegate::AppendToFile(
    const std::string& url, const std::string& content) {
}

void DevToolsDelegate::RequestFileSystems() {
}

void DevToolsDelegate::AddFileSystem() {
}

void DevToolsDelegate::RemoveFileSystem(const std::string& file_system_path) {
}

void DevToolsDelegate::IndexPath(
    int request_id, const std::string& file_system_path) {
}

void DevToolsDelegate::StopIndexing(int request_id) {
}

void DevToolsDelegate::SearchInPath(
    int request_id,
    const std::string& file_system_path,
    const std::string& query) {
}

}  // namespace atom
<commit_msg>Correctly free devtools window.<commit_after>// Copyright (c) 2014 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "browser/devtools_delegate.h"

#include "base/message_loop/message_loop.h"
#include "base/values.h"
#include "browser/native_window.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/devtools_client_host.h"
#include "content/public/browser/devtools_http_handler.h"
#include "content/public/browser/devtools_manager.h"
#include "content/public/browser/web_contents.h"
#include "ui/gfx/point.h"

namespace atom {

DevToolsDelegate::DevToolsDelegate(NativeWindow* window,
                                   content::WebContents* target_web_contents)
    : content::WebContentsObserver(window->GetWebContents()),
      owner_window_(window),
      embedder_message_dispatcher_(
          new DevToolsEmbedderMessageDispatcher(this)) {
  content::WebContents* web_contents = window->GetWebContents();

  // Setup devtools.
  devtools_agent_host_ = content::DevToolsAgentHost::GetOrCreateFor(
      target_web_contents->GetRenderViewHost());
  devtools_client_host_.reset(
      content::DevToolsClientHost::CreateDevToolsFrontendHost(web_contents,
                                                              this));
  content::DevToolsManager::GetInstance()->RegisterDevToolsClientHostFor(
      devtools_agent_host_.get(), devtools_client_host_.get());

  // Go!
  base::DictionaryValue options;
  options.SetString("title", "DevTools Debugger");
  window->InitFromOptions(&options);
  window->AddObserver(this);
  web_contents->GetController().LoadURL(
      GURL("chrome-devtools://devtools/devtools.html?dockSide=undocked"),
      content::Referrer(),
      content::PAGE_TRANSITION_AUTO_TOPLEVEL,
      std::string());
}

DevToolsDelegate::~DevToolsDelegate() {
}

void DevToolsDelegate::DispatchOnEmbedder(const std::string& message) {
  embedder_message_dispatcher_->Dispatch(message);
}

void DevToolsDelegate::InspectedContentsClosing() {
  owner_window_->Close();
}

void DevToolsDelegate::AboutToNavigateRenderView(
      content::RenderViewHost* render_view_host) {
  content::DevToolsClientHost::SetupDevToolsFrontendClient(
      owner_window_->GetWebContents()->GetRenderViewHost());
}

void DevToolsDelegate::OnWindowClosed() {
  base::MessageLoop::current()->DeleteSoon(FROM_HERE, owner_window_);
}

void DevToolsDelegate::ActivateWindow() {
}

void DevToolsDelegate::CloseWindow() {
  owner_window_->Close();
}

void DevToolsDelegate::MoveWindow(int x, int y) {
  owner_window_->SetPosition(gfx::Point(x, y));
}

void DevToolsDelegate::SetDockSide(const std::string& dock_side) {
  owner_window_->Close();
}

void DevToolsDelegate::OpenInNewTab(const std::string& url) {
}

void DevToolsDelegate::SaveToFile(
    const std::string& url, const std::string& content, bool save_as) {
}

void DevToolsDelegate::AppendToFile(
    const std::string& url, const std::string& content) {
}

void DevToolsDelegate::RequestFileSystems() {
}

void DevToolsDelegate::AddFileSystem() {
}

void DevToolsDelegate::RemoveFileSystem(const std::string& file_system_path) {
}

void DevToolsDelegate::IndexPath(
    int request_id, const std::string& file_system_path) {
}

void DevToolsDelegate::StopIndexing(int request_id) {
}

void DevToolsDelegate::SearchInPath(
    int request_id,
    const std::string& file_system_path,
    const std::string& query) {
}

}  // namespace atom
<|endoftext|>


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

#include "chrome/browser/chromeos/gdata/gdata_file_system_proxy.h"

#include <vector>

#include "base/bind.h"
#include "base/platform_file.h"
#include "base/string_util.h"
#include "base/values.h"
#include "content/public/browser/browser_thread.h"
#include "chrome/browser/chromeos/gdata/gdata_system_service.h"
#include "chrome/browser/chromeos/gdata/gdata_file_system.h"
#include "webkit/blob/shareable_file_reference.h"
#include "webkit/fileapi/file_system_file_util_proxy.h"
#include "webkit/fileapi/file_system_types.h"
#include "webkit/fileapi/file_system_util.h"

using base::MessageLoopProxy;
using content::BrowserThread;
using fileapi::FileSystemOperationInterface;
using webkit_blob::ShareableFileReference;

namespace {

const char kGDataRootDirectory[] = "gdata";
const char kFeedField[] = "feed";

// Helper function to run SnapshotFileCallback from
// GDataFileSystemProxy::CreateSnapshotFile().
void CallSnapshotFileCallback(
    const FileSystemOperationInterface::SnapshotFileCallback& callback,
    base::PlatformFileInfo file_info,
    base::PlatformFileError error,
    const FilePath& local_path,
    const std::string& unused_mime_type,
    gdata::GDataFileType file_type) {
  scoped_refptr<ShareableFileReference> file_ref;

  // If the file is a hosted document, a temporary JSON file is created to
  // represent the document. The JSON file is not cached and its lifetime
  // is managed by ShareableFileReference.
  if (error == base::PLATFORM_FILE_OK && file_type == gdata::HOSTED_DOCUMENT) {
    file_ref = ShareableFileReference::GetOrCreate(
        local_path, ShareableFileReference::DELETE_ON_FINAL_RELEASE,
        base::MessageLoopProxy::current());
  }

  callback.Run(error, file_info, local_path, file_ref);
}

}  // namespace

namespace gdata {

base::FileUtilProxy::Entry GDataFileToFileUtilProxyEntry(
    const GDataFileBase& file) {
  base::FileUtilProxy::Entry entry;
  entry.is_directory = file.file_info().is_directory;

  // TODO(zelidrag): Add file name modification logic to enforce uniquness of
  // file paths across this file system.
  entry.name = file.file_name();

  entry.size = file.file_info().size;
  entry.last_modified_time = file.file_info().last_modified;
  return entry;
}

// GDataFileSystemProxy class implementation.

GDataFileSystemProxy::GDataFileSystemProxy(
    GDataFileSystemInterface* file_system)
    : file_system_(file_system) {
  // Should be created from the file browser extension API (AddMountFunction)
  // on UI thread.
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

GDataFileSystemProxy::~GDataFileSystemProxy() {
  // Should be deleted from the CrosMountPointProvider on IO thread.
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
}

void GDataFileSystemProxy::GetFileInfo(const GURL& file_url,
    const FileSystemOperationInterface::GetMetadataCallback& callback) {
  scoped_refptr<base::MessageLoopProxy> proxy =
      base::MessageLoopProxy::current();
  FilePath file_path;
  if (!ValidateUrl(file_url, &file_path)) {
    proxy->PostTask(FROM_HERE,
                    base::Bind(callback,
                               base::PLATFORM_FILE_ERROR_NOT_FOUND,
                               base::PlatformFileInfo(),
                               FilePath()));
    return;
  }

  file_system_->FindFileByPathAsync(
      file_path,
      base::Bind(&GDataFileSystemProxy::OnGetMetadata,
                 this,
                 file_path,
                 proxy,
                 callback));
}

void GDataFileSystemProxy::Copy(const GURL& src_file_url,
    const GURL& dest_file_url,
    const FileSystemOperationInterface::StatusCallback& callback) {
  FilePath src_file_path, dest_file_path;
  if (!ValidateUrl(src_file_url, &src_file_path) ||
      !ValidateUrl(dest_file_url, &dest_file_path)) {
    MessageLoopProxy::current()->PostTask(FROM_HERE,
         base::Bind(callback, base::PLATFORM_FILE_ERROR_NOT_FOUND));
    return;
  }

  file_system_->Copy(src_file_path, dest_file_path, callback);
}

void GDataFileSystemProxy::Move(const GURL& src_file_url,
    const GURL& dest_file_url,
    const FileSystemOperationInterface::StatusCallback& callback) {
  FilePath src_file_path, dest_file_path;
  if (!ValidateUrl(src_file_url, &src_file_path) ||
      !ValidateUrl(dest_file_url, &dest_file_path)) {
    MessageLoopProxy::current()->PostTask(FROM_HERE,
         base::Bind(callback, base::PLATFORM_FILE_ERROR_NOT_FOUND));
    return;
  }

  file_system_->Move(src_file_path, dest_file_path, callback);
}

void DoNothing(base::PlatformFileError /*error*/,
               int /*bytes_total*/,
               int /*bytes_used*/) {
}

void GDataFileSystemProxy::ReadDirectory(const GURL& file_url,
    const FileSystemOperationInterface::ReadDirectoryCallback& callback) {
  scoped_refptr<base::MessageLoopProxy> proxy =
      base::MessageLoopProxy::current();
  FilePath file_path;
  if (!ValidateUrl(file_url, &file_path)) {
    proxy->PostTask(FROM_HERE,
                    base::Bind(callback,
                               base::PLATFORM_FILE_ERROR_NOT_FOUND,
                               std::vector<base::FileUtilProxy::Entry>(),
                               false));
    return;
  }

  file_system_->FindFileByPathAsync(
      file_path,
      base::Bind(&GDataFileSystemProxy::OnReadDirectory,
                 this,
                 proxy,
                 callback));
}

void GDataFileSystemProxy::Remove(const GURL& file_url, bool recursive,
    const FileSystemOperationInterface::StatusCallback& callback) {
  FilePath file_path;
  if (!ValidateUrl(file_url, &file_path)) {
    MessageLoopProxy::current()->PostTask(FROM_HERE,
         base::Bind(callback, base::PLATFORM_FILE_ERROR_NOT_FOUND));
    return;
  }

  file_system_->Remove(file_path, recursive, callback);
}

void GDataFileSystemProxy::CreateDirectory(
    const GURL& file_url,
    bool exclusive,
    bool recursive,
    const FileSystemOperationInterface::StatusCallback& callback) {
  FilePath file_path;
  if (!ValidateUrl(file_url, &file_path)) {
    MessageLoopProxy::current()->PostTask(FROM_HERE,
         base::Bind(callback, base::PLATFORM_FILE_ERROR_NOT_FOUND));
    return;
  }

  file_system_->CreateDirectory(file_path, exclusive, recursive, callback);
}

void GDataFileSystemProxy::CreateSnapshotFile(
    const GURL& file_url,
    const FileSystemOperationInterface::SnapshotFileCallback& callback) {
  FilePath file_path;
  base::PlatformFileInfo file_info;
  GDataFileProperties file_properties;
  if (!ValidateUrl(file_url, &file_path) ||
      !file_system_->GetFileInfoFromPath(file_path, &file_properties)) {
    MessageLoopProxy::current()->PostTask(FROM_HERE,
         base::Bind(callback,
                    base::PLATFORM_FILE_ERROR_NOT_FOUND,
                    base::PlatformFileInfo(),
                    FilePath(),
                    scoped_refptr<ShareableFileReference>(NULL)));
    return;
  }

  file_system_->GetFile(file_path,
                        base::Bind(&CallSnapshotFileCallback,
                                   callback,
                                   file_properties.file_info));
}

// static.
bool GDataFileSystemProxy::ValidateUrl(const GURL& url, FilePath* file_path) {
  // what platform you're on.
  FilePath raw_path;
  fileapi::FileSystemType type = fileapi::kFileSystemTypeUnknown;
  if (!fileapi::CrackFileSystemURL(url, NULL, &type, file_path) ||
      type != fileapi::kFileSystemTypeExternal) {
    return false;
  }
  return true;
}

void GDataFileSystemProxy::OnGetMetadata(
    const FilePath& file_path,
    scoped_refptr<base::MessageLoopProxy> proxy,
    const FileSystemOperationInterface::GetMetadataCallback& callback,
    base::PlatformFileError error,
    const FilePath& directory_path,
    GDataFileBase* file) {
  if (error != base::PLATFORM_FILE_OK) {
    proxy->PostTask(FROM_HERE,
                    base::Bind(callback,
                               error,
                               base::PlatformFileInfo(),
                               FilePath()));
    return;
  }

  proxy->PostTask(FROM_HERE,
                  base::Bind(callback,
                             base::PLATFORM_FILE_OK,
                             file->file_info(),
                             file_path));
}

void GDataFileSystemProxy::OnReadDirectory(
    scoped_refptr<base::MessageLoopProxy> proxy,
    const FileSystemOperationInterface::ReadDirectoryCallback& callback,
    base::PlatformFileError error,
    const FilePath& directory_path,
    GDataFileBase* file) {
  DCHECK(file);
  GDataDirectory* directory = file->AsGDataDirectory();
  if (!directory)
    error = base::PLATFORM_FILE_ERROR_NOT_A_DIRECTORY;

  if (error != base::PLATFORM_FILE_OK) {
    proxy->PostTask(FROM_HERE,
                    base::Bind(callback,
                               error,
                               std::vector<base::FileUtilProxy::Entry>(),
                               false));
    return;
  }
  std::vector<base::FileUtilProxy::Entry> entries;
  // Convert gdata files to something File API stack can understand.
  for (GDataFileCollection::const_iterator iter =
            directory->children().begin();
       iter != directory->children().end(); ++iter) {
    entries.push_back(GDataFileToFileUtilProxyEntry(*(iter->second)));
  }

  proxy->PostTask(FROM_HERE,
                  base::Bind(callback,
                             base::PLATFORM_FILE_OK,
                             entries,
                             false));
}

}  // namespace gdata
<commit_msg>gdata: Pass an IO-allowed message loop proxy to ShareableFileReference.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/gdata/gdata_file_system_proxy.h"

#include <vector>

#include "base/bind.h"
#include "base/platform_file.h"
#include "base/string_util.h"
#include "base/values.h"
#include "content/public/browser/browser_thread.h"
#include "chrome/browser/chromeos/gdata/gdata_system_service.h"
#include "chrome/browser/chromeos/gdata/gdata_file_system.h"
#include "webkit/blob/shareable_file_reference.h"
#include "webkit/fileapi/file_system_file_util_proxy.h"
#include "webkit/fileapi/file_system_types.h"
#include "webkit/fileapi/file_system_util.h"

using base::MessageLoopProxy;
using content::BrowserThread;
using fileapi::FileSystemOperationInterface;
using webkit_blob::ShareableFileReference;

namespace {

const char kGDataRootDirectory[] = "gdata";
const char kFeedField[] = "feed";

// Helper function to run SnapshotFileCallback from
// GDataFileSystemProxy::CreateSnapshotFile().
void CallSnapshotFileCallback(
    const FileSystemOperationInterface::SnapshotFileCallback& callback,
    base::PlatformFileInfo file_info,
    base::PlatformFileError error,
    const FilePath& local_path,
    const std::string& unused_mime_type,
    gdata::GDataFileType file_type) {
  scoped_refptr<ShareableFileReference> file_ref;

  // If the file is a hosted document, a temporary JSON file is created to
  // represent the document. The JSON file is not cached and its lifetime
  // is managed by ShareableFileReference.
  if (error == base::PLATFORM_FILE_OK && file_type == gdata::HOSTED_DOCUMENT) {
    file_ref = ShareableFileReference::GetOrCreate(
        local_path, ShareableFileReference::DELETE_ON_FINAL_RELEASE,
        BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
  }

  callback.Run(error, file_info, local_path, file_ref);
}

}  // namespace

namespace gdata {

base::FileUtilProxy::Entry GDataFileToFileUtilProxyEntry(
    const GDataFileBase& file) {
  base::FileUtilProxy::Entry entry;
  entry.is_directory = file.file_info().is_directory;

  // TODO(zelidrag): Add file name modification logic to enforce uniquness of
  // file paths across this file system.
  entry.name = file.file_name();

  entry.size = file.file_info().size;
  entry.last_modified_time = file.file_info().last_modified;
  return entry;
}

// GDataFileSystemProxy class implementation.

GDataFileSystemProxy::GDataFileSystemProxy(
    GDataFileSystemInterface* file_system)
    : file_system_(file_system) {
  // Should be created from the file browser extension API (AddMountFunction)
  // on UI thread.
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

GDataFileSystemProxy::~GDataFileSystemProxy() {
  // Should be deleted from the CrosMountPointProvider on IO thread.
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
}

void GDataFileSystemProxy::GetFileInfo(const GURL& file_url,
    const FileSystemOperationInterface::GetMetadataCallback& callback) {
  scoped_refptr<base::MessageLoopProxy> proxy =
      base::MessageLoopProxy::current();
  FilePath file_path;
  if (!ValidateUrl(file_url, &file_path)) {
    proxy->PostTask(FROM_HERE,
                    base::Bind(callback,
                               base::PLATFORM_FILE_ERROR_NOT_FOUND,
                               base::PlatformFileInfo(),
                               FilePath()));
    return;
  }

  file_system_->FindFileByPathAsync(
      file_path,
      base::Bind(&GDataFileSystemProxy::OnGetMetadata,
                 this,
                 file_path,
                 proxy,
                 callback));
}

void GDataFileSystemProxy::Copy(const GURL& src_file_url,
    const GURL& dest_file_url,
    const FileSystemOperationInterface::StatusCallback& callback) {
  FilePath src_file_path, dest_file_path;
  if (!ValidateUrl(src_file_url, &src_file_path) ||
      !ValidateUrl(dest_file_url, &dest_file_path)) {
    MessageLoopProxy::current()->PostTask(FROM_HERE,
         base::Bind(callback, base::PLATFORM_FILE_ERROR_NOT_FOUND));
    return;
  }

  file_system_->Copy(src_file_path, dest_file_path, callback);
}

void GDataFileSystemProxy::Move(const GURL& src_file_url,
    const GURL& dest_file_url,
    const FileSystemOperationInterface::StatusCallback& callback) {
  FilePath src_file_path, dest_file_path;
  if (!ValidateUrl(src_file_url, &src_file_path) ||
      !ValidateUrl(dest_file_url, &dest_file_path)) {
    MessageLoopProxy::current()->PostTask(FROM_HERE,
         base::Bind(callback, base::PLATFORM_FILE_ERROR_NOT_FOUND));
    return;
  }

  file_system_->Move(src_file_path, dest_file_path, callback);
}

void DoNothing(base::PlatformFileError /*error*/,
               int /*bytes_total*/,
               int /*bytes_used*/) {
}

void GDataFileSystemProxy::ReadDirectory(const GURL& file_url,
    const FileSystemOperationInterface::ReadDirectoryCallback& callback) {
  scoped_refptr<base::MessageLoopProxy> proxy =
      base::MessageLoopProxy::current();
  FilePath file_path;
  if (!ValidateUrl(file_url, &file_path)) {
    proxy->PostTask(FROM_HERE,
                    base::Bind(callback,
                               base::PLATFORM_FILE_ERROR_NOT_FOUND,
                               std::vector<base::FileUtilProxy::Entry>(),
                               false));
    return;
  }

  file_system_->FindFileByPathAsync(
      file_path,
      base::Bind(&GDataFileSystemProxy::OnReadDirectory,
                 this,
                 proxy,
                 callback));
}

void GDataFileSystemProxy::Remove(const GURL& file_url, bool recursive,
    const FileSystemOperationInterface::StatusCallback& callback) {
  FilePath file_path;
  if (!ValidateUrl(file_url, &file_path)) {
    MessageLoopProxy::current()->PostTask(FROM_HERE,
         base::Bind(callback, base::PLATFORM_FILE_ERROR_NOT_FOUND));
    return;
  }

  file_system_->Remove(file_path, recursive, callback);
}

void GDataFileSystemProxy::CreateDirectory(
    const GURL& file_url,
    bool exclusive,
    bool recursive,
    const FileSystemOperationInterface::StatusCallback& callback) {
  FilePath file_path;
  if (!ValidateUrl(file_url, &file_path)) {
    MessageLoopProxy::current()->PostTask(FROM_HERE,
         base::Bind(callback, base::PLATFORM_FILE_ERROR_NOT_FOUND));
    return;
  }

  file_system_->CreateDirectory(file_path, exclusive, recursive, callback);
}

void GDataFileSystemProxy::CreateSnapshotFile(
    const GURL& file_url,
    const FileSystemOperationInterface::SnapshotFileCallback& callback) {
  FilePath file_path;
  base::PlatformFileInfo file_info;
  GDataFileProperties file_properties;
  if (!ValidateUrl(file_url, &file_path) ||
      !file_system_->GetFileInfoFromPath(file_path, &file_properties)) {
    MessageLoopProxy::current()->PostTask(FROM_HERE,
         base::Bind(callback,
                    base::PLATFORM_FILE_ERROR_NOT_FOUND,
                    base::PlatformFileInfo(),
                    FilePath(),
                    scoped_refptr<ShareableFileReference>(NULL)));
    return;
  }

  file_system_->GetFile(file_path,
                        base::Bind(&CallSnapshotFileCallback,
                                   callback,
                                   file_properties.file_info));
}

// static.
bool GDataFileSystemProxy::ValidateUrl(const GURL& url, FilePath* file_path) {
  // what platform you're on.
  FilePath raw_path;
  fileapi::FileSystemType type = fileapi::kFileSystemTypeUnknown;
  if (!fileapi::CrackFileSystemURL(url, NULL, &type, file_path) ||
      type != fileapi::kFileSystemTypeExternal) {
    return false;
  }
  return true;
}

void GDataFileSystemProxy::OnGetMetadata(
    const FilePath& file_path,
    scoped_refptr<base::MessageLoopProxy> proxy,
    const FileSystemOperationInterface::GetMetadataCallback& callback,
    base::PlatformFileError error,
    const FilePath& directory_path,
    GDataFileBase* file) {
  if (error != base::PLATFORM_FILE_OK) {
    proxy->PostTask(FROM_HERE,
                    base::Bind(callback,
                               error,
                               base::PlatformFileInfo(),
                               FilePath()));
    return;
  }

  proxy->PostTask(FROM_HERE,
                  base::Bind(callback,
                             base::PLATFORM_FILE_OK,
                             file->file_info(),
                             file_path));
}

void GDataFileSystemProxy::OnReadDirectory(
    scoped_refptr<base::MessageLoopProxy> proxy,
    const FileSystemOperationInterface::ReadDirectoryCallback& callback,
    base::PlatformFileError error,
    const FilePath& directory_path,
    GDataFileBase* file) {
  DCHECK(file);
  GDataDirectory* directory = file->AsGDataDirectory();
  if (!directory)
    error = base::PLATFORM_FILE_ERROR_NOT_A_DIRECTORY;

  if (error != base::PLATFORM_FILE_OK) {
    proxy->PostTask(FROM_HERE,
                    base::Bind(callback,
                               error,
                               std::vector<base::FileUtilProxy::Entry>(),
                               false));
    return;
  }
  std::vector<base::FileUtilProxy::Entry> entries;
  // Convert gdata files to something File API stack can understand.
  for (GDataFileCollection::const_iterator iter =
            directory->children().begin();
       iter != directory->children().end(); ++iter) {
    entries.push_back(GDataFileToFileUtilProxyEntry(*(iter->second)));
  }

  proxy->PostTask(FROM_HERE,
                  base::Bind(callback,
                             base::PLATFORM_FILE_OK,
                             entries,
                             false));
}

}  // namespace gdata
<|endoftext|>


<commit_before>/**
  @file main.cpp
*/
#include "ktx.h"
#include <TextureConverter.h>
#include <FreeImage.h>
#include <stdio.h>
#include <string>
#include <iostream>

void PrintUsage() {
  std::cout << "ATCConv ver.0.1" << std::endl;
  std::cout << "Convert PNG(24/32bit) image to KTX(ATC/ETC1 compressed format) image." << std::endl;
  std::cout << std::endl;
  std::cout << "usage: atcconv.exe [infile] [outfile]" << std::endl;
  std::cout << std::endl;
  std::cout << "  infile : input PNG(24/32bit) file path." << std::endl;
  std::cout << "  outfile: output KTX file path." << std::endl;
  std::cout << "           if not passed this option, use the infile that has replaced" << std::endl;
  std::cout << "           extention ot '.ktx'." << std::endl;
}

uint32_t GetBytePerPixel(uint32_t format) {
  switch (format) {
  case Q_FORMAT_RGB_8I: return 3;
  default:
  case Q_FORMAT_RGBA_8I: return 4;
  }
}

TQonvertImage TQonvertImage_Create( void* data, uint32_t w, uint32_t h, uint32_t format = Q_FORMAT_RGBA_8I) {
  TQonvertImage n;
  n.nWidth = w;
  n.nHeight = h;
  n.nFormat = format;
  n.pFormatFlags = nullptr;
  n.nDataSize = data ? w * h * GetBytePerPixel(format) : 0;
  n.pData = reinterpret_cast<unsigned char*>(data);
  n.compressionOptions = nullptr;
  return n;
}

int main(int argc, char** argv) {
  std::string infilename;
  std::string outfilename;
  for (int i = 1; i < argc; ++i) {
	if (infilename.empty()) {
	  infilename = argv[i];
	} else if (outfilename.empty()) {
	  outfilename = argv[i];
	  break;
	}
  }
  if (infilename.empty()) {
	PrintUsage();
	return 0;
  }
  if (outfilename.empty()) {
	outfilename = infilename;
	auto dotPos = outfilename.find_last_of('.');
	if (dotPos != std::string::npos) {
	  outfilename.erase(dotPos, std::string::npos);
	}
	outfilename += ".ktx";
  }

#ifdef FREE_IMAGE_STATIC_LIBRARY
  FreeImage_Initialise(FALSE);
#endif // FREE_ISTATIC_LIBRARY

  FIBITMAP* dib = FreeImage_Load(FIF_PNG, infilename.c_str(), PNG_DEFAULT);
  if (!dib) {
	std::cout << "Can't read '" << infilename << "'." << std::endl;
	return 1;
  }

  const uint32_t width = FreeImage_GetWidth(dib);
  const uint32_t height = FreeImage_GetHeight(dib);
  const uint32_t bitPerPixel = FreeImage_GetBPP(dib);
  const uint32_t destFormat = bitPerPixel == 32 ? Q_FORMAT_ATC_RGBA_INTERPOLATED_ALPHA : Q_FORMAT_ETC1_RGB8;

  TQonvertImage  src = TQonvertImage_Create(FreeImage_GetBits(dib), width, height);
  TQonvertImage  dest = TQonvertImage_Create(nullptr, width, height, destFormat);
  std::vector<uint8_t> buf;
  buf.resize(width * height * 4, 0);
  dest.nDataSize = buf.size();
  dest.pData = &buf[0];
  {
    const int result = Qonvert(&src, &dest);
    if (result != Q_SUCCESS) {
	  std::cout << "Can't convert '" << infilename << "'." << std::endl;
	  FreeImage_Unload(dib);
	  return 2;
    }
  }
  FreeImage_Unload(dib);

  KTX::Header ktxheader;
  KTX::initialize(&ktxheader, width, height, bitPerPixel, bitPerPixel == 32 ? KTX::Format_ATC_I : KTX::Format_ETC1);
  FILE* fp;
  {
	const errno_t result = fopen_s(&fp, outfilename.c_str(), "wb");
	if (result != 0) {
	  std::cout << "Can't open '" << outfilename << std::endl;
	  return 3;
	}
  }
  fwrite(&ktxheader, 1, sizeof(KTX::Header), fp);
  fwrite(&dest.nDataSize, 1, 4, fp);
  fwrite(dest.pData, 1, dest.nDataSize, fp);
  fclose(fp);

#ifdef FREE_IMAGE_STATIC_LIBRARY
  FreeImage_Deinitialise();
#endif // FREE_ISTATIC_LIBRARY
}
<commit_msg>Add the description commnet to each functions.<commit_after>/**
  @file main.cpp
*/
#include "ktx.h"
#include <TextureConverter.h>
#include <FreeImage.h>
#include <stdio.h>
#include <string>
#include <iostream>

/** Print the program usage.
*/
void PrintUsage() {
  std::cout << "ATCConv ver.0.1" << std::endl;
  std::cout << "Convert PNG(24/32bit) image to KTX(ATC/ETC1 compressed format) image." << std::endl;
  std::cout << std::endl;
  std::cout << "usage: atcconv.exe [infile] [outfile]" << std::endl;
  std::cout << std::endl;
  std::cout << "  infile : input PNG(24/32bit) file path." << std::endl;
  std::cout << "  outfile: output KTX file path." << std::endl;
  std::cout << "           if not passed this option, use the infile that has replaced" << std::endl;
  std::cout << "           extention ot '.ktx'." << std::endl;
}

/** Get bytes per pixel from the format.

  @param format Q_FORMAT_???

  @return byte per pixel.
*/
uint32_t GetBytePerPixel(uint32_t format) {
  switch (format) {
  case Q_FORMAT_RGB_8I: return 3;
  default:
  case Q_FORMAT_RGBA_8I: return 4;
  }
}

/** Create TQonvertImage structure.

  @param data    the pointer to the raw image data.
  @param w       the pixel width of the image.
  @param h       the pixel height of the image.
  @param foramt  Q_FORMAT_???

  @return TQonvertImage object created with the parameter.
*/
TQonvertImage TQonvertImage_Create( void* data, uint32_t w, uint32_t h, uint32_t format = Q_FORMAT_RGBA_8I) {
  TQonvertImage n;
  n.nWidth = w;
  n.nHeight = h;
  n.nFormat = format;
  n.pFormatFlags = nullptr;
  n.nDataSize = data ? w * h * GetBytePerPixel(format) : 0;
  n.pData = reinterpret_cast<unsigned char*>(data);
  n.compressionOptions = nullptr;
  return n;
}

/** The entry point.
*/
int main(int argc, char** argv) {
  std::string infilename;
  std::string outfilename;
  for (int i = 1; i < argc; ++i) {
	if (infilename.empty()) {
	  infilename = argv[i];
	} else if (outfilename.empty()) {
	  outfilename = argv[i];
	  break;
	}
  }
  if (infilename.empty()) {
	PrintUsage();
	return 0;
  }
  if (outfilename.empty()) {
	outfilename = infilename;
	auto dotPos = outfilename.find_last_of('.');
	if (dotPos != std::string::npos) {
	  outfilename.erase(dotPos, std::string::npos);
	}
	outfilename += ".ktx";
  }

#ifdef FREE_IMAGE_STATIC_LIBRARY
  FreeImage_Initialise(FALSE);
#endif // FREE_ISTATIC_LIBRARY

  FIBITMAP* dib = FreeImage_Load(FIF_PNG, infilename.c_str(), PNG_DEFAULT);
  if (!dib) {
	std::cout << "Can't read '" << infilename << "'." << std::endl;
	return 1;
  }

  const uint32_t width = FreeImage_GetWidth(dib);
  const uint32_t height = FreeImage_GetHeight(dib);
  const uint32_t bitPerPixel = FreeImage_GetBPP(dib);
  const uint32_t destFormat = bitPerPixel == 32 ? Q_FORMAT_ATC_RGBA_INTERPOLATED_ALPHA : Q_FORMAT_ETC1_RGB8;

  TQonvertImage  src = TQonvertImage_Create(FreeImage_GetBits(dib), width, height);
  TQonvertImage  dest = TQonvertImage_Create(nullptr, width, height, destFormat);
  std::vector<uint8_t> buf;
  buf.resize(width * height * 4, 0);
  dest.nDataSize = static_cast<unsigned int>(buf.size());
  dest.pData = &buf[0];
  {
    const int result = Qonvert(&src, &dest);
    if (result != Q_SUCCESS) {
	  std::cout << "Can't convert '" << infilename << "'." << std::endl;
	  FreeImage_Unload(dib);
	  return 2;
    }
  }
  FreeImage_Unload(dib);

  KTX::Header ktxheader;
  KTX::initialize(&ktxheader, width, height, bitPerPixel, bitPerPixel == 32 ? KTX::Format_ATC_I : KTX::Format_ETC1);
  FILE* fp;
  {
	const errno_t result = fopen_s(&fp, outfilename.c_str(), "wb");
	if (result != 0) {
	  std::cout << "Can't open '" << outfilename << std::endl;
	  return 3;
	}
  }
  fwrite(&ktxheader, 1, sizeof(KTX::Header), fp);
  fwrite(&dest.nDataSize, 1, 4, fp);
  fwrite(dest.pData, 1, dest.nDataSize, fp);
  fclose(fp);

#ifdef FREE_IMAGE_STATIC_LIBRARY
  FreeImage_Deinitialise();
#endif // FREE_ISTATIC_LIBRARY
}
<|endoftext|>


<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __RAPICORN_CXXAUX_HH__
#define __RAPICORN_CXXAUX_HH__

#include <rcore/rapicornconfig.h>       // _GNU_SOURCE
#include <stdbool.h>
#include <stdarg.h>
#include <stddef.h>			// NULL
#include <sys/types.h>			// uint, ssize
#include <stdint.h>			// uint64_t
#include <limits.h>                     // {INT|CHAR|...}_{MIN|MAX}
#include <float.h>                      // {FLT|DBL}_{MIN|MAX|EPSILON}

// == Standard Macros ==
#ifndef FALSE
#  define FALSE					false
#endif
#ifndef TRUE
#  define TRUE					true
#endif
#define RAPICORN_ABS(a)                       	((a) > -(a) ? (a) : -(a))
#define RAPICORN_MIN(a,b)                         ((a) <= (b) ? (a) : (b))
#define RAPICORN_MAX(a,b)                         ((a) >= (b) ? (a) : (b))
#define RAPICORN_CLAMP(v,mi,ma)                   ((v) < (mi) ? (mi) : ((v) > (ma) ? (ma) : (v)))
#define RAPICORN_ARRAY_SIZE(array)		(sizeof (array) / sizeof ((array)[0]))
#undef ABS
#define ABS                                     RAPICORN_ABS
#undef MIN
#define MIN                                     RAPICORN_MIN
#undef MAX
#define MAX                                     RAPICORN_MAX
#undef CLAMP
#define CLAMP                                   RAPICORN_CLAMP
#undef ARRAY_SIZE
#define ARRAY_SIZE				RAPICORN_ARRAY_SIZE
#undef EXTERN_C
#ifdef	__cplusplus
#define EXTERN_C                                extern "C"
#else
#define EXTERN_C                                extern
#endif
#undef STRFUNC
#define STRFUNC				        RAPICORN_SIMPLE_FUNCTION
#if     !defined (INT64_MAX) || !defined (INT64_MIN) || !defined (UINT64_MAX)
#ifdef  LLONG_MAX       // some gcc versions ship limits.h that fail to define LLONG_MAX for C99
#  define INT64_MAX     LLONG_MAX       // +9223372036854775807LL
#  define INT64_MIN     LLONG_MIN       // -9223372036854775808LL
#  define UINT64_MAX    ULLONG_MAX      // +18446744073709551615LLU
#else   // !LLONG_MAX but gcc always has __LONG_LONG_MAX__
#  define INT64_MAX     __LONG_LONG_MAX__
#  define INT64_MIN     (-INT64_MAX - 1LL)
#  define UINT64_MAX    (INT64_MAX * 2ULL + 1ULL)
#endif
#endif
#ifndef SIZE_T_MAX
#define SIZE_T_MAX              (~size_t (0))
#define SSIZE_T_MAX             (ssize_t (SIZE_T_MAX / 2))
#endif

// == Likelyness Hinting ==
#define	RAPICORN__BOOL(expr)		__extension__ ({ bool _rapicorn__bool; if (expr) _rapicorn__bool = 1; else _rapicorn__bool = 0; _rapicorn__bool; })
#define	RAPICORN_ISLIKELY(expr)		__builtin_expect (RAPICORN__BOOL (expr), 1)
#define	RAPICORN_UNLIKELY(expr)		__builtin_expect (RAPICORN__BOOL (expr), 0)
#define	RAPICORN_LIKELY			RAPICORN_ISLIKELY

// == Convenience Macros ==
#ifdef  RAPICORN_CONVENIENCE
#define	ISLIKELY		RAPICORN_ISLIKELY       ///< Compiler hint that @a expression is likely to be true.
#define	UNLIKELY		RAPICORN_UNLIKELY       ///< Compiler hint that @a expression is unlikely to be true.
#define	LIKELY			RAPICORN_LIKELY         ///< Compiler hint that @a expression is likely to be true.
#define	STRINGIFY               RAPICORN_CPP_STRINGIFY  ///< Produces a const char C string from the macro @a argument.
#endif
/**
 * @def RAPICORN_CONVENIENCE
 * Configuration macro to enable convenience macros.
 * Defining this before inclusion of rapicorn.hh or rapicorn-core.hh enables several convenience
 * macros that are defined in the global namespace without the usual "RAPICORN_" prefix,
 * see e.g. critical_unless(), UNLIKELY().
 */
#ifdef  RAPICORN_DOXYGEN
#  define RAPICORN_CONVENIENCE
#endif // RAPICORN_DOXYGEN

// == Preprocessor Convenience ==
#define RAPICORN_CPP_PASTE2_(a,b)               a ## b  // indirection required to expand macros like __LINE__
#define RAPICORN_CPP_PASTE2(a,b)                RAPICORN_CPP_PASTE2_ (a,b)
#define RAPICORN_CPP_STRINGIFY_(s)              #s      // indirection required to expand macros like __LINE__
#define RAPICORN_CPP_STRINGIFY(s)               RAPICORN_CPP_STRINGIFY_ (s)
#define RAPICORN_STATIC_ASSERT(expr)            static_assert (expr, #expr)

// == GCC Attributes ==
#if     __GNUC__ >= 4
#define RAPICORN_PURE                           __attribute__ ((__pure__))
#define RAPICORN_MALLOC                         __attribute__ ((__malloc__))
#define RAPICORN_PRINTF(format_idx, arg_idx)    __attribute__ ((__format__ (__printf__, format_idx, arg_idx)))
#define RAPICORN_SCANF(format_idx, arg_idx)     __attribute__ ((__format__ (__scanf__, format_idx, arg_idx)))
#define RAPICORN_FORMAT(arg_idx)                __attribute__ ((__format_arg__ (arg_idx)))
#define RAPICORN_SENTINEL                       __attribute__ ((__sentinel__))
#define RAPICORN_NORETURN                       __attribute__ ((__noreturn__))
#define RAPICORN_CONST                          __attribute__ ((__const__))
#define RAPICORN_UNUSED                         __attribute__ ((__unused__))
#define RAPICORN_NO_INSTRUMENT                  __attribute__ ((__no_instrument_function__))
#define RAPICORN_DEPRECATED                     __attribute__ ((__deprecated__))
#define RAPICORN_ALWAYS_INLINE			__attribute__ ((always_inline))
#define RAPICORN_NEVER_INLINE			__attribute__ ((noinline))
#define RAPICORN_CONSTRUCTOR			__attribute__ ((constructor,used))      // gcc-3.3 also needs "used" to emit code
#define RAPICORN_MAY_ALIAS                      __attribute__ ((may_alias))
#define	RAPICORN_SIMPLE_FUNCTION	       (::Rapicorn::string_from_pretty_function_name (__PRETTY_FUNCTION__).c_str())
#else   // !__GNUC__
#define RAPICORN_PURE
#define RAPICORN_MALLOC
#define RAPICORN_PRINTF(format_idx, arg_idx)
#define RAPICORN_SCANF(format_idx, arg_idx)
#define RAPICORN_FORMAT(arg_idx)
#define RAPICORN_SENTINEL
#define RAPICORN_NORETURN
#define RAPICORN_CONST
#define RAPICORN_UNUSED
#define RAPICORN_NO_INSTRUMENT
#define RAPICORN_DEPRECATED
#define RAPICORN_ALWAYS_INLINE
#define RAPICORN_NEVER_INLINE
#define RAPICORN_CONSTRUCTOR
#define RAPICORN_MAY_ALIAS
#define	RAPICORN_SIMPLE_FUNCTION	       (__func__)
#error  Failed to detect a recent GCC version (>= 4)
#endif  // !__GNUC__

// == Ensure 'uint' in global namespace ==
#if 	RAPICORN_SIZEOF_SYS_TYPESH_UINT == 0
typedef unsigned int		uint;           // for systems that don't define uint in sys/types.h
#else
RAPICORN_STATIC_ASSERT (RAPICORN_SIZEOF_SYS_TYPESH_UINT == 4);
#endif
RAPICORN_STATIC_ASSERT (sizeof (uint) == 4);

// == Rapicorn Namespace ==
namespace Rapicorn {

// == Provide Canonical Integer Types ==
typedef uint8_t                 uint8;          ///< An 8-bit unsigned integer.
typedef uint16_t                uint16;         ///< A 16-bit unsigned integer.
typedef uint32_t                uint32;         ///< A 32-bit unsigned integer.
typedef unsigned long long int  uint64;         ///< A 64-bit unsigned integer, use "%llu" in format strings.
// typedef uint64_t             uint64;         // int64_t / uint64_t are longs on AMD64 which breaks printf
typedef int8_t                  int8;           ///< An 8-bit signed integer.
typedef int16_t                 int16;          ///< A 16-bit signed integer.
typedef int32_t                 int32;          ///< A 32-bit signed integer.
typedef signed long long int    int64;          ///< A 64-bit unsigned integer, use "%lld" in format strings.
typedef uint32_t                unichar;        ///< A 32-bit unsigned integer used for Unicode characters.
RAPICORN_STATIC_ASSERT (sizeof (uint8) == 1 && sizeof (uint16) == 2 && sizeof (uint32) == 4 && sizeof (uint64) == 8);
RAPICORN_STATIC_ASSERT (sizeof (int8)  == 1 && sizeof (int16)  == 2 && sizeof (int32)  == 4 && sizeof (int64)  == 8);
RAPICORN_STATIC_ASSERT (sizeof (int) == 4 && sizeof (uint) == 4 && sizeof (unichar) == 4);

// == File Path Handling ==
#ifdef	RAPICORN_OS_WIN32
#define RAPICORN_DIR_SEPARATOR		  '\\'
#define RAPICORN_DIR_SEPARATOR_S	  "\\"
#define RAPICORN_SEARCHPATH_SEPARATOR	  ';'
#define RAPICORN_SEARCHPATH_SEPARATOR_S	  ";"
#else   // !RAPICORN_OS_WIN32
#define RAPICORN_DIR_SEPARATOR		  '/'
#define RAPICORN_DIR_SEPARATOR_S	  "/"
#define RAPICORN_SEARCHPATH_SEPARATOR	  ':'
#define RAPICORN_SEARCHPATH_SEPARATOR_S	  ":"
#endif  // !RAPICORN_OS_WIN32
#define	RAPICORN_IS_DIR_SEPARATOR(c)        (RAPICORN_DIR_SEPARATOR == (c))
#define RAPICORN_IS_SEARCHPATH_SEPARATOR(c) (RAPICORN_SEARCHPATH_SEPARATOR == (c))

// == C++ Macros ==
#define RAPICORN_CLASS_NON_COPYABLE(ClassName)                                  private: \
  /*copy-ctor*/ ClassName  (const ClassName&) __attribute__ ((error ("NON_COPYABLE"))); \
  ClassName&    operator=  (const ClassName&) __attribute__ ((error ("NON_COPYABLE")))

// == X86 Architecture ==
#if defined __i386__ || defined __x86_64__
#define RAPICORN_HAVE_X86_RDTSC  1
#define RAPICORN_X86_RDTSC()     ({ Rapicorn::uint32 __l_, __h_, __s_; \
                                    __asm__ __volatile__ ("rdtsc" : "=a" (__l_), "=d" (__h_));  \
                                    __s_ = __l_ + (Rapicorn::uint64 (__h_) << 32); __s_; })
#else
#define RAPICORN_HAVE_X86_RDTSC  0
#define RAPICORN_X86_RDTSC()    (0)
#endif

} // Rapicorn

#endif // __RAPICORN_CXXAUX_HH__
<commit_msg>RCORE: add helper class to call one-line lambda initializers as static ctor<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __RAPICORN_CXXAUX_HH__
#define __RAPICORN_CXXAUX_HH__

#include <rcore/rapicornconfig.h>       // _GNU_SOURCE
#include <stdbool.h>
#include <stdarg.h>
#include <stddef.h>			// NULL
#include <sys/types.h>			// uint, ssize
#include <stdint.h>			// uint64_t
#include <limits.h>                     // {INT|CHAR|...}_{MIN|MAX}
#include <float.h>                      // {FLT|DBL}_{MIN|MAX|EPSILON}

// == Standard Macros ==
#ifndef FALSE
#  define FALSE					false
#endif
#ifndef TRUE
#  define TRUE					true
#endif
#define RAPICORN_ABS(a)                       	((a) > -(a) ? (a) : -(a))
#define RAPICORN_MIN(a,b)                         ((a) <= (b) ? (a) : (b))
#define RAPICORN_MAX(a,b)                         ((a) >= (b) ? (a) : (b))
#define RAPICORN_CLAMP(v,mi,ma)                   ((v) < (mi) ? (mi) : ((v) > (ma) ? (ma) : (v)))
#define RAPICORN_ARRAY_SIZE(array)		(sizeof (array) / sizeof ((array)[0]))
#undef ABS
#define ABS                                     RAPICORN_ABS
#undef MIN
#define MIN                                     RAPICORN_MIN
#undef MAX
#define MAX                                     RAPICORN_MAX
#undef CLAMP
#define CLAMP                                   RAPICORN_CLAMP
#undef ARRAY_SIZE
#define ARRAY_SIZE				RAPICORN_ARRAY_SIZE
#undef EXTERN_C
#ifdef	__cplusplus
#define EXTERN_C                                extern "C"
#else
#define EXTERN_C                                extern
#endif
#undef STRFUNC
#define STRFUNC				        RAPICORN_SIMPLE_FUNCTION
#if     !defined (INT64_MAX) || !defined (INT64_MIN) || !defined (UINT64_MAX)
#ifdef  LLONG_MAX       // some gcc versions ship limits.h that fail to define LLONG_MAX for C99
#  define INT64_MAX     LLONG_MAX       // +9223372036854775807LL
#  define INT64_MIN     LLONG_MIN       // -9223372036854775808LL
#  define UINT64_MAX    ULLONG_MAX      // +18446744073709551615LLU
#else   // !LLONG_MAX but gcc always has __LONG_LONG_MAX__
#  define INT64_MAX     __LONG_LONG_MAX__
#  define INT64_MIN     (-INT64_MAX - 1LL)
#  define UINT64_MAX    (INT64_MAX * 2ULL + 1ULL)
#endif
#endif
#ifndef SIZE_T_MAX
#define SIZE_T_MAX              (~size_t (0))
#define SSIZE_T_MAX             (ssize_t (SIZE_T_MAX / 2))
#endif

// == Likelyness Hinting ==
#define	RAPICORN__BOOL(expr)		__extension__ ({ bool _rapicorn__bool; if (expr) _rapicorn__bool = 1; else _rapicorn__bool = 0; _rapicorn__bool; })
#define	RAPICORN_ISLIKELY(expr)		__builtin_expect (RAPICORN__BOOL (expr), 1)
#define	RAPICORN_UNLIKELY(expr)		__builtin_expect (RAPICORN__BOOL (expr), 0)
#define	RAPICORN_LIKELY			RAPICORN_ISLIKELY

// == Convenience Macros ==
#ifdef  RAPICORN_CONVENIENCE
#define	ISLIKELY		RAPICORN_ISLIKELY       ///< Compiler hint that @a expression is likely to be true.
#define	UNLIKELY		RAPICORN_UNLIKELY       ///< Compiler hint that @a expression is unlikely to be true.
#define	LIKELY			RAPICORN_LIKELY         ///< Compiler hint that @a expression is likely to be true.
#define	STRINGIFY               RAPICORN_CPP_STRINGIFY  ///< Produces a const char C string from the macro @a argument.
#endif
/**
 * @def RAPICORN_CONVENIENCE
 * Configuration macro to enable convenience macros.
 * Defining this before inclusion of rapicorn.hh or rapicorn-core.hh enables several convenience
 * macros that are defined in the global namespace without the usual "RAPICORN_" prefix,
 * see e.g. critical_unless(), UNLIKELY().
 */
#ifdef  RAPICORN_DOXYGEN
#  define RAPICORN_CONVENIENCE
#endif // RAPICORN_DOXYGEN

// == Preprocessor Convenience ==
#define RAPICORN_CPP_PASTE2_(a,b)               a ## b  // indirection required to expand macros like __LINE__
#define RAPICORN_CPP_PASTE2(a,b)                RAPICORN_CPP_PASTE2_ (a,b)
#define RAPICORN_CPP_STRINGIFY_(s)              #s      // indirection required to expand macros like __LINE__
#define RAPICORN_CPP_STRINGIFY(s)               RAPICORN_CPP_STRINGIFY_ (s)
#define RAPICORN_STATIC_ASSERT(expr)            static_assert (expr, #expr)

// == GCC Attributes ==
#if     __GNUC__ >= 4
#define RAPICORN_PURE                           __attribute__ ((__pure__))
#define RAPICORN_MALLOC                         __attribute__ ((__malloc__))
#define RAPICORN_PRINTF(format_idx, arg_idx)    __attribute__ ((__format__ (__printf__, format_idx, arg_idx)))
#define RAPICORN_SCANF(format_idx, arg_idx)     __attribute__ ((__format__ (__scanf__, format_idx, arg_idx)))
#define RAPICORN_FORMAT(arg_idx)                __attribute__ ((__format_arg__ (arg_idx)))
#define RAPICORN_SENTINEL                       __attribute__ ((__sentinel__))
#define RAPICORN_NORETURN                       __attribute__ ((__noreturn__))
#define RAPICORN_CONST                          __attribute__ ((__const__))
#define RAPICORN_UNUSED                         __attribute__ ((__unused__))
#define RAPICORN_NO_INSTRUMENT                  __attribute__ ((__no_instrument_function__))
#define RAPICORN_DEPRECATED                     __attribute__ ((__deprecated__))
#define RAPICORN_ALWAYS_INLINE			__attribute__ ((always_inline))
#define RAPICORN_NEVER_INLINE			__attribute__ ((noinline))
#define RAPICORN_CONSTRUCTOR			__attribute__ ((constructor,used))      // gcc-3.3 also needs "used" to emit code
#define RAPICORN_MAY_ALIAS                      __attribute__ ((may_alias))
#define	RAPICORN_SIMPLE_FUNCTION	       (::Rapicorn::string_from_pretty_function_name (__PRETTY_FUNCTION__).c_str())
#else   // !__GNUC__
#define RAPICORN_PURE
#define RAPICORN_MALLOC
#define RAPICORN_PRINTF(format_idx, arg_idx)
#define RAPICORN_SCANF(format_idx, arg_idx)
#define RAPICORN_FORMAT(arg_idx)
#define RAPICORN_SENTINEL
#define RAPICORN_NORETURN
#define RAPICORN_CONST
#define RAPICORN_UNUSED
#define RAPICORN_NO_INSTRUMENT
#define RAPICORN_DEPRECATED
#define RAPICORN_ALWAYS_INLINE
#define RAPICORN_NEVER_INLINE
#define RAPICORN_CONSTRUCTOR
#define RAPICORN_MAY_ALIAS
#define	RAPICORN_SIMPLE_FUNCTION	       (__func__)
#error  Failed to detect a recent GCC version (>= 4)
#endif  // !__GNUC__

// == Ensure 'uint' in global namespace ==
#if 	RAPICORN_SIZEOF_SYS_TYPESH_UINT == 0
typedef unsigned int		uint;           // for systems that don't define uint in sys/types.h
#else
RAPICORN_STATIC_ASSERT (RAPICORN_SIZEOF_SYS_TYPESH_UINT == 4);
#endif
RAPICORN_STATIC_ASSERT (sizeof (uint) == 4);

// == Rapicorn Namespace ==
namespace Rapicorn {

// == Provide Canonical Integer Types ==
typedef uint8_t                 uint8;          ///< An 8-bit unsigned integer.
typedef uint16_t                uint16;         ///< A 16-bit unsigned integer.
typedef uint32_t                uint32;         ///< A 32-bit unsigned integer.
typedef unsigned long long int  uint64;         ///< A 64-bit unsigned integer, use "%llu" in format strings.
// typedef uint64_t             uint64;         // int64_t / uint64_t are longs on AMD64 which breaks printf
typedef int8_t                  int8;           ///< An 8-bit signed integer.
typedef int16_t                 int16;          ///< A 16-bit signed integer.
typedef int32_t                 int32;          ///< A 32-bit signed integer.
typedef signed long long int    int64;          ///< A 64-bit unsigned integer, use "%lld" in format strings.
typedef uint32_t                unichar;        ///< A 32-bit unsigned integer used for Unicode characters.
RAPICORN_STATIC_ASSERT (sizeof (uint8) == 1 && sizeof (uint16) == 2 && sizeof (uint32) == 4 && sizeof (uint64) == 8);
RAPICORN_STATIC_ASSERT (sizeof (int8)  == 1 && sizeof (int16)  == 2 && sizeof (int32)  == 4 && sizeof (int64)  == 8);
RAPICORN_STATIC_ASSERT (sizeof (int) == 4 && sizeof (uint) == 4 && sizeof (unichar) == 4);

// == File Path Handling ==
#ifdef	RAPICORN_OS_WIN32
#define RAPICORN_DIR_SEPARATOR		  '\\'
#define RAPICORN_DIR_SEPARATOR_S	  "\\"
#define RAPICORN_SEARCHPATH_SEPARATOR	  ';'
#define RAPICORN_SEARCHPATH_SEPARATOR_S	  ";"
#else   // !RAPICORN_OS_WIN32
#define RAPICORN_DIR_SEPARATOR		  '/'
#define RAPICORN_DIR_SEPARATOR_S	  "/"
#define RAPICORN_SEARCHPATH_SEPARATOR	  ':'
#define RAPICORN_SEARCHPATH_SEPARATOR_S	  ":"
#endif  // !RAPICORN_OS_WIN32
#define	RAPICORN_IS_DIR_SEPARATOR(c)        (RAPICORN_DIR_SEPARATOR == (c))
#define RAPICORN_IS_SEARCHPATH_SEPARATOR(c) (RAPICORN_SEARCHPATH_SEPARATOR == (c))

// == C++ Macros ==
#define RAPICORN_CLASS_NON_COPYABLE(ClassName)                                  private: \
  /*copy-ctor*/ ClassName  (const ClassName&) __attribute__ ((error ("NON_COPYABLE"))); \
  ClassName&    operator=  (const ClassName&) __attribute__ ((error ("NON_COPYABLE")))

// == C++ Helper Classes ==
/// Simple helper class to call one-line lambda initializers as static constructor.
struct Init {
  explicit Init (void (*f) ()) { f(); }
};

// == X86 Architecture ==
#if defined __i386__ || defined __x86_64__
#define RAPICORN_HAVE_X86_RDTSC  1
#define RAPICORN_X86_RDTSC()     ({ Rapicorn::uint32 __l_, __h_, __s_; \
                                    __asm__ __volatile__ ("rdtsc" : "=a" (__l_), "=d" (__h_));  \
                                    __s_ = __l_ + (Rapicorn::uint64 (__h_) << 32); __s_; })
#else
#define RAPICORN_HAVE_X86_RDTSC  0
#define RAPICORN_X86_RDTSC()    (0)
#endif

} // Rapicorn

#endif // __RAPICORN_CXXAUX_HH__
<|endoftext|>


<commit_before>// Terminal.cpp -- source file
/*
 *
 * Author: septimomend (Ivan Chapkailo)
 *
 * 30.06.2017
 *
 */

#include "stdafx.h"
#include "Terminal.h"

Terminal::Terminal() // cstr
{
}

/*
 * 0 - STDIN_FILENO - standard input descriptor
 * 1 - STDOUT_FILENO - standard output descriptor
 * 2 - STDERR_FILENO - standard errors output descriptor
 */

void Terminal::emergencyDestruction(const char* str)
{
  write(STDOUT_FILENO, "\x1b[2J", 4); // write clr code to file
  write(STDOUT_FILENO, "\x1b[H", 3);

  perror(str);
  exit(1);  // exit with error
}

void Terminal::rowModeOff()
{
  AllControllers all;
  ConfigurationController* configObj = all.getConfigObj();
  struct termios* termObj = configObj->getTermios();

  // the change will occur after all output written to STDIN_FILENO is transmitted,
  // and all input so far received but not read will be discarded before the change is made
  if (tcsetattr(STDIN_FILENO, TCSAFLUSH, termObj) == -1)
    emergencyDestruction("tcsetattr");
}

void Terminal::rowModeOn()
{
  AllControllers all;
  ConfigurationController* configObj = all.getConfigObj();
  struct termios* termObj = configObj->getTermios();

  if (tcgetattr(STDIN_FILENO, termObj) == -1)
    emergencyDestruction("tcgetattr");
  atexit(rowModeOff);

  struct termios raw = *termObj;
  // setting flags
  //
  raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
  raw.c_oflag &= ~(OPOST); // Post-process output
  raw.c_cflag |= (CS8); // Character size 8 bits
  raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
  raw.c_cc[VMIN] = 0;
  raw.c_cc[VTIME] = 1;
}

int Terminal::whatKey() // defines key pressing
{
  int countRD;
  char c;
  while ((countRD = read(STDIN_FILENO, &c, 1)) != 1)  // read 1 byte from input device and write to c
  {
    if (countRD == -1 && errno != EAGAIN)
      emergencyDestruction("read");
  }

  if (c == '\x1b') // if this is the escape key
  {
    char sequence[3];

    if (read(STDIN_FILENO, &sequence[0], 1) != 1) // if no errors
      return '\x1b';
    if (read(STDIN_FILENO, &sequence[1], 1) != 1)
      return '\x1b';

    // this is escape-sequence
    //          \x1b[...m
    // where ... is numbers of parameters
    // more on https://en.wikipedia.org/wiki/Escape_sequences_in_C
    //
    if (sequence[0] == '[')
    {
      if (sequence[1] >= '0' && sequence[1] <= '9')
      {
        if (read(STDIN_FILENO, &sequence[2], 1) != 1)
          return '\x1b'; // if escape calls 3rd time - exit
        if (sequence[2] == '~')
        {
          switch (sequence[1])
          {
            case '1':
              return HOME_KEY;
            case '3':
              return DELETE_KEY;
            case '4':
              return END_KEY;
            case '5':
              return PAGE_UP;
            case '6':
              return PAGE_DOWN;
            case '7':
              return HOME_KEY;
            case '8':
              return END_KEY;
          }
        }
      }
      else  // else if sequence[1] is not numbers
      {
        switch (sequence[1])
        {
          case 'A':
            return ARROW_UP;
          case 'B':
            return ARROW_DOWN;
          case 'C':
            return ARROW_RIGHT;
          case 'D':
            return ARROW_LEFT;
          case 'H':
            return HOME_KEY;
          case 'F':
            return END_KEY;
        }
      }
    }
    else if (sequence[0] == 'O')
    {
      switch (sequence[1])
      {
        case 'H':
          return HOME_KEY;
        case 'F':
          return END_KEY;
      }
    }
    return '\x1b';
  }
  else
    return c;
}

int Terminal::getCursorPosition(int *row, int *column) // returns cursor position
{
  // TODO
}

int Terminal::getWindowSize(int *row, int *column) // returns size of window
{
  // TODO
}
<commit_msg>getCursorPosition() func definition<commit_after>// Terminal.cpp -- source file
/*
 *
 * Author: septimomend (Ivan Chapkailo)
 *
 * 30.06.2017
 *
 */

#include "stdafx.h"
#include "Terminal.h"

Terminal::Terminal() // cstr
{
}

/*
 * 0 - STDIN_FILENO - standard input descriptor
 * 1 - STDOUT_FILENO - standard output descriptor
 * 2 - STDERR_FILENO - standard errors output descriptor
 */

void Terminal::emergencyDestruction(const char* str)
{
  write(STDOUT_FILENO, "\x1b[2J", 4); // write clr code to file
  write(STDOUT_FILENO, "\x1b[H", 3);

  perror(str);
  exit(1);  // exit with error
}

void Terminal::rowModeOff()
{
  AllControllers all;
  ConfigurationController* configObj = all.getConfigObj();
  struct termios* termObj = configObj->getTermios();

  // the change will occur after all output written to STDIN_FILENO is transmitted,
  // and all input so far received but not read will be discarded before the change is made
  if (tcsetattr(STDIN_FILENO, TCSAFLUSH, termObj) == -1)
    emergencyDestruction("tcsetattr");
}

void Terminal::rowModeOn()
{
  AllControllers all;
  ConfigurationController* configObj = all.getConfigObj();
  struct termios* termObj = configObj->getTermios();

  if (tcgetattr(STDIN_FILENO, termObj) == -1)
    emergencyDestruction("tcgetattr");
  atexit(rowModeOff);

  struct termios raw = *termObj;
  // setting flags
  //
  raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
  raw.c_oflag &= ~(OPOST); // Post-process output
  raw.c_cflag |= (CS8); // Character size 8 bits
  raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
  raw.c_cc[VMIN] = 0;
  raw.c_cc[VTIME] = 1;
}

int Terminal::whatKey() // defines key pressing
{
  int countRD;
  char c;
  while ((countRD = read(STDIN_FILENO, &c, 1)) != 1)  // read 1 byte from input device and write to c
  {
    if (countRD == -1 && errno != EAGAIN)
      emergencyDestruction("read");
  }

  if (c == '\x1b') // if this is the escape key
  {
    char sequence[3];

    if (read(STDIN_FILENO, &sequence[0], 1) != 1) // if no errors
      return '\x1b';
    if (read(STDIN_FILENO, &sequence[1], 1) != 1)
      return '\x1b';

    // this is escape-sequence
    //          \x1b[...m
    // where ... is numbers of parameters
    // more on https://en.wikipedia.org/wiki/Escape_sequences_in_C
    //
    if (sequence[0] == '[')
    {
      if (sequence[1] >= '0' && sequence[1] <= '9')
      {
        if (read(STDIN_FILENO, &sequence[2], 1) != 1)
          return '\x1b'; // if escape calls 3rd time - exit
        if (sequence[2] == '~')
        {
          switch (sequence[1])
          {
            case '1':
              return HOME_KEY;
            case '3':
              return DELETE_KEY;
            case '4':
              return END_KEY;
            case '5':
              return PAGE_UP;
            case '6':
              return PAGE_DOWN;
            case '7':
              return HOME_KEY;
            case '8':
              return END_KEY;
          }
        }
      }
      else  // else if sequence[1] is not numbers
      {
        switch (sequence[1])
        {
          case 'A':
            return ARROW_UP;
          case 'B':
            return ARROW_DOWN;
          case 'C':
            return ARROW_RIGHT;
          case 'D':
            return ARROW_LEFT;
          case 'H':
            return HOME_KEY;
          case 'F':
            return END_KEY;
        }
      }
    }
    else if (sequence[0] == 'O')
    {
      switch (sequence[1])
      {
        case 'H':
          return HOME_KEY;
        case 'F':
          return END_KEY;
      }
    }
    return '\x1b';
  }
  else
    return c;
}

int Terminal::getCursorPosition(int *row, int *column) // returns cursor position
{
  char buff[32];
  unsigned int i = 0;

  if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4) // output 4 bytes to standard output device
    return -1;

  while (i < sizeof(buff) - 1)
  {
    if (read(STDIN_FILENO, &buff[i], 1) != 1) // read from ouput to buff 1 byte
      break;
    if (buff[i] == 'R')
      break;
    i++;
  }
  buff[i] = '\0';

  if (buff[0] != '\x1b' || buff[1] != '[') // if wrong data
    return -1;
  if (sscanf(&buff[2], "%d;%d", row, column) != 2) // read data from buff and check number of fields
    return -1;

  return 0;
}

int Terminal::getWindowSize(int *row, int *column) // returns size of window
{
  // TODO
}
<|endoftext|>


<commit_before>#pragma once

#include <string>
#include <vector>

#include "blackhole/error.hpp"
#include "blackhole/repository/config/base.hpp"
#include "blackhole/repository/config/log.hpp"

namespace blackhole {

namespace repository {

namespace config {

template<class T>
struct transformer_t;

template<class To>
class parser_t;

template<>
class parser_t<repository::config::base_t> {
public:
    template<class T>
    static
    typename std::enable_if<
        std::is_base_of<base_t, T>::value,
        T
    >::type
    parse(std::string component, dynamic_t value) {
        if (!value.contains("type")) {
            //!@todo: Throw specialized exception.
            throw blackhole::error_t("'type' field is missing for '%s' component", component);
        }

        std::string type = value["type"].to<std::string>();
        T config(std::move(type));
        config.config(std::move(value.to<dynamic_t::object_t>()));
        return config;
    }
};

template<>
class parser_t<formatter_config_t> {
public:
    static formatter_config_t parse(dynamic_t value) {
        return parser_t<
            repository::config::base_t
        >::template parse<formatter_config_t>("formatter", std::move(value));
    }
};

template<>
class parser_t<sink_config_t> {
public:
    static sink_config_t parse(dynamic_t value) {
        return parser_t<
            repository::config::base_t
        >::template parse<sink_config_t>("sink", std::move(value));
    }
};

template<>
class parser_t<frontend_config_t> {
public:
    static frontend_config_t parse(dynamic_t value) {
        if (!(value.contains("formatter") && value.contains("sink"))) {
            //!@todo: Throw specialized exception.
            throw blackhole::error_t("both 'formatter' and 'sink' sections must be specified");
        }

        auto form = parser_t<formatter_config_t>::parse(value["formatter"]);
        auto sink = parser_t<sink_config_t>::parse(value["sink"]);
        return frontend_config_t { std::move(form), std::move(sink) };
    }
};

template<>
class parser_t<log_config_t> {
public:
    static log_config_t parse(std::string name, dynamic_t value) {
        log_config_t config;
        config.name = std::move(name);

        auto array = value.to<dynamic_t::array_t>();
        for (auto it = array.begin(); it != array.end(); ++it) {
            auto frontend = parser_t<frontend_config_t>::parse(*it);
            config.frontends.push_back(std::move(frontend));
        }

        return config;
    }
};

template<>
class parser_t<std::vector<log_config_t>> {
public:
    static std::vector<log_config_t> parse(dynamic_t root) {
        std::vector<log_config_t> configs;
        auto object = root.to<dynamic_t::object_t>();
        for (auto it = object.begin(); it != object.end(); ++it) {
            auto config = parser_t<
                log_config_t
            >::parse(it->first, it->second);
            configs.push_back(std::move(config));
        }

        return configs;
    }
};

namespace parser {

template<class From, class To>
class adapter_t {
public:
    static To parse(const From& value) {
        return parser_t<To>::parse(
            transformer_t<From>::transform(value)
        );
    }
};

} // namespace parser

} // namespace config

} // namespace repository

} // namespace blackhole
<commit_msg>[GCC 4.4] Removed unnecessary `template` disambiguator.<commit_after>#pragma once

#include <string>
#include <vector>

#include "blackhole/error.hpp"
#include "blackhole/repository/config/base.hpp"
#include "blackhole/repository/config/log.hpp"

namespace blackhole {

namespace repository {

namespace config {

template<class T>
struct transformer_t;

template<class To>
class parser_t;

template<>
class parser_t<repository::config::base_t> {
public:
    template<class T>
    static
    typename std::enable_if<
        std::is_base_of<base_t, T>::value,
        T
    >::type
    parse(std::string component, dynamic_t value) {
        if (!value.contains("type")) {
            //!@todo: Throw specialized exception.
            throw blackhole::error_t("'type' field is missing for '%s' component", component);
        }

        std::string type = value["type"].to<std::string>();
        T config(std::move(type));
        config.config(std::move(value.to<dynamic_t::object_t>()));
        return config;
    }
};

template<>
class parser_t<formatter_config_t> {
public:
    static formatter_config_t parse(dynamic_t value) {
        return parser_t<
            repository::config::base_t
        >::parse<formatter_config_t>("formatter", std::move(value));
    }
};

template<>
class parser_t<sink_config_t> {
public:
    static sink_config_t parse(dynamic_t value) {
        return parser_t<
            repository::config::base_t
        >::parse<sink_config_t>("sink", std::move(value));
    }
};

template<>
class parser_t<frontend_config_t> {
public:
    static frontend_config_t parse(dynamic_t value) {
        if (!(value.contains("formatter") && value.contains("sink"))) {
            //!@todo: Throw specialized exception.
            throw blackhole::error_t("both 'formatter' and 'sink' sections must be specified");
        }

        auto form = parser_t<formatter_config_t>::parse(value["formatter"]);
        auto sink = parser_t<sink_config_t>::parse(value["sink"]);
        return frontend_config_t { std::move(form), std::move(sink) };
    }
};

template<>
class parser_t<log_config_t> {
public:
    static log_config_t parse(std::string name, dynamic_t value) {
        log_config_t config;
        config.name = std::move(name);

        auto array = value.to<dynamic_t::array_t>();
        for (auto it = array.begin(); it != array.end(); ++it) {
            auto frontend = parser_t<frontend_config_t>::parse(*it);
            config.frontends.push_back(std::move(frontend));
        }

        return config;
    }
};

template<>
class parser_t<std::vector<log_config_t>> {
public:
    static std::vector<log_config_t> parse(dynamic_t root) {
        std::vector<log_config_t> configs;
        auto object = root.to<dynamic_t::object_t>();
        for (auto it = object.begin(); it != object.end(); ++it) {
            auto config = parser_t<
                log_config_t
            >::parse(it->first, it->second);
            configs.push_back(std::move(config));
        }

        return configs;
    }
};

namespace parser {

template<class From, class To>
class adapter_t {
public:
    static To parse(const From& value) {
        return parser_t<To>::parse(
            transformer_t<From>::transform(value)
        );
    }
};

} // namespace parser

} // namespace config

} // namespace repository

} // namespace blackhole
<|endoftext|>


<commit_before>#include <QMainWindow>
#include <QGridLayout>
#include <QButtonGroup>
#include <QHBoxLayout>
#include <QPushButton>
#include <QComboBox>
#include <QSpinBox>
#include <QLabel>
#include <QFutureWatcher>
#include <QtConcurrent>
#include <QDir>
#include <QDate>
#include <QGroupBox>
#include <iterator>
#include <QProgressBar>
#include <QFileDialog>
#include <QStandardPaths>

#include "protocol.h"
#include "heart_cell_sim.h"
#include "varmenu.h"
#include "dialog.h"
#include "runWidget.h"
#include "chooseProtoWidget.h"

Simulation::Simulation(QWidget* parent){
//setup class variables
    this->parent = parent;
    date_time = QDate::currentDate().toString("MMddyy") + "-" + QTime::currentTime().toString("hhmm");
//create layouts
    main_layout = new QGridLayout(this);
//organizational widgets
    menu = new QStackedWidget();
    menu_options = new QListWidget();
//create Widgets
    next_button = new QPushButton("Next");
    cancel_button = new QPushButton("Cancel");
    chooseProtoWidget* choose = new chooseProtoWidget(this);
    this->proto = choose->getCurrentProto();
    proto->datadir = (QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation).first() + "/data" + date_time).toStdString();
    simvarMenu* sims = new simvarMenu(proto,QDir(proto->datadir.c_str()), this);
    dvarMenu* dvars = new dvarMenu(proto,QDir(proto->datadir.c_str()) , this);
    mvarMenu* mvars =  new mvarMenu(proto,QDir(proto->datadir.c_str()), this);
    pvarMenu* pvars =  new pvarMenu(proto,QDir(proto->datadir.c_str()), this);
    runWidget* run = new runWidget(proto,QDir(proto->datadir.c_str()));
//add items menu_list
    menu_list.append(choose);
    menu_list.append(sims);
    menu_list.append(dvars);
    menu_list.append(mvars);
    menu_list.append(pvars);
    menu_list.append(run);

    connect(choose, SIGNAL(protocolChanged(Protocol*)), sims, SLOT(changeProto(Protocol*)));
    connect(choose, SIGNAL(protocolChanged(Protocol*)), dvars, SLOT(changeProto(Protocol*)));
    connect(choose, SIGNAL(protocolChanged(Protocol*)), pvars, SLOT(changeProto(Protocol*)));
    connect(choose, SIGNAL(protocolChanged(Protocol*)), mvars, SLOT(changeProto(Protocol*)));
    connect(choose, SIGNAL(protocolChanged(Protocol*)), this, SLOT(changeProto(Protocol*)));
    connect(choose, SIGNAL(cell_type_changed()), this, SIGNAL(cell_type_changed()));
    connect(this, SIGNAL(cell_type_changed()), choose, SLOT(cellChangedSlot()));
    connect(sims, SIGNAL(working_dir_changed(QDir&)), this, SIGNAL(working_dir_changed(QDir&)));
    connect(sims, SIGNAL(cell_type_changed()), this, SIGNAL(cell_type_changed()));
    connect(this, SIGNAL(working_dir_changed(QDir&)), dvars, SLOT(setWorkingDir(QDir&)));
    connect(this, SIGNAL(working_dir_changed(QDir&)), mvars, SLOT(setWorkingDir(QDir&)));
    connect(this, SIGNAL(working_dir_changed(QDir&)), pvars, SLOT(setWorkingDir(QDir&)));
    connect(this, SIGNAL(working_dir_changed(QDir&)), run, SLOT(setWorkingDir(QDir&)));
    connect(this, SIGNAL(cell_type_changed()), sims, SLOT(changeCellType()));
    connect(this, SIGNAL(cell_type_changed()), dvars, SLOT(reset()));
    connect(this, SIGNAL(cell_type_changed()), mvars, SLOT(reset()));
    connect(this, SIGNAL(cell_type_changed()), pvars, SLOT(reset()));
    connect(run, SIGNAL(canceled()), this, SLOT(canceled()));
    connect(run, SIGNAL(finished()), this, SLOT(finished()));
    connect(run, SIGNAL(running()), this, SLOT(running()));
    connect(cancel_button, SIGNAL(clicked()),run, SLOT(cancel()));
//set button/combo box inital values
    cancel_button->hide();
//menu
    menu_options->addItem("Simulation Protocol");
    menu_options->addItem("Simulation Varibales");
    menu_options->addItem("Tracked Cell Values");
    menu_options->addItem("Measured Cell Values");
    menu_options->addItem("Cell Initializers");
    menu_options->addItem("Run Simulation");
    for(auto it = menu_list.begin(); it != menu_list.end(); it++) {
        menu->addWidget(*it);
    }
//main_layout
    main_layout->addWidget(menu_options, 0,0,-1,1);
    main_layout->addWidget(menu, 0, 1);
    main_layout->addWidget(next_button, 1, 2);
    main_layout->addWidget(cancel_button, 1, 2);
    QSizePolicy sPol(QSizePolicy::Minimum, QSizePolicy::Expanding);
    menu_options->setSizePolicy(sPol);
    menu_options->setWindowTitle(date_time);
    showMaximized();
//connect buttons
    connect(menu_options, SIGNAL(currentRowChanged(int)), this, SLOT(list_click_aciton(int)));
    connect(next_button, SIGNAL(clicked()), this, SLOT(next_button_aciton()));
};
Simulation::~Simulation(){};
void Simulation::changeProto(Protocol* proto) {
    this->proto = proto;
}
void Simulation::list_click_aciton (int next_row) {
    menu->setCurrentIndex(next_row);
    menu_options->setCurrentRow(next_row);
}
void Simulation::next_button_aciton () {
    int current_row = menu->currentIndex();
    if(menu->count() > current_row +1) {
        menu->setCurrentIndex(current_row +1);
        menu_options->setCurrentRow(current_row +1);
    }
}
void Simulation::canceled() {
    qDebug()<<"canceled!";
    QMessageBox::critical(this,"Cancel","Simulation canceled!");
    cancel_button->hide();
    next_button->show();
}
void Simulation::finished() {
    menu_list.append(new Dialog(proto,QDir(proto->datadir.c_str()), this));
    menu->addWidget(menu_list.last());
    menu_options->addItem("Graph " + date_time);
    date_time = QDate::currentDate().toString("MMddyy") + "-" + QTime::currentTime().toString("hhmm");
    QDir working_dir = (QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation).first() + "/data" + date_time);
    proto->datadir = working_dir.absolutePath().toStdString();
    emit working_dir_changed(working_dir);
    cancel_button->hide();
    next_button->show();
}
void Simulation::running() {
    next_button->hide();
    cancel_button->show();
}
<commit_msg>fixed bug where what was being run wasn't getting set by menus<commit_after>#include <QMainWindow>
#include <QGridLayout>
#include <QButtonGroup>
#include <QHBoxLayout>
#include <QPushButton>
#include <QComboBox>
#include <QSpinBox>
#include <QLabel>
#include <QFutureWatcher>
#include <QtConcurrent>
#include <QDir>
#include <QDate>
#include <QGroupBox>
#include <iterator>
#include <QProgressBar>
#include <QFileDialog>
#include <QStandardPaths>

#include "protocol.h"
#include "heart_cell_sim.h"
#include "varmenu.h"
#include "dialog.h"
#include "runWidget.h"
#include "chooseProtoWidget.h"

Simulation::Simulation(QWidget* parent){
//setup class variables
    this->parent = parent;
    date_time = QDate::currentDate().toString("MMddyy") + "-" + QTime::currentTime().toString("hhmm");
//create layouts
    main_layout = new QGridLayout(this);
//organizational widgets
    menu = new QStackedWidget();
    menu_options = new QListWidget();
//create Widgets
    next_button = new QPushButton("Next");
    cancel_button = new QPushButton("Cancel");
    chooseProtoWidget* choose = new chooseProtoWidget(this);
    this->proto = choose->getCurrentProto();
    proto->datadir = (QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation).first() + "/data" + date_time).toStdString();
    simvarMenu* sims = new simvarMenu(proto,QDir(proto->datadir.c_str()), this);
    dvarMenu* dvars = new dvarMenu(proto,QDir(proto->datadir.c_str()) , this);
    mvarMenu* mvars =  new mvarMenu(proto,QDir(proto->datadir.c_str()), this);
    pvarMenu* pvars =  new pvarMenu(proto,QDir(proto->datadir.c_str()), this);
    runWidget* run = new runWidget(proto,QDir(proto->datadir.c_str()));
//add items menu_list
    menu_list.append(choose);
    menu_list.append(sims);
    menu_list.append(dvars);
    menu_list.append(mvars);
    menu_list.append(pvars);
    menu_list.append(run);

    connect(choose, SIGNAL(protocolChanged(Protocol*)), sims, SLOT(changeProto(Protocol*)));
    connect(choose, SIGNAL(protocolChanged(Protocol*)), dvars, SLOT(changeProto(Protocol*)));
    connect(choose, SIGNAL(protocolChanged(Protocol*)), pvars, SLOT(changeProto(Protocol*)));
    connect(choose, SIGNAL(protocolChanged(Protocol*)), mvars, SLOT(changeProto(Protocol*)));
    connect(choose, SIGNAL(protocolChanged(Protocol*)), run, SLOT(setProto(Protocol*)));
    connect(choose, SIGNAL(protocolChanged(Protocol*)), this, SLOT(changeProto(Protocol*)));
    connect(choose, SIGNAL(cell_type_changed()), this, SIGNAL(cell_type_changed()));
    connect(this, SIGNAL(cell_type_changed()), choose, SLOT(cellChangedSlot()));
    connect(sims, SIGNAL(working_dir_changed(QDir&)), this, SIGNAL(working_dir_changed(QDir&)));
    connect(sims, SIGNAL(cell_type_changed()), this, SIGNAL(cell_type_changed()));
    connect(this, SIGNAL(working_dir_changed(QDir&)), dvars, SLOT(setWorkingDir(QDir&)));
    connect(this, SIGNAL(working_dir_changed(QDir&)), mvars, SLOT(setWorkingDir(QDir&)));
    connect(this, SIGNAL(working_dir_changed(QDir&)), pvars, SLOT(setWorkingDir(QDir&)));
    connect(this, SIGNAL(working_dir_changed(QDir&)), run, SLOT(setWorkingDir(QDir&)));
    connect(this, SIGNAL(cell_type_changed()), sims, SLOT(changeCellType()));
    connect(this, SIGNAL(cell_type_changed()), dvars, SLOT(reset()));
    connect(this, SIGNAL(cell_type_changed()), mvars, SLOT(reset()));
    connect(this, SIGNAL(cell_type_changed()), pvars, SLOT(reset()));
    connect(run, SIGNAL(canceled()), this, SLOT(canceled()));
    connect(run, SIGNAL(finished()), this, SLOT(finished()));
    connect(run, SIGNAL(running()), this, SLOT(running()));
    connect(cancel_button, SIGNAL(clicked()),run, SLOT(cancel()));
//set button/combo box inital values
    cancel_button->hide();
//menu
    menu_options->addItem("Simulation Protocol");
    menu_options->addItem("Simulation Varibales");
    menu_options->addItem("Tracked Cell Values");
    menu_options->addItem("Measured Cell Values");
    menu_options->addItem("Cell Initializers");
    menu_options->addItem("Run Simulation");
    for(auto it = menu_list.begin(); it != menu_list.end(); it++) {
        menu->addWidget(*it);
    }
//main_layout
    main_layout->addWidget(menu_options, 0,0,-1,1);
    main_layout->addWidget(menu, 0, 1);
    main_layout->addWidget(next_button, 1, 2);
    main_layout->addWidget(cancel_button, 1, 2);
    QSizePolicy sPol(QSizePolicy::Minimum, QSizePolicy::Expanding);
    menu_options->setSizePolicy(sPol);
    menu_options->setWindowTitle(date_time);
    showMaximized();
//connect buttons
    connect(menu_options, SIGNAL(currentRowChanged(int)), this, SLOT(list_click_aciton(int)));
    connect(next_button, SIGNAL(clicked()), this, SLOT(next_button_aciton()));
};
Simulation::~Simulation(){};
void Simulation::changeProto(Protocol* proto) {
    this->proto = proto;
}
void Simulation::list_click_aciton (int next_row) {
    menu->setCurrentIndex(next_row);
    menu_options->setCurrentRow(next_row);
}
void Simulation::next_button_aciton () {
    int current_row = menu->currentIndex();
    if(menu->count() > current_row +1) {
        menu->setCurrentIndex(current_row +1);
        menu_options->setCurrentRow(current_row +1);
    }
}
void Simulation::canceled() {
    qDebug()<<"canceled!";
    QMessageBox::critical(this,"Cancel","Simulation canceled!");
    cancel_button->hide();
    next_button->show();
}
void Simulation::finished() {
    menu_list.append(new Dialog(proto,QDir(proto->datadir.c_str()), this));
    menu->addWidget(menu_list.last());
    menu_options->addItem("Graph " + date_time);
    date_time = QDate::currentDate().toString("MMddyy") + "-" + QTime::currentTime().toString("hhmm");
    QDir working_dir = (QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation).first() + "/data" + date_time);
    proto->datadir = working_dir.absolutePath().toStdString();
    emit working_dir_changed(working_dir);
    cancel_button->hide();
    next_button->show();
}
void Simulation::running() {
    next_button->hide();
    cancel_button->show();
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
 *
 * This file is part of libbitcoin.
 *
 * libbitcoin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <iostream>
#include <sstream>
#include <bitcoin/bitcoin/utility/logger.hpp>
#include <bitcoin/bitcoin/unicode/unicode.hpp>

namespace libbitcoin {

std::string level_repr(log_level level)
{
    switch (level)
    {
        case log_level::null:
            return "NULL";
        case log_level::debug:
            return "DEBUG";
        case log_level::info:
            return "INFO";
        case log_level::warning:
            return "WARNING";
        case log_level::error:
            return "ERROR";
        case log_level::fatal:
            return "FATAL";
    }

    return "";
}

static void output_ostream(std::ostream& out, log_level level,
    const std::string& domain, const std::string& body)
{
    std::ostringstream buffer;
    buffer << level_repr(level);
    if (!domain.empty())
        buffer << " [" << domain << "]";

    buffer << ": " << body << std::endl;

    // Buffering prevents line interleaving across threads.
    out << buffer.str();
    out.flush();
}

void ignore_output(log_level,
    const std::string&, const std::string&)
{
}

void output_cout(log_level level,
    const std::string& domain, const std::string& body)
{
    output_ostream(bc::cout, level, domain, body);
}

void output_cerr(log_level level,
    const std::string& domain, const std::string& body)
{
    output_ostream(bc::cerr, level, domain, body);
}

logger_wrapper::destination_map logger_wrapper::dests_
{
#ifdef DEBUG
    std::make_pair(log_level::debug, output_cout),
#else
    std::make_pair(log_level::debug, ignore_output),
#endif
    std::make_pair(log_level::info, output_cout),
    std::make_pair(log_level::warning, output_cerr),
    std::make_pair(log_level::error, output_cerr),
    std::make_pair(log_level::fatal, output_cerr)
};

logger_wrapper::logger_wrapper(log_level level, const std::string& domain)
    : level_(level), domain_(domain)
{
}

// g++ bug in initializer list.
// It should be: stream_(std::move(other.stream_))
// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=54316
logger_wrapper::logger_wrapper(logger_wrapper&& other)
  : level_(other.level_), domain_(std::move(other.domain_)),
    stream_(other.stream_.str())
{
}

logger_wrapper::~logger_wrapper()
{
    if (!dests_.count(level_))
        return;

    auto& outfunc = dests_[level_];
    outfunc(level_, domain_, stream_.str());
}

void logger_wrapper::set_output_function(logger_output_func func)
{
    dests_[level_] = func;
}

logger_wrapper log_debug(const std::string& domain)
{
    return logger_wrapper(log_level::debug, domain);
}

logger_wrapper log_info(const std::string& domain)
{
    return logger_wrapper(log_level::info, domain);
}

logger_wrapper log_warning(const std::string& domain)
{
    return logger_wrapper(log_level::warning, domain);
}

logger_wrapper log_error(const std::string& domain)
{
    return logger_wrapper(log_level::error, domain);
}

logger_wrapper log_fatal(const std::string& domain)
{
    return logger_wrapper(log_level::fatal, domain);
}

} // namespace libbitcoin

<commit_msg>Sort include.<commit_after>/**
 * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
 *
 * This file is part of libbitcoin.
 *
 * libbitcoin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <bitcoin/bitcoin/utility/logger.hpp>

#include <iostream>
#include <sstream>
#include <bitcoin/bitcoin/unicode/unicode.hpp>

namespace libbitcoin {

std::string level_repr(log_level level)
{
    switch (level)
    {
        case log_level::null:
            return "NULL";
        case log_level::debug:
            return "DEBUG";
        case log_level::info:
            return "INFO";
        case log_level::warning:
            return "WARNING";
        case log_level::error:
            return "ERROR";
        case log_level::fatal:
            return "FATAL";
    }

    return "";
}

static void output_ostream(std::ostream& out, log_level level,
    const std::string& domain, const std::string& body)
{
    std::ostringstream buffer;
    buffer << level_repr(level);
    if (!domain.empty())
        buffer << " [" << domain << "]";

    buffer << ": " << body << std::endl;

    // Buffering prevents line interleaving across threads.
    out << buffer.str();
    out.flush();
}

void ignore_output(log_level,
    const std::string&, const std::string&)
{
}

void output_cout(log_level level,
    const std::string& domain, const std::string& body)
{
    output_ostream(bc::cout, level, domain, body);
}

void output_cerr(log_level level,
    const std::string& domain, const std::string& body)
{
    output_ostream(bc::cerr, level, domain, body);
}

logger_wrapper::destination_map logger_wrapper::dests_
{
#ifdef DEBUG
    std::make_pair(log_level::debug, output_cout),
#else
    std::make_pair(log_level::debug, ignore_output),
#endif
    std::make_pair(log_level::info, output_cout),
    std::make_pair(log_level::warning, output_cerr),
    std::make_pair(log_level::error, output_cerr),
    std::make_pair(log_level::fatal, output_cerr)
};

logger_wrapper::logger_wrapper(log_level level, const std::string& domain)
    : level_(level), domain_(domain)
{
}

// g++ bug in initializer list.
// It should be: stream_(std::move(other.stream_))
// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=54316
logger_wrapper::logger_wrapper(logger_wrapper&& other)
  : level_(other.level_), domain_(std::move(other.domain_)),
    stream_(other.stream_.str())
{
}

logger_wrapper::~logger_wrapper()
{
    if (!dests_.count(level_))
        return;

    auto& outfunc = dests_[level_];
    outfunc(level_, domain_, stream_.str());
}

void logger_wrapper::set_output_function(logger_output_func func)
{
    dests_[level_] = func;
}

logger_wrapper log_debug(const std::string& domain)
{
    return logger_wrapper(log_level::debug, domain);
}

logger_wrapper log_info(const std::string& domain)
{
    return logger_wrapper(log_level::info, domain);
}

logger_wrapper log_warning(const std::string& domain)
{
    return logger_wrapper(log_level::warning, domain);
}

logger_wrapper log_error(const std::string& domain)
{
    return logger_wrapper(log_level::error, domain);
}

logger_wrapper log_fatal(const std::string& domain)
{
    return logger_wrapper(log_level::fatal, domain);
}

} // namespace libbitcoin

<|endoftext|>


<commit_before>// Copyright 2012 Luis Pedro Coelho <luis@luispedro.org>
// License: MIT (see COPYING.MIT file)

#if defined(_MSC_VER)
 #include <io.h>
#else
 #include <unistd.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 const int O_BINARY = 0;
#endif

#include <sstream>

#include "lib/base.h"
#include "lib/formats.h"
#include "lib/file.h"
#include "lib/numpy.h"

extern "C" {
    #include <Python.h>
    #include <numpy/ndarrayobject.h>
}

namespace{

const char TypeErrorMsg[] =
    "Type not understood. "
    "This is caused by either a direct call to _imread (which is dangerous: types are not checked!) or a bug in imread.py.\n";

PyObject* py_imread_may_multi(PyObject* self, PyObject* args, bool is_multi) {
    const char* filename;
    const char* formatstr;
    if (!PyArg_ParseTuple(args, "ss", &filename, &formatstr)) {
        PyErr_SetString(PyExc_RuntimeError,TypeErrorMsg);
        return NULL;
    }

    int fd = ::open(filename, O_RDONLY|O_BINARY);
    if (fd < 0) {
        std::stringstream ss;
        ss << "File `" << filename << "` does not exist";
        PyErr_SetString(PyExc_OSError, ss.str().c_str());
        return 0;
    }

    try {
        std::auto_ptr<ImageFormat> format(get_format(formatstr));
        if (!format.get()) {
            std::stringstream ss;
            ss << "This format (" << formatstr << ") is unknown to imread";
            throw CannotReadError(ss.str());
        }
        if (is_multi && !format->can_read_multi()) {
            std::stringstream ss;
            ss << "imread cannot read_multi in this format (" << formatstr << ")";
            if (format->can_read()) {
                ss << " but read() will work.";
            }
            throw CannotReadError(ss.str());
        }
        if (!is_multi && !format->can_read()) {
            std::stringstream ss;
            ss << "imread cannot read_in this format (" << formatstr << ")";
            if (format->can_read_multi()) {
                ss << "(but can read_multi!)";
            }
            throw CannotReadError(ss.str());
        }

        NumpyFactory factory;
        std::auto_ptr<byte_source> input(new fd_source_sink(fd));
        if (is_multi) {
            std::auto_ptr<image_list> images = format->read_multi(input.get(), &factory);
            PyObject* output = PyList_New(images->size());
            if (!output) return NULL;
            std::vector<Image*> pages = images->release();
            for (unsigned i = 0; i != pages.size(); ++i) {
                PyList_SET_ITEM(output, i, static_cast<NumpyImage&>(*pages[i]).releasePyObject());
                delete pages[i];
            }
            return output;
        } else {
            std::auto_ptr<Image> output = format->read(input.get(), &factory);
            return static_cast<NumpyImage&>(*output).releasePyObject();
        }
    } catch (const std::exception& e) {
        PyErr_SetString(PyExc_RuntimeError, e.what());
        return 0;
    } catch (...) {
        PyErr_SetString(PyExc_RuntimeError, "Mysterious error");
        return 0;
    }
}

PyObject* py_imread      (PyObject* self, PyObject* args) { return py_imread_may_multi(self, args, false); }
PyObject* py_imread_multi(PyObject* self, PyObject* args) { return py_imread_may_multi(self, args, true); }

PyObject* py_imsave(PyObject* self, PyObject* args) {
    const char* filename;
    const char* formatstr;
    PyArrayObject* array;
    if (!PyArg_ParseTuple(args, "ssO", &filename, &formatstr, &array) || !PyArray_Check(array)) {
        PyErr_SetString(PyExc_RuntimeError,TypeErrorMsg);
        return NULL;
    }
    int fd = ::open(filename, O_CREAT|O_WRONLY|O_BINARY|O_TRUNC, 0644);
    if (fd < 0) {
        std::stringstream ss;
        ss << "Cannot open file '" << filename << "' for writing";
        PyErr_SetString(PyExc_OSError, ss.str().c_str());
        return 0;
    }

    Py_INCREF(array);
    try {
        NumpyImage input(array);
        std::auto_ptr<byte_sink> output(new fd_source_sink(fd));
        std::auto_ptr<ImageFormat> format(get_format(formatstr));
        if (!format->can_write()) {
            std::stringstream ss;
            ss << "Cannot write this format (" << formatstr << ")";
            throw CannotWriteError(ss.str());
        }
        format->write(&input, output.get());
        Py_RETURN_NONE;
    } catch (const std::exception& e) {
        PyErr_SetString(PyExc_RuntimeError, e.what());
        return 0;
    } catch (...) {
        PyErr_SetString(PyExc_RuntimeError, "Mysterious error");
        return 0;
    }
}

PyMethodDef methods[] = {
  {"imread",(PyCFunction)py_imread, METH_VARARGS, NULL},
  {"imread_multi",(PyCFunction)py_imread_multi, METH_VARARGS, NULL},
  {"imsave",(PyCFunction)py_imsave, METH_VARARGS, NULL},
  {NULL, NULL,0,NULL},
};

} // namespace
extern "C"
void init_imread()
  {
    import_array();
    (void)Py_InitModule("_imread", methods);
  }

<commit_msg>Python 3 compatibility<commit_after>// Copyright 2012 Luis Pedro Coelho <luis@luispedro.org>
// License: MIT (see COPYING.MIT file)

#if defined(_MSC_VER)
 #include <io.h>
#else
 #include <unistd.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 const int O_BINARY = 0;
#endif

#include <sstream>

#include "lib/base.h"
#include "lib/formats.h"
#include "lib/file.h"
#include "lib/numpy.h"

extern "C" {
    #include <Python.h>
    #include <numpy/ndarrayobject.h>
}

namespace{

const char TypeErrorMsg[] =
    "Type not understood. "
    "This is caused by either a direct call to _imread (which is dangerous: types are not checked!) or a bug in imread.py.\n";

PyObject* py_imread_may_multi(PyObject* self, PyObject* args, bool is_multi) {
    const char* filename;
    const char* formatstr;
    if (!PyArg_ParseTuple(args, "ss", &filename, &formatstr)) {
        PyErr_SetString(PyExc_RuntimeError,TypeErrorMsg);
        return NULL;
    }

    int fd = ::open(filename, O_RDONLY|O_BINARY);
    if (fd < 0) {
        std::stringstream ss;
        ss << "File `" << filename << "` does not exist";
        PyErr_SetString(PyExc_OSError, ss.str().c_str());
        return 0;
    }

    try {
        std::auto_ptr<ImageFormat> format(get_format(formatstr));
        if (!format.get()) {
            std::stringstream ss;
            ss << "This format (" << formatstr << ") is unknown to imread";
            throw CannotReadError(ss.str());
        }
        if (is_multi && !format->can_read_multi()) {
            std::stringstream ss;
            ss << "imread cannot read_multi in this format (" << formatstr << ")";
            if (format->can_read()) {
                ss << " but read() will work.";
            }
            throw CannotReadError(ss.str());
        }
        if (!is_multi && !format->can_read()) {
            std::stringstream ss;
            ss << "imread cannot read_in this format (" << formatstr << ")";
            if (format->can_read_multi()) {
                ss << "(but can read_multi!)";
            }
            throw CannotReadError(ss.str());
        }

        NumpyFactory factory;
        std::auto_ptr<byte_source> input(new fd_source_sink(fd));
        if (is_multi) {
            std::auto_ptr<image_list> images = format->read_multi(input.get(), &factory);
            PyObject* output = PyList_New(images->size());
            if (!output) return NULL;
            std::vector<Image*> pages = images->release();
            for (unsigned i = 0; i != pages.size(); ++i) {
                PyList_SET_ITEM(output, i, static_cast<NumpyImage&>(*pages[i]).releasePyObject());
                delete pages[i];
            }
            return output;
        } else {
            std::auto_ptr<Image> output = format->read(input.get(), &factory);
            return static_cast<NumpyImage&>(*output).releasePyObject();
        }
    } catch (const std::exception& e) {
        PyErr_SetString(PyExc_RuntimeError, e.what());
        return 0;
    } catch (...) {
        PyErr_SetString(PyExc_RuntimeError, "Mysterious error");
        return 0;
    }
}

PyObject* py_imread      (PyObject* self, PyObject* args) { return py_imread_may_multi(self, args, false); }
PyObject* py_imread_multi(PyObject* self, PyObject* args) { return py_imread_may_multi(self, args, true); }

PyObject* py_imsave(PyObject* self, PyObject* args) {
    const char* filename;
    const char* formatstr;
    PyArrayObject* array;
    if (!PyArg_ParseTuple(args, "ssO", &filename, &formatstr, &array) || !PyArray_Check(array)) {
        PyErr_SetString(PyExc_RuntimeError,TypeErrorMsg);
        return NULL;
    }
    int fd = ::open(filename, O_CREAT|O_WRONLY|O_BINARY|O_TRUNC, 0644);
    if (fd < 0) {
        std::stringstream ss;
        ss << "Cannot open file '" << filename << "' for writing";
        PyErr_SetString(PyExc_OSError, ss.str().c_str());
        return 0;
    }

    Py_INCREF(array);
    try {
        NumpyImage input(array);
        std::auto_ptr<byte_sink> output(new fd_source_sink(fd));
        std::auto_ptr<ImageFormat> format(get_format(formatstr));
        if (!format->can_write()) {
            std::stringstream ss;
            ss << "Cannot write this format (" << formatstr << ")";
            throw CannotWriteError(ss.str());
        }
        format->write(&input, output.get());
        Py_RETURN_NONE;
    } catch (const std::exception& e) {
        PyErr_SetString(PyExc_RuntimeError, e.what());
        return 0;
    } catch (...) {
        PyErr_SetString(PyExc_RuntimeError, "Mysterious error");
        return 0;
    }
}

PyMethodDef methods[] = {
  {"imread",(PyCFunction)py_imread, METH_VARARGS, NULL},
  {"imread_multi",(PyCFunction)py_imread_multi, METH_VARARGS, NULL},
  {"imsave",(PyCFunction)py_imsave, METH_VARARGS, NULL},
  {NULL, NULL,0,NULL},
};

} // namespace

#if PY_MAJOR_VERSION < 3
PyMODINIT_FUNC
init_imread()
  {
    import_array();
    (void)Py_InitModule("_imread", methods);
  }
#else

static struct PyModuleDef moduledef = {
        PyModuleDef_HEAD_INIT,
        "_imread",
        NULL,
        -1,
        methods,
        NULL,
        NULL,
        NULL,
        NULL
};

PyMODINIT_FUNC
PyInit__imread()
  {
    import_array();
    PyObject *module = PyModule_Create(&moduledef);
    return module;
  }
#endif
<|endoftext|>