<commit_before>#include "core/io/config_file.h"
#include "os/file_access.h"

#include "oamlGodotModule.h"

void oamlGodotModule::set_mix_rate(int p_rate) {
	if (oaml == NULL)
		return;

	oaml->SetAudioFormat(p_rate, 2, 4, true);
}

bool oamlGodotModule::mix(AudioFrame *p_buffer, int p_frames) {

	if (oaml == NULL)
		return true;

	zeromem(p_buffer, p_frames*sizeof(AudioFrame));
	oaml->MixToBuffer(p_buffer, p_frames*2);

	return true;
}

// Called from audio thread
void oamlGodotModule::_mix_audio() {

	AudioFrame *buffer = mix_buffer.ptrw();
	int buffer_size = mix_buffer.size();

	if (!mix(buffer, buffer_size))
		return;

	AudioFrame *target = AudioServer::get_singleton()->thread_get_channel_mix_buffer(0, 0);

	for (int j = 0; j < buffer_size; j++) {
		target[j] += buffer[j];
	}
}

int oamlGodotModule::sp_get_channel_count() const {

	return 2;
}

void oamlGodotModule::AddTension(int value) {
	if (oaml == NULL)
		return;

	oaml->AddTension(value);
}

void oamlGodotModule::EnableDynamicCompressor(bool enable, double thresholdDb, double ratio) {
	if (oaml == NULL)
		return;

	oaml->EnableDynamicCompressor(enable, thresholdDb, ratio);
}

String oamlGodotModule::GetPlayingInfo() {
	if (oaml == NULL)
		return "";

	return String(oaml->GetPlayingInfo());
}

String oamlGodotModule::GetVersion() {
	if (oaml == NULL)
		return "";

	return oaml->GetVersion();
}

float oamlGodotModule::GetVolume() {
	if (oaml == NULL)
		return 1.0f;

	return oaml->GetVolume();
}

void oamlGodotModule::Init(String defsFilename) {
	if (oaml == NULL)
		return;

	oaml->Init(defsFilename.ascii().get_data());
}

void oamlGodotModule::InitString(String defs) {
	if (oaml == NULL)
		return;

	oaml->InitString(defs.ascii());
}

bool oamlGodotModule::IsPaused() {
	if (oaml == NULL)
		return true;

	return oaml->IsPaused();
}

bool oamlGodotModule::IsPlaying() {
	if (oaml == NULL)
		return false;

	return oaml->IsPlaying();
}

bool oamlGodotModule::IsTrackPlaying(String name) {
	if (oaml == NULL)
		return false;

	return oaml->IsTrackPlaying(name.ascii());
}

void oamlGodotModule::LoadTrack(String name) {
	if (oaml == NULL)
		return;

	oaml->LoadTrack(name.ascii());
}

float oamlGodotModule::LoadTrackProgress(String name) {
	if (oaml == NULL)
		return -1.f;

	return oaml->LoadTrackProgress(name.ascii());
}

void oamlGodotModule::Pause() {
	if (oaml == NULL)
		return;

	oaml->Pause();
}

void oamlGodotModule::PlayTrack(String name) {
	if (oaml == NULL)
		return;

	oaml->PlayTrack(name.ascii());
}

void oamlGodotModule::PlayTrackWithStringRandom(String str) {
	if (oaml == NULL)
		return;

	oaml->PlayTrackWithStringRandom(str.ascii());
}

void oamlGodotModule::PlayTrackByGroupRandom(String group) {
	if (oaml == NULL)
		return;

	oaml->PlayTrackByGroupRandom(group.ascii());
}

void oamlGodotModule::PlayTrackByGroupAndSubgroupRandom(String group, String subgroup) {
	if (oaml == NULL)
		return;

	oaml->PlayTrackByGroupAndSubgroupRandom(group.ascii(), subgroup.ascii());
}

void oamlGodotModule::Resume() {
	if (oaml == NULL)
		return;

	oaml->Resume();
}

void oamlGodotModule::SetMainLoopCondition(int value) {
	if (oaml == NULL)
		return;

	oaml->SetMainLoopCondition(value);
}

void oamlGodotModule::SetCondition(int id, int value) {
	if (oaml == NULL)
		return;

	oaml->SetCondition(id, value);
}

void oamlGodotModule::SetLayerGain(String layer, float gain) {
	if (oaml == NULL)
		return;

	oaml->SetLayerGain(layer.ascii(), gain);
}

void oamlGodotModule::SetLayerRandomChance(String layer, int randomChance) {
	if (oaml == NULL)
		return;

	oaml->SetLayerRandomChance(layer.ascii(), randomChance);
}

void oamlGodotModule::SetTension(int value) {
	if (oaml == NULL)
		return;

	oaml->SetTension(value);
}

void oamlGodotModule::SetVolume(float value) {
	if (oaml == NULL)
		return;

	oaml->SetVolume(value);
}

void oamlGodotModule::StopPlaying() {
	if (oaml == NULL)
		return;

	oaml->StopPlaying();
}

String oamlGodotModule::SaveState() {
	if (oaml == NULL)
		return "";

	return oaml->SaveState().c_str();
}

void oamlGodotModule::LoadState(String state) {
	if (oaml == NULL)
		return;

	oaml->LoadState(state.utf8().get_data());
}

void oamlGodotModule::_bind_methods() {
	ClassDB::bind_method("AddTension", &oamlGodotModule::AddTension);
	ClassDB::bind_method("EnableDynamicCompressor", &oamlGodotModule::EnableDynamicCompressor);
	ClassDB::bind_method("GetPlayingInfo", &oamlGodotModule::GetPlayingInfo);
	ClassDB::bind_method("GetVersion", &oamlGodotModule::GetVersion);
	ClassDB::bind_method("GetVolume", &oamlGodotModule::GetVolume);
	ClassDB::bind_method("Init", &oamlGodotModule::Init);
	ClassDB::bind_method("InitString", &oamlGodotModule::InitString);
	ClassDB::bind_method("IsPaused", &oamlGodotModule::IsPaused);
	ClassDB::bind_method("IsPlaying", &oamlGodotModule::IsPlaying);
	ClassDB::bind_method("IsTrackPlaying", &oamlGodotModule::IsTrackPlaying);
	ClassDB::bind_method("LoadState", &oamlGodotModule::LoadState);
	ClassDB::bind_method("LoadTrack", &oamlGodotModule::LoadTrack);
	ClassDB::bind_method("LoadTrackProgress", &oamlGodotModule::LoadTrackProgress);
	ClassDB::bind_method("Pause", &oamlGodotModule::Pause);
	ClassDB::bind_method("PlayTrack", &oamlGodotModule::PlayTrack);
	ClassDB::bind_method("PlayTrackWithStringRandom", &oamlGodotModule::PlayTrackWithStringRandom);
	ClassDB::bind_method("PlayTrackByGroupRandom", &oamlGodotModule::PlayTrackByGroupRandom);
	ClassDB::bind_method("PlayTrackByGroupAndSubgroupRandom", &oamlGodotModule::PlayTrackByGroupAndSubgroupRandom);
	ClassDB::bind_method("Resume", &oamlGodotModule::Resume);
	ClassDB::bind_method("SaveState", &oamlGodotModule::SaveState);
	ClassDB::bind_method("SetMainLoopCondition", &oamlGodotModule::SetMainLoopCondition);
	ClassDB::bind_method("SetCondition", &oamlGodotModule::SetCondition);
	ClassDB::bind_method("SetLayerGain", &oamlGodotModule::SetLayerGain);
	ClassDB::bind_method("SetLayerRandomChance", &oamlGodotModule::SetLayerRandomChance);
	ClassDB::bind_method("SetTension", &oamlGodotModule::SetTension);
	ClassDB::bind_method("SetVolume", &oamlGodotModule::SetVolume);
	ClassDB::bind_method("StopPlaying", &oamlGodotModule::StopPlaying);
}

static void* oamlOpen(const char *filename) {
	String path = "res://"+String(filename);
	FileAccess *f = FileAccess::open(path, FileAccess::READ);
	if (f == NULL) {
		ConfigFile cf;
		Error err = cf.load(path + ".import");
		if (err == OK) {
			f = FileAccess::open(cf.get_value("remap", "path"), FileAccess::READ);
			if (f != NULL) {
				char header[5] = "0000";
				f->seek(28);
				while (strncmp(header, "OggS", 4) != 0) {
					f->get_buffer((uint8_t*)header, 4);
					f->seek(f->get_position()-3);
				}
				f->seek(f->get_position()-1);
				return (void*)f;
			}
		}

		print_line("oaml: Error opening resource file:" + path);
		return NULL;
	}
	return (void*)f;
}

static size_t oamlRead(void *ptr, size_t size, size_t nitems, void *fd) {
	FileAccess *f = (FileAccess*)fd;
	return f->get_buffer((uint8_t*)ptr, size*nitems);
}

static int oamlSeek(void *fd, long offset, int whence) {
	FileAccess *f = (FileAccess*)fd;
	if (whence == SEEK_SET)
		f->seek(offset);
	else if (whence == SEEK_END)
		f->seek_end(offset);
	else if (whence == SEEK_CUR)
		f->seek(f->get_position()+offset);
	return 0;
}

static long oamlTell(void *fd) {
	FileAccess *f = (FileAccess*)fd;
	return f->get_position();
}

static int oamlClose(void *fd) {
	FileAccess *f = (FileAccess*)fd;
	f->close();
	memdelete(f);
	return 0;
}

static oamlFileCallbacks fileCbs = {
	&oamlOpen,
	&oamlRead,
	&oamlSeek,
	&oamlTell,
	&oamlClose
};

oamlGodotModule::oamlGodotModule() {
	oaml = new oamlApi();
	oaml->SetFileCallbacks(&fileCbs);
	oaml->SetAudioFormat(AudioServer::get_singleton()->get_mix_rate(), 2, 4, true);

	AudioServer::get_singleton()->lock();
	mix_buffer.resize(AudioServer::get_singleton()->thread_get_mix_buffer_size());
	AudioServer::get_singleton()->unlock();

	AudioServer::get_singleton()->add_callback(_mix_audios, this);
}

oamlGodotModule::~oamlGodotModule() {
	if (oaml != NULL) {
		oaml->Shutdown();
		delete oaml;
		oaml = NULL;
	}

	AudioServer::get_singleton()->remove_callback(_mix_audios, this);
}
<commit_msg>Replace exported method names with snake_case equivalents<commit_after>#include "core/io/config_file.h"
#include "os/file_access.h"

#include "oamlGodotModule.h"

void oamlGodotModule::set_mix_rate(int p_rate) {
	if (oaml == NULL)
		return;

	oaml->SetAudioFormat(p_rate, 2, 4, true);
}

bool oamlGodotModule::mix(AudioFrame *p_buffer, int p_frames) {

	if (oaml == NULL)
		return true;

	zeromem(p_buffer, p_frames*sizeof(AudioFrame));
	oaml->MixToBuffer(p_buffer, p_frames*2);

	return true;
}

// Called from audio thread
void oamlGodotModule::_mix_audio() {

	AudioFrame *buffer = mix_buffer.ptrw();
	int buffer_size = mix_buffer.size();

	if (!mix(buffer, buffer_size))
		return;

	AudioFrame *target = AudioServer::get_singleton()->thread_get_channel_mix_buffer(0, 0);

	for (int j = 0; j < buffer_size; j++) {
		target[j] += buffer[j];
	}
}

int oamlGodotModule::sp_get_channel_count() const {

	return 2;
}

void oamlGodotModule::AddTension(int value) {
	if (oaml == NULL)
		return;

	oaml->AddTension(value);
}

void oamlGodotModule::EnableDynamicCompressor(bool enable, double thresholdDb, double ratio) {
	if (oaml == NULL)
		return;

	oaml->EnableDynamicCompressor(enable, thresholdDb, ratio);
}

String oamlGodotModule::GetPlayingInfo() {
	if (oaml == NULL)
		return "";

	return String(oaml->GetPlayingInfo());
}

String oamlGodotModule::GetVersion() {
	if (oaml == NULL)
		return "";

	return oaml->GetVersion();
}

float oamlGodotModule::GetVolume() {
	if (oaml == NULL)
		return 1.0f;

	return oaml->GetVolume();
}

void oamlGodotModule::Init(String defsFilename) {
	if (oaml == NULL)
		return;

	oaml->Init(defsFilename.ascii().get_data());
}

void oamlGodotModule::InitString(String defs) {
	if (oaml == NULL)
		return;

	oaml->InitString(defs.ascii());
}

bool oamlGodotModule::IsPaused() {
	if (oaml == NULL)
		return true;

	return oaml->IsPaused();
}

bool oamlGodotModule::IsPlaying() {
	if (oaml == NULL)
		return false;

	return oaml->IsPlaying();
}

bool oamlGodotModule::IsTrackPlaying(String name) {
	if (oaml == NULL)
		return false;

	return oaml->IsTrackPlaying(name.ascii());
}

void oamlGodotModule::LoadTrack(String name) {
	if (oaml == NULL)
		return;

	oaml->LoadTrack(name.ascii());
}

float oamlGodotModule::LoadTrackProgress(String name) {
	if (oaml == NULL)
		return -1.f;

	return oaml->LoadTrackProgress(name.ascii());
}

void oamlGodotModule::Pause() {
	if (oaml == NULL)
		return;

	oaml->Pause();
}

void oamlGodotModule::PlayTrack(String name) {
	if (oaml == NULL)
		return;

	oaml->PlayTrack(name.ascii());
}

void oamlGodotModule::PlayTrackWithStringRandom(String str) {
	if (oaml == NULL)
		return;

	oaml->PlayTrackWithStringRandom(str.ascii());
}

void oamlGodotModule::PlayTrackByGroupRandom(String group) {
	if (oaml == NULL)
		return;

	oaml->PlayTrackByGroupRandom(group.ascii());
}

void oamlGodotModule::PlayTrackByGroupAndSubgroupRandom(String group, String subgroup) {
	if (oaml == NULL)
		return;

	oaml->PlayTrackByGroupAndSubgroupRandom(group.ascii(), subgroup.ascii());
}

void oamlGodotModule::Resume() {
	if (oaml == NULL)
		return;

	oaml->Resume();
}

void oamlGodotModule::SetMainLoopCondition(int value) {
	if (oaml == NULL)
		return;

	oaml->SetMainLoopCondition(value);
}

void oamlGodotModule::SetCondition(int id, int value) {
	if (oaml == NULL)
		return;

	oaml->SetCondition(id, value);
}

void oamlGodotModule::SetLayerGain(String layer, float gain) {
	if (oaml == NULL)
		return;

	oaml->SetLayerGain(layer.ascii(), gain);
}

void oamlGodotModule::SetLayerRandomChance(String layer, int randomChance) {
	if (oaml == NULL)
		return;

	oaml->SetLayerRandomChance(layer.ascii(), randomChance);
}

void oamlGodotModule::SetTension(int value) {
	if (oaml == NULL)
		return;

	oaml->SetTension(value);
}

void oamlGodotModule::SetVolume(float value) {
	if (oaml == NULL)
		return;

	oaml->SetVolume(value);
}

void oamlGodotModule::StopPlaying() {
	if (oaml == NULL)
		return;

	oaml->StopPlaying();
}

String oamlGodotModule::SaveState() {
	if (oaml == NULL)
		return "";

	return oaml->SaveState().c_str();
}

void oamlGodotModule::LoadState(String state) {
	if (oaml == NULL)
		return;

	oaml->LoadState(state.utf8().get_data());
}

void oamlGodotModule::_bind_methods() {
	ClassDB::bind_method(D_METHOD("add_tension", "value"), &oamlGodotModule::AddTension);
	ClassDB::bind_method(D_METHOD("enable_dynamic_compressor", "enable", "thresholdDb", "ratio"), &oamlGodotModule::EnableDynamicCompressor, true, -3.0, 4.0);
	ClassDB::bind_method(D_METHOD("get_playing_info"), &oamlGodotModule::GetPlayingInfo);
	ClassDB::bind_method(D_METHOD("get_version"), &oamlGodotModule::GetVersion);
	ClassDB::bind_method(D_METHOD("get_volume"), &oamlGodotModule::GetVolume);
	ClassDB::bind_method(D_METHOD("init", "defsFilename"), &oamlGodotModule::Init);
	ClassDB::bind_method(D_METHOD("init_string", "defs"), &oamlGodotModule::InitString);
	ClassDB::bind_method(D_METHOD("is_paused"), &oamlGodotModule::IsPaused);
	ClassDB::bind_method(D_METHOD("is_playing"), &oamlGodotModule::IsPlaying);
	ClassDB::bind_method(D_METHOD("is_track_playing", "name"), &oamlGodotModule::IsTrackPlaying);
	ClassDB::bind_method(D_METHOD("load_state", "state"), &oamlGodotModule::LoadState);
	ClassDB::bind_method(D_METHOD("load_track", "name"), &oamlGodotModule::LoadTrack);
	ClassDB::bind_method(D_METHOD("load_track_progress", "name"), &oamlGodotModule::LoadTrackProgress);
	ClassDB::bind_method(D_METHOD("pause"), &oamlGodotModule::Pause);
	ClassDB::bind_method(D_METHOD("play_track", "name"), &oamlGodotModule::PlayTrack);
	ClassDB::bind_method(D_METHOD("play_track_with_string_random", "str"), &oamlGodotModule::PlayTrackWithStringRandom);
	ClassDB::bind_method(D_METHOD("play_track_by_group_random", "group"), &oamlGodotModule::PlayTrackByGroupRandom);
	ClassDB::bind_method(D_METHOD("play_track_by_group_and_subgroup_random", "group", "subgroup"), &oamlGodotModule::PlayTrackByGroupAndSubgroupRandom);
	ClassDB::bind_method(D_METHOD("resume"), &oamlGodotModule::Resume);
	ClassDB::bind_method(D_METHOD("save_state"), &oamlGodotModule::SaveState);
	ClassDB::bind_method(D_METHOD("set_main_loop_condition", "value"), &oamlGodotModule::SetMainLoopCondition);
	ClassDB::bind_method(D_METHOD("set_condition", "id", "value"), &oamlGodotModule::SetCondition);
	ClassDB::bind_method(D_METHOD("set_layer_gain", "layer", "gain"), &oamlGodotModule::SetLayerGain);
	ClassDB::bind_method(D_METHOD("set_layer_random_chance", "layer", "randomChance"), &oamlGodotModule::SetLayerRandomChance);
	ClassDB::bind_method(D_METHOD("set_tension", "value"), &oamlGodotModule::SetTension);
	ClassDB::bind_method(D_METHOD("set_volume", "vol"), &oamlGodotModule::SetVolume);
	ClassDB::bind_method(D_METHOD("stop_playing"), &oamlGodotModule::StopPlaying);
}

static void* oamlOpen(const char *filename) {
	String path = "res://"+String(filename);
	FileAccess *f = FileAccess::open(path, FileAccess::READ);
	if (f == NULL) {
		ConfigFile cf;
		Error err = cf.load(path + ".import");
		if (err == OK) {
			f = FileAccess::open(cf.get_value("remap", "path"), FileAccess::READ);
			if (f != NULL) {
				char header[5] = "0000";
				f->seek(28);
				while (strncmp(header, "OggS", 4) != 0) {
					f->get_buffer((uint8_t*)header, 4);
					f->seek(f->get_position()-3);
				}
				f->seek(f->get_position()-1);
				return (void*)f;
			}
		}

		print_line("oaml: Error opening resource file:" + path);
		return NULL;
	}
	return (void*)f;
}

static size_t oamlRead(void *ptr, size_t size, size_t nitems, void *fd) {
	FileAccess *f = (FileAccess*)fd;
	return f->get_buffer((uint8_t*)ptr, size*nitems);
}

static int oamlSeek(void *fd, long offset, int whence) {
	FileAccess *f = (FileAccess*)fd;
	if (whence == SEEK_SET)
		f->seek(offset);
	else if (whence == SEEK_END)
		f->seek_end(offset);
	else if (whence == SEEK_CUR)
		f->seek(f->get_position()+offset);
	return 0;
}

static long oamlTell(void *fd) {
	FileAccess *f = (FileAccess*)fd;
	return f->get_position();
}

static int oamlClose(void *fd) {
	FileAccess *f = (FileAccess*)fd;
	f->close();
	memdelete(f);
	return 0;
}

static oamlFileCallbacks fileCbs = {
	&oamlOpen,
	&oamlRead,
	&oamlSeek,
	&oamlTell,
	&oamlClose
};

oamlGodotModule::oamlGodotModule() {
	oaml = new oamlApi();
	oaml->SetFileCallbacks(&fileCbs);
	oaml->SetAudioFormat(AudioServer::get_singleton()->get_mix_rate(), 2, 4, true);

	AudioServer::get_singleton()->lock();
	mix_buffer.resize(AudioServer::get_singleton()->thread_get_mix_buffer_size());
	AudioServer::get_singleton()->unlock();

	AudioServer::get_singleton()->add_callback(_mix_audios, this);
}

oamlGodotModule::~oamlGodotModule() {
	if (oaml != NULL) {
		oaml->Shutdown();
		delete oaml;
		oaml = NULL;
	}

	AudioServer::get_singleton()->remove_callback(_mix_audios, this);
}
<|endoftext|>


<commit_before>// Copyright 2013 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 "content/renderer/media/android/media_info_loader.h"

#include "base/bits.h"
#include "base/callback_helpers.h"
#include "base/metrics/histogram.h"
#include "third_party/WebKit/public/platform/WebURLError.h"
#include "third_party/WebKit/public/platform/WebURLLoader.h"
#include "third_party/WebKit/public/platform/WebURLResponse.h"
#include "third_party/WebKit/public/web/WebFrame.h"

using blink::WebFrame;
using blink::WebURLError;
using blink::WebURLLoader;
using blink::WebURLLoaderOptions;
using blink::WebURLRequest;
using blink::WebURLResponse;

namespace content {

static const int kHttpOK = 200;

MediaInfoLoader::MediaInfoLoader(
    const GURL& url,
    blink::WebMediaPlayer::CORSMode cors_mode,
    const ReadyCB& ready_cb)
    : loader_failed_(false),
      url_(url),
      allow_stored_credentials_(false),
      cors_mode_(cors_mode),
      single_origin_(true),
      ready_cb_(ready_cb) {}

MediaInfoLoader::~MediaInfoLoader() {}

void MediaInfoLoader::Start(blink::WebFrame* frame) {
  // Make sure we have not started.
  DCHECK(!ready_cb_.is_null());
  CHECK(frame);

  start_time_ = base::TimeTicks::Now();
  first_party_url_ = frame->document().firstPartyForCookies();

  // Prepare the request.
  WebURLRequest request(url_);
  // TODO(mkwst): Split this into video/audio.
  request.setRequestContext(WebURLRequest::RequestContextVideo);
  frame->setReferrerForRequest(request, blink::WebURL());

  scoped_ptr<WebURLLoader> loader;
  if (test_loader_) {
    loader = test_loader_.Pass();
  } else {
    WebURLLoaderOptions options;
    if (cors_mode_ == blink::WebMediaPlayer::CORSModeUnspecified) {
      options.allowCredentials = true;
      options.crossOriginRequestPolicy =
          WebURLLoaderOptions::CrossOriginRequestPolicyAllow;
      allow_stored_credentials_ = true;
    } else {
      options.exposeAllResponseHeaders = true;
      // The author header set is empty, no preflight should go ahead.
      options.preflightPolicy = WebURLLoaderOptions::PreventPreflight;
      options.crossOriginRequestPolicy =
          WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;
      if (cors_mode_ == blink::WebMediaPlayer::CORSModeUseCredentials) {
        options.allowCredentials = true;
        allow_stored_credentials_ = true;
      }
    }
    loader.reset(frame->createAssociatedURLLoader(options));
  }

  // Start the resource loading.
  loader->loadAsynchronously(request, this);
  active_loader_.reset(new ActiveLoader(loader.Pass()));
}

/////////////////////////////////////////////////////////////////////////////
// blink::WebURLLoaderClient implementation.
void MediaInfoLoader::willSendRequest(
    WebURLLoader* loader,
    WebURLRequest& newRequest,
    const WebURLResponse& redirectResponse) {
  // The load may have been stopped and |ready_cb| is destroyed.
  // In this case we shouldn't do anything.
  if (ready_cb_.is_null()) {
    // Set the url in the request to an invalid value (empty url).
    newRequest.setURL(blink::WebURL());
    return;
  }

  // Only allow |single_origin_| if we haven't seen a different origin yet.
  if (single_origin_)
    single_origin_ = url_.GetOrigin() == GURL(newRequest.url()).GetOrigin();

  url_ = newRequest.url();
  first_party_url_ = newRequest.firstPartyForCookies();
  allow_stored_credentials_ = newRequest.allowStoredCredentials();
}

void MediaInfoLoader::didSendData(
    WebURLLoader* loader,
    unsigned long long bytes_sent,
    unsigned long long total_bytes_to_be_sent) {
  NOTIMPLEMENTED();
}

void MediaInfoLoader::didReceiveResponse(
    WebURLLoader* loader,
    const WebURLResponse& response) {
  DVLOG(1) << "didReceiveResponse: HTTP/"
           << (response.httpVersion() == WebURLResponse::HTTP_0_9 ? "0.9" :
               response.httpVersion() == WebURLResponse::HTTP_1_0 ? "1.0" :
               response.httpVersion() == WebURLResponse::HTTP_1_1 ? "1.1" :
               "Unknown")
           << " " << response.httpStatusCode();
  DCHECK(active_loader_.get());
  if (!url_.SchemeIs("http") && !url_.SchemeIs("https")) {
      DidBecomeReady(kOk);
      return;
  }
  if (response.httpStatusCode() == kHttpOK) {
    DidBecomeReady(kOk);
    return;
  }
  loader_failed_ = true;
  DidBecomeReady(kFailed);
}

void MediaInfoLoader::didReceiveData(
    WebURLLoader* loader,
    const char* data,
    int data_length,
    int encoded_data_length) {
  // Ignored.
}

void MediaInfoLoader::didDownloadData(
    blink::WebURLLoader* loader,
    int dataLength,
    int encodedDataLength) {
  NOTIMPLEMENTED();
}

void MediaInfoLoader::didReceiveCachedMetadata(
    WebURLLoader* loader,
    const char* data,
    int data_length) {
  NOTIMPLEMENTED();
}

void MediaInfoLoader::didFinishLoading(
    WebURLLoader* loader,
    double finishTime,
    int64_t total_encoded_data_length) {
  DCHECK(active_loader_.get());
  DidBecomeReady(kOk);
}

void MediaInfoLoader::didFail(
    WebURLLoader* loader,
    const WebURLError& error) {
  DVLOG(1) << "didFail: reason=" << error.reason
           << ", isCancellation=" << error.isCancellation
           << ", domain=" << error.domain.utf8().data()
           << ", localizedDescription="
           << error.localizedDescription.utf8().data();
  DCHECK(active_loader_.get());
  loader_failed_ = true;
  DidBecomeReady(kFailed);
}

bool MediaInfoLoader::HasSingleOrigin() const {
  DCHECK(ready_cb_.is_null())
      << "Must become ready before calling HasSingleOrigin()";
  return single_origin_;
}

bool MediaInfoLoader::DidPassCORSAccessCheck() const {
  DCHECK(ready_cb_.is_null())
      << "Must become ready before calling DidPassCORSAccessCheck()";
  return !loader_failed_ &&
      cors_mode_ != blink::WebMediaPlayer::CORSModeUnspecified;
}

/////////////////////////////////////////////////////////////////////////////
// Helper methods.

void MediaInfoLoader::DidBecomeReady(Status status) {
  UMA_HISTOGRAM_TIMES("Media.InfoLoadDelay",
                      base::TimeTicks::Now() - start_time_);
  active_loader_.reset();
  if (!ready_cb_.is_null())
    base::ResetAndReturn(&ready_cb_).Run(status, url_, first_party_url_,
                                         allow_stored_credentials_);
}

}  // namespace content
<commit_msg>Use range request for CORS access check on Android.<commit_after>// Copyright 2013 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 "content/renderer/media/android/media_info_loader.h"

#include "base/bits.h"
#include "base/callback_helpers.h"
#include "base/metrics/histogram.h"
#include "third_party/WebKit/public/platform/WebURLError.h"
#include "third_party/WebKit/public/platform/WebURLLoader.h"
#include "third_party/WebKit/public/platform/WebURLResponse.h"
#include "third_party/WebKit/public/web/WebFrame.h"

using blink::WebFrame;
using blink::WebURLError;
using blink::WebURLLoader;
using blink::WebURLLoaderOptions;
using blink::WebURLRequest;
using blink::WebURLResponse;

namespace content {

static const int kHttpOK = 200;
static const int kHttpPartialContentOK = 206;

MediaInfoLoader::MediaInfoLoader(
    const GURL& url,
    blink::WebMediaPlayer::CORSMode cors_mode,
    const ReadyCB& ready_cb)
    : loader_failed_(false),
      url_(url),
      allow_stored_credentials_(false),
      cors_mode_(cors_mode),
      single_origin_(true),
      ready_cb_(ready_cb) {}

MediaInfoLoader::~MediaInfoLoader() {}

void MediaInfoLoader::Start(blink::WebFrame* frame) {
  // Make sure we have not started.
  DCHECK(!ready_cb_.is_null());
  CHECK(frame);

  start_time_ = base::TimeTicks::Now();
  first_party_url_ = frame->document().firstPartyForCookies();

  // Prepare the request.
  WebURLRequest request(url_);
  // TODO(mkwst): Split this into video/audio.
  request.setRequestContext(WebURLRequest::RequestContextVideo);
  frame->setReferrerForRequest(request, blink::WebURL());

  // Since we don't actually care about the media data at this time, use a two
  // byte range request to avoid unnecessarily downloading resources.  Not all
  // servers support HEAD unfortunately, so use a range request; which is no
  // worse than the previous request+cancel code.  See http://crbug.com/400788
  request.addHTTPHeaderField("Range", "bytes=0-1");

  scoped_ptr<WebURLLoader> loader;
  if (test_loader_) {
    loader = test_loader_.Pass();
  } else {
    WebURLLoaderOptions options;
    if (cors_mode_ == blink::WebMediaPlayer::CORSModeUnspecified) {
      options.allowCredentials = true;
      options.crossOriginRequestPolicy =
          WebURLLoaderOptions::CrossOriginRequestPolicyAllow;
      allow_stored_credentials_ = true;
    } else {
      options.exposeAllResponseHeaders = true;
      // The author header set is empty, no preflight should go ahead.
      options.preflightPolicy = WebURLLoaderOptions::PreventPreflight;
      options.crossOriginRequestPolicy =
          WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;
      if (cors_mode_ == blink::WebMediaPlayer::CORSModeUseCredentials) {
        options.allowCredentials = true;
        allow_stored_credentials_ = true;
      }
    }
    loader.reset(frame->createAssociatedURLLoader(options));
  }

  // Start the resource loading.
  loader->loadAsynchronously(request, this);
  active_loader_.reset(new ActiveLoader(loader.Pass()));
}

/////////////////////////////////////////////////////////////////////////////
// blink::WebURLLoaderClient implementation.
void MediaInfoLoader::willSendRequest(
    WebURLLoader* loader,
    WebURLRequest& newRequest,
    const WebURLResponse& redirectResponse) {
  // The load may have been stopped and |ready_cb| is destroyed.
  // In this case we shouldn't do anything.
  if (ready_cb_.is_null()) {
    // Set the url in the request to an invalid value (empty url).
    newRequest.setURL(blink::WebURL());
    return;
  }

  // Only allow |single_origin_| if we haven't seen a different origin yet.
  if (single_origin_)
    single_origin_ = url_.GetOrigin() == GURL(newRequest.url()).GetOrigin();

  url_ = newRequest.url();
  first_party_url_ = newRequest.firstPartyForCookies();
  allow_stored_credentials_ = newRequest.allowStoredCredentials();
}

void MediaInfoLoader::didSendData(
    WebURLLoader* loader,
    unsigned long long bytes_sent,
    unsigned long long total_bytes_to_be_sent) {
  NOTIMPLEMENTED();
}

void MediaInfoLoader::didReceiveResponse(
    WebURLLoader* loader,
    const WebURLResponse& response) {
  DVLOG(1) << "didReceiveResponse: HTTP/"
           << (response.httpVersion() == WebURLResponse::HTTP_0_9 ? "0.9" :
               response.httpVersion() == WebURLResponse::HTTP_1_0 ? "1.0" :
               response.httpVersion() == WebURLResponse::HTTP_1_1 ? "1.1" :
               "Unknown")
           << " " << response.httpStatusCode();
  DCHECK(active_loader_.get());
  if (!url_.SchemeIs("http") && !url_.SchemeIs("https")) {
      DidBecomeReady(kOk);
      return;
  }
  if (response.httpStatusCode() == kHttpOK ||
      response.httpStatusCode() == kHttpPartialContentOK) {
    DidBecomeReady(kOk);
    return;
  }
  loader_failed_ = true;
  DidBecomeReady(kFailed);
}

void MediaInfoLoader::didReceiveData(
    WebURLLoader* loader,
    const char* data,
    int data_length,
    int encoded_data_length) {
  // Ignored.
}

void MediaInfoLoader::didDownloadData(
    blink::WebURLLoader* loader,
    int dataLength,
    int encodedDataLength) {
  NOTIMPLEMENTED();
}

void MediaInfoLoader::didReceiveCachedMetadata(
    WebURLLoader* loader,
    const char* data,
    int data_length) {
  NOTIMPLEMENTED();
}

void MediaInfoLoader::didFinishLoading(
    WebURLLoader* loader,
    double finishTime,
    int64_t total_encoded_data_length) {
  DCHECK(active_loader_.get());
  DidBecomeReady(kOk);
}

void MediaInfoLoader::didFail(
    WebURLLoader* loader,
    const WebURLError& error) {
  DVLOG(1) << "didFail: reason=" << error.reason
           << ", isCancellation=" << error.isCancellation
           << ", domain=" << error.domain.utf8().data()
           << ", localizedDescription="
           << error.localizedDescription.utf8().data();
  DCHECK(active_loader_.get());
  loader_failed_ = true;
  DidBecomeReady(kFailed);
}

bool MediaInfoLoader::HasSingleOrigin() const {
  DCHECK(ready_cb_.is_null())
      << "Must become ready before calling HasSingleOrigin()";
  return single_origin_;
}

bool MediaInfoLoader::DidPassCORSAccessCheck() const {
  DCHECK(ready_cb_.is_null())
      << "Must become ready before calling DidPassCORSAccessCheck()";
  return !loader_failed_ &&
      cors_mode_ != blink::WebMediaPlayer::CORSModeUnspecified;
}

/////////////////////////////////////////////////////////////////////////////
// Helper methods.

void MediaInfoLoader::DidBecomeReady(Status status) {
  UMA_HISTOGRAM_TIMES("Media.InfoLoadDelay",
                      base::TimeTicks::Now() - start_time_);
  active_loader_.reset();
  if (!ready_cb_.is_null())
    base::ResetAndReturn(&ready_cb_).Run(status, url_, first_party_url_,
                                         allow_stored_credentials_);
}

}  // namespace content
<|endoftext|>


<commit_before>// Copyright (c) 2013 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 "ash/display/root_window_transformers.h"

#include <cmath>

#include "ash/display/display_info.h"
#include "ash/display/display_manager.h"
#include "ash/magnifier/magnification_controller.h"
#include "ash/shell.h"
#include "base/basictypes.h"
#include "base/memory/scoped_ptr.h"
#include "third_party/skia/include/utils/SkMatrix44.h"
#include "ui/aura/root_window.h"
#include "ui/aura/root_window_transformer.h"
#include "ui/aura/window_property.h"
#include "ui/compositor/dip_util.h"
#include "ui/gfx/display.h"
#include "ui/gfx/insets.h"
#include "ui/gfx/size_conversions.h"
#include "ui/gfx/transform.h"
#include "ui/gfx/transform.h"

DECLARE_WINDOW_PROPERTY_TYPE(gfx::Display::Rotation);

namespace ash {
namespace internal {
namespace {

DEFINE_WINDOW_PROPERTY_KEY(gfx::Display::Rotation, kRotationPropertyKey,
                           gfx::Display::ROTATE_0);

// Round near zero value to zero.
void RoundNearZero(gfx::Transform* transform) {
  const float kEpsilon = 0.001f;
  SkMatrix44& matrix = transform->matrix();
  for (int x = 0; x < 4; ++x) {
    for (int y = 0; y < 4; ++y) {
      if (std::abs(SkMScalarToFloat(matrix.get(x, y))) < kEpsilon)
        matrix.set(x, y, SkFloatToMScalar(0.0f));
    }
  }
}

gfx::Transform CreateRotationTransform(aura::RootWindow* root_window,
                                       const gfx::Display& display) {
  DisplayInfo info =
      Shell::GetInstance()->display_manager()->GetDisplayInfo(display.id());

  // TODO(oshima): Add animation. (crossfade+rotation, or just cross-fade)
#if defined(OS_WIN)
  // Windows 8 bots refused to resize the host window, and
  // updating the transform results in incorrectly resizing
  // the root window. Don't apply the transform unless
  // necessary so that unit tests pass on win8 bots.
  if (info.rotation() == root_window->GetProperty(kRotationPropertyKey))
    return gfx::Transform();
  root_window->SetProperty(kRotationPropertyKey, info.rotation());
#endif

  gfx::Transform rotate;
  // The origin is (0, 0), so the translate width/height must be reduced by
  // 1 pixel.
  float one_pixel = 1.0f / display.device_scale_factor();
  switch (info.rotation()) {
    case gfx::Display::ROTATE_0:
      break;
    case gfx::Display::ROTATE_90:
      rotate.Translate(display.bounds().height() - one_pixel, 0);
      rotate.Rotate(90);
      break;
    case gfx::Display::ROTATE_270:
      rotate.Translate(0, display.bounds().width() - one_pixel);
      rotate.Rotate(270);
      break;
    case gfx::Display::ROTATE_180:
      rotate.Translate(display.bounds().width() - one_pixel,
                       display.bounds().height() - one_pixel);
      rotate.Rotate(180);
      break;
  }

  RoundNearZero(&rotate);
  return rotate;
}

gfx::Transform CreateMagnifierTransform(aura::RootWindow* root_window) {
  MagnificationController* magnifier =
      Shell::GetInstance()->magnification_controller();
  float magnifier_scale = 1.f;
  gfx::Point magnifier_offset;
  if (magnifier && magnifier->IsEnabled()) {
    magnifier_scale = magnifier->GetScale();
    magnifier_offset = magnifier->GetWindowPosition();
  }
  gfx::Transform transform;
  if (magnifier_scale != 1.f) {
    transform.Scale(magnifier_scale, magnifier_scale);
    transform.Translate(-magnifier_offset.x(), -magnifier_offset.y());
  }
  return transform;
}

gfx::Transform CreateInsetsAndScaleTransform(const gfx::Insets& insets,
                                             float device_scale_factor,
                                             float ui_scale) {
  gfx::Transform transform;
  if (insets.top() != 0 || insets.left() != 0) {
    float x_offset = insets.left() / device_scale_factor;
    float y_offset = insets.top() / device_scale_factor;
    transform.Translate(x_offset, y_offset);
  }
  float inverted_scale = 1.0f / ui_scale;
  transform.Scale(inverted_scale, inverted_scale);
  return transform;
}

gfx::Transform CreateOverscanAndUIScaleTransform(aura::RootWindow* root_window,
                                                 const gfx::Display& display) {
  DisplayInfo info =
      Shell::GetInstance()->display_manager()->GetDisplayInfo(display.id());
  return CreateInsetsAndScaleTransform(
      info.GetOverscanInsetsInPixel(),
      ui::GetDeviceScaleFactor(root_window->layer()),
      info.ui_scale());
}

// RootWindowTransformer for ash environment.
class AshRootWindowTransformer : public aura::RootWindowTransformer {
 public:
  AshRootWindowTransformer(aura::RootWindow* root,
                           const gfx::Display& display)
      : root_window_(root) {
    root_window_bounds_transform_ =
        CreateOverscanAndUIScaleTransform(root, display) *
        CreateRotationTransform(root, display);
    transform_ = root_window_bounds_transform_ * CreateMagnifierTransform(root);
    CHECK(transform_.GetInverse(&invert_transform_));

    DisplayInfo info = Shell::GetInstance()->display_manager()->
        GetDisplayInfo(display.id());
    root_window_ui_scale_ = info.ui_scale();
    host_insets_ = info.GetOverscanInsetsInPixel();
    MagnificationController* magnifier =
        Shell::GetInstance()->magnification_controller();

    bool scaled = (root_window_ui_scale_ != 1.f) ||
        (magnifier && magnifier->GetScale() != 1.f);
    root_window_->layer()->SetForceRenderSurface(scaled);
  }

  // aura::RootWindowTransformer overrides:
  virtual gfx::Transform GetTransform() const OVERRIDE {
    return transform_;
  }
  virtual gfx::Transform GetInverseTransform() const OVERRIDE {
    return invert_transform_;
  }
  virtual gfx::Rect GetRootWindowBounds(
      const gfx::Size& host_size) const OVERRIDE {
    gfx::Rect bounds(host_size);
    bounds.Inset(host_insets_);
    bounds = ui::ConvertRectToDIP(root_window_->layer(), bounds);
    gfx::RectF new_bounds(bounds);
    root_window_bounds_transform_.TransformRect(&new_bounds);
    // Apply |root_window_scale_| twice as the downscaling
    // is already applied once in |SetTransformInternal()|.
    // TODO(oshima): This is a bit ugly. Consider specifying
    // the pseudo host resolution instead.
    new_bounds.Scale(root_window_ui_scale_ * root_window_ui_scale_);
    // Ignore the origin because RootWindow's insets are handled by
    // the transform.
    // Floor the size because the bounds is no longer aligned to
    // backing pixel when |root_window_scale_| is specified
    // (850 height at 1.25 scale becomes 1062.5 for example.)
    return gfx::Rect(gfx::ToFlooredSize(new_bounds.size()));
  }

  virtual gfx::Insets GetHostInsets() const OVERRIDE {
    return host_insets_;
  }

 private:
  virtual ~AshRootWindowTransformer() {}

  aura::RootWindow* root_window_;
  gfx::Transform transform_;

  // The accurate representation of the inverse of the |transform_|.
  // This is used to avoid computation error caused by
  // |gfx::Transform::GetInverse|.
  gfx::Transform invert_transform_;

  // The transform of the root window bounds. This is used to calculate
  // the size of root window.
  gfx::Transform root_window_bounds_transform_;

  // The scale of the root window. This is used to expand the
  // area of the root window (useful in HighDPI display).
  // Note that this should not be confused with the device scale
  // factor, which specfies the pixel density of the display.
  float root_window_ui_scale_;

  gfx::Insets host_insets_;

  DISALLOW_COPY_AND_ASSIGN(AshRootWindowTransformer);
};

// RootWindowTransformer for mirror root window. We simply copy the
// texture (bitmap) of the source display into the mirror window, so
// the root window bounds is the same as the source display's
// pixel size (excluding overscan insets).
class MirrorRootWindowTransformer : public aura::RootWindowTransformer {
 public:
  MirrorRootWindowTransformer(const DisplayInfo& source_display_info,
                              const DisplayInfo& mirror_display_info) {
    root_bounds_ = gfx::Rect(source_display_info.bounds_in_pixel().size());
    gfx::Rect mirror_display_rect =
        gfx::Rect(mirror_display_info.bounds_in_pixel().size());

    bool letterbox = root_bounds_.width() * mirror_display_rect.height() >
        root_bounds_.height() * mirror_display_rect.width();
    if (letterbox) {
      float mirror_scale_ratio =
          (static_cast<float>(root_bounds_.width()) /
           static_cast<float>(mirror_display_rect.width()));
      float inverted_scale = 1.0f / mirror_scale_ratio;
      int margin = static_cast<int>(
          (mirror_display_rect.height() -
           root_bounds_.height() * inverted_scale) / 2);
      insets_.Set(0, margin, 0, margin);

      transform_.Translate(0,  margin);
      transform_.Scale(inverted_scale, inverted_scale);
    } else {
      float mirror_scale_ratio =
          (static_cast<float>(root_bounds_.height()) /
           static_cast<float>(mirror_display_rect.height()));
      float inverted_scale = 1.0f / mirror_scale_ratio;
      int margin = static_cast<int>(
          (mirror_display_rect.width() -
           root_bounds_.width() * inverted_scale) / 2);
      insets_.Set(margin, 0, margin, 0);

      transform_.Translate(margin, 0);
      transform_.Scale(inverted_scale, inverted_scale);
    }
  }

  // aura::RootWindowTransformer overrides:
  virtual gfx::Transform GetTransform() const OVERRIDE {
    return transform_;
  }
  virtual gfx::Transform GetInverseTransform() const OVERRIDE {
    gfx::Transform invert;
    CHECK(transform_.GetInverse(&invert));
    return invert;
  }
  virtual gfx::Rect GetRootWindowBounds(
      const gfx::Size& host_size) const OVERRIDE {
    return root_bounds_;
  }
  virtual gfx::Insets GetHostInsets() const OVERRIDE {
    return insets_;
  }

 private:
  virtual ~MirrorRootWindowTransformer() {}

  gfx::Transform transform_;
  gfx::Rect root_bounds_;
  gfx::Insets insets_;

  DISALLOW_COPY_AND_ASSIGN(MirrorRootWindowTransformer);
};

}  // namespace

aura::RootWindowTransformer* CreateRootWindowTransformerForDisplay(
    aura::RootWindow* root,
    const gfx::Display& display) {
  return new AshRootWindowTransformer(root, display);
}

aura::RootWindowTransformer* CreateRootWindowTransformerForMirroredDisplay(
    const DisplayInfo& source_display_info,
    const DisplayInfo& mirror_display_info) {
  return new MirrorRootWindowTransformer(source_display_info,
                                         mirror_display_info);
}

}  // namespace internal
}  // namespace ash
<commit_msg>Stop using ForceRenderSurface for ui scaling  This causes issue with inverse filter, and  UI looks perfectly fine without this option.<commit_after>// Copyright (c) 2013 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 "ash/display/root_window_transformers.h"

#include <cmath>

#include "ash/display/display_info.h"
#include "ash/display/display_manager.h"
#include "ash/magnifier/magnification_controller.h"
#include "ash/shell.h"
#include "base/basictypes.h"
#include "base/memory/scoped_ptr.h"
#include "third_party/skia/include/utils/SkMatrix44.h"
#include "ui/aura/root_window.h"
#include "ui/aura/root_window_transformer.h"
#include "ui/aura/window_property.h"
#include "ui/compositor/dip_util.h"
#include "ui/gfx/display.h"
#include "ui/gfx/insets.h"
#include "ui/gfx/size_conversions.h"
#include "ui/gfx/transform.h"
#include "ui/gfx/transform.h"

DECLARE_WINDOW_PROPERTY_TYPE(gfx::Display::Rotation);

namespace ash {
namespace internal {
namespace {

DEFINE_WINDOW_PROPERTY_KEY(gfx::Display::Rotation, kRotationPropertyKey,
                           gfx::Display::ROTATE_0);

// Round near zero value to zero.
void RoundNearZero(gfx::Transform* transform) {
  const float kEpsilon = 0.001f;
  SkMatrix44& matrix = transform->matrix();
  for (int x = 0; x < 4; ++x) {
    for (int y = 0; y < 4; ++y) {
      if (std::abs(SkMScalarToFloat(matrix.get(x, y))) < kEpsilon)
        matrix.set(x, y, SkFloatToMScalar(0.0f));
    }
  }
}

gfx::Transform CreateRotationTransform(aura::RootWindow* root_window,
                                       const gfx::Display& display) {
  DisplayInfo info =
      Shell::GetInstance()->display_manager()->GetDisplayInfo(display.id());

  // TODO(oshima): Add animation. (crossfade+rotation, or just cross-fade)
#if defined(OS_WIN)
  // Windows 8 bots refused to resize the host window, and
  // updating the transform results in incorrectly resizing
  // the root window. Don't apply the transform unless
  // necessary so that unit tests pass on win8 bots.
  if (info.rotation() == root_window->GetProperty(kRotationPropertyKey))
    return gfx::Transform();
  root_window->SetProperty(kRotationPropertyKey, info.rotation());
#endif

  gfx::Transform rotate;
  // The origin is (0, 0), so the translate width/height must be reduced by
  // 1 pixel.
  float one_pixel = 1.0f / display.device_scale_factor();
  switch (info.rotation()) {
    case gfx::Display::ROTATE_0:
      break;
    case gfx::Display::ROTATE_90:
      rotate.Translate(display.bounds().height() - one_pixel, 0);
      rotate.Rotate(90);
      break;
    case gfx::Display::ROTATE_270:
      rotate.Translate(0, display.bounds().width() - one_pixel);
      rotate.Rotate(270);
      break;
    case gfx::Display::ROTATE_180:
      rotate.Translate(display.bounds().width() - one_pixel,
                       display.bounds().height() - one_pixel);
      rotate.Rotate(180);
      break;
  }

  RoundNearZero(&rotate);
  return rotate;
}

gfx::Transform CreateMagnifierTransform(aura::RootWindow* root_window) {
  MagnificationController* magnifier =
      Shell::GetInstance()->magnification_controller();
  float magnifier_scale = 1.f;
  gfx::Point magnifier_offset;
  if (magnifier && magnifier->IsEnabled()) {
    magnifier_scale = magnifier->GetScale();
    magnifier_offset = magnifier->GetWindowPosition();
  }
  gfx::Transform transform;
  if (magnifier_scale != 1.f) {
    transform.Scale(magnifier_scale, magnifier_scale);
    transform.Translate(-magnifier_offset.x(), -magnifier_offset.y());
  }
  return transform;
}

gfx::Transform CreateInsetsAndScaleTransform(const gfx::Insets& insets,
                                             float device_scale_factor,
                                             float ui_scale) {
  gfx::Transform transform;
  if (insets.top() != 0 || insets.left() != 0) {
    float x_offset = insets.left() / device_scale_factor;
    float y_offset = insets.top() / device_scale_factor;
    transform.Translate(x_offset, y_offset);
  }
  float inverted_scale = 1.0f / ui_scale;
  transform.Scale(inverted_scale, inverted_scale);
  return transform;
}

gfx::Transform CreateOverscanAndUIScaleTransform(aura::RootWindow* root_window,
                                                 const gfx::Display& display) {
  DisplayInfo info =
      Shell::GetInstance()->display_manager()->GetDisplayInfo(display.id());
  return CreateInsetsAndScaleTransform(
      info.GetOverscanInsetsInPixel(),
      ui::GetDeviceScaleFactor(root_window->layer()),
      info.ui_scale());
}

// RootWindowTransformer for ash environment.
class AshRootWindowTransformer : public aura::RootWindowTransformer {
 public:
  AshRootWindowTransformer(aura::RootWindow* root,
                           const gfx::Display& display)
      : root_window_(root) {
    root_window_bounds_transform_ =
        CreateOverscanAndUIScaleTransform(root, display) *
        CreateRotationTransform(root, display);
    transform_ = root_window_bounds_transform_ * CreateMagnifierTransform(root);
    CHECK(transform_.GetInverse(&invert_transform_));

    DisplayInfo info = Shell::GetInstance()->display_manager()->
        GetDisplayInfo(display.id());
    root_window_ui_scale_ = info.ui_scale();
    host_insets_ = info.GetOverscanInsetsInPixel();
  }

  // aura::RootWindowTransformer overrides:
  virtual gfx::Transform GetTransform() const OVERRIDE {
    return transform_;
  }
  virtual gfx::Transform GetInverseTransform() const OVERRIDE {
    return invert_transform_;
  }
  virtual gfx::Rect GetRootWindowBounds(
      const gfx::Size& host_size) const OVERRIDE {
    gfx::Rect bounds(host_size);
    bounds.Inset(host_insets_);
    bounds = ui::ConvertRectToDIP(root_window_->layer(), bounds);
    gfx::RectF new_bounds(bounds);
    root_window_bounds_transform_.TransformRect(&new_bounds);
    // Apply |root_window_scale_| twice as the downscaling
    // is already applied once in |SetTransformInternal()|.
    // TODO(oshima): This is a bit ugly. Consider specifying
    // the pseudo host resolution instead.
    new_bounds.Scale(root_window_ui_scale_ * root_window_ui_scale_);
    // Ignore the origin because RootWindow's insets are handled by
    // the transform.
    // Floor the size because the bounds is no longer aligned to
    // backing pixel when |root_window_scale_| is specified
    // (850 height at 1.25 scale becomes 1062.5 for example.)
    return gfx::Rect(gfx::ToFlooredSize(new_bounds.size()));
  }

  virtual gfx::Insets GetHostInsets() const OVERRIDE {
    return host_insets_;
  }

 private:
  virtual ~AshRootWindowTransformer() {}

  aura::RootWindow* root_window_;
  gfx::Transform transform_;

  // The accurate representation of the inverse of the |transform_|.
  // This is used to avoid computation error caused by
  // |gfx::Transform::GetInverse|.
  gfx::Transform invert_transform_;

  // The transform of the root window bounds. This is used to calculate
  // the size of root window.
  gfx::Transform root_window_bounds_transform_;

  // The scale of the root window. This is used to expand the
  // area of the root window (useful in HighDPI display).
  // Note that this should not be confused with the device scale
  // factor, which specfies the pixel density of the display.
  float root_window_ui_scale_;

  gfx::Insets host_insets_;

  DISALLOW_COPY_AND_ASSIGN(AshRootWindowTransformer);
};

// RootWindowTransformer for mirror root window. We simply copy the
// texture (bitmap) of the source display into the mirror window, so
// the root window bounds is the same as the source display's
// pixel size (excluding overscan insets).
class MirrorRootWindowTransformer : public aura::RootWindowTransformer {
 public:
  MirrorRootWindowTransformer(const DisplayInfo& source_display_info,
                              const DisplayInfo& mirror_display_info) {
    root_bounds_ = gfx::Rect(source_display_info.bounds_in_pixel().size());
    gfx::Rect mirror_display_rect =
        gfx::Rect(mirror_display_info.bounds_in_pixel().size());

    bool letterbox = root_bounds_.width() * mirror_display_rect.height() >
        root_bounds_.height() * mirror_display_rect.width();
    if (letterbox) {
      float mirror_scale_ratio =
          (static_cast<float>(root_bounds_.width()) /
           static_cast<float>(mirror_display_rect.width()));
      float inverted_scale = 1.0f / mirror_scale_ratio;
      int margin = static_cast<int>(
          (mirror_display_rect.height() -
           root_bounds_.height() * inverted_scale) / 2);
      insets_.Set(0, margin, 0, margin);

      transform_.Translate(0,  margin);
      transform_.Scale(inverted_scale, inverted_scale);
    } else {
      float mirror_scale_ratio =
          (static_cast<float>(root_bounds_.height()) /
           static_cast<float>(mirror_display_rect.height()));
      float inverted_scale = 1.0f / mirror_scale_ratio;
      int margin = static_cast<int>(
          (mirror_display_rect.width() -
           root_bounds_.width() * inverted_scale) / 2);
      insets_.Set(margin, 0, margin, 0);

      transform_.Translate(margin, 0);
      transform_.Scale(inverted_scale, inverted_scale);
    }
  }

  // aura::RootWindowTransformer overrides:
  virtual gfx::Transform GetTransform() const OVERRIDE {
    return transform_;
  }
  virtual gfx::Transform GetInverseTransform() const OVERRIDE {
    gfx::Transform invert;
    CHECK(transform_.GetInverse(&invert));
    return invert;
  }
  virtual gfx::Rect GetRootWindowBounds(
      const gfx::Size& host_size) const OVERRIDE {
    return root_bounds_;
  }
  virtual gfx::Insets GetHostInsets() const OVERRIDE {
    return insets_;
  }

 private:
  virtual ~MirrorRootWindowTransformer() {}

  gfx::Transform transform_;
  gfx::Rect root_bounds_;
  gfx::Insets insets_;

  DISALLOW_COPY_AND_ASSIGN(MirrorRootWindowTransformer);
};

}  // namespace

aura::RootWindowTransformer* CreateRootWindowTransformerForDisplay(
    aura::RootWindow* root,
    const gfx::Display& display) {
  return new AshRootWindowTransformer(root, display);
}

aura::RootWindowTransformer* CreateRootWindowTransformerForMirroredDisplay(
    const DisplayInfo& source_display_info,
    const DisplayInfo& mirror_display_info) {
  return new MirrorRootWindowTransformer(source_display_info,
                                         mirror_display_info);
}

}  // namespace internal
}  // namespace ash
<|endoftext|>


<commit_before>// Copyright (c) 2011 - 2017, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#include <stingraykit/thread/posix/PosixConditionVariable.h>

#include <stingraykit/ScopeExit.h>
#include <stingraykit/Singleton.h>
#include <stingraykit/reference.h>
#include <stingraykit/thread/CancellationRegistrator.h>
#include <stingraykit/time/posix/TimeEngine.h>
#include <stingraykit/time/posix/utils.h>

#include <errno.h>

namespace stingray
{

	struct CancellationHolder : public CancellationRegistratorBase
	{
		struct CancellationHandler : public ICancellationHandler
		{
		private:
			const PosixMutex&		_mutex;
			PosixConditionVariable&	_cond;

		public:
			CancellationHandler(const PosixMutex& mutex, PosixConditionVariable& cond) : _mutex(mutex), _cond(cond)
			{ }

			virtual ~CancellationHandler()
			{ }

			virtual void Cancel()
			{
				MutexLock l(_mutex);
				_cond.Broadcast();
			}

			const PosixMutex& GetMutex() const
			{ return _mutex; }
		};

	private:
		CancellationHandler	_handler;

	public:
		CancellationHolder(const PosixMutex& mutex, PosixConditionVariable& cond, const ICancellationToken& token) :
			CancellationRegistratorBase(token), _handler(mutex, cond)
		{ Register(_handler); }

		~CancellationHolder()
		{
			if (TryUnregister(_handler))
				return;

			MutexUnlock ul(_handler.GetMutex());
			Unregister(_handler);
		}
	};

	class PosixConditionVariableAttr : public Singleton<PosixConditionVariableAttr>
	{
		STINGRAYKIT_SINGLETON(PosixConditionVariableAttr);

	private:
		pthread_condattr_t		_condAttr;

	private:
		PosixConditionVariableAttr()
		{
			int ret = 0;
			STINGRAYKIT_CHECK((ret = pthread_condattr_init(&_condAttr)) == 0, SystemException("pthread_condattr_init", ret));
			STINGRAYKIT_CHECK((ret = pthread_condattr_setclock(&_condAttr, CLOCK_MONOTONIC)) == 0, SystemException("pthread_condattr_setclock", ret));
		}

	public:
		~PosixConditionVariableAttr() { pthread_condattr_destroy(&_condAttr); }

		const pthread_condattr_t& Get() const { return _condAttr; }
	};

	PosixConditionVariable::PosixConditionVariable()
	{
		int ret = 0;
		STINGRAYKIT_CHECK((ret = pthread_cond_init(&_cond, &PosixConditionVariableAttr::ConstInstance().Get())) == 0, SystemException("pthread_cond_init", ret));
	}

	PosixConditionVariable::~PosixConditionVariable()
	{
		pthread_cond_destroy(&_cond);
	}

	void PosixConditionVariable::Wait(const PosixMutex& mutex, const ICancellationToken& token)
	{
		CancellationHolder holder(mutex, *this, token);
		if (holder.IsCancelled())
			return;
		Wait(mutex);
	}

	bool PosixConditionVariable::TimedWait(const PosixMutex& mutex, TimeDuration interval, const ICancellationToken& token)
	{
		CancellationHolder holder(mutex, *this, token);
		if (holder.IsCancelled())
			return true;
		return TimedWait(mutex, interval);
	}

	void PosixConditionVariable::Wait(const PosixMutex& mutex) const
	{
		int ret = pthread_cond_wait(&_cond, &mutex._rawMutex);
		if (ret != 0)
			STINGRAYKIT_THROW(SystemException("pthread_cond_wait", ret));
	}

	bool PosixConditionVariable::TimedWait(const PosixMutex& mutex, TimeDuration interval) const
	{
		timespec t = { };
		posix::timespec_now(CLOCK_MONOTONIC, &t);
		posix::timespec_add(&t, interval);
		int ret = pthread_cond_timedwait(&_cond, &mutex._rawMutex, &t);
		if (ret != 0 && ret != ETIMEDOUT)
			STINGRAYKIT_THROW(SystemException("pthread_cond_timedwait", ret));

		return ret != ETIMEDOUT;
	}

	void PosixConditionVariable::Broadcast()
	{
		int ret = pthread_cond_broadcast(&_cond);
		if (ret != 0)
			STINGRAYKIT_THROW(SystemException("pthread_cond_broadcast", ret));
	}

}
<commit_msg>PosixConditionVariable: use STINGRAYKIT_CHECK (for STINGRAYKIT_UNLIKELY)<commit_after>// Copyright (c) 2011 - 2017, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#include <stingraykit/thread/posix/PosixConditionVariable.h>

#include <stingraykit/ScopeExit.h>
#include <stingraykit/Singleton.h>
#include <stingraykit/reference.h>
#include <stingraykit/thread/CancellationRegistrator.h>
#include <stingraykit/time/posix/TimeEngine.h>
#include <stingraykit/time/posix/utils.h>

#include <errno.h>

namespace stingray
{

	struct CancellationHolder : public CancellationRegistratorBase
	{
		struct CancellationHandler : public ICancellationHandler
		{
		private:
			const PosixMutex&		_mutex;
			PosixConditionVariable&	_cond;

		public:
			CancellationHandler(const PosixMutex& mutex, PosixConditionVariable& cond) : _mutex(mutex), _cond(cond)
			{ }

			virtual ~CancellationHandler()
			{ }

			virtual void Cancel()
			{
				MutexLock l(_mutex);
				_cond.Broadcast();
			}

			const PosixMutex& GetMutex() const
			{ return _mutex; }
		};

	private:
		CancellationHandler	_handler;

	public:
		CancellationHolder(const PosixMutex& mutex, PosixConditionVariable& cond, const ICancellationToken& token) :
			CancellationRegistratorBase(token), _handler(mutex, cond)
		{ Register(_handler); }

		~CancellationHolder()
		{
			if (TryUnregister(_handler))
				return;

			MutexUnlock ul(_handler.GetMutex());
			Unregister(_handler);
		}
	};

	class PosixConditionVariableAttr : public Singleton<PosixConditionVariableAttr>
	{
		STINGRAYKIT_SINGLETON(PosixConditionVariableAttr);

	private:
		pthread_condattr_t		_condAttr;

	private:
		PosixConditionVariableAttr()
		{
			int ret = 0;
			STINGRAYKIT_CHECK((ret = pthread_condattr_init(&_condAttr)) == 0, SystemException("pthread_condattr_init", ret));
			STINGRAYKIT_CHECK((ret = pthread_condattr_setclock(&_condAttr, CLOCK_MONOTONIC)) == 0, SystemException("pthread_condattr_setclock", ret));
		}

	public:
		~PosixConditionVariableAttr() { pthread_condattr_destroy(&_condAttr); }

		const pthread_condattr_t& Get() const { return _condAttr; }
	};

	PosixConditionVariable::PosixConditionVariable()
	{
		int ret = 0;
		STINGRAYKIT_CHECK((ret = pthread_cond_init(&_cond, &PosixConditionVariableAttr::ConstInstance().Get())) == 0, SystemException("pthread_cond_init", ret));
	}

	PosixConditionVariable::~PosixConditionVariable()
	{
		pthread_cond_destroy(&_cond);
	}

	void PosixConditionVariable::Wait(const PosixMutex& mutex, const ICancellationToken& token)
	{
		CancellationHolder holder(mutex, *this, token);
		if (holder.IsCancelled())
			return;
		Wait(mutex);
	}

	bool PosixConditionVariable::TimedWait(const PosixMutex& mutex, TimeDuration interval, const ICancellationToken& token)
	{
		CancellationHolder holder(mutex, *this, token);
		if (holder.IsCancelled())
			return true;
		return TimedWait(mutex, interval);
	}

	void PosixConditionVariable::Wait(const PosixMutex& mutex) const
	{
		int ret = pthread_cond_wait(&_cond, &mutex._rawMutex);
		STINGRAYKIT_CHECK(ret == 0, SystemException("pthread_cond_wait", ret));
	}

	bool PosixConditionVariable::TimedWait(const PosixMutex& mutex, TimeDuration interval) const
	{
		timespec t = { };
		posix::timespec_now(CLOCK_MONOTONIC, &t);
		posix::timespec_add(&t, interval);
		int ret = pthread_cond_timedwait(&_cond, &mutex._rawMutex, &t);
		STINGRAYKIT_CHECK(ret == 0 || ret == ETIMEDOUT, SystemException("pthread_cond_timedwait", ret));

		return ret != ETIMEDOUT;
	}

	void PosixConditionVariable::Broadcast()
	{
		int ret = pthread_cond_broadcast(&_cond);
		STINGRAYKIT_CHECK(ret == 0, SystemException("pthread_cond_broadcast", ret));
	}

}
<|endoftext|>


<commit_before>#ifndef AMGCL_RELAXATION_ILU0_HPP
#define AMGCL_RELAXATION_ILU0_HPP

/*
The MIT License

Copyright (c) 2012-2015 Denis Demidov <dennis.demidov@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
 * \file   amgcl/relaxation/ilu0.hpp
 * \author Denis Demidov <dennis.demidov@gmail.com>
 * \brief  Incomplete LU with zero fill-in relaxation scheme.
 */

#include <amgcl/backend/builtin.hpp>
#include <amgcl/util.hpp>

namespace amgcl {
namespace relaxation {

/// ILU(0) smoother.
/**
 * \note ILU(0) is a serial algorithm and is only applicable to backends that
 * support matrix row iteration (e.g. amgcl::backend::builtin or
 * amgcl::backend::eigen).
 *
 * \param Backend Backend for temporary structures allocation.
 * \ingroup relaxation
 */
template <class Backend>
struct ilu0 {
    typedef typename Backend::value_type value_type;
    typedef typename Backend::vector     vector;

    /// Relaxation parameters.
    struct params {
        /// Damping factor.
        float damping;

        params(float damping = 1) : damping(damping) {}

        params(const boost::property_tree::ptree &p)
            : AMGCL_PARAMS_IMPORT_VALUE(p, damping)
        {}

        void get(boost::property_tree::ptree &p, const std::string &path) const {
            AMGCL_PARAMS_EXPORT_VALUE(p, path, damping);
        }
    };

    /// \copydoc amgcl::relaxation::damped_jacobi::damped_jacobi
    template <class Matrix>
    ilu0( const Matrix &A, const params &, const typename Backend::params&)
        : luval( A.val ),
          dia  ( backend::rows(A) )
    {
        const size_t n = backend::rows(A);
        const value_type eps = amgcl::detail::eps<value_type>(1);

        std::vector<ptrdiff_t> work(n, -1);

        for(size_t i = 0; i < n; ++i) {
            ptrdiff_t row_beg = A.ptr[i];
            ptrdiff_t row_end = A.ptr[i + 1];

            for(ptrdiff_t j = row_beg; j < row_end; ++j)
                work[ A.col[j] ] = j;

            for(ptrdiff_t j = row_beg; j < row_end; ++j) {
                ptrdiff_t c = A.col[j];

                // Exit if diagonal is reached
                if (static_cast<size_t>(c) >= i) {
                    precondition(
                            static_cast<size_t>(c) == i,
                            "No diagonal value in system matrix"
                            );
                    precondition(
                            fabs(luval[j]) > eps,
                            "Zero pivot in ILU"
                            );

                    dia[i]   = j;
                    luval[j] = 1 / luval[j];
                    break;
                }

                // Compute the multiplier for jrow
                value_type tl = luval[j] * luval[dia[c]];
                luval[j] = tl;

                // Perform linear combination
                for(ptrdiff_t k = dia[c] + 1; k < A.ptr[c + 1]; ++k) {
                    ptrdiff_t w = work[A.col[k]];
                    if (w >= 0) luval[w] -= tl * luval[k];
                }
            }

            // Refresh work
            for(ptrdiff_t j = row_beg; j < row_end; ++j)
                work[A.col[j]] = -1;
        }
    }

    /// \copydoc amgcl::relaxation::damped_jacobi::apply_pre
    template <class Matrix, class VectorRHS, class VectorX, class VectorTMP>
    void apply_pre(
            const Matrix &A, const VectorRHS &rhs, VectorX &x, VectorTMP &tmp,
            const params &prm
            ) const
    {
        apply(A, rhs, x, tmp, prm);
    }

    /// \copydoc amgcl::relaxation::damped_jacobi::apply_post
    template <class Matrix, class VectorRHS, class VectorX, class VectorTMP>
    void apply_post(
            const Matrix &A, const VectorRHS &rhs, VectorX &x, VectorTMP &tmp,
            const params &prm
            ) const
    {
        apply(A, rhs, x, tmp, prm);
    }

    private:
        std::vector<value_type> luval;
        std::vector<ptrdiff_t>  dia;

        template <class Matrix, class VectorRHS, class VectorX, class VectorTMP>
        void apply(
                const Matrix &A, const VectorRHS &rhs, VectorX &x, VectorTMP &tmp,
                const params &prm
                ) const
        {
            const size_t n = backend::rows(A);

#pragma omp parallel for
            for(ptrdiff_t i = 0; i < static_cast<ptrdiff_t>(n); ++i) {
                value_type buf = rhs[i];
                for(ptrdiff_t j = A.ptr[i], e = A.ptr[i + 1]; j < e; ++j)
                    buf -= A.val[j] * x[A.col[j]];
                tmp[i] = buf;
            }

            for(size_t i = 0; i < n; i++) {
                for(ptrdiff_t j = A.ptr[i], e = dia[i]; j < e; ++j)
                    tmp[i] -= luval[j] * tmp[A.col[j]];
            }

            for(size_t i = n; i-- > 0;) {
                for(ptrdiff_t j = dia[i] + 1, e = A.ptr[i + 1]; j < e; ++j)
                    tmp[i] -= luval[j] * tmp[A.col[j]];
                tmp[i] *= luval[dia[i]];
            }

#pragma omp parallel for
            for(ptrdiff_t i = 0; i < static_cast<ptrdiff_t>(n); ++i)
                x[i] += prm.damping * tmp[i];
        }

};

} // namespace relaxation

namespace backend {

template <class Backend>
struct relaxation_is_supported<
    Backend,
    relaxation::ilu0,
    typename boost::disable_if<
            typename boost::is_same<
                Backend,
                builtin<typename Backend::value_type>
            >::type
        >::type
    > : boost::false_type
{};

} // namespace backend
} // namespace amgcl

#endif
<commit_msg>Use backend operations in ilu0<commit_after>#ifndef AMGCL_RELAXATION_ILU0_HPP
#define AMGCL_RELAXATION_ILU0_HPP

/*
The MIT License

Copyright (c) 2012-2015 Denis Demidov <dennis.demidov@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
 * \file   amgcl/relaxation/ilu0.hpp
 * \author Denis Demidov <dennis.demidov@gmail.com>
 * \brief  Incomplete LU with zero fill-in relaxation scheme.
 */

#include <amgcl/backend/builtin.hpp>
#include <amgcl/util.hpp>

namespace amgcl {
namespace relaxation {

/// ILU(0) smoother.
/**
 * \note ILU(0) is a serial algorithm and is only applicable to backends that
 * support matrix row iteration (e.g. amgcl::backend::builtin or
 * amgcl::backend::eigen).
 *
 * \param Backend Backend for temporary structures allocation.
 * \ingroup relaxation
 */
template <class Backend>
struct ilu0 {
    typedef typename Backend::value_type value_type;
    typedef typename Backend::vector     vector;

    /// Relaxation parameters.
    struct params {
        /// Damping factor.
        float damping;

        params(float damping = 1) : damping(damping) {}

        params(const boost::property_tree::ptree &p)
            : AMGCL_PARAMS_IMPORT_VALUE(p, damping)
        {}

        void get(boost::property_tree::ptree &p, const std::string &path) const {
            AMGCL_PARAMS_EXPORT_VALUE(p, path, damping);
        }
    };

    /// \copydoc amgcl::relaxation::damped_jacobi::damped_jacobi
    template <class Matrix>
    ilu0( const Matrix &A, const params &, const typename Backend::params&)
        : luval( A.val ),
          dia  ( backend::rows(A) )
    {
        const size_t n = backend::rows(A);
        const value_type eps = amgcl::detail::eps<value_type>(1);

        std::vector<ptrdiff_t> work(n, -1);

        for(size_t i = 0; i < n; ++i) {
            ptrdiff_t row_beg = A.ptr[i];
            ptrdiff_t row_end = A.ptr[i + 1];

            for(ptrdiff_t j = row_beg; j < row_end; ++j)
                work[ A.col[j] ] = j;

            for(ptrdiff_t j = row_beg; j < row_end; ++j) {
                ptrdiff_t c = A.col[j];

                // Exit if diagonal is reached
                if (static_cast<size_t>(c) >= i) {
                    precondition(
                            static_cast<size_t>(c) == i,
                            "No diagonal value in system matrix"
                            );
                    precondition(
                            fabs(luval[j]) > eps,
                            "Zero pivot in ILU"
                            );

                    dia[i]   = j;
                    luval[j] = 1 / luval[j];
                    break;
                }

                // Compute the multiplier for jrow
                value_type tl = luval[j] * luval[dia[c]];
                luval[j] = tl;

                // Perform linear combination
                for(ptrdiff_t k = dia[c] + 1; k < A.ptr[c + 1]; ++k) {
                    ptrdiff_t w = work[A.col[k]];
                    if (w >= 0) luval[w] -= tl * luval[k];
                }
            }

            // Refresh work
            for(ptrdiff_t j = row_beg; j < row_end; ++j)
                work[A.col[j]] = -1;
        }
    }

    /// \copydoc amgcl::relaxation::damped_jacobi::apply_pre
    template <class Matrix, class VectorRHS, class VectorX, class VectorTMP>
    void apply_pre(
            const Matrix &A, const VectorRHS &rhs, VectorX &x, VectorTMP &tmp,
            const params &prm
            ) const
    {
        apply(A, rhs, x, tmp, prm);
    }

    /// \copydoc amgcl::relaxation::damped_jacobi::apply_post
    template <class Matrix, class VectorRHS, class VectorX, class VectorTMP>
    void apply_post(
            const Matrix &A, const VectorRHS &rhs, VectorX &x, VectorTMP &tmp,
            const params &prm
            ) const
    {
        apply(A, rhs, x, tmp, prm);
    }

    private:
        std::vector<value_type> luval;
        std::vector<ptrdiff_t>  dia;

        template <class Matrix, class VectorRHS, class VectorX, class VectorTMP>
        void apply(
                const Matrix &A, const VectorRHS &rhs, VectorX &x, VectorTMP &tmp,
                const params &prm
                ) const
        {
            const size_t n = backend::rows(A);

            backend::residual(rhs, A, x, tmp);

            for(size_t i = 0; i < n; i++) {
                for(ptrdiff_t j = A.ptr[i], e = dia[i]; j < e; ++j)
                    tmp[i] -= luval[j] * tmp[A.col[j]];
            }

            for(size_t i = n; i-- > 0;) {
                for(ptrdiff_t j = dia[i] + 1, e = A.ptr[i + 1]; j < e; ++j)
                    tmp[i] -= luval[j] * tmp[A.col[j]];
                tmp[i] *= luval[dia[i]];
            }

            backend::axpby(prm.damping, tmp, 1, x);
        }

};

} // namespace relaxation

namespace backend {

template <class Backend>
struct relaxation_is_supported<
    Backend,
    relaxation::ilu0,
    typename boost::disable_if<
            typename boost::is_same<
                Backend,
                builtin<typename Backend::value_type>
            >::type
        >::type
    > : boost::false_type
{};

} // namespace backend
} // namespace amgcl

#endif
<|endoftext|>


<commit_before>/*
* SHACAL-2 using x86 SHA extensions
* (C) 2017 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/shacal2.h>
#include <immintrin.h>

namespace Botan {

/*
Only encryption is supported since the inverse round function would
require a different instruction
*/

BOTAN_FUNC_ISA("sha,ssse3")
void SHACAL2::x86_encrypt_blocks(const uint8_t in[], uint8_t out[], size_t blocks) const
   {
   const __m128i MASK1 = _mm_set_epi8(8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7);
   const __m128i MASK2 = _mm_set_epi8(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);

   const __m128i* RK_mm = reinterpret_cast<const __m128i*>(m_RK.data());
   const __m128i* in_mm = reinterpret_cast<const __m128i*>(in);
   __m128i* out_mm = reinterpret_cast<__m128i*>(out);

   while(blocks >= 2)
      {
      __m128i B0_0 = _mm_loadu_si128(in_mm);
      __m128i B0_1 = _mm_loadu_si128(in_mm+1);
      __m128i B1_0 = _mm_loadu_si128(in_mm+2);
      __m128i B1_1 = _mm_loadu_si128(in_mm+3);

      __m128i TMP = _mm_shuffle_epi8(_mm_unpacklo_epi64(B0_0, B0_1), MASK2);
      B0_1 = _mm_shuffle_epi8(_mm_unpackhi_epi64(B0_0, B0_1), MASK2);
      B0_0 = TMP;

      TMP = _mm_shuffle_epi8(_mm_unpacklo_epi64(B1_0, B1_1), MASK2);
      B1_1 = _mm_shuffle_epi8(_mm_unpackhi_epi64(B1_0, B1_1), MASK2);
      B1_0 = TMP;

      for(size_t i = 0; i != 8; ++i)
         {
         const __m128i RK0 = _mm_loadu_si128(RK_mm + 2*i);
         const __m128i RK2 = _mm_loadu_si128(RK_mm + 2*i+1);
         const __m128i RK1 = _mm_srli_si128(RK0, 8);
         const __m128i RK3 = _mm_srli_si128(RK2, 8);

         B0_1 = _mm_sha256rnds2_epu32(B0_1, B0_0, RK0);
         B1_1 = _mm_sha256rnds2_epu32(B1_1, B1_0, RK0);

         B0_0 = _mm_sha256rnds2_epu32(B0_0, B0_1, RK1);
         B1_0 = _mm_sha256rnds2_epu32(B1_0, B1_1, RK1);

         B0_1 = _mm_sha256rnds2_epu32(B0_1, B0_0, RK2);
         B1_1 = _mm_sha256rnds2_epu32(B1_1, B1_0, RK2);

         B0_0 = _mm_sha256rnds2_epu32(B0_0, B0_1, RK3);
         B1_0 = _mm_sha256rnds2_epu32(B1_0, B1_1, RK3);
         }

      TMP = _mm_shuffle_epi8(_mm_unpackhi_epi64(B0_0, B0_1), MASK1);
      B0_1 = _mm_shuffle_epi8(_mm_unpacklo_epi64(B0_0, B0_1), MASK1);
      B0_0 = TMP;

      TMP = _mm_shuffle_epi8(_mm_unpackhi_epi64(B1_0, B1_1), MASK1);
      B1_1 = _mm_shuffle_epi8(_mm_unpacklo_epi64(B1_0, B1_1), MASK1);
      B1_0 = TMP;

      // Save state
      _mm_storeu_si128(out_mm + 0, B0_0);
      _mm_storeu_si128(out_mm + 1, B0_1);
      _mm_storeu_si128(out_mm + 2, B1_0);
      _mm_storeu_si128(out_mm + 3, B1_1);

      blocks -= 2;
      in_mm += 4;
      out_mm += 4;
      }

   while(blocks)
      {
      __m128i B0 = _mm_loadu_si128(in_mm);
      __m128i B1 = _mm_loadu_si128(in_mm+1);

      __m128i TMP = _mm_shuffle_epi8(_mm_unpacklo_epi64(B0, B1), MASK2);
      B1 = _mm_shuffle_epi8(_mm_unpackhi_epi64(B0, B1), MASK2);
      B0 = TMP;

      for(size_t i = 0; i != 8; ++i)
         {
         const __m128i RK0 = _mm_loadu_si128(RK_mm + 2*i);
         const __m128i RK2 = _mm_loadu_si128(RK_mm + 2*i+1);
         const __m128i RK1 = _mm_srli_si128(RK0, 8);
         const __m128i RK3 = _mm_srli_si128(RK2, 8);

         B1 = _mm_sha256rnds2_epu32(B1, B0, RK0);
         B0 = _mm_sha256rnds2_epu32(B0, B1, RK1);
         B1 = _mm_sha256rnds2_epu32(B1, B0, RK2);
         B0 = _mm_sha256rnds2_epu32(B0, B1, RK3);
         }

      TMP = _mm_shuffle_epi8(_mm_unpackhi_epi64(B0, B1), MASK1);
      B1 = _mm_shuffle_epi8(_mm_unpacklo_epi64(B0, B1), MASK1);
      B0 = TMP;

      // Save state
      _mm_storeu_si128(out_mm, B0);
      _mm_storeu_si128(out_mm + 1, B1);

      blocks--;
      in_mm += 2;
      out_mm += 2;
      }
   }

}
<commit_msg>Simplify this store code a bit<commit_after>/*
* SHACAL-2 using x86 SHA extensions
* (C) 2017 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/shacal2.h>
#include <immintrin.h>

namespace Botan {

/*
Only encryption is supported since the inverse round function would
require a different instruction
*/

BOTAN_FUNC_ISA("sha,ssse3")
void SHACAL2::x86_encrypt_blocks(const uint8_t in[], uint8_t out[], size_t blocks) const
   {
   const __m128i MASK1 = _mm_set_epi8(8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7);
   const __m128i MASK2 = _mm_set_epi8(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);

   const __m128i* RK_mm = reinterpret_cast<const __m128i*>(m_RK.data());
   const __m128i* in_mm = reinterpret_cast<const __m128i*>(in);
   __m128i* out_mm = reinterpret_cast<__m128i*>(out);

   while(blocks >= 2)
      {
      __m128i B0_0 = _mm_loadu_si128(in_mm);
      __m128i B0_1 = _mm_loadu_si128(in_mm+1);
      __m128i B1_0 = _mm_loadu_si128(in_mm+2);
      __m128i B1_1 = _mm_loadu_si128(in_mm+3);

      __m128i TMP = _mm_shuffle_epi8(_mm_unpacklo_epi64(B0_0, B0_1), MASK2);
      B0_1 = _mm_shuffle_epi8(_mm_unpackhi_epi64(B0_0, B0_1), MASK2);
      B0_0 = TMP;

      TMP = _mm_shuffle_epi8(_mm_unpacklo_epi64(B1_0, B1_1), MASK2);
      B1_1 = _mm_shuffle_epi8(_mm_unpackhi_epi64(B1_0, B1_1), MASK2);
      B1_0 = TMP;

      for(size_t i = 0; i != 8; ++i)
         {
         const __m128i RK0 = _mm_loadu_si128(RK_mm + 2*i);
         const __m128i RK2 = _mm_loadu_si128(RK_mm + 2*i+1);
         const __m128i RK1 = _mm_srli_si128(RK0, 8);
         const __m128i RK3 = _mm_srli_si128(RK2, 8);

         B0_1 = _mm_sha256rnds2_epu32(B0_1, B0_0, RK0);
         B1_1 = _mm_sha256rnds2_epu32(B1_1, B1_0, RK0);

         B0_0 = _mm_sha256rnds2_epu32(B0_0, B0_1, RK1);
         B1_0 = _mm_sha256rnds2_epu32(B1_0, B1_1, RK1);

         B0_1 = _mm_sha256rnds2_epu32(B0_1, B0_0, RK2);
         B1_1 = _mm_sha256rnds2_epu32(B1_1, B1_0, RK2);

         B0_0 = _mm_sha256rnds2_epu32(B0_0, B0_1, RK3);
         B1_0 = _mm_sha256rnds2_epu32(B1_0, B1_1, RK3);
         }

      _mm_storeu_si128(out_mm + 0, _mm_shuffle_epi8(_mm_unpackhi_epi64(B0_0, B0_1), MASK1));
      _mm_storeu_si128(out_mm + 1, _mm_shuffle_epi8(_mm_unpacklo_epi64(B0_0, B0_1), MASK1));
      _mm_storeu_si128(out_mm + 2, _mm_shuffle_epi8(_mm_unpackhi_epi64(B1_0, B1_1), MASK1));
      _mm_storeu_si128(out_mm + 3, _mm_shuffle_epi8(_mm_unpacklo_epi64(B1_0, B1_1), MASK1));

      blocks -= 2;
      in_mm += 4;
      out_mm += 4;
      }

   while(blocks)
      {
      __m128i B0 = _mm_loadu_si128(in_mm);
      __m128i B1 = _mm_loadu_si128(in_mm+1);

      __m128i TMP = _mm_shuffle_epi8(_mm_unpacklo_epi64(B0, B1), MASK2);
      B1 = _mm_shuffle_epi8(_mm_unpackhi_epi64(B0, B1), MASK2);
      B0 = TMP;

      for(size_t i = 0; i != 8; ++i)
         {
         const __m128i RK0 = _mm_loadu_si128(RK_mm + 2*i);
         const __m128i RK2 = _mm_loadu_si128(RK_mm + 2*i+1);
         const __m128i RK1 = _mm_srli_si128(RK0, 8);
         const __m128i RK3 = _mm_srli_si128(RK2, 8);

         B1 = _mm_sha256rnds2_epu32(B1, B0, RK0);
         B0 = _mm_sha256rnds2_epu32(B0, B1, RK1);
         B1 = _mm_sha256rnds2_epu32(B1, B0, RK2);
         B0 = _mm_sha256rnds2_epu32(B0, B1, RK3);
         }

      _mm_storeu_si128(out_mm    , _mm_shuffle_epi8(_mm_unpackhi_epi64(B0, B1), MASK1));
      _mm_storeu_si128(out_mm + 1, _mm_shuffle_epi8(_mm_unpacklo_epi64(B0, B1), MASK1));

      blocks--;
      in_mm += 2;
      out_mm += 2;
      }
   }

}
<|endoftext|>


<commit_before>#pragma once
#include "geometry.hpp"

template <size_t dim>
struct PtWithIdx {
    std::array<double,dim> pt;
    size_t orig_idx;
};

// template <size_t dim>
// Ball<dim> tree_bounds(PtWithIdx<dim>* pts, size_t n_pts) {
//     std::array<double,dim> com{};
//
//     for (size_t i = 0; i < n_pts; i++) {
//         for (size_t d = 0; d < dim; d++) {
//             com[d] += pts[i].pt[d];
//         }
//     }
//     for (size_t d = 0; d < dim; d++) {
//         com[d] /= n_pts;
//     }
//
//     double max_r2 = 0.0;
//     for (size_t i = 0; i < n_pts; i++) {
//         for (size_t d = 0; d < dim; d++) {
//             max_r2 = std::max(max_r2, dist2(pts[i].pt, com));
//         }
//     }
//
//     return {com, std::sqrt(max_r2)};
// }

template <size_t dim>
std::pair<size_t,double> furthest_pt(PtWithIdx<dim>* pts, size_t n_pts,
    const std::array<double,dim>& from)
{
    size_t furthest_idx = 0;
    double furthest_dist2 = dist2(from, pts[furthest_idx].pt);
    for (size_t i = 1; i < n_pts; i++) {
        double d2 = dist2(from, pts[i].pt);
        if (d2 > furthest_dist2) {
            furthest_idx = i;
            furthest_dist2 = d2;
        }
    }
    return {furthest_idx, furthest_dist2};
}

template <size_t dim>
Ball<dim> tree_bounds(PtWithIdx<dim>* pts, size_t n_pts) {
    if (n_pts == 1) {
        return {pts[0].pt, 0};
    }
    auto x = pts[0].pt;
    auto y = furthest_pt(pts, n_pts, x);
    auto z = furthest_pt(pts, n_pts, pts[y.first].pt);
    auto center = mult(add(pts[y.first].pt, pts[z.first].pt), 0.5);
    auto w = furthest_pt(pts, n_pts, center);
    auto R = std::sqrt(w.second);
    return {center, R};
}

template <size_t dim>
std::vector<PtWithIdx<dim>> combine_pts_idxs(std::array<double,dim>* pts, size_t n_pts) {
    std::vector<PtWithIdx<dim>> pts_idxs(n_pts);
    for (size_t i = 0; i < n_pts; i++) {
        pts_idxs[i] = {pts[i], i};
    }
    return pts_idxs;
}
<commit_msg>Revert bounding sphere change.<commit_after>#pragma once
#include "geometry.hpp"

template <size_t dim>
struct PtWithIdx {
    std::array<double,dim> pt;
    size_t orig_idx;
};

// Note: I tried using a minimum bounding sphere algorithm. This didn't help and actually hurt a little bit(?!). Furthermore, the tree construction cost went up quite a lot. On second thought, this makes sense, because there's probably some value in having the center of a node at its center of mass for the sake of the error in the translation operator. Also, for most nodes, the center of mass approach will be quite close to the minimum bounding sphere.
template <size_t dim>
Ball<dim> tree_bounds(PtWithIdx<dim>* pts, size_t n_pts) {
    std::array<double,dim> com{};

    for (size_t i = 0; i < n_pts; i++) {
        for (size_t d = 0; d < dim; d++) {
            com[d] += pts[i].pt[d];
        }
    }
    for (size_t d = 0; d < dim; d++) {
        com[d] /= n_pts;
    }

    double max_r2 = 0.0;
    for (size_t i = 0; i < n_pts; i++) {
        for (size_t d = 0; d < dim; d++) {
            max_r2 = std::max(max_r2, dist2(pts[i].pt, com));
        }
    }

    return {com, std::sqrt(max_r2)};
}

template <size_t dim>
std::vector<PtWithIdx<dim>> combine_pts_idxs(std::array<double,dim>* pts, size_t n_pts) {
    std::vector<PtWithIdx<dim>> pts_idxs(n_pts);
    for (size_t i = 0; i < n_pts; i++) {
        pts_idxs[i] = {pts[i], i};
    }
    return pts_idxs;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: retrievedinputstreamdata.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2007-07-18 13:31:32 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#include "precompiled_sw.hxx"

#ifndef _RETRIEVEDINPUTSTREAMDATA_HXX
#include <retrievedinputstreamdata.hxx>
#endif
#ifndef _RETRIEVEINPUTSTREAMCONSUMER_HXX
#include <retrieveinputstreamconsumer.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

/** implementation of class <SwRetrievedInputStreamDataManager>

    OD 2007-01-30 #i73788#
*/
SwRetrievedInputStreamDataManager* SwRetrievedInputStreamDataManager::mpManager = 0;
SwRetrievedInputStreamDataManager::tDataKey SwRetrievedInputStreamDataManager::mnNextKeyValue = 1;
osl::Mutex SwRetrievedInputStreamDataManager::maGetManagerMutex;

SwRetrievedInputStreamDataManager& SwRetrievedInputStreamDataManager::GetManager()
{
    osl::MutexGuard aGuard(maGetManagerMutex);

    if ( mpManager == 0 )
    {
        mpManager = new SwRetrievedInputStreamDataManager();
    }

    return *mpManager;
}

SwRetrievedInputStreamDataManager::tDataKey SwRetrievedInputStreamDataManager::ReserveData(
                        boost::weak_ptr< SwAsyncRetrieveInputStreamThreadConsumer > pThreadConsumer )
{
    osl::MutexGuard aGuard(maMutex);

    // create empty data container for given thread Consumer
    tDataKey nDataKey( mnNextKeyValue );
    tData aNewEntry( pThreadConsumer );
    maInputStreamData[ nDataKey ] = aNewEntry;

    // prepare next data key value
    if ( mnNextKeyValue < SAL_MAX_UINT64 )
    {
        ++mnNextKeyValue;
    }
    else
    {
        mnNextKeyValue = 1;
    }

    return nDataKey;
}

void SwRetrievedInputStreamDataManager::ReleaseData( const tDataKey nDataKey )
{
    osl::MutexGuard aGuard(maMutex);

    std::map< tDataKey, tData >::iterator aIter = maInputStreamData.find( nDataKey );

    if ( aIter != maInputStreamData.end() )
    {
        maInputStreamData.erase( aIter );
    }
}

void SwRetrievedInputStreamDataManager::PushData(
        const tDataKey nDataKey,
        com::sun::star::uno::Reference<com::sun::star::io::XInputStream> xInputStream,
        const sal_Bool bIsStreamReadOnly )
{
    osl::MutexGuard aGuard(maMutex);

    std::map< tDataKey, tData >::iterator aIter = maInputStreamData.find( nDataKey );

    if ( aIter != maInputStreamData.end() )
    {
        // Fill data container.
        (*aIter).second.mxInputStream = xInputStream;
        (*aIter).second.mbIsStreamReadOnly = bIsStreamReadOnly;

        // post user event to process the retrieved input stream data
        if ( GetpApp() )
        {

            tDataKey* pDataKey = new tDataKey;
            *pDataKey = nDataKey;
            GetpApp()->PostUserEvent( LINK( this, SwRetrievedInputStreamDataManager, LinkedInputStreamReady ), pDataKey );
        }
        else
        {
            // no application available -> discard data
            maInputStreamData.erase( aIter );
        }
    }
}

bool SwRetrievedInputStreamDataManager::PopData( const tDataKey nDataKey,
                                                 tData& rData )
{
    osl::MutexGuard aGuard(maMutex);

    bool bDataProvided( false );

    std::map< tDataKey, tData >::iterator aIter = maInputStreamData.find( nDataKey );

    if ( aIter != maInputStreamData.end() )
    {
        rData.mpThreadConsumer = (*aIter).second.mpThreadConsumer;
        rData.mxInputStream = (*aIter).second.mxInputStream;
        rData.mbIsStreamReadOnly = (*aIter).second.mbIsStreamReadOnly;

        maInputStreamData.erase( aIter );

        bDataProvided = true;
    }

    return bDataProvided;
}

/** callback function, which is triggered by input stream data manager on
    filling of the data container to provide retrieved input stream to the
    thread Consumer using <Application::PostUserEvent(..)>

    OD 2007-01-29 #i73788#
    Note: This method has to be run in the main thread.

    @author OD
*/
IMPL_LINK( SwRetrievedInputStreamDataManager,
           LinkedInputStreamReady,
           SwRetrievedInputStreamDataManager::tDataKey*,
           pDataKey )
{
    if ( !pDataKey )
    {
        return 0;
    }

    osl::MutexGuard aGuard(maMutex);

    SwRetrievedInputStreamDataManager& rDataManager =
                            SwRetrievedInputStreamDataManager::GetManager();
    SwRetrievedInputStreamDataManager::tData aInputStreamData;
    if ( rDataManager.PopData( *pDataKey, aInputStreamData ) )
    {
        boost::shared_ptr< SwAsyncRetrieveInputStreamThreadConsumer > pThreadConsumer =
                                    aInputStreamData.mpThreadConsumer.lock();
        if ( pThreadConsumer )
        {
            pThreadConsumer->ApplyInputStream( aInputStreamData.mxInputStream,
                                               aInputStreamData.mbIsStreamReadOnly );
        }
    }
    delete pDataKey;

    return 0;
}

<commit_msg>INTEGRATION: CWS sw8u10bf05 (1.2.236); FILE MERGED 2008/01/24 10:54:17 ama 1.2.236.1: Fix #i85182#: Remove unused code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: retrievedinputstreamdata.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2008-03-18 15:56:01 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#include "precompiled_sw.hxx"

#ifndef _RETRIEVEDINPUTSTREAMDATA_HXX
#include <retrievedinputstreamdata.hxx>
#endif
#ifndef _RETRIEVEINPUTSTREAMCONSUMER_HXX
#include <retrieveinputstreamconsumer.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

/** implementation of class <SwRetrievedInputStreamDataManager>

    OD 2007-01-30 #i73788#
*/
SwRetrievedInputStreamDataManager* SwRetrievedInputStreamDataManager::mpManager = 0;
SwRetrievedInputStreamDataManager::tDataKey SwRetrievedInputStreamDataManager::mnNextKeyValue = 1;
osl::Mutex SwRetrievedInputStreamDataManager::maGetManagerMutex;

SwRetrievedInputStreamDataManager& SwRetrievedInputStreamDataManager::GetManager()
{
    osl::MutexGuard aGuard(maGetManagerMutex);

    if ( mpManager == 0 )
    {
        mpManager = new SwRetrievedInputStreamDataManager();
    }

    return *mpManager;
}

SwRetrievedInputStreamDataManager::tDataKey SwRetrievedInputStreamDataManager::ReserveData(
                        boost::weak_ptr< SwAsyncRetrieveInputStreamThreadConsumer > pThreadConsumer )
{
    osl::MutexGuard aGuard(maMutex);

    // create empty data container for given thread Consumer
    tDataKey nDataKey( mnNextKeyValue );
    tData aNewEntry( pThreadConsumer );
    maInputStreamData[ nDataKey ] = aNewEntry;

    // prepare next data key value
    if ( mnNextKeyValue < SAL_MAX_UINT64 )
    {
        ++mnNextKeyValue;
    }
    else
    {
        mnNextKeyValue = 1;
    }

    return nDataKey;
}

void SwRetrievedInputStreamDataManager::PushData(
        const tDataKey nDataKey,
        com::sun::star::uno::Reference<com::sun::star::io::XInputStream> xInputStream,
        const sal_Bool bIsStreamReadOnly )
{
    osl::MutexGuard aGuard(maMutex);

    std::map< tDataKey, tData >::iterator aIter = maInputStreamData.find( nDataKey );

    if ( aIter != maInputStreamData.end() )
    {
        // Fill data container.
        (*aIter).second.mxInputStream = xInputStream;
        (*aIter).second.mbIsStreamReadOnly = bIsStreamReadOnly;

        // post user event to process the retrieved input stream data
        if ( GetpApp() )
        {

            tDataKey* pDataKey = new tDataKey;
            *pDataKey = nDataKey;
            GetpApp()->PostUserEvent( LINK( this, SwRetrievedInputStreamDataManager, LinkedInputStreamReady ), pDataKey );
        }
        else
        {
            // no application available -> discard data
            maInputStreamData.erase( aIter );
        }
    }
}

bool SwRetrievedInputStreamDataManager::PopData( const tDataKey nDataKey,
                                                 tData& rData )
{
    osl::MutexGuard aGuard(maMutex);

    bool bDataProvided( false );

    std::map< tDataKey, tData >::iterator aIter = maInputStreamData.find( nDataKey );

    if ( aIter != maInputStreamData.end() )
    {
        rData.mpThreadConsumer = (*aIter).second.mpThreadConsumer;
        rData.mxInputStream = (*aIter).second.mxInputStream;
        rData.mbIsStreamReadOnly = (*aIter).second.mbIsStreamReadOnly;

        maInputStreamData.erase( aIter );

        bDataProvided = true;
    }

    return bDataProvided;
}

/** callback function, which is triggered by input stream data manager on
    filling of the data container to provide retrieved input stream to the
    thread Consumer using <Application::PostUserEvent(..)>

    OD 2007-01-29 #i73788#
    Note: This method has to be run in the main thread.

    @author OD
*/
IMPL_LINK( SwRetrievedInputStreamDataManager,
           LinkedInputStreamReady,
           SwRetrievedInputStreamDataManager::tDataKey*,
           pDataKey )
{
    if ( !pDataKey )
    {
        return 0;
    }

    osl::MutexGuard aGuard(maMutex);

    SwRetrievedInputStreamDataManager& rDataManager =
                            SwRetrievedInputStreamDataManager::GetManager();
    SwRetrievedInputStreamDataManager::tData aInputStreamData;
    if ( rDataManager.PopData( *pDataKey, aInputStreamData ) )
    {
        boost::shared_ptr< SwAsyncRetrieveInputStreamThreadConsumer > pThreadConsumer =
                                    aInputStreamData.mpThreadConsumer.lock();
        if ( pThreadConsumer )
        {
            pThreadConsumer->ApplyInputStream( aInputStreamData.mxInputStream,
                                               aInputStreamData.mbIsStreamReadOnly );
        }
    }
    delete pDataKey;

    return 0;
}

<|endoftext|>


<commit_before>#include <stdio.h>
#include <mapEditorBuiltin.class.hpp>
#include <fileLoader.class.hpp>
#include <shutdown.class.hpp>
#include <runtimeLibrary.class.hpp>
#include <basicLightFactory.class.hpp>
#include <directorySmartLoader.class.hpp>

void debut()
{
	uint32_t asset = fileLoader::load_fs_asset_sync("./assets/graphic/mesh/cube/cube.obj", E_3D);
	renderDataSys::set_programm(E_SKYBOX, asset);
	renderBuiltIn::modify_skybox(asset);
	basicFPSControlManagerBuiltin::create(256 * 1300 * -0, 0000, -256 * 1300 * 0, 0, 0, 1, 1);
	renderBuiltIn::modify_skybox_light(1.2);
	basicLightFactory::create(glm::vec3(0, 10000, 0), glm::vec3(0, 0, 0), glm::vec3(1, 1, 1), E_UNI, glm::vec3(1, 1, 1));
	directorySmartLoader::execute();
		terrainGenerationBuiltin::add_biom(0, 0, 0, 256,
	500, 1550, texture_builtin::create_instance(fileLoader::load_fs_asset_sync("./assets/graphic/texture/grass.jpg", 1)), 100,
	texture_builtin::create_instance(fileLoader::load_fs_asset_sync("./assets/graphic/texture/hills.jpg", 1)));

}
<commit_msg>ouaiz<commit_after>#include <stdio.h>
#include <mapEditorBuiltin.class.hpp>
#include <fileLoader.class.hpp>
#include <shutdown.class.hpp>
#include <runtimeLibrary.class.hpp>
#include <basicLightFactory.class.hpp>
#include <directorySmartLoader.class.hpp>

void debut()
{
	uint32_t asset = fileLoader::load_fs_asset_sync("./assets/graphic/mesh/cube/cube.obj", E_3D);
	renderDataSys::set_programm(E_SKYBOX, asset);
	renderBuiltIn::modify_skybox(asset);
	basicFPSControlManagerBuiltin::create(256 * 1300 * -0, 0000, -256 * 1300 * 0, 0, 0, 1, 1);
	renderBuiltIn::modify_skybox_light(1.2);
	basicLightFactory::create(glm::vec3(0, 10000, 0), glm::vec3(0, 0, 0), glm::vec3(1, 1, 1), E_UNI, glm::vec3(1, 1, 1));
	directorySmartLoader::execute();
		terrainGenerationBuiltin::add_biom(0, 0, 0, 256,
	500, 4550, texture_builtin::create_instance(fileLoader::load_fs_asset_sync("./assets/graphic/texture/rock.jpeg", 1)), 100,
	texture_builtin::create_instance(fileLoader::load_fs_asset_sync("./assets/graphic/texture/hills.jpg", 1)));

	/*			terrainGenerationBuiltin::add_biom(0, 0, 0, 256,
	500, 1550, texture_builtin::create_instance(fileLoader::load_fs_asset_sync("./assets/graphic/texture/grass.jpg", 1)), 100,
	texture_builtin::create_instance(fileLoader::load_fs_asset_sync("./assets/graphic/texture/hills.jpg", 1)));
*/
}
<|endoftext|>